@stll/folio-core 0.71.1 → 0.73.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.
Files changed (213) hide show
  1. package/README.md +14 -8
  2. package/dist/ai-edits/apply.d.ts +6 -114
  3. package/dist/ai-edits/apply.js +9 -131
  4. package/dist/ai-edits/applyTypes.d.ts +85 -0
  5. package/dist/ai-edits/applyTypes.js +24 -0
  6. package/dist/ai-edits/clean-text.d.ts +7 -1
  7. package/dist/ai-edits/clean-text.js +23 -2
  8. package/dist/ai-edits/finalSectionReview.d.ts +1 -1
  9. package/dist/ai-edits/headless.d.ts +29 -147
  10. package/dist/ai-edits/headless.js +213 -1634
  11. package/dist/ai-edits/index.d.ts +3 -3
  12. package/dist/ai-edits/index.js +2 -3
  13. package/dist/ai-edits/pending-suggestions.d.ts +14 -4
  14. package/dist/ai-edits/pending-suggestions.js +183 -90
  15. package/dist/ai-edits/result-validation.js +1 -1
  16. package/dist/ai-edits/retired-comment-receipts.d.ts +1 -1
  17. package/dist/ai-edits/snapshot.js +8 -3
  18. package/dist/ai-edits/table-cell-mutations.d.ts +1 -1
  19. package/dist/ai-edits/table-cell-mutations.js +1 -1
  20. package/dist/ai-edits/table-geometry.d.ts +1 -1
  21. package/dist/ai-edits/table-geometry.js +1 -1
  22. package/dist/ai-edits/table-row-column-mutations.d.ts +1 -1
  23. package/dist/ai-edits/table-row-column-mutations.js +1 -1
  24. package/dist/ai-edits/tableNodes.d.ts +38 -0
  25. package/dist/ai-edits/tableNodes.js +86 -0
  26. package/dist/ai-edits/tracked-batch-fidelity.d.ts +1 -1
  27. package/dist/ai-edits/undefinedReferences.d.ts +7 -0
  28. package/dist/canonical/batchCommentReferences.js +1 -0
  29. package/dist/canonical/canonicalInlineProjection.js +1 -1
  30. package/dist/canonical/canonicalPublicOperations.js +228 -64
  31. package/dist/canonical/canonicalSession.d.ts +9 -1
  32. package/dist/canonical/canonicalSession.js +95 -15
  33. package/dist/compare/compare.d.ts +1 -1
  34. package/dist/compare/inline-atoms-model.d.ts +1 -1
  35. package/dist/compare/inline-atoms.d.ts +2 -2
  36. package/dist/compare/inline-provenance-model.d.ts +1 -1
  37. package/dist/compare/inline-provenance.d.ts +2 -2
  38. package/dist/compat/eigenpal.d.ts +3 -4
  39. package/dist/compat/eigenpal.js +2 -4
  40. package/dist/controller/canonicalClipboard.d.ts +13 -3
  41. package/dist/controller/canonicalClipboard.js +185 -49
  42. package/dist/controller/canonicalClipboardResources.d.ts +9 -1
  43. package/dist/controller/canonicalClipboardResources.js +22 -2
  44. package/dist/controller/canonicalReview.d.ts +1 -1
  45. package/dist/controller/canonicalReview.js +1 -1
  46. package/dist/controller/canonicalStructure.js +1 -1
  47. package/dist/controller/canonicalWatermark.d.ts +10 -0
  48. package/dist/controller/canonicalWatermark.js +37 -0
  49. package/dist/controller/canonicalYjsRoom.d.ts +1 -1
  50. package/dist/controller/headerFooterEditorManager.d.ts +11 -7
  51. package/dist/controller/headerFooterEditorManager.js +39 -151
  52. package/dist/controller/hiddenEditorApi.d.ts +1 -1
  53. package/dist/controller/hiddenEditorManager.d.ts +6 -40
  54. package/dist/controller/hiddenEditorManager.js +173 -306
  55. package/dist/controller/noteEditorManager.d.ts +3 -10
  56. package/dist/controller/noteEditorManager.js +33 -206
  57. package/dist/document-operations-apply.d.ts +15 -0
  58. package/dist/document-operations-apply.js +280 -0
  59. package/dist/document-operations.d.ts +1 -14
  60. package/dist/document-operations.js +2 -279
  61. package/dist/docx/modelValidation.js +1 -1
  62. package/dist/docx/paragraphParser.js +2 -2
  63. package/dist/docx/paragraphPropertySource.d.ts +1 -1
  64. package/dist/docx/reviewResolutionProvenance.d.ts +3 -2
  65. package/dist/docx/reviewResolutionProvenance.js +32 -9
  66. package/dist/docx/revisionIdNormalization.js +30 -7
  67. package/dist/docx/rezip.js +1 -1
  68. package/dist/docx/serializer/borderSerializer.js +1 -1
  69. package/dist/docx/serializer/commentSerializer.js +1 -1
  70. package/dist/docx/serializer/documentSerializer.js +1 -1
  71. package/dist/docx/serializer/paragraphSerializer.js +3 -3
  72. package/dist/docx/serializer/runSerializer.js +1 -1
  73. package/dist/docx/serializer/sectionPropertiesSerializer.js +1 -1
  74. package/dist/docx/serializer/tableSerializer.js +5 -37
  75. package/dist/docx/serializer/textFormattingSerializer.js +1 -1
  76. package/dist/docx/serializer/trackedChangeAttributes.js +1 -1
  77. package/dist/docx/server/templatePlan/apply.d.ts +15 -0
  78. package/dist/docx/server/templatePlan/apply.js +600 -0
  79. package/dist/docx/server/templatePlan/blocks.d.ts +97 -0
  80. package/dist/docx/server/templatePlan/blocks.js +355 -0
  81. package/dist/docx/server/templatePlan/builders.d.ts +72 -0
  82. package/dist/docx/server/templatePlan/builders.js +237 -0
  83. package/dist/docx/server/templatePlan/emit.d.ts +118 -0
  84. package/dist/docx/server/templatePlan/emit.js +466 -0
  85. package/dist/docx/server/templatePlan/emphasis.d.ts +62 -0
  86. package/dist/docx/server/templatePlan/emphasis.js +173 -0
  87. package/dist/docx/server/templatePlan/inspect.d.ts +22 -0
  88. package/dist/docx/server/templatePlan/inspect.js +177 -0
  89. package/dist/docx/server/templatePlan/labels.d.ts +36 -0
  90. package/dist/docx/server/templatePlan/labels.js +126 -0
  91. package/dist/docx/server/templatePlan/package.d.ts +34 -0
  92. package/dist/docx/server/templatePlan/package.js +99 -0
  93. package/dist/docx/server/templatePlan/plan.d.ts +143 -0
  94. package/dist/docx/server/templatePlan/plan.js +841 -0
  95. package/dist/docx/server/templatePlan/planShape.d.ts +9 -0
  96. package/dist/docx/server/templatePlan/planShape.js +161 -0
  97. package/dist/docx/server/templatePlan/resources.d.ts +41 -0
  98. package/dist/docx/server/templatePlan/resources.js +136 -0
  99. package/dist/docx/server/templatePlan/story.d.ts +128 -0
  100. package/dist/docx/server/templatePlan/story.js +440 -0
  101. package/dist/docx/server/templatePlan/types.d.ts +406 -0
  102. package/dist/docx/server/templatePlan/types.js +28 -0
  103. package/dist/docx/server/templatePlan/verify.d.ts +40 -0
  104. package/dist/docx/server/templatePlan/verify.js +968 -0
  105. package/dist/docx/server/templatePlan/xml.d.ts +69 -0
  106. package/dist/docx/server/templatePlan/xml.js +119 -0
  107. package/dist/docx/settingsHeaderFooterUpdate.d.ts +9 -0
  108. package/dist/docx/settingsHeaderFooterUpdate.js +45 -10
  109. package/dist/docx/storyBlockReplay.js +1 -1
  110. package/dist/docx/structuralXmlPatch.js +9 -1
  111. package/dist/docx/tableGridXml.d.ts +30 -0
  112. package/dist/docx/tableGridXml.js +54 -0
  113. package/dist/docx/tableParser.js +7 -0
  114. package/dist/docx/xmlParser.js +1 -1
  115. package/dist/index.d.ts +3 -4
  116. package/dist/index.js +2 -4
  117. package/dist/internal/paragraphFormattingSerialization.js +1 -1
  118. package/dist/internal/wholeStoryRevisionResolution.js +1 -1
  119. package/dist/managers/ContextMenuManager.js +2 -1
  120. package/dist/managers/DocumentLoaderManager.d.ts +0 -4
  121. package/dist/managers/DocumentLoaderManager.js +4 -12
  122. package/dist/managers/editorShortcuts.d.ts +1 -1
  123. package/dist/prosemirror/anchoredTextBoxes.d.ts +1 -1
  124. package/dist/prosemirror/canonicalCommands.d.ts +1 -1
  125. package/dist/prosemirror/canonicalSelectionRange.d.ts +1 -1
  126. package/dist/prosemirror/canonicalTableCommands.js +2 -2
  127. package/dist/prosemirror/commands/comments.js +3 -3
  128. package/dist/prosemirror/commands/contentControls.d.ts +1 -1
  129. package/dist/prosemirror/commands/formatPainter.d.ts +1 -1
  130. package/dist/prosemirror/commands/formatting.d.ts +1 -1
  131. package/dist/prosemirror/commands/pastePlainText.d.ts +1 -1
  132. package/dist/prosemirror/commands/sectionBreak.js +1 -1
  133. package/dist/prosemirror/commands/tableCellMergeResolution.d.ts +1 -1
  134. package/dist/prosemirror/commands/tableMergeFoldDecisions.d.ts +1 -1
  135. package/dist/prosemirror/commentRecords.d.ts +1 -1
  136. package/dist/prosemirror/contentControlRevisions.d.ts +1 -1
  137. package/dist/prosemirror/conversion/fromProseDoc.js +1 -1
  138. package/dist/prosemirror/documentStructureCounts.d.ts +24 -0
  139. package/dist/prosemirror/documentStructureCounts.js +76 -0
  140. package/dist/prosemirror/extensions/ExtensionManager.d.ts +1 -1
  141. package/dist/prosemirror/extensions/StarterKit.d.ts +1 -1
  142. package/dist/prosemirror/extensions/core/HistoryExtension.d.ts +1 -7
  143. package/dist/prosemirror/extensions/core/HistoryExtension.js +5 -13
  144. package/dist/prosemirror/extensions/core/ParagraphExtension.js +1 -1
  145. package/dist/prosemirror/extensions/core/historyCommands.d.ts +16 -0
  146. package/dist/prosemirror/extensions/core/historyCommands.js +19 -0
  147. package/dist/prosemirror/extensions/features/AutoBidiDetectionExtension.js +1 -1
  148. package/dist/prosemirror/extensions/features/ParaIdAllocatorExtension.d.ts +2 -35
  149. package/dist/prosemirror/extensions/features/ParaIdAllocatorExtension.js +4 -142
  150. package/dist/prosemirror/extensions/features/ParagraphChangeTrackerExtension.d.ts +3 -87
  151. package/dist/prosemirror/extensions/features/ParagraphChangeTrackerExtension.js +7 -162
  152. package/dist/prosemirror/extensions/features/pastedCellSections.d.ts +1 -1
  153. package/dist/prosemirror/extensions/features/pastedHeadingStyles.js +1 -1
  154. package/dist/prosemirror/extensions/marks/markUtils.d.ts +1 -1
  155. package/dist/prosemirror/extensions/nodes/TableExtension.d.ts +1 -1
  156. package/dist/prosemirror/extensions/nodes/TableExtension.js +2 -2
  157. package/dist/prosemirror/extensions/types.d.ts +1 -1
  158. package/dist/prosemirror/findReplaceSelection.d.ts +1 -1
  159. package/dist/prosemirror/hyperlinkRemoval.d.ts +1 -1
  160. package/dist/prosemirror/index.d.ts +1 -1
  161. package/dist/prosemirror/index.js +1 -1
  162. package/dist/prosemirror/insertionGaps.d.ts +1 -1
  163. package/dist/prosemirror/keptRangeBoundaries.d.ts +1 -1
  164. package/dist/prosemirror/listNumbering.d.ts +1 -1
  165. package/dist/prosemirror/lockedControls.d.ts +1 -1
  166. package/dist/prosemirror/markupViewProjection.d.ts +1 -1
  167. package/dist/prosemirror/noteReferenceOccurrences.d.ts +1 -1
  168. package/dist/prosemirror/noteReferenceReview.js +1 -1
  169. package/dist/prosemirror/numberingAttr.d.ts +1 -2
  170. package/dist/prosemirror/numberingAttr.js +1 -2
  171. package/dist/prosemirror/outlineLevelAttr.d.ts +1 -2
  172. package/dist/prosemirror/outlineLevelAttr.js +1 -2
  173. package/dist/prosemirror/paraIds.d.ts +46 -0
  174. package/dist/prosemirror/paraIds.js +152 -0
  175. package/dist/prosemirror/paragraphChangeTrackerMeta.d.ts +97 -0
  176. package/dist/prosemirror/paragraphChangeTrackerMeta.js +87 -0
  177. package/dist/prosemirror/paragraphMarkJoin.d.ts +1 -1
  178. package/dist/prosemirror/paragraphPropertyCarry.d.ts +1 -1
  179. package/dist/prosemirror/pastedCommentCopies.d.ts +1 -1
  180. package/dist/prosemirror/pastedCommentCopies.js +1 -1
  181. package/dist/prosemirror/plugins/createDocScanPlugin.d.ts +1 -1
  182. package/dist/prosemirror/plugins/documentNumbering.d.ts +1 -1
  183. package/dist/prosemirror/plugins/suggestionMode.d.ts +1 -1
  184. package/dist/prosemirror/plugins/templateDirectives.d.ts +1 -1
  185. package/dist/prosemirror/rebaseParagraphRunFormatting.d.ts +1 -1
  186. package/dist/prosemirror/rebaseParagraphRuns.d.ts +1 -1
  187. package/dist/prosemirror/rejoinRunCarriers.d.ts +1 -1
  188. package/dist/prosemirror/replacedAnnotations.d.ts +1 -1
  189. package/dist/prosemirror/replacedAnnotations.js +16 -1
  190. package/dist/prosemirror/revisionCarriers.d.ts +1 -1
  191. package/dist/prosemirror/runFormattingInlineCarriers.d.ts +1 -1
  192. package/dist/prosemirror/sectionMarkEdits.d.ts +1 -1
  193. package/dist/prosemirror/selectionBounds.d.ts +10 -0
  194. package/dist/prosemirror/selectionBounds.js +22 -0
  195. package/dist/prosemirror/storyListNumbering.d.ts +1 -1
  196. package/dist/prosemirror/tableCellPaste.d.ts +1 -1
  197. package/dist/prosemirror/tableGridMutation.d.ts +1 -1
  198. package/dist/prosemirror/textInput.d.ts +1 -1
  199. package/dist/server.d.ts +7 -5
  200. package/dist/server.js +6 -4
  201. package/dist/types/canonicalCapabilities.d.ts +8 -41
  202. package/dist/types/canonicalCapabilities.js +6 -34
  203. package/package.json +4 -6
  204. package/dist/controller/collaborationModules.d.ts +0 -3
  205. package/dist/controller/collaborationModules.js +0 -14
  206. package/dist/docx/server/materializeYjsDocx.d.ts +0 -30
  207. package/dist/docx/server/materializeYjsDocx.js +0 -96
  208. package/dist/docx/server/migrateYjsAttrSchema.d.ts +0 -53
  209. package/dist/docx/server/migrateYjsAttrSchema.js +0 -111
  210. package/dist/prosemirror/plugins/derivedFields.d.ts +0 -8
  211. package/dist/prosemirror/plugins/derivedFields.js +0 -52
  212. package/dist/prosemirror/yjsDocumentMetadata.d.ts +0 -89
  213. package/dist/prosemirror/yjsDocumentMetadata.js +0 -697
@@ -0,0 +1,968 @@
1
+ import { isNumberingReference } from "../../numberingReference.js";
2
+ import { parseSettings } from "../../settingsParser.js";
3
+ import { validateDocxConformance } from "../validateDocxConformance.js";
4
+ import { analyzeDocument } from "./blocks.js";
5
+ import { fieldBookmarkOf } from "./builders.js";
6
+ import { linkAddress, linkAddressKey, templateCharacterStyles } from "./emit.js";
7
+ import { emphasisSignature, readDirectEmphasis, signatureHighlight, signatureWithoutHighlight } from "./emphasis.js";
8
+ import { partFields, readHeaderFooterParts } from "./inspect.js";
9
+ import { styleNumbering } from "./labels.js";
10
+ import { guarded, readPartText } from "./package.js";
11
+ import { hyperlinkFieldLink, paragraphPieces, piecesContent, resolvePlan, segmentPieces } from "./plan.js";
12
+ import { objectFingerprint, objectTargets, readStoryResources, relationshipIdsOf } from "./resources.js";
13
+ import { createStoryState, endStory, readParagraph, walkBlocks } from "./story.js";
14
+ import { integerOrNull, isW, readRawPart, wAttr, wChild, wChildVal, wChildren, wName, walkElements } from "./xml.js";
15
+ import { Result } from "better-result";
16
+ // src/docx/server/templatePlan/verify.ts
17
+ /**
18
+ * Verification of an applied template plan. The output package is read back
19
+ * with the same reader that analysed the source and compared, block by block,
20
+ * against what the plan resolves to from the source alone: text, stated
21
+ * emphasis, notes, references, paragraph style and list membership, and the
22
+ * integrity of every id the body uses. A kept template block must read as
23
+ * the template has it.
24
+ *
25
+ * Limits. These are not compared, so a change to them passes:
26
+ * - run formatting other than emphasis and highlight (fonts, sizes, colours)
27
+ * and paragraph formatting other than the style and the list, on placed
28
+ * and on kept blocks alike;
29
+ * - the content of headers, footers and text boxes, beyond the fields they
30
+ * carry;
31
+ * - cell spans and merges of a table;
32
+ * - levels of the numbering part the plan neither patches nor restarts;
33
+ * - what a field shows once it updates: a cached result is compared, the
34
+ * label a list will render is only predicted.
35
+ */
36
+ const PROMPTING_FIELD_KINDS = /* @__PURE__ */ new Set(["FILLIN", "ASK"]);
37
+ const NOTE_REFERENCE_KINDS = /* @__PURE__ */ new Set(["footnoteReference", "endnoteReference"]);
38
+ const BOOKMARK_FIELD_KINDS = /* @__PURE__ */ new Set([
39
+ "REF",
40
+ "PAGEREF",
41
+ "NOTEREF"
42
+ ]);
43
+ const emptyContent = () => ({
44
+ text: "",
45
+ signatures: [],
46
+ links: [],
47
+ marks: []
48
+ });
49
+ const appendUnit = (content, { kind, text, signature, link, element, origin }, resources) => {
50
+ content.text += text;
51
+ for (let unit = 0; unit < text.length; unit += 1) {
52
+ content.signatures.push(signature);
53
+ content.links.push(link);
54
+ }
55
+ const at = content.text.length - text.length;
56
+ if (kind === "pageBreak") content.marks.push(`${at}:break:${wAttr(element, "type") ?? "page"}`);
57
+ else if (kind === "object" && element !== null) content.marks.push(`${at}:object:${objectFingerprint(element)}:${objectTargets(element, origin, resources).join(",")}`);
58
+ };
59
+ /** A paragraph break inside a note. */
60
+ const appendParagraphBreak = (content) => {
61
+ content.text += "\n";
62
+ content.signatures.push("");
63
+ content.links.push("");
64
+ };
65
+ /** What the source's pieces say the output must hold. */
66
+ const expectedContent = (pieces, resources, content = emptyContent()) => {
67
+ for (const piece of pieces) appendUnit(content, {
68
+ kind: piece.kind,
69
+ text: piece.text,
70
+ signature: piece.signature,
71
+ link: linkAddressKey(linkAddress(piece.link, resources.relationships[piece.origin])),
72
+ element: piece.atom?.element ?? null,
73
+ origin: piece.origin
74
+ }, resources);
75
+ return content;
76
+ };
77
+ /**
78
+ * What a paragraph of the output holds, read off its runs. A character style
79
+ * counts as stated emphasis unless it is the one the writer gives a link or
80
+ * a note reference mark, so a style slipped onto a run does not pass unseen.
81
+ */
82
+ const outputContent = ({ read, origin, resources, styles, content = emptyContent() }) => {
83
+ for (const atom of read.atoms) {
84
+ const link = linkAddressKey(linkAddress(atom.link, resources.relationships[origin]));
85
+ const isNoteReference = NOTE_REFERENCE_KINDS.has(atom.kind);
86
+ const styleId = wChildVal(atom.runProperties, "rStyle");
87
+ let expectedStyle = null;
88
+ if (atom.kind === "footnoteReference") expectedStyle = styles.footnoteReference;
89
+ else if (atom.kind === "endnoteReference") expectedStyle = styles.endnoteReference;
90
+ else if (link !== "") expectedStyle = styles.hyperlink;
91
+ const stated = isNoteReference ? "" : emphasisSignature(readDirectEmphasis(atom.runProperties));
92
+ appendUnit(content, {
93
+ kind: atom.kind,
94
+ text: atom.text,
95
+ signature: styleId === null || styleId === expectedStyle ? stated : `${stated};rStyle=${styleId}`,
96
+ link,
97
+ element: atom.element,
98
+ origin
99
+ }, resources);
100
+ }
101
+ return content;
102
+ };
103
+ const sameList = (left, right) => left.length === right.length && left.every((entry, index) => entry === right[index]);
104
+ /** Whether two contents read the same, emphasis aside. */
105
+ const sameReading = (left, right) => left.text === right.text && sameList(left.links, right.links) && sameList(left.marks, right.marks);
106
+ /** Maximal runs of units for which `project` gives one non-empty value. */
107
+ const countSpans = (signatures, project) => {
108
+ let count = 0;
109
+ let previous = "";
110
+ for (const signature of signatures) {
111
+ const value = project(signature);
112
+ if (value !== "" && value !== previous) count += 1;
113
+ previous = value;
114
+ }
115
+ return count;
116
+ };
117
+ const emphasisSpans = (signatures) => countSpans(signatures, signatureWithoutHighlight);
118
+ const highlightSpans = (signatures) => countSpans(signatures, (signature) => signatureHighlight(signature) ?? "");
119
+ const tally = (target, signatures) => {
120
+ target.emphasis += emphasisSpans(signatures);
121
+ target.highlight += highlightSpans(signatures);
122
+ };
123
+ const nestedParagraphs = (story, topLevelId) => story.order.filter((block) => block.topLevelId === topLevelId && block.read !== null);
124
+ const noteReferenceIds = (atoms, kind) => atoms.flatMap((atom) => {
125
+ const id = atom.kind === kind ? wAttr(atom.element, "id") : null;
126
+ return id === null ? [] : [id];
127
+ });
128
+ const sourceNoteContent = ({ note, source, origin, fields, resources }) => {
129
+ const content = emptyContent();
130
+ for (const [index, read] of note.paragraphs.entries()) {
131
+ if (index > 0) appendParagraphBreak(content);
132
+ expectedContent(paragraphPieces({
133
+ read,
134
+ context: source,
135
+ origin,
136
+ fields
137
+ }), resources, content);
138
+ }
139
+ return content;
140
+ };
141
+ const outputNoteContent = ({ note, ...options }) => {
142
+ const content = emptyContent();
143
+ for (const [index, read] of note.paragraphs.entries()) {
144
+ if (index > 0) appendParagraphBreak(content);
145
+ outputContent({
146
+ ...options,
147
+ read,
148
+ content
149
+ });
150
+ }
151
+ return content;
152
+ };
153
+ const countByKind = (part, fields) => {
154
+ const counts = /* @__PURE__ */ new Map();
155
+ for (const { kind } of fields) counts.set(kind, (counts.get(kind) ?? 0) + 1);
156
+ return [...counts].map(([kind, count]) => ({
157
+ part,
158
+ kind,
159
+ count
160
+ }));
161
+ };
162
+ const partText = (part) => {
163
+ const state = createStoryState();
164
+ const texts = [];
165
+ const readUnder = (container) => {
166
+ walkBlocks(container, {
167
+ paragraph: (paragraph) => {
168
+ texts.push(readParagraph(paragraph, state).text);
169
+ },
170
+ tableStart: () => {},
171
+ cellStart: () => {},
172
+ tableEnd: () => {},
173
+ unread: () => {},
174
+ tracked: () => {}
175
+ });
176
+ };
177
+ if (isW(part.root, "footnotes") || isW(part.root, "endnotes")) {
178
+ for (const note of part.root.elements ?? []) if (note.type === "element") {
179
+ readUnder(note);
180
+ endStory(state);
181
+ }
182
+ } else readUnder(part.root);
183
+ return texts.join("\n");
184
+ };
185
+ const occurrences = (text, needle) => {
186
+ if (needle === "") return 0;
187
+ let count = 0;
188
+ let from = text.indexOf(needle);
189
+ while (from !== -1) {
190
+ count += 1;
191
+ from = text.indexOf(needle, from + needle.length);
192
+ }
193
+ return count;
194
+ };
195
+ const CONFORMANCE_RANK = {
196
+ conformant: 2,
197
+ indeterminate: 1,
198
+ invalid: 0
199
+ };
200
+ const NUMBER_SWITCH = /\\[nrw]\b/u;
201
+ const statedProperties = (paragraph) => {
202
+ const properties = wChild(paragraph, "pPr");
203
+ const numbering = wChild(properties, "numPr");
204
+ return {
205
+ styleId: wChildVal(properties, "pStyle"),
206
+ numId: integerOrNull(wChildVal(numbering, "numId")),
207
+ ilvl: integerOrNull(wChildVal(numbering, "ilvl"))
208
+ };
209
+ };
210
+ /** Whether a bookmark of `read` holds all of the paragraph's content. */
211
+ const bookmarkEncloses = (read, name) => {
212
+ const start = read?.bookmarks.find((bookmark) => bookmark.name === name);
213
+ const end = start === void 0 ? void 0 : read?.bookmarkEnds.find(({ id }) => id === start.id);
214
+ return read !== null && start !== void 0 && end !== void 0 && start.atomIndex === 0 && end.atomIndex === read.atoms.length;
215
+ };
216
+ const segmentLength = (segment) => piecesContent(segment.kind === "piece" ? [segment.piece] : segment.pieces).text.length;
217
+ /** The rows and cells of a table, without the ids of what they hold. */
218
+ const tableShape = (block) => JSON.stringify((block.block.cells ?? []).map(({ row, col, blockIds }) => [
219
+ row,
220
+ col,
221
+ blockIds.length
222
+ ]));
223
+ /** Read `output` back and report how it compares with the resolved plan. */
224
+ const reportTemplatePlanOutput = async ({ source, template, output, plan, resolved, options }) => {
225
+ const analyzedOutput = await analyzeDocument(output);
226
+ if (Result.isError(analyzedOutput)) return analyzedOutput;
227
+ const out = analyzedOutput.value;
228
+ const issues = [];
229
+ const warnings = [...source.manifest.warnings.map((warning) => `Source: ${warning}`), ...out.story.warnings];
230
+ const sourceResourcesRead = await readStoryResources(source);
231
+ if (Result.isError(sourceResourcesRead)) return sourceResourcesRead;
232
+ const outputResourcesRead = await readStoryResources(out);
233
+ if (Result.isError(outputResourcesRead)) return outputResourcesRead;
234
+ const templateResourcesRead = await readStoryResources(template);
235
+ if (Result.isError(templateResourcesRead)) return templateResourcesRead;
236
+ const sourceResources = sourceResourcesRead.value;
237
+ const outputResources = outputResourcesRead.value;
238
+ const templateResources = templateResourcesRead.value;
239
+ const characterStyles = templateCharacterStyles(template);
240
+ const slotBlocks = /* @__PURE__ */ new Map();
241
+ for (const item of resolved.items) if (item.kind === "slot") slotBlocks.set(item.paragraph, item.templateBlock);
242
+ for (const slot of resolved.nestedSlots) slotBlocks.set(slot.paragraph, slot.templateBlock);
243
+ const slottedTemplateBlocks = new Set(slotBlocks.values());
244
+ const plannedProperties = (paragraph) => {
245
+ const slot = slotBlocks.get(paragraph);
246
+ if (slot !== void 0) return statedProperties(slot.element);
247
+ const { styleId, numbering } = paragraph;
248
+ if (numbering.kind === "direct") return {
249
+ styleId,
250
+ numId: numbering.numId,
251
+ ilvl: numbering.ilvl
252
+ };
253
+ return {
254
+ styleId,
255
+ numId: numbering.kind === "none" && styleNumbering(styleId ?? template.defaultStyleId, template.styles, template.numbering)?.kind === "reference" ? 0 : null,
256
+ ilvl: null
257
+ };
258
+ };
259
+ const checkProperties = (planned, stated, blockId) => {
260
+ if (stated.styleId !== planned.styleId) issues.push({
261
+ code: "style-mismatch",
262
+ message: `Block ${blockId} has the style ${stated.styleId ?? "(none)"}, the plan gives it ${planned.styleId ?? "(none)"}.`,
263
+ blockId
264
+ });
265
+ if (stated.numId !== planned.numId || stated.ilvl !== planned.ilvl) issues.push({
266
+ code: "numbering-mismatch",
267
+ message: `Block ${blockId} is not in the list, or at the level, the plan gives it.`,
268
+ blockId
269
+ });
270
+ };
271
+ const outputOf = /* @__PURE__ */ new Map();
272
+ const templateOutputIds = /* @__PURE__ */ new Set();
273
+ const missing = (message) => {
274
+ issues.push({
275
+ code: "block-missing",
276
+ message
277
+ });
278
+ };
279
+ const assign = (paragraph, block) => {
280
+ if (paragraph === void 0) return;
281
+ if (block === void 0 || block.read === null) {
282
+ missing(`Source block ${paragraph.parts.at(0)?.block.block.id ?? "?"} has no paragraph in the output.`);
283
+ return;
284
+ }
285
+ outputOf.set(paragraph, block);
286
+ };
287
+ const tableOutputs = /* @__PURE__ */ new Map();
288
+ const mapTable = (cells, sourceTable, outputTable) => {
289
+ const tableId = sourceTable.block.id;
290
+ tableOutputs.set(tableId, outputTable.block.id);
291
+ const sourceCells = sourceTable.block.cells ?? [];
292
+ const outputCells = outputTable.block.cells ?? [];
293
+ if (sourceCells.length !== outputCells.length || sourceCells.some(({ row, col }, index) => outputCells[index]?.row !== row || outputCells[index]?.col !== col)) {
294
+ missing(`Source table ${tableId} does not keep its rows and cells.`);
295
+ return;
296
+ }
297
+ for (const [index, sourceCell] of sourceCells.entries()) {
298
+ const sourceBlocks = sourceCell.blockIds.map((id) => source.story.byId.get(id));
299
+ const outputBlocks = (outputCells[index]?.blockIds ?? []).map((id) => out.story.byId.get(id));
300
+ const last = sourceBlocks.at(-1);
301
+ const closing = last === void 0 || last.read === null ? 1 : 0;
302
+ const added = closing === 1 ? outputBlocks.at(-1) : void 0;
303
+ if (outputBlocks.length !== sourceBlocks.length + closing || closing === 1 && (added?.read === void 0 || added.read === null || added.read.atoms.length > 0)) {
304
+ missing(`A cell of source table ${tableId} does not keep its blocks.`);
305
+ continue;
306
+ }
307
+ for (const [position, sourceBlock] of sourceBlocks.entries()) {
308
+ const outputBlock = outputBlocks[position];
309
+ if (sourceBlock === void 0) continue;
310
+ if (sourceBlock.read !== null) assign(cells.get(sourceBlock.element), outputBlock);
311
+ else if (outputBlock === void 0 || outputBlock.read !== null) missing(`Source table ${sourceBlock.block.id} is not in the output.`);
312
+ else mapTable(cells, sourceBlock, outputBlock);
313
+ }
314
+ }
315
+ };
316
+ const outputTopLevel = out.story.topLevel;
317
+ for (const [position, item] of resolved.items.entries()) {
318
+ const block = outputTopLevel[position];
319
+ switch (item.kind) {
320
+ case "template": {
321
+ if (block === void 0 || block.block.kind !== item.block.block.kind) {
322
+ missing(`Template block ${item.block.block.id} is not where the plan puts it.`);
323
+ break;
324
+ }
325
+ templateOutputIds.add(block.block.id);
326
+ const templateNested = nestedParagraphs(template.story, item.block.block.id);
327
+ const outputNested = nestedParagraphs(out.story, block.block.id);
328
+ if (!(templateNested.length === outputNested.length && tableShape(item.block) === tableShape(block) && templateNested.every((templateParagraph, index) => {
329
+ const outputParagraph = outputNested[index];
330
+ if (outputParagraph === void 0 || templateParagraph.read === null || outputParagraph.read === null) return false;
331
+ if (slottedTemplateBlocks.has(templateParagraph)) return true;
332
+ const before = statedProperties(templateParagraph.element);
333
+ const after = statedProperties(outputParagraph.element);
334
+ const was = outputContent({
335
+ read: templateParagraph.read,
336
+ origin: "document",
337
+ resources: templateResources,
338
+ styles: characterStyles
339
+ });
340
+ const is = outputContent({
341
+ read: outputParagraph.read,
342
+ origin: "document",
343
+ resources: outputResources,
344
+ styles: characterStyles
345
+ });
346
+ return before.styleId === after.styleId && before.numId === after.numId && before.ilvl === after.ilvl && sameReading(was, is) && sameList(was.signatures, is.signatures);
347
+ }))) issues.push({
348
+ code: "template-mismatch",
349
+ message: `Template block ${item.block.block.id} does not read as the template has it.`,
350
+ blockId: item.block.block.id
351
+ });
352
+ for (const slot of resolved.nestedSlots) {
353
+ if (slot.templateBlock.topLevelId !== item.block.block.id) continue;
354
+ assign(slot.paragraph, outputNested[templateNested.indexOf(slot.templateBlock)]);
355
+ }
356
+ break;
357
+ }
358
+ case "paragraph":
359
+ assign(item.paragraph, block);
360
+ break;
361
+ case "slot":
362
+ assign(item.paragraph, block);
363
+ break;
364
+ case "table": {
365
+ if (block === void 0 || block.read !== null) {
366
+ missing(`Source table ${item.block.block.id} is not in the output.`);
367
+ break;
368
+ }
369
+ mapTable(item.cells, item.block, block);
370
+ const tableStyle = wChildVal(wChild(block.element, "tblPr"), "tblStyle");
371
+ if (tableStyle !== item.styleId) issues.push({
372
+ code: "style-mismatch",
373
+ message: `Table ${item.block.block.id} has the style ${tableStyle ?? "(none)"}, the plan gives it ${item.styleId ?? "(none)"}.`,
374
+ blockId: item.block.block.id
375
+ });
376
+ break;
377
+ }
378
+ }
379
+ }
380
+ if (outputTopLevel.length !== resolved.items.length) missing(`The plan places ${resolved.items.length} block(s), the output holds ${outputTopLevel.length}.`);
381
+ const comparisons = /* @__PURE__ */ new Map();
382
+ const spans = {
383
+ source: {
384
+ emphasis: 0,
385
+ highlight: 0
386
+ },
387
+ expected: {
388
+ emphasis: 0,
389
+ highlight: 0
390
+ },
391
+ output: {
392
+ emphasis: 0,
393
+ highlight: 0
394
+ }
395
+ };
396
+ const resolvedParagraphs = [...new Set(resolved.byBlockId.values())];
397
+ for (const paragraph of resolvedParagraphs) {
398
+ tally(spans.expected, paragraph.signatures);
399
+ const block = outputOf.get(paragraph);
400
+ const blockId = paragraph.parts.at(0)?.block.block.id ?? "";
401
+ if (block === void 0 || block.read === null) {
402
+ comparisons.set(paragraph, {
403
+ text: "mismatch",
404
+ emphasis: "mismatch",
405
+ output: null
406
+ });
407
+ continue;
408
+ }
409
+ const expected = expectedContent(segmentPieces(paragraph.segments), sourceResources);
410
+ const actual = outputContent({
411
+ read: block.read,
412
+ origin: "document",
413
+ resources: outputResources,
414
+ styles: characterStyles
415
+ });
416
+ tally(spans.output, actual.signatures);
417
+ checkProperties(plannedProperties(paragraph), statedProperties(block.element), blockId);
418
+ const text = sameReading(actual, expected) ? "identical" : "mismatch";
419
+ const emphasis = sameList(actual.signatures, expected.signatures) ? "identical" : "mismatch";
420
+ if (block.read.openFieldsAtStart > 0 || block.read.atoms.some(({ fields }) => fields.some((index) => out.story.state.fields[index]?.paragraphOrdinal !== block.read?.ordinal))) issues.push({
421
+ code: "field-unbalanced",
422
+ message: `Block ${blockId} sits inside a field of the template.`,
423
+ blockId
424
+ });
425
+ if (text === "mismatch") issues.push({
426
+ code: "text-mismatch",
427
+ message: `Block ${blockId} does not read back as its source text, links, breaks and objects.`,
428
+ blockId
429
+ });
430
+ if (emphasis === "mismatch" && text === "identical") issues.push({
431
+ code: "emphasis-mismatch",
432
+ message: `Block ${blockId} lost or gained emphasis or highlight.`,
433
+ blockId
434
+ });
435
+ comparisons.set(paragraph, {
436
+ text,
437
+ emphasis,
438
+ output: block
439
+ });
440
+ }
441
+ for (const block of source.story.order) if (block.read !== null) tally(spans.source, piecesContent(paragraphPieces({
442
+ read: block.read,
443
+ context: source,
444
+ origin: "document",
445
+ fields: source.story.state.fields
446
+ })).signatures);
447
+ const noteCounts = (kind, sourceNotes, outputNotes) => {
448
+ const origin = kind === "footnoteReference" ? "footnotes" : "endnotes";
449
+ const counts = {
450
+ source: sourceNotes.notes.length,
451
+ expected: 0,
452
+ output: 0,
453
+ identical: 0,
454
+ mismatch: 0
455
+ };
456
+ for (const note of sourceNotes.notes) tally(spans.source, sourceNoteContent({
457
+ note,
458
+ source,
459
+ origin,
460
+ fields: sourceNotes.state.fields,
461
+ resources: sourceResources
462
+ }).signatures);
463
+ const outputIdOf = /* @__PURE__ */ new Map();
464
+ const seenOutput = /* @__PURE__ */ new Set();
465
+ for (const paragraph of resolvedParagraphs) {
466
+ const blockId = paragraph.parts.at(0)?.block.block.id ?? "";
467
+ const expectedIds = noteReferenceIds(segmentPieces(paragraph.segments).map(({ kind: pieceKind, atom }) => ({
468
+ kind: pieceKind,
469
+ element: atom?.element ?? null
470
+ })), kind);
471
+ const outputIds = noteReferenceIds(outputOf.get(paragraph)?.read?.atoms ?? [], kind);
472
+ for (const [index, sourceId] of expectedIds.entries()) {
473
+ const outputId = outputIds[index];
474
+ if (outputIdOf.has(sourceId)) {
475
+ if (outputIdOf.get(sourceId) !== outputId) issues.push({
476
+ code: "note-mismatch",
477
+ message: `Two references to note ${sourceId} of the source lead to different notes.`,
478
+ blockId
479
+ });
480
+ continue;
481
+ }
482
+ outputIdOf.set(sourceId, outputId);
483
+ counts.expected += 1;
484
+ const sourceNote = sourceNotes.byId.get(sourceId);
485
+ const outputNote = outputId === void 0 ? void 0 : outputNotes.byId.get(outputId);
486
+ const reused = outputId !== void 0 && seenOutput.has(outputId);
487
+ if (outputId !== void 0 && !reused) {
488
+ seenOutput.add(outputId);
489
+ counts.output += 1;
490
+ }
491
+ const expected = sourceNote === void 0 ? null : sourceNoteContent({
492
+ note: sourceNote,
493
+ source,
494
+ origin,
495
+ fields: sourceNotes.state.fields,
496
+ resources: sourceResources
497
+ });
498
+ const actual = outputNote === void 0 ? null : outputNoteContent({
499
+ note: outputNote,
500
+ origin,
501
+ resources: outputResources,
502
+ styles: characterStyles
503
+ });
504
+ if (expected !== null) tally(spans.expected, expected.signatures);
505
+ if (actual !== null) tally(spans.output, actual.signatures);
506
+ if (!reused && expected !== null && actual !== null && outputNote?.hasOtherBlocks === false && sameReading(actual, expected) && sameList(actual.signatures, expected.signatures)) {
507
+ counts.identical += 1;
508
+ continue;
509
+ }
510
+ counts.mismatch += 1;
511
+ issues.push({
512
+ code: "note-mismatch",
513
+ message: `Note ${sourceId} of the source does not read back identical.`,
514
+ blockId
515
+ });
516
+ }
517
+ }
518
+ return counts;
519
+ };
520
+ const footnotes = noteCounts("footnoteReference", source.footnotes, out.footnotes);
521
+ const endnotes = noteCounts("endnoteReference", source.endnotes, out.endnotes);
522
+ const outputBookmarks = /* @__PURE__ */ new Map();
523
+ for (const block of out.story.order) for (const { name } of block.read?.bookmarks ?? []) outputBookmarks.set(name, block);
524
+ const referenceResults = [];
525
+ const referencesOf = /* @__PURE__ */ new Map();
526
+ for (const entry of resolved.references) referencesOf.set(entry.paragraph, [...referencesOf.get(entry.paragraph) ?? [], entry]);
527
+ for (const [paragraph, entries] of referencesOf) {
528
+ const block = outputOf.get(paragraph);
529
+ const fields = (block?.read?.fieldIndices ?? []).map((index) => out.story.state.fields[index]).filter((field) => field?.kind === "REF");
530
+ let offset = 0;
531
+ const ordered = paragraph.segments.flatMap((segment) => {
532
+ const at = offset;
533
+ offset += segmentLength(segment);
534
+ const entry = segment.kind === "reference" ? entries.find(({ reference }) => reference === segment.reference) : void 0;
535
+ return entry === void 0 ? [] : [{
536
+ entry,
537
+ at
538
+ }];
539
+ });
540
+ for (const [index, { entry, at }] of ordered.entries()) {
541
+ const field = fields[index];
542
+ const bookmark = resolved.bookmarks.get(entry.target)?.name ?? "";
543
+ const targetBlock = outputOf.get(entry.target);
544
+ const hasNumberSwitch = NUMBER_SWITCH.test(entry.reference.instruction);
545
+ const usesNumber = /\\n\b/u.test(entry.reference.instruction);
546
+ let predictedText = null;
547
+ if (targetBlock !== void 0) {
548
+ if (!hasNumberSwitch) predictedText = targetBlock.block.text;
549
+ else if (usesNumber) predictedText = /\\t\b/u.test(entry.reference.instruction) ? targetBlock.label?.numberOnly ?? null : targetBlock.label?.paragraphNumber ?? null;
550
+ }
551
+ let status = "ok";
552
+ if (field === void 0 || fieldBookmarkOf(field.instruction) !== bookmark || field.instruction.trim() !== entry.instruction.trim() || comparisons.get(paragraph)?.text === "identical" && (field.paragraphOrdinal !== block?.read?.ordinal || field.resultStart !== at)) status = "missing-field";
553
+ else if (targetBlock === void 0 || outputBookmarks.get(bookmark) !== targetBlock || !bookmarkEncloses(targetBlock.read, bookmark)) status = "missing-bookmark";
554
+ else if (field.result !== entry.reference.expectedText) status = "cache-mismatch";
555
+ if (status !== "ok") issues.push({
556
+ code: "reference-broken",
557
+ message: `A reference in block ${entry.reference.blockId} to ${entry.reference.targetBlockId} is ${status}.`,
558
+ blockId: entry.reference.blockId
559
+ });
560
+ referenceResults.push({
561
+ blockId: entry.reference.blockId,
562
+ targetBlockId: entry.reference.targetBlockId,
563
+ bookmark,
564
+ instruction: entry.reference.instruction,
565
+ expectedText: entry.reference.expectedText,
566
+ cachedText: field?.result ?? null,
567
+ replacedText: entry.replacedText,
568
+ predictedText,
569
+ status
570
+ });
571
+ }
572
+ }
573
+ const outputNumbering = out.numberingPath === null || out.numberingXml === null ? null : readRawPart(out.numberingPath, out.numberingXml);
574
+ const numberingMismatch = (message) => {
575
+ issues.push({
576
+ code: "numbering-mismatch",
577
+ message,
578
+ ...out.numberingPath === null ? {} : { part: out.numberingPath }
579
+ });
580
+ };
581
+ for (const mint of resolved.mints) {
582
+ const instance = wChildren(outputNumbering?.root, "num").find((element) => integerOrNull(wAttr(element, "numId")) === mint.numId);
583
+ if (instance === void 0 || integerOrNull(wChildVal(instance, "abstractNumId")) !== mint.abstractNumId) {
584
+ numberingMismatch(`List ${mint.numId} is not an instance of list definition ${mint.abstractNumId}.`);
585
+ continue;
586
+ }
587
+ for (const [level, start] of mint.starts) {
588
+ const override = wChildren(instance, "lvlOverride").find((element) => integerOrNull(wAttr(element, "ilvl")) === level);
589
+ if (integerOrNull(wChildVal(override, "startOverride")) !== start) numberingMismatch(`Level ${level} of list ${mint.numId} does not start at ${start}.`);
590
+ }
591
+ }
592
+ for (const patch of plan.numberingPatches ?? []) {
593
+ const definition = wChildren(outputNumbering?.root, "abstractNum").find((element) => integerOrNull(wAttr(element, "abstractNumId")) === patch.abstractNumId);
594
+ const level = wChildren(definition, "lvl").find((element) => integerOrNull(wAttr(element, "ilvl")) === patch.ilvl);
595
+ const planned = {
596
+ start: patch.start === void 0 ? void 0 : String(patch.start),
597
+ numFmt: patch.numFmt,
598
+ suff: patch.suff,
599
+ lvlText: patch.lvlText
600
+ };
601
+ for (const [name, value] of Object.entries(planned)) if (value !== void 0 && wChildVal(level, name) !== value) numberingMismatch(`Level ${patch.ilvl} of list definition ${patch.abstractNumId} does not carry the planned ${name}.`);
602
+ }
603
+ const bookmarkNames = /* @__PURE__ */ new Map();
604
+ const bump = (map, key) => {
605
+ map.set(key, (map.get(key) ?? 0) + 1);
606
+ };
607
+ const checkedParts = [{
608
+ origin: "document",
609
+ part: out.document
610
+ }];
611
+ for (const [origin, notes] of [["footnotes", out.footnotes], ["endnotes", out.endnotes]]) if (notes.part !== null) checkedParts.push({
612
+ origin,
613
+ part: notes.part
614
+ });
615
+ for (const { origin, part } of checkedParts) {
616
+ const bookmarkStarts = /* @__PURE__ */ new Map();
617
+ const bookmarkEnds = /* @__PURE__ */ new Map();
618
+ const endsBeforeStart = /* @__PURE__ */ new Set();
619
+ const dangling = {
620
+ relationships: /* @__PURE__ */ new Set(),
621
+ styles: /* @__PURE__ */ new Set(),
622
+ numbering: /* @__PURE__ */ new Set()
623
+ };
624
+ walkElements(part.root, (element) => {
625
+ const name = wName(element);
626
+ if (name === "bookmarkStart") {
627
+ bump(bookmarkStarts, wAttr(element, "id") ?? "");
628
+ bump(bookmarkNames, wAttr(element, "name") ?? "");
629
+ } else if (name === "bookmarkEnd") {
630
+ const id = wAttr(element, "id") ?? "";
631
+ if (!bookmarkStarts.has(id)) endsBeforeStart.add(id);
632
+ bump(bookmarkEnds, id);
633
+ } else if (name === "pStyle" || name === "rStyle" || name === "tblStyle") {
634
+ const styleId = wAttr(element, "val");
635
+ if (styleId !== null && !out.styles.has(styleId)) dangling.styles.add(styleId);
636
+ } else if (name === "numId") {
637
+ const numId = integerOrNull(wAttr(element, "val")) ?? void 0;
638
+ if (isNumberingReference(numId) && out.numbering?.hasNumbering(numId) !== true) dangling.numbering.add(String(numId));
639
+ }
640
+ });
641
+ for (const id of relationshipIdsOf(part.root)) {
642
+ const relationship = outputResources.relationships[origin].get(id);
643
+ if (relationship === void 0 || relationship.targetMode !== "External" && !out.pkg.paths.has(outputResources.resolveTarget(origin, relationship.target))) dangling.relationships.add(id);
644
+ }
645
+ for (const [id, count] of bookmarkStarts) if (count !== 1 || bookmarkEnds.get(id) !== 1) issues.push({
646
+ code: "bookmark-dangling",
647
+ message: `Bookmark id ${id} is not one start and one end.`,
648
+ part: part.path
649
+ });
650
+ for (const id of endsBeforeStart) issues.push({
651
+ code: "bookmark-dangling",
652
+ message: `Bookmark ${id} ends before it starts.`,
653
+ part: part.path
654
+ });
655
+ for (const id of dangling.relationships) issues.push({
656
+ code: "relationship-dangling",
657
+ message: `Relationship ${id} of ${part.path} leads nowhere.`,
658
+ part: part.path
659
+ });
660
+ for (const styleId of dangling.styles) issues.push({
661
+ code: "style-dangling",
662
+ message: `Style ${styleId} is used and not defined.`,
663
+ part: part.path
664
+ });
665
+ for (const numId of dangling.numbering) issues.push({
666
+ code: "numbering-dangling",
667
+ message: `List ${numId} is used and not defined.`,
668
+ part: part.path
669
+ });
670
+ }
671
+ for (const [name, count] of bookmarkNames) if (count > 1) issues.push({
672
+ code: "bookmark-dangling",
673
+ message: `Bookmark name ${name} is used ${count} times.`,
674
+ part: out.pkg.documentPath
675
+ });
676
+ for (const block of out.story.order) {
677
+ const atoms = block.read?.atoms ?? [];
678
+ for (const [kind, notes] of [["footnoteReference", out.footnotes], ["endnoteReference", out.endnotes]]) for (const id of noteReferenceIds(atoms, kind)) if (!notes.byId.has(id)) issues.push({
679
+ code: "note-dangling",
680
+ message: `Block ${block.block.id} refers to the missing note ${id}.`,
681
+ blockId: block.block.id
682
+ });
683
+ }
684
+ for (const { path, state } of [
685
+ {
686
+ path: out.pkg.documentPath,
687
+ state: out.story.state
688
+ },
689
+ {
690
+ path: out.footnotes.path,
691
+ state: out.footnotes.state
692
+ },
693
+ {
694
+ path: out.endnotes.path,
695
+ state: out.endnotes.state
696
+ }
697
+ ]) if (state.open.length > 0 || state.strayFieldEnds > 0) issues.push({
698
+ code: "field-unbalanced",
699
+ message: "Complex field marks do not pair up: a kept template field was split.",
700
+ ...path === null ? {} : { part: path }
701
+ });
702
+ const outputParts = [];
703
+ const outputHeadersAndFooters = await readHeaderFooterParts(out);
704
+ if (Result.isError(outputHeadersAndFooters)) return outputHeadersAndFooters;
705
+ for (const part of outputHeadersAndFooters.value) outputParts.push({
706
+ part: part.path,
707
+ fields: partFields(part),
708
+ text: partText(part)
709
+ });
710
+ for (const notes of [out.footnotes, out.endnotes]) if (notes.part !== null) outputParts.push({
711
+ part: notes.part.path,
712
+ fields: notes.state.fields,
713
+ text: partText(notes.part)
714
+ });
715
+ const writtenOrdinals = new Set([...outputOf.values()].map((block) => block.read?.ordinal ?? -1));
716
+ const templateFields = out.story.state.fields.filter((field) => !writtenOrdinals.has(field.paragraphOrdinal) && templateOutputIds.has(out.story.paragraphs[field.paragraphOrdinal]?.topLevelId ?? ""));
717
+ const leftoverFields = [...countByKind(out.pkg.documentPath, templateFields), ...outputParts.flatMap(({ part, fields }) => countByKind(part, fields))];
718
+ const settingsXml = await readPartText(out.pkg, out.pkg.partPath("settings"));
719
+ if (Result.isError(settingsXml)) return settingsXml;
720
+ const updatesOnOpen = parseSettings(settingsXml.value).updateFields === true;
721
+ const allFields = [...out.story.state.fields, ...outputParts.flatMap(({ fields }) => fields)];
722
+ let nestedUnfrozen = 0;
723
+ for (const field of allFields) if (updatesOnOpen && PROMPTING_FIELD_KINDS.has(field.kind)) issues.push({
724
+ code: "prompting-field-left",
725
+ message: `A ${field.kind} field would prompt when fields update on open.`
726
+ });
727
+ else if (resolved.freezeKinds.has(field.kind) && field.nestedInCode) nestedUnfrozen += 1;
728
+ else if (resolved.freezeKinds.has(field.kind)) issues.push({
729
+ code: "field-not-frozen",
730
+ message: `A ${field.kind} field the plan freezes is still live.`
731
+ });
732
+ if (nestedUnfrozen > 0) warnings.push(`${nestedUnfrozen} field(s) of a frozen kind sit inside another field's code and stay live.`);
733
+ const updateOnOpen = plan.fields?.updateOnOpen;
734
+ if (updateOnOpen !== void 0 && updateOnOpen !== updatesOnOpen) issues.push({
735
+ code: "update-fields-mismatch",
736
+ message: "The update-on-open setting is not what the plan asks for."
737
+ });
738
+ for (const field of templateFields) {
739
+ const bookmark = BOOKMARK_FIELD_KINDS.has(field.kind) ? fieldBookmarkOf(field.instruction) : null;
740
+ if (bookmark !== null && !bookmarkNames.has(bookmark)) warnings.push(`A kept ${field.kind} field points at the bookmark ${bookmark}, which the output does not hold; its cached text is stale until fields update.`);
741
+ }
742
+ const keptToc = templateFields.filter(({ kind }) => kind === "TOC").length;
743
+ if (keptToc > 0) warnings.push(`${keptToc} table of contents field(s) keep the template's cached entries until fields update.`);
744
+ const keptTemplateIds = new Set(resolved.keptTemplateBlocks.map(({ block }) => block.id));
745
+ const frozenFields = [];
746
+ if (resolved.freezeKinds.size > 0) {
747
+ const slotOrdinals = new Set(resolved.nestedSlots.map(({ templateBlock }) => templateBlock.read?.ordinal ?? -1));
748
+ const frozenIn = (fields) => fields.filter(({ kind, nestedInCode }) => resolved.freezeKinds.has(kind) && !nestedInCode);
749
+ frozenFields.push(...countByKind(template.pkg.documentPath, frozenIn(template.story.state.fields).filter((field) => !slotOrdinals.has(field.paragraphOrdinal) && keptTemplateIds.has(template.story.paragraphs[field.paragraphOrdinal]?.topLevelId ?? ""))));
750
+ for (const notes of [template.footnotes, template.endnotes]) if (notes.path !== null) frozenFields.push(...countByKind(notes.path, frozenIn(notes.state.fields)));
751
+ const templateHeadersAndFooters = await readHeaderFooterParts(template);
752
+ if (Result.isError(templateHeadersAndFooters)) return templateHeadersAndFooters;
753
+ for (const part of templateHeadersAndFooters.value) frozenFields.push(...countByKind(part.path, frozenIn(partFields(part))));
754
+ }
755
+ const filler = [];
756
+ const documentText = out.story.order.flatMap(({ read }) => read === null ? [] : [read.text]).join("\n");
757
+ for (const text of options?.fillerStrings ?? []) for (const { part, text: haystack } of [{
758
+ part: out.pkg.documentPath,
759
+ text: documentText
760
+ }, ...outputParts]) {
761
+ const count = occurrences(haystack, text);
762
+ if (count > 0) filler.push({
763
+ text,
764
+ part,
765
+ count
766
+ });
767
+ }
768
+ if (filler.length > 0) warnings.push(`${filler.length} filler string(s) of the template are still in the output.`);
769
+ const blocks = [];
770
+ const counts = {
771
+ sourceBlocks: source.story.order.length,
772
+ placed: 0,
773
+ merged: 0,
774
+ omitted: 0,
775
+ templateBlocksKept: resolved.keptTemplateBlocks.length,
776
+ textIdentical: 0,
777
+ textMismatch: 0,
778
+ emphasisMismatch: 0,
779
+ labelChanged: 0,
780
+ labelLost: 0
781
+ };
782
+ const tables = /* @__PURE__ */ new Map();
783
+ for (const block of source.story.order) {
784
+ const { id } = block.block;
785
+ const omitReason = resolved.omitted.get(block.topLevelId) ?? resolved.omitted.get(id);
786
+ if (omitReason !== void 0) {
787
+ counts.omitted += 1;
788
+ blocks.push({
789
+ blockId: id,
790
+ outputBlockId: null,
791
+ disposition: "omitted",
792
+ text: "omitted",
793
+ emphasis: "omitted",
794
+ sourceLabel: block.block.label,
795
+ outputLabel: null,
796
+ omitReason
797
+ });
798
+ continue;
799
+ }
800
+ if (block.read === null) {
801
+ const result = {
802
+ blockId: id,
803
+ outputBlockId: tableOutputs.get(id) ?? null,
804
+ disposition: block.parentId === null ? "placed" : "nested",
805
+ text: "identical",
806
+ emphasis: "identical",
807
+ sourceLabel: null,
808
+ outputLabel: null
809
+ };
810
+ counts.placed += 1;
811
+ tables.set(id, result);
812
+ blocks.push(result);
813
+ continue;
814
+ }
815
+ const paragraph = resolved.byBlockId.get(id);
816
+ const comparison = paragraph === void 0 ? void 0 : comparisons.get(paragraph);
817
+ const partIndex = paragraph?.parts.findIndex((part) => part.block === block) ?? -1;
818
+ const part = paragraph?.parts[partIndex];
819
+ const leads = partIndex === 0;
820
+ const strippedLabel = part?.strippedPrefix.trim() ?? "";
821
+ const sourceLabel = block.block.label ?? (strippedLabel === "" ? null : strippedLabel);
822
+ const outputLabel = leads ? comparison?.output?.block.label ?? null : null;
823
+ let disposition = "placed";
824
+ if (!leads) disposition = "merged";
825
+ else if (paragraph?.placement === "slot") disposition = "slot";
826
+ else if (paragraph?.placement === "nested") disposition = "nested";
827
+ const text = comparison?.text ?? "mismatch";
828
+ const emphasis = comparison?.emphasis ?? "mismatch";
829
+ if (disposition === "merged") counts.merged += 1;
830
+ else counts.placed += 1;
831
+ if (text === "identical") counts.textIdentical += 1;
832
+ else counts.textMismatch += 1;
833
+ if (emphasis === "mismatch") counts.emphasisMismatch += 1;
834
+ if (sourceLabel !== null && outputLabel === null) counts.labelLost += 1;
835
+ else if (sourceLabel !== null && outputLabel !== null && sourceLabel.trim() !== outputLabel.trim()) counts.labelChanged += 1;
836
+ let tableId = block.parentId;
837
+ while (tableId !== null) {
838
+ const table = tables.get(tableId);
839
+ if (table !== void 0 && text === "mismatch") table.text = "mismatch";
840
+ if (table !== void 0 && emphasis === "mismatch") table.emphasis = "mismatch";
841
+ tableId = source.story.byId.get(tableId)?.parentId ?? null;
842
+ }
843
+ blocks.push({
844
+ blockId: id,
845
+ outputBlockId: comparison?.output?.block.id ?? null,
846
+ disposition,
847
+ text,
848
+ emphasis,
849
+ ...part === void 0 || part.strippedPrefix === "" ? {} : { strippedPrefix: part.strippedPrefix },
850
+ sourceLabel,
851
+ outputLabel
852
+ });
853
+ }
854
+ if (counts.labelLost > 0) warnings.push(`${counts.labelLost} block(s) showed a number or label in the source and render none.`);
855
+ if (counts.labelChanged > 0) warnings.push(`${counts.labelChanged} block(s) render a label that differs from the source's.`);
856
+ const placedReads = resolvedParagraphs.flatMap(({ parts }) => parts.flatMap(({ block }) => block.read === null ? [] : [block.read]));
857
+ const droppedFields = /* @__PURE__ */ new Map();
858
+ let internalHyperlinks = 0;
859
+ for (const read of placedReads) {
860
+ for (const index of read.fieldIndices) {
861
+ const field = source.story.state.fields[index];
862
+ if (field !== void 0 && hyperlinkFieldLink(field) === null) droppedFields.set(field.kind, (droppedFields.get(field.kind) ?? 0) + 1);
863
+ }
864
+ let previous = null;
865
+ for (const { link } of read.atoms) {
866
+ const lost = link !== null && linkAddress(link, sourceResources.relationships.document) === null;
867
+ if (lost && link !== previous) internalHyperlinks += 1;
868
+ previous = lost ? link : null;
869
+ }
870
+ }
871
+ const sectionBreaks = source.story.paragraphs.filter((block) => block.read?.hasSectionBreak === true).length;
872
+ const omittedBlocks = source.story.order.filter((block) => resolved.omitted.has(block.topLevelId) || resolved.omitted.has(block.block.id));
873
+ let omittedBreaks = 0;
874
+ for (const block of omittedBlocks) for (const atom of block.read?.atoms ?? []) if (atom.kind === "pageBreak") omittedBreaks += 1;
875
+ const omittedLabels = omittedBlocks.filter(({ block }) => block.label !== null).length;
876
+ if (omittedBreaks > 0) warnings.push(`${omittedBreaks} page or column break(s) of the source sit in omitted blocks.`);
877
+ if (omittedLabels > 0) warnings.push(`${omittedLabels} omitted block(s) showed a number or label in the source.`);
878
+ if (source.story.state.comments > 0) warnings.push(`${source.story.state.comments} comment(s) of the source are not carried over.`);
879
+ if (droppedFields.size > 0) warnings.push("Fields of the source are carried over as their cached text.");
880
+ if (internalHyperlinks > 0) warnings.push(`${internalHyperlinks} link(s) to bookmarks of the source are carried over as text.`);
881
+ if (sectionBreaks > 0) warnings.push(`${sectionBreaks} section break(s) of the source are not carried over.`);
882
+ const [conformance, templateConformance] = await Promise.all([validateDocxConformance(output), validateDocxConformance(template.pkg.bytes)]);
883
+ if (CONFORMANCE_RANK[conformance.status] < CONFORMANCE_RANK[templateConformance.status]) issues.push({
884
+ code: "conformance",
885
+ message: `The output package is ${conformance.status}; the template is ${templateConformance.status}.`
886
+ });
887
+ const predictionMismatch = referenceResults.filter(({ predictedText }) => predictedText !== null).filter(({ predictedText, expectedText }) => predictedText !== expectedText).length;
888
+ if (predictionMismatch > 0) warnings.push(`${predictionMismatch} reference(s) cache a text that differs from the target's rendered label.`);
889
+ const textChanging = referenceResults.filter(({ expectedText, replacedText }) => expectedText !== replacedText).length;
890
+ if (textChanging > 0) warnings.push(`${textChanging} reference(s) show a text that differs from the source's wording.`);
891
+ let updateFields = "unchanged";
892
+ if (updateOnOpen === true) updateFields = "set";
893
+ else if (updateOnOpen === false) updateFields = "cleared";
894
+ return Result.ok({
895
+ version: 1,
896
+ ok: issues.length === 0,
897
+ sourceSha256: source.manifest.sha256,
898
+ templateSha256: template.manifest.sha256,
899
+ outputSha256: out.manifest.sha256,
900
+ blocks,
901
+ counts,
902
+ footnotes,
903
+ endnotes,
904
+ emphasisSpans: {
905
+ source: spans.source.emphasis,
906
+ expected: spans.expected.emphasis,
907
+ output: spans.output.emphasis
908
+ },
909
+ highlightSpans: {
910
+ source: spans.source.highlight,
911
+ expected: spans.expected.highlight,
912
+ output: spans.output.highlight
913
+ },
914
+ references: {
915
+ planned: resolved.references.length,
916
+ ok: referenceResults.filter(({ status }) => status === "ok").length,
917
+ textChanging,
918
+ predictionMismatch,
919
+ results: referenceResults
920
+ },
921
+ leftovers: {
922
+ fields: leftoverFields,
923
+ frozenFields,
924
+ filler,
925
+ templateBlockIds: resolved.keptTemplateBlocks.map(({ block }) => block.id)
926
+ },
927
+ dropped: {
928
+ comments: source.story.state.comments,
929
+ sourceFields: [...droppedFields].map(([kind, count]) => ({
930
+ kind,
931
+ count
932
+ })),
933
+ internalHyperlinks,
934
+ sectionBreaks
935
+ },
936
+ updateFields,
937
+ conformance: {
938
+ status: conformance.status,
939
+ templateStatus: templateConformance.status,
940
+ issues: [...conformance.issues]
941
+ },
942
+ issues,
943
+ warnings
944
+ });
945
+ };
946
+ const verifyUnguarded = async ({ source, template, output, plan, options }) => {
947
+ const analyzedSource = await analyzeDocument(source);
948
+ if (Result.isError(analyzedSource)) return analyzedSource;
949
+ const analyzedTemplate = await analyzeDocument(template);
950
+ if (Result.isError(analyzedTemplate)) return analyzedTemplate;
951
+ const resolved = resolvePlan(analyzedSource.value, analyzedTemplate.value, plan);
952
+ if (Result.isError(resolved)) return resolved;
953
+ return await reportTemplatePlanOutput({
954
+ source: analyzedSource.value,
955
+ template: analyzedTemplate.value,
956
+ output,
957
+ plan,
958
+ resolved: resolved.value,
959
+ options
960
+ });
961
+ };
962
+ /**
963
+ * Check `output` against `source`, `template` and `plan` without trusting
964
+ * whoever wrote it: every expectation is derived again from the inputs.
965
+ * A refused plan is an error; a failed check is a report with `ok: false`.
966
+ */
967
+ const verifyTemplatePlanOutput = async (input) => await guarded(async () => await verifyUnguarded(input));
968
+ export { reportTemplatePlanOutput, verifyTemplatePlanOutput };