@stll/folio-core 0.72.0 → 0.74.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 (244) hide show
  1. package/README.md +12 -6
  2. package/dist/ai-edits/applyTypes.d.ts +85 -0
  3. package/dist/ai-edits/applyTypes.js +24 -0
  4. package/dist/ai-edits/clean-text.d.ts +7 -1
  5. package/dist/ai-edits/clean-text.js +23 -2
  6. package/dist/ai-edits/finalSectionReview.d.ts +1 -1
  7. package/dist/ai-edits/headless.d.ts +29 -147
  8. package/dist/ai-edits/headless.js +215 -1639
  9. package/dist/ai-edits/index.d.ts +3 -3
  10. package/dist/ai-edits/index.js +2 -3
  11. package/dist/ai-edits/pending-suggestions.d.ts +14 -4
  12. package/dist/ai-edits/pending-suggestions.js +183 -90
  13. package/dist/ai-edits/pendingJoin.js +6 -1
  14. package/dist/ai-edits/retired-comment-receipts.d.ts +1 -1
  15. package/dist/ai-edits/snapshot.js +9 -4
  16. package/dist/ai-edits/table-cell-mutations.d.ts +1 -1
  17. package/dist/ai-edits/table-cell-mutations.js +2 -2
  18. package/dist/ai-edits/table-geometry.d.ts +1 -1
  19. package/dist/ai-edits/table-geometry.js +1 -1
  20. package/dist/ai-edits/table-row-column-mutations.d.ts +1 -1
  21. package/dist/ai-edits/table-row-column-mutations.js +1 -1
  22. package/dist/ai-edits/tableNodes.d.ts +38 -0
  23. package/dist/ai-edits/tableNodes.js +86 -0
  24. package/dist/ai-edits/tracked-batch-fidelity.d.ts +1 -1
  25. package/dist/ai-edits/tracked-batch-fidelity.js +1 -1
  26. package/dist/ai-edits/undefinedReferences.d.ts +7 -0
  27. package/dist/canonical/batchCommentReferences.js +1 -0
  28. package/dist/canonical/canonicalInlineGaps.d.ts +56 -0
  29. package/dist/canonical/canonicalInlineGaps.js +118 -0
  30. package/dist/canonical/canonicalInlineProjection.d.ts +4 -13
  31. package/dist/canonical/canonicalInlineProjection.js +5 -27
  32. package/dist/canonical/canonicalProjectionBlocks.d.ts +4 -4
  33. package/dist/canonical/canonicalPublicOperations.js +282 -75
  34. package/dist/canonical/canonicalSelection.js +1 -1
  35. package/dist/canonical/canonicalSession.d.ts +9 -1
  36. package/dist/canonical/canonicalSession.js +106 -33
  37. package/dist/compare/compare.d.ts +1 -1
  38. package/dist/compare/inline-atoms-model.d.ts +1 -1
  39. package/dist/compare/inline-atoms.d.ts +2 -2
  40. package/dist/compare/inline-provenance-model.d.ts +1 -1
  41. package/dist/compare/inline-provenance.d.ts +2 -2
  42. package/dist/compat/eigenpal.d.ts +3 -3
  43. package/dist/compat/eigenpal.js +2 -3
  44. package/dist/controller/autocompleteSuggestion.js +1 -1
  45. package/dist/controller/canonicalClipboard.d.ts +13 -3
  46. package/dist/controller/canonicalClipboard.js +186 -50
  47. package/dist/controller/canonicalClipboardResources.d.ts +9 -1
  48. package/dist/controller/canonicalClipboardResources.js +22 -2
  49. package/dist/controller/canonicalComposition.js +1 -1
  50. package/dist/controller/canonicalInput.js +1 -1
  51. package/dist/controller/canonicalPresence.js +1 -1
  52. package/dist/controller/canonicalReview.d.ts +1 -1
  53. package/dist/controller/canonicalReview.js +1 -1
  54. package/dist/controller/canonicalRoomAuthority.js +1 -1
  55. package/dist/controller/canonicalRoomWire.js +1 -1
  56. package/dist/controller/canonicalStructure.js +1 -1
  57. package/dist/controller/canonicalTabRoom.js +1 -1
  58. package/dist/controller/canonicalWatermark.d.ts +10 -0
  59. package/dist/controller/canonicalWatermark.js +37 -0
  60. package/dist/controller/canonicalYjsRoom.js +1 -1
  61. package/dist/controller/hiddenEditorApi.d.ts +1 -1
  62. package/dist/controller/hiddenEditorApi.js +2 -17
  63. package/dist/controller/hiddenEditorManager.d.ts +4 -3
  64. package/dist/controller/hiddenEditorManager.js +79 -23
  65. package/dist/document-operations.d.ts +1 -14
  66. package/dist/document-operations.js +1 -278
  67. package/dist/docx/canonicalSave.d.ts +1 -1
  68. package/dist/docx/canonicalSave.js +1 -1
  69. package/dist/docx/canonicalSessionInput.js +1 -1
  70. package/dist/docx/containerChildren.js +1 -1
  71. package/dist/docx/createDocx.d.ts +4 -0
  72. package/dist/docx/createDocx.js +6 -0
  73. package/dist/docx/paragraphParser.js +2 -2
  74. package/dist/docx/paragraphPropertySource.d.ts +1 -1
  75. package/dist/docx/parser.js +1 -1
  76. package/dist/docx/reviewResolutionProvenance.d.ts +3 -2
  77. package/dist/docx/reviewResolutionProvenance.js +31 -8
  78. package/dist/docx/revisionIdNormalization.js +30 -7
  79. package/dist/docx/rezip.d.ts +1 -1
  80. package/dist/docx/rezip.js +1 -1
  81. package/dist/docx/serializer/tableSerializer.js +4 -36
  82. package/dist/docx/server/templatePlan/apply.d.ts +15 -0
  83. package/dist/docx/server/templatePlan/apply.js +658 -0
  84. package/dist/docx/server/templatePlan/blocks.d.ts +97 -0
  85. package/dist/docx/server/templatePlan/blocks.js +355 -0
  86. package/dist/docx/server/templatePlan/builders.d.ts +72 -0
  87. package/dist/docx/server/templatePlan/builders.js +237 -0
  88. package/dist/docx/server/templatePlan/emit.d.ts +118 -0
  89. package/dist/docx/server/templatePlan/emit.js +466 -0
  90. package/dist/docx/server/templatePlan/emphasis.d.ts +62 -0
  91. package/dist/docx/server/templatePlan/emphasis.js +173 -0
  92. package/dist/docx/server/templatePlan/inspect.d.ts +22 -0
  93. package/dist/docx/server/templatePlan/inspect.js +230 -0
  94. package/dist/docx/server/templatePlan/labels.d.ts +45 -0
  95. package/dist/docx/server/templatePlan/labels.js +155 -0
  96. package/dist/docx/server/templatePlan/package.d.ts +34 -0
  97. package/dist/docx/server/templatePlan/package.js +99 -0
  98. package/dist/docx/server/templatePlan/plan.d.ts +145 -0
  99. package/dist/docx/server/templatePlan/plan.js +875 -0
  100. package/dist/docx/server/templatePlan/planShape.d.ts +9 -0
  101. package/dist/docx/server/templatePlan/planShape.js +180 -0
  102. package/dist/docx/server/templatePlan/resources.d.ts +41 -0
  103. package/dist/docx/server/templatePlan/resources.js +136 -0
  104. package/dist/docx/server/templatePlan/story.d.ts +128 -0
  105. package/dist/docx/server/templatePlan/story.js +440 -0
  106. package/dist/docx/server/templatePlan/types.d.ts +442 -0
  107. package/dist/docx/server/templatePlan/types.js +29 -0
  108. package/dist/docx/server/templatePlan/verify.d.ts +40 -0
  109. package/dist/docx/server/templatePlan/verify.js +976 -0
  110. package/dist/docx/server/templatePlan/xml.d.ts +74 -0
  111. package/dist/docx/server/templatePlan/xml.js +125 -0
  112. package/dist/docx/settingsHeaderFooterUpdate.d.ts +9 -0
  113. package/dist/docx/settingsHeaderFooterUpdate.js +45 -10
  114. package/dist/docx/structuralXmlPatch.js +9 -1
  115. package/dist/docx/tableGridXml.d.ts +30 -0
  116. package/dist/docx/tableGridXml.js +54 -0
  117. package/dist/docx/tableParser.js +7 -0
  118. package/dist/i18n/loadMessages.d.ts +5 -0
  119. package/dist/i18n/loadMessages.js +46 -0
  120. package/dist/i18n/locales.d.ts +3 -0
  121. package/dist/i18n/locales.js +17 -0
  122. package/dist/i18n/messages.d.ts +3 -2
  123. package/dist/i18n/messages.js +4 -16
  124. package/dist/index.d.ts +3 -3
  125. package/dist/index.js +2 -3
  126. package/dist/internal/clipboardTransformPlugin.d.ts +3 -0
  127. package/dist/internal/clipboardTransformPlugin.js +13 -0
  128. package/dist/internal/extensionRuntime.d.ts +7 -0
  129. package/dist/internal/extensionRuntime.js +28 -0
  130. package/dist/internal/starterKitExtensions.d.ts +20 -0
  131. package/dist/internal/starterKitExtensions.js +123 -0
  132. package/dist/internal/wholeStoryRevisionResolution.js +1 -1
  133. package/dist/managers/ContextMenuManager.js +2 -1
  134. package/dist/managers/editorShortcuts.d.ts +1 -1
  135. package/dist/prosemirror/anchoredTextBoxes.d.ts +1 -1
  136. package/dist/prosemirror/attrs/index.js +1 -1
  137. package/dist/prosemirror/canonicalCommands.d.ts +1 -1
  138. package/dist/prosemirror/canonicalSelectionRange.d.ts +1 -1
  139. package/dist/prosemirror/canonicalSelectionRange.js +1 -1
  140. package/dist/prosemirror/canonicalTableCommands.js +3 -3
  141. package/dist/prosemirror/commands/comments.js +4 -4
  142. package/dist/prosemirror/commands/contentControls.d.ts +1 -1
  143. package/dist/prosemirror/commands/contentControls.js +1 -1
  144. package/dist/prosemirror/commands/formatPainter.d.ts +1 -1
  145. package/dist/prosemirror/commands/formatting.d.ts +1 -1
  146. package/dist/prosemirror/commands/pastePlainText.d.ts +1 -1
  147. package/dist/prosemirror/commands/pastePlainText.js +2 -3
  148. package/dist/prosemirror/commands/replaceRangeText.js +1 -1
  149. package/dist/prosemirror/commands/sectionBreak.js +1 -1
  150. package/dist/prosemirror/commands/tableCellMergeResolution.d.ts +1 -1
  151. package/dist/prosemirror/commands/tableMergeFoldDecisions.d.ts +1 -1
  152. package/dist/prosemirror/commentRecords.d.ts +1 -1
  153. package/dist/prosemirror/commentRecords.js +2 -2
  154. package/dist/prosemirror/contentControlRevisions.d.ts +1 -1
  155. package/dist/prosemirror/conversion/fromProseDoc.d.ts +0 -5
  156. package/dist/prosemirror/conversion/fromProseDoc.js +2 -9
  157. package/dist/prosemirror/conversion/index.d.ts +2 -2
  158. package/dist/prosemirror/conversion/index.js +2 -2
  159. package/dist/prosemirror/documentStructureCounts.d.ts +24 -0
  160. package/dist/prosemirror/documentStructureCounts.js +76 -0
  161. package/dist/prosemirror/extensions/ExtensionManager.d.ts +1 -1
  162. package/dist/prosemirror/extensions/ExtensionManager.js +4 -22
  163. package/dist/prosemirror/extensions/StarterKit.d.ts +4 -27
  164. package/dist/prosemirror/extensions/StarterKit.js +29 -115
  165. package/dist/prosemirror/extensions/core/ParagraphExtension.js +1 -1
  166. package/dist/prosemirror/extensions/core/historyCommands.d.ts +16 -0
  167. package/dist/prosemirror/extensions/core/historyCommands.js +19 -0
  168. package/dist/prosemirror/extensions/features/AutoBidiDetectionExtension.js +1 -1
  169. package/dist/prosemirror/extensions/features/BaseKeymapExtension.js +1 -1
  170. package/dist/prosemirror/extensions/features/ListExtension.js +7 -2
  171. package/dist/prosemirror/extensions/features/pastedCellSections.d.ts +1 -1
  172. package/dist/prosemirror/extensions/index.d.ts +2 -1
  173. package/dist/prosemirror/extensions/marks/FootnoteRefExtension.js +8 -3
  174. package/dist/prosemirror/extensions/marks/markUtils.d.ts +1 -1
  175. package/dist/prosemirror/extensions/nodes/TableExtension.d.ts +1 -1
  176. package/dist/prosemirror/extensions/nodes/TableExtension.js +8 -41
  177. package/dist/prosemirror/extensions/types.d.ts +1 -1
  178. package/dist/prosemirror/findReplaceSelection.d.ts +1 -1
  179. package/dist/prosemirror/hyperlinkRemoval.d.ts +1 -1
  180. package/dist/prosemirror/hyperlinkRemoval.js +7 -2
  181. package/dist/prosemirror/index.d.ts +3 -3
  182. package/dist/prosemirror/index.js +3 -3
  183. package/dist/prosemirror/insertionGaps.d.ts +1 -1
  184. package/dist/prosemirror/keptRangeBoundaries.d.ts +1 -1
  185. package/dist/prosemirror/keptRangeBoundaries.js +1 -1
  186. package/dist/prosemirror/listNumbering.d.ts +1 -1
  187. package/dist/prosemirror/listNumbering.js +1 -1
  188. package/dist/prosemirror/lockedControls.d.ts +1 -1
  189. package/dist/prosemirror/markupViewProjection.d.ts +1 -1
  190. package/dist/prosemirror/noteReferenceOccurrences.d.ts +1 -1
  191. package/dist/prosemirror/noteReferenceOccurrences.js +1 -1
  192. package/dist/prosemirror/noteReferenceReview.d.ts +2 -56
  193. package/dist/prosemirror/noteReferenceReview.js +2 -243
  194. package/dist/prosemirror/{extensions/features/ParaIdAllocatorExtension.d.ts → paraIds.d.ts} +13 -23
  195. package/dist/prosemirror/paraIds.js +152 -0
  196. package/dist/prosemirror/paragraphChangeTrackerMeta.d.ts +97 -0
  197. package/dist/prosemirror/paragraphChangeTrackerMeta.js +87 -0
  198. package/dist/prosemirror/paragraphMarkJoin.d.ts +1 -1
  199. package/dist/prosemirror/paragraphPropertyCarry.d.ts +1 -1
  200. package/dist/prosemirror/pastedCommentCopies.d.ts +1 -1
  201. package/dist/prosemirror/plugins/createDocScanPlugin.d.ts +1 -1
  202. package/dist/prosemirror/plugins/documentNumbering.d.ts +1 -1
  203. package/dist/prosemirror/plugins/documentNumbering.js +1 -1
  204. package/dist/prosemirror/plugins/documentStyles.js +1 -1
  205. package/dist/prosemirror/plugins/templateDirectives.d.ts +1 -1
  206. package/dist/prosemirror/rebaseParagraphRunFormatting.d.ts +1 -1
  207. package/dist/prosemirror/rebaseParagraphRuns.d.ts +1 -1
  208. package/dist/prosemirror/rejoinRunCarriers.d.ts +1 -1
  209. package/dist/prosemirror/replacedAnnotations.d.ts +1 -1
  210. package/dist/prosemirror/replacedAnnotations.js +17 -2
  211. package/dist/prosemirror/revisionCarriers.d.ts +1 -1
  212. package/dist/prosemirror/runFormattingInlineCarriers.d.ts +1 -1
  213. package/dist/prosemirror/sectionMarkEdits.d.ts +1 -1
  214. package/dist/prosemirror/selectionBounds.d.ts +10 -0
  215. package/dist/prosemirror/selectionBounds.js +22 -0
  216. package/dist/prosemirror/storyListNumbering.d.ts +1 -1
  217. package/dist/prosemirror/suggestionCommands.d.ts +47 -0
  218. package/dist/prosemirror/suggestionCommands.js +31 -0
  219. package/dist/prosemirror/tableCellPaste.d.ts +1 -1
  220. package/dist/prosemirror/tableCellPaste.js +1 -1
  221. package/dist/prosemirror/tableGridMutation.d.ts +1 -1
  222. package/dist/prosemirror/tableRunIn.js +1 -1
  223. package/dist/prosemirror/textInput.d.ts +1 -1
  224. package/dist/prosemirror/textInput.js +1 -1
  225. package/dist/server.d.ts +7 -2
  226. package/dist/server.js +6 -1
  227. package/dist/types/canonicalCapabilities.d.ts +13 -92
  228. package/dist/types/canonicalCapabilities.js +11 -85
  229. package/package.json +4 -4
  230. package/dist/ai-edits/apply.d.ts +0 -202
  231. package/dist/ai-edits/apply.js +0 -6759
  232. package/dist/ai-edits/note-story-inventory.d.ts +0 -5
  233. package/dist/ai-edits/note-story-inventory.js +0 -10
  234. package/dist/ai-edits/revisionStretches.d.ts +0 -32
  235. package/dist/ai-edits/revisionStretches.js +0 -147
  236. package/dist/prosemirror/extensions/core/HistoryExtension.d.ts +0 -18
  237. package/dist/prosemirror/extensions/core/HistoryExtension.js +0 -122
  238. package/dist/prosemirror/extensions/features/ParaIdAllocatorExtension.js +0 -408
  239. package/dist/prosemirror/extensions/features/ParagraphChangeTrackerExtension.d.ts +0 -135
  240. package/dist/prosemirror/extensions/features/ParagraphChangeTrackerExtension.js +0 -566
  241. package/dist/prosemirror/plugins/suggestionMode.d.ts +0 -92
  242. package/dist/prosemirror/plugins/suggestionMode.js +0 -1515
  243. package/dist/prosemirror/tablePositionedBookmarks.d.ts +0 -8
  244. package/dist/prosemirror/tablePositionedBookmarks.js +0 -80
@@ -0,0 +1,658 @@
1
+ import { registerContentTypeParts } from "../../contentTypeRegistry.js";
2
+ import { RELATIONSHIP_TYPES } from "../../relsParser.js";
3
+ import { spliceXml } from "../../selectiveXmlPatch.js";
4
+ import { NAMESPACES, getLocalName } from "../../xmlParser.js";
5
+ import { appendToXmlRoot } from "../../xmlRootInsertion.js";
6
+ import { analyzeDocument } from "./blocks.js";
7
+ import { freezeFields, setUpdateFieldsOnOpen, withoutContained } from "./builders.js";
8
+ import { createRelationshipsEditor, noteXml, paragraphContentXml, paragraphXml, tableXml, templateCharacterStyles } from "./emit.js";
9
+ import { readHeaderFooterParts } from "./inspect.js";
10
+ import { styleNumbering } from "./labels.js";
11
+ import { guarded, readPartText, relationshipsPathFor } from "./package.js";
12
+ import { resolvePlan } from "./plan.js";
13
+ import { readStoryResources } from "./resources.js";
14
+ import { TemplatePlanError } from "./types.js";
15
+ import { reportTemplatePlanOutput } from "./verify.js";
16
+ import { elementChildren, escapeXmlAttribute, innerRangeOf, integerOrNull, isW, maxOf, partPrefixes, rangeOf, readRawPart, sliceWithSplices, twipsOrNull, wAttr, wChild, wChildren, wName, walkElements } from "./xml.js";
17
+ import { Result } from "better-result";
18
+ import { ZipArchive } from "@stll/docx-core/zip";
19
+ // src/docx/server/templatePlan/apply.ts
20
+ /**
21
+ * Apply a source document onto a template from a plan: the output is the
22
+ * template's own package with a new main story. Parts the plan does not
23
+ * touch keep their bytes; the ones it does are spliced, not re-serialized.
24
+ */
25
+ const CONTENT_TYPES_PATH = "[Content_Types].xml";
26
+ const WORDPROCESSINGML_CONTENT_TYPE_PREFIX = "application/vnd.openxmlformats-officedocument.wordprocessingml.";
27
+ const RELATIONSHIPS_NAMESPACE = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
28
+ const MEDIA_CONTENT_TYPES = {
29
+ png: "image/png",
30
+ jpg: "image/jpeg",
31
+ jpeg: "image/jpeg",
32
+ gif: "image/gif",
33
+ bmp: "image/bmp",
34
+ tif: "image/tiff",
35
+ tiff: "image/tiff",
36
+ emf: "image/x-emf",
37
+ wmf: "image/x-wmf",
38
+ svg: "image/svg+xml",
39
+ webp: "image/webp"
40
+ };
41
+ const NOTE_PARTS = {
42
+ footnote: {
43
+ origin: "footnotes",
44
+ fileName: "footnotes.xml",
45
+ root: "footnotes",
46
+ contentType: `${WORDPROCESSINGML_CONTENT_TYPE_PREFIX}footnotes+xml`,
47
+ relationshipType: RELATIONSHIP_TYPES.footnotes
48
+ },
49
+ endnote: {
50
+ origin: "endnotes",
51
+ fileName: "endnotes.xml",
52
+ root: "endnotes",
53
+ contentType: `${WORDPROCESSINGML_CONTENT_TYPE_PREFIX}endnotes+xml`,
54
+ relationshipType: RELATIONSHIP_TYPES.endnotes
55
+ }
56
+ };
57
+ const unreadable = (part, message) => new TemplatePlanError({
58
+ code: "xml-unreadable",
59
+ message,
60
+ part
61
+ });
62
+ const directoryOf = (path) => {
63
+ const slash = path.lastIndexOf("/");
64
+ return slash === -1 ? "" : path.slice(0, slash + 1);
65
+ };
66
+ const RANGE_MARKERS = [["bookmarkStart", "bookmarkEnd"], ["commentRangeStart", "commentRangeEnd"]];
67
+ /**
68
+ * Splices removing range markers whose other half the output does not carry:
69
+ * a bookmark or comment range that started in a block the plan dropped.
70
+ */
71
+ const orphanMarkerSplices = ({ kept, replaced }) => {
72
+ const splices = [];
73
+ for (const [startName, endName] of RANGE_MARKERS) {
74
+ const starts = /* @__PURE__ */ new Map();
75
+ const ends = /* @__PURE__ */ new Map();
76
+ for (const block of kept) walkElements(block, (element) => {
77
+ let side = null;
78
+ if (isW(element, startName)) side = starts;
79
+ else if (isW(element, endName)) side = ends;
80
+ const range = rangeOf(element);
81
+ const id = wAttr(element, "id");
82
+ if (side === null || range === null || id === null || replaced.some(({ start, end }) => range.start >= start && range.end <= end)) return;
83
+ side.set(id, [...side.get(id) ?? [], element]);
84
+ });
85
+ for (const [own, other] of [[starts, ends], [ends, starts]]) for (const [id, elements] of own) {
86
+ if (other.has(id)) continue;
87
+ for (const element of elements) {
88
+ const range = rangeOf(element);
89
+ if (range !== null) splices.push({
90
+ ...range,
91
+ newXml: ""
92
+ });
93
+ }
94
+ }
95
+ }
96
+ return splices;
97
+ };
98
+ const LEVEL_CHILD_ORDER = [
99
+ "start",
100
+ "numFmt",
101
+ "lvlRestart",
102
+ "pStyle",
103
+ "isLgl",
104
+ "suff",
105
+ "lvlText",
106
+ "lvlPicBulletId",
107
+ "legacy",
108
+ "lvlJc",
109
+ "pPr",
110
+ "rPr"
111
+ ];
112
+ /** Children of `w:pPr` that follow `w:ind` in the schema's order. */
113
+ const AFTER_INDENT = [
114
+ "contextualSpacing",
115
+ "mirrorIndents",
116
+ "suppressOverlap",
117
+ "jc",
118
+ "textDirection",
119
+ "textAlignment",
120
+ "textboxTightWrap",
121
+ "outlineLvl",
122
+ "divId",
123
+ "cnfStyle",
124
+ "rPr",
125
+ "sectPr",
126
+ "pPrChange"
127
+ ];
128
+ /**
129
+ * The `w:pPr` of a level with the planned indent. What the level states and
130
+ * the patch leaves out is kept; a hanging and a first-line indent exclude
131
+ * each other, and an indent counted in characters would override the planned
132
+ * one, so those are not carried over.
133
+ */
134
+ const levelPropertiesXml = ({ part, level, w, indent }) => {
135
+ const properties = wChild(level, "pPr");
136
+ const existing = wChild(properties, "ind");
137
+ const stated = (name) => twipsOrNull(wAttr(existing, name));
138
+ const hanging = indent.hanging ?? (indent.firstLine === void 0 ? stated("hanging") : null);
139
+ const firstLine = indent.firstLine ?? (indent.hanging === void 0 ? stated("firstLine") : null);
140
+ const indentXml = `<${w}:ind${[
141
+ ["left", indent.left ?? stated("left") ?? stated("start")],
142
+ ["right", wAttr(existing, "right") ?? wAttr(existing, "end")],
143
+ ["hanging", hanging],
144
+ ["firstLine", firstLine]
145
+ ].flatMap(([name, value]) => value === null ? [] : [` ${w}:${name}="${escapeXmlAttribute(String(value))}"`]).join("")}/>`;
146
+ const range = properties === null ? null : rangeOf(properties);
147
+ if (properties === null || range === null) return `<${w}:pPr>${indentXml}</${w}:pPr>`;
148
+ const existingRange = existing === null ? null : rangeOf(existing);
149
+ if (existingRange !== null) return sliceWithSplices(part.xml, range, [{
150
+ ...existingRange,
151
+ newXml: indentXml
152
+ }]);
153
+ const inner = innerRangeOf(part.xml, properties);
154
+ if (inner === null) {
155
+ const name = properties.name ?? `${w}:pPr`;
156
+ return `${part.xml.slice(range.start, range.end - 2).trimEnd()}>${indentXml}</${name}>`;
157
+ }
158
+ const later = AFTER_INDENT.map((name) => wChild(properties, name)).find((element) => element !== null);
159
+ const at = (later === void 0 || later === null ? null : rangeOf(later))?.start ?? inner.end;
160
+ return `${part.xml.slice(range.start, at)}${indentXml}${part.xml.slice(at, range.end)}`;
161
+ };
162
+ /** The template numbering part with level patches and new list instances. */
163
+ const editNumbering = (part, { patches, mints }) => {
164
+ const prefixes = partPrefixes(part.root);
165
+ if (prefixes === null) return Result.err(unreadable(part.path, "The numbering part binds no WordprocessingML prefix."));
166
+ const { w } = prefixes;
167
+ const splices = [];
168
+ const insertions = /* @__PURE__ */ new Map();
169
+ const insert = (offset, xml) => {
170
+ insertions.set(offset, [...insertions.get(offset) ?? [], xml]);
171
+ };
172
+ for (const patch of patches) {
173
+ const abstract = wChildren(part.root, "abstractNum").find((element) => integerOrNull(wAttr(element, "abstractNumId")) === patch.abstractNumId);
174
+ const level = wChildren(abstract, "lvl").find((element) => integerOrNull(wAttr(element, "ilvl")) === patch.ilvl);
175
+ const levelRange = level === void 0 ? null : rangeOf(level);
176
+ if (level === void 0 || levelRange === null) return Result.err(new TemplatePlanError({
177
+ code: "numbering-unknown",
178
+ message: `The numbering part has no level ${patch.ilvl} in list definition ${patch.abstractNumId}.`
179
+ }));
180
+ if (elementChildren(level).some((child) => wName(child) === null)) return Result.err(new TemplatePlanError({
181
+ code: "unsupported-content",
182
+ message: `Level ${patch.ilvl} of list definition ${patch.abstractNumId} holds markup a patch cannot change.`
183
+ }));
184
+ const valued = (name, value) => `<${w}:${name} ${w}:val="${escapeXmlAttribute(value)}"/>`;
185
+ const properties = patch.indent === void 0 ? void 0 : levelPropertiesXml({
186
+ part,
187
+ level,
188
+ w,
189
+ indent: patch.indent
190
+ });
191
+ if (properties === null) return Result.err(unreadable(part.path, "The numbering part could not be patched."));
192
+ const planned = {
193
+ ...patch.start === void 0 ? {} : { start: valued("start", String(patch.start)) },
194
+ ...patch.numFmt === void 0 ? {} : { numFmt: valued("numFmt", patch.numFmt) },
195
+ ...patch.suff === void 0 ? {} : { suff: valued("suff", patch.suff) },
196
+ ...patch.lvlText === void 0 ? {} : { lvlText: valued("lvlText", patch.lvlText) },
197
+ ...properties === void 0 ? {} : { pPr: properties }
198
+ };
199
+ const inner = innerRangeOf(part.xml, level);
200
+ for (const [index, name] of LEVEL_CHILD_ORDER.entries()) {
201
+ const xml = planned[name];
202
+ if (xml === void 0) continue;
203
+ const existing = wChild(level, name);
204
+ const existingRange = existing === null ? null : rangeOf(existing);
205
+ if (existingRange !== null) {
206
+ splices.push({
207
+ ...existingRange,
208
+ newXml: xml
209
+ });
210
+ continue;
211
+ }
212
+ if (inner === null) {
213
+ insert(levelRange.end - 2, "");
214
+ continue;
215
+ }
216
+ const later = LEVEL_CHILD_ORDER.slice(index + 1).map((following) => wChild(level, following)).find((element) => element !== null);
217
+ insert((later === void 0 || later === null ? null : rangeOf(later))?.start ?? inner.end, xml);
218
+ }
219
+ if (inner === null) {
220
+ const children = LEVEL_CHILD_ORDER.flatMap((name) => {
221
+ const xml = planned[name];
222
+ return xml === void 0 ? [] : [xml];
223
+ }).join("");
224
+ insertions.delete(levelRange.end - 2);
225
+ splices.push({
226
+ start: levelRange.end - 2,
227
+ end: levelRange.end,
228
+ newXml: `>${children}</${level.name ?? `${w}:lvl`}>`
229
+ });
230
+ }
231
+ }
232
+ if (mints.length > 0) {
233
+ const nums = wChildren(part.root, "num");
234
+ const markup = mints.map(({ numId, baseNumId, abstractNumId, starts }) => {
235
+ const base = nums.find((element) => integerOrNull(wAttr(element, "numId")) === baseNumId);
236
+ const inherited = /* @__PURE__ */ new Map();
237
+ for (const override of wChildren(base, "lvlOverride")) {
238
+ const level = integerOrNull(wAttr(override, "ilvl"));
239
+ if (level !== null) inherited.set(level, override);
240
+ }
241
+ const raw = (element) => {
242
+ const range = element === null || element === void 0 ? null : rangeOf(element);
243
+ return range === null ? "" : part.xml.slice(range.start, range.end);
244
+ };
245
+ const overrides = [.../* @__PURE__ */ new Set([...inherited.keys(), ...starts.keys()])].toSorted((left, right) => left - right).map((level) => {
246
+ const start = starts.get(level);
247
+ const kept = inherited.get(level);
248
+ if (start === void 0) return raw(kept);
249
+ const startOverride = (prefix) => `<${prefix}:startOverride ${prefix}:val="${start}"/>`;
250
+ const keptRange = kept === void 0 ? null : rangeOf(kept);
251
+ const keptInner = kept === void 0 ? null : innerRangeOf(part.xml, kept);
252
+ const keptPrefix = kept?.name?.includes(":") ? kept.name.slice(0, kept.name.indexOf(":")) : null;
253
+ if (kept === void 0 || keptRange === null || keptInner === null || keptPrefix === null) return `<${w}:lvlOverride ${w}:ilvl="${level}">${startOverride(w)}</${w}:lvlOverride>`;
254
+ const replaced = wChild(kept, "startOverride");
255
+ const replacedRange = replaced === null ? null : rangeOf(replaced);
256
+ const rest = replacedRange === null ? part.xml.slice(keptInner.start, keptInner.end) : part.xml.slice(keptInner.start, replacedRange.start) + part.xml.slice(replacedRange.end, keptInner.end);
257
+ return part.xml.slice(keptRange.start, keptInner.start) + startOverride(keptPrefix) + rest + part.xml.slice(keptInner.end, keptRange.end);
258
+ }).join("");
259
+ return `<${w}:num ${w}:numId="${numId}"><${w}:abstractNumId ${w}:val="${abstractNumId}"/>${overrides}</${w}:num>`;
260
+ }).join("");
261
+ const lastNum = nums.at(-1);
262
+ const cleanup = wChild(part.root, "numIdMacAtCleanup");
263
+ const inner = innerRangeOf(part.xml, part.root);
264
+ const at = (lastNum === void 0 ? null : rangeOf(lastNum)?.end) ?? (cleanup === null ? null : rangeOf(cleanup)?.start) ?? inner?.end;
265
+ if (at === void 0) return Result.err(unreadable(part.path, "The numbering part has no place for a new list."));
266
+ insert(at, markup);
267
+ }
268
+ for (const [offset, xmls] of insertions) splices.push({
269
+ start: offset,
270
+ end: offset,
271
+ newXml: xmls.join("")
272
+ });
273
+ const edited = spliceXml(part.xml, splices);
274
+ return edited === null ? Result.err(unreadable(part.path, "The numbering part could not be patched.")) : Result.ok(edited);
275
+ };
276
+ /** Write the output package for a resolved plan. */
277
+ const writeOutput = async ({ source, template, plan, resolved }) => {
278
+ const { pkg } = template;
279
+ const documentPrefixes = partPrefixes(template.document.root);
280
+ const bodyInner = innerRangeOf(template.document.xml, template.body);
281
+ if (documentPrefixes === null || bodyInner === null) return Result.err(unreadable(pkg.documentPath, "The template body cannot be rewritten."));
282
+ const documentDirectory = directoryOf(pkg.documentPath);
283
+ const parts = /* @__PURE__ */ new Map();
284
+ const readTemplateText = async (path) => await readPartText(pkg, path);
285
+ const sourceResources = await readStoryResources(source);
286
+ if (Result.isError(sourceResources)) return sourceResources;
287
+ const sourceMedia = /* @__PURE__ */ new Map();
288
+ for (const [path, bytes] of sourceResources.value.media) {
289
+ const dot = path.lastIndexOf(".");
290
+ sourceMedia.set(path, {
291
+ bytes,
292
+ extension: dot === -1 ? "" : path.slice(dot + 1).toLowerCase()
293
+ });
294
+ }
295
+ const documentRelationshipsXml = await readTemplateText(pkg.documentRelationshipsPath);
296
+ if (Result.isError(documentRelationshipsXml)) return documentRelationshipsXml;
297
+ const documentRelationships = createRelationshipsEditor(pkg.documentRelationshipsPath, documentRelationshipsXml.value);
298
+ if (documentRelationships === null) return Result.err(unreadable(pkg.documentRelationshipsPath, "The template's relationships part is not a relationships part."));
299
+ const takenPaths = new Set([...pkg.paths].map((path) => path.toLowerCase()));
300
+ const notePartState = async (kind) => {
301
+ const existing = kind === "footnote" ? template.footnotes : template.endnotes;
302
+ const path = existing.path ?? `${documentDirectory}${NOTE_PARTS[kind].fileName}`;
303
+ const prefixes = existing.part === null ? documentPrefixes : partPrefixes(existing.part.root);
304
+ if (prefixes === null) return Result.err(unreadable(path, "The notes part binds no WordprocessingML prefix."));
305
+ const relationshipsPath = relationshipsPathFor(path);
306
+ const relationshipsXml = await readTemplateText(pkg.paths.has(relationshipsPath) ? relationshipsPath : null);
307
+ if (Result.isError(relationshipsXml)) return relationshipsXml;
308
+ const relationships = createRelationshipsEditor(relationshipsPath, relationshipsXml.value);
309
+ if (relationships === null) return Result.err(unreadable(relationshipsPath, "A notes relationships part is not a relationships part."));
310
+ return Result.ok({
311
+ kind,
312
+ path,
313
+ existing,
314
+ prefixes,
315
+ relationships,
316
+ nextId: maxOf(existing.usedIds, 0) + 1,
317
+ pathTaken: existing.path === null && takenPaths.has(path.toLowerCase()),
318
+ allocated: /* @__PURE__ */ new Map()
319
+ });
320
+ };
321
+ const footnoteState = await notePartState("footnote");
322
+ if (Result.isError(footnoteState)) return footnoteState;
323
+ const endnoteState = await notePartState("endnote");
324
+ if (Result.isError(endnoteState)) return endnoteState;
325
+ const noteParts = {
326
+ footnote: footnoteState.value,
327
+ endnote: endnoteState.value
328
+ };
329
+ const media = /* @__PURE__ */ new Map();
330
+ const mediaPaths = /* @__PURE__ */ new Set();
331
+ let unsupportedMedia = null;
332
+ let drawingId = 0;
333
+ const noteDrawingIds = (root) => {
334
+ walkElements(root, (element) => {
335
+ if (getLocalName(element.name) !== "docPr") return;
336
+ const id = integerOrNull(String(element.attributes?.["id"] ?? ""));
337
+ if (id !== null && id > drawingId) drawingId = id;
338
+ });
339
+ };
340
+ noteDrawingIds(template.document.root);
341
+ for (const notes of [template.footnotes, template.endnotes]) if (notes.part !== null) noteDrawingIds(notes.part.root);
342
+ const headersAndFooters = await readHeaderFooterParts(template);
343
+ if (Result.isError(headersAndFooters)) return headersAndFooters;
344
+ const headerFooterParts = headersAndFooters.value;
345
+ for (const part of headerFooterParts) noteDrawingIds(part.root);
346
+ const shared = {
347
+ styles: templateCharacterStyles(template),
348
+ sourceRelationships: sourceResources.value.relationships,
349
+ sourceMedia,
350
+ resolveSourceTarget: sourceResources.value.resolveTarget,
351
+ noteId: (kind, sourceId) => {
352
+ const state = noteParts[kind];
353
+ const known = state.allocated.get(sourceId);
354
+ if (known !== void 0) return known;
355
+ const id = state.nextId;
356
+ state.nextId += 1;
357
+ state.allocated.set(sourceId, id);
358
+ return id;
359
+ },
360
+ addMedia: (sourcePath, sourceItem) => {
361
+ let entry = media.get(sourcePath);
362
+ if (entry === void 0) {
363
+ if (MEDIA_CONTENT_TYPES[sourceItem.extension] === void 0) unsupportedMedia ??= sourcePath;
364
+ let index = media.size + 1;
365
+ let path = `${documentDirectory}media/placed${index}.${sourceItem.extension}`;
366
+ while (pkg.paths.has(path) || mediaPaths.has(path)) {
367
+ index += 1;
368
+ path = `${documentDirectory}media/placed${index}.${sourceItem.extension}`;
369
+ }
370
+ mediaPaths.add(path);
371
+ entry = {
372
+ path,
373
+ media: sourceItem
374
+ };
375
+ media.set(sourcePath, entry);
376
+ }
377
+ return `/${entry.path}`;
378
+ },
379
+ nextDrawingId: () => {
380
+ drawingId += 1;
381
+ return drawingId;
382
+ }
383
+ };
384
+ const documentContext = {
385
+ ...shared,
386
+ prefixes: documentPrefixes,
387
+ relationships: documentRelationships
388
+ };
389
+ const instructions = new Map(resolved.references.map(({ reference, instruction }) => [reference, instruction]));
390
+ const instructionOf = (segment) => segment.kind === "reference" ? instructions.get(segment.reference) ?? null : null;
391
+ const emitOf = (paragraph) => ({
392
+ paragraph,
393
+ bookmark: resolved.bookmarks.get(paragraph),
394
+ instructionOf,
395
+ styleBindsList: styleNumbering(paragraph.styleId ?? template.defaultStyleId, template.styles, template.numbering)?.kind === "reference"
396
+ });
397
+ const templateSplices = [...freezeFields(template.document, resolved.freezeKinds).splices];
398
+ const replaced = [];
399
+ const slots = [...resolved.nestedSlots, ...resolved.items.flatMap((item) => item.kind === "slot" ? [item] : [])];
400
+ for (const { templateBlock, paragraph } of slots) {
401
+ const content = paragraphContentXml(emitOf(paragraph), documentContext);
402
+ if (Result.isError(content)) return content;
403
+ const range = rangeOf(templateBlock.element);
404
+ if (range === null) return Result.err(unreadable(pkg.documentPath, "A slot paragraph has no source range."));
405
+ const inner = innerRangeOf(template.document.xml, templateBlock.element);
406
+ if (inner === null) {
407
+ const name = templateBlock.element.name ?? `${documentPrefixes.w}:p`;
408
+ templateSplices.push({
409
+ start: range.end - 2,
410
+ end: range.end,
411
+ newXml: `>${content.value}</${name}>`
412
+ });
413
+ continue;
414
+ }
415
+ const properties = wChild(templateBlock.element, "pPr");
416
+ const start = (properties === null ? null : rangeOf(properties)?.end) ?? inner.start;
417
+ templateSplices.push({
418
+ start,
419
+ end: inner.end,
420
+ newXml: content.value
421
+ });
422
+ replaced.push({
423
+ start,
424
+ end: inner.end
425
+ });
426
+ }
427
+ const bodySection = wChild(template.body, "sectPr");
428
+ const keptElements = [
429
+ ...resolved.keptTemplateBlocks.map(({ element }) => element),
430
+ ...resolved.items.flatMap((item) => item.kind === "slot" ? [item.templateBlock.element] : []),
431
+ ...bodySection === null ? [] : [bodySection]
432
+ ];
433
+ templateSplices.push(...orphanMarkerSplices({
434
+ kept: keptElements,
435
+ replaced
436
+ }));
437
+ const documentSplices = withoutContained(templateSplices);
438
+ const keptXml = (element) => {
439
+ const range = rangeOf(element);
440
+ const xml = range === null ? null : sliceWithSplices(template.document.xml, range, documentSplices);
441
+ return xml === null ? Result.err(unreadable(pkg.documentPath, "A template block could not be carried over.")) : Result.ok(xml);
442
+ };
443
+ const body = [];
444
+ for (const item of resolved.items) {
445
+ let xml;
446
+ switch (item.kind) {
447
+ case "template":
448
+ xml = keptXml(item.block.element);
449
+ break;
450
+ case "slot":
451
+ xml = keptXml(item.templateBlock.element);
452
+ break;
453
+ case "paragraph":
454
+ xml = paragraphXml(emitOf(item.paragraph), documentContext);
455
+ break;
456
+ case "table":
457
+ xml = tableXml({
458
+ table: item.block.element,
459
+ styleId: item.styleId,
460
+ paragraphOf: (element) => {
461
+ const paragraph = item.cells.get(element);
462
+ return paragraph === void 0 ? Result.ok("") : paragraphXml(emitOf(paragraph), documentContext);
463
+ }
464
+ }, documentContext);
465
+ break;
466
+ default: return item;
467
+ }
468
+ if (Result.isError(xml)) return xml;
469
+ body.push(xml.value);
470
+ }
471
+ if (bodySection !== null) {
472
+ const section = keptXml(bodySection);
473
+ if (Result.isError(section)) return section;
474
+ body.push(section.value);
475
+ }
476
+ const documentXml = spliceXml(template.document.xml, [{
477
+ start: bodyInner.start,
478
+ end: bodyInner.end,
479
+ newXml: body.join("")
480
+ }]);
481
+ if (documentXml === null) return Result.err(unreadable(pkg.documentPath, "The new body could not be written."));
482
+ parts.set(pkg.documentPath, documentXml);
483
+ const newContentTypes = [];
484
+ for (const kind of ["footnote", "endnote"]) {
485
+ const state = noteParts[kind];
486
+ const definition = NOTE_PARTS[kind];
487
+ const sourceNotes = kind === "footnote" ? source.footnotes : source.endnotes;
488
+ const context = {
489
+ ...shared,
490
+ prefixes: state.prefixes,
491
+ relationships: state.relationships
492
+ };
493
+ const { w } = state.prefixes;
494
+ const markup = [];
495
+ for (const [sourceId, id] of state.allocated) {
496
+ const note = sourceNotes.byId.get(sourceId);
497
+ const xml = note === void 0 ? Result.ok(`<${w}:${kind} ${w}:id="${id}"><${w}:p/></${w}:${kind}>`) : noteXml({
498
+ kind,
499
+ id,
500
+ note,
501
+ source,
502
+ fields: sourceNotes.state.fields
503
+ }, context);
504
+ if (Result.isError(xml)) return xml;
505
+ markup.push(xml.value);
506
+ }
507
+ let partXml = null;
508
+ if (state.existing.part !== null) {
509
+ const frozen = spliceXml(state.existing.part.xml, freezeFields(state.existing.part, resolved.freezeKinds).splices);
510
+ if (frozen === null) return Result.err(unreadable(state.path, "The notes part could not be rewritten."));
511
+ const appended = markup.length === 0 ? frozen : appendToXmlRoot(frozen, {
512
+ rootName: state.existing.part.root.name ?? "",
513
+ markup: markup.join("")
514
+ });
515
+ partXml = appended === state.existing.part.xml ? null : appended;
516
+ } else if (markup.length > 0) {
517
+ if (state.pathTaken) return Result.err(new TemplatePlanError({
518
+ code: "unsupported-content",
519
+ message: `The template keeps another part at ${state.path}, where its ${kind}s would go.`,
520
+ part: state.path
521
+ }));
522
+ const separators = [-1, 0].map((id, index) => `<${w}:${kind} ${w}:type="${index === 0 ? "separator" : "continuationSeparator"}" ${w}:id="${id}"><${w}:p><${w}:r><${w}:${index === 0 ? "separator" : "continuationSeparator"}/></${w}:r></${w}:p></${w}:${kind}>`).join("");
523
+ partXml = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?><${w}:${definition.root} xmlns:${w}="${state.prefixes.wUri}" xmlns:${state.prefixes.r}="${RELATIONSHIPS_NAMESPACE}">${separators}${markup.join("")}</${w}:${definition.root}>`;
524
+ documentRelationships.add({
525
+ type: definition.relationshipType,
526
+ target: definition.fileName,
527
+ external: false
528
+ });
529
+ newContentTypes.push({
530
+ partName: `/${state.path}`,
531
+ contentType: definition.contentType
532
+ });
533
+ }
534
+ if (partXml !== null) parts.set(state.path, partXml);
535
+ const relationshipsXml = state.relationships.xml();
536
+ if (relationshipsXml !== null) parts.set(state.relationships.path, relationshipsXml);
537
+ }
538
+ if (unsupportedMedia !== null) return Result.err(new TemplatePlanError({
539
+ code: "unsupported-content",
540
+ message: "A picture of the source is in a format the output cannot declare.",
541
+ part: unsupportedMedia
542
+ }));
543
+ for (const { path, media: item } of media.values()) {
544
+ parts.set(path, item.bytes);
545
+ newContentTypes.push({
546
+ partName: `/${path}`,
547
+ contentType: MEDIA_CONTENT_TYPES[item.extension] ?? ""
548
+ });
549
+ }
550
+ const documentRelationshipsOut = documentRelationships.xml();
551
+ if (documentRelationshipsOut !== null) parts.set(pkg.documentRelationshipsPath, documentRelationshipsOut);
552
+ if (newContentTypes.length > 0) {
553
+ const contentTypes = await readTemplateText(CONTENT_TYPES_PATH);
554
+ if (Result.isError(contentTypes)) return contentTypes;
555
+ if (contentTypes.value === null) return Result.err(new TemplatePlanError({
556
+ code: "part-missing",
557
+ message: "The template has no content-type registry.",
558
+ part: CONTENT_TYPES_PATH
559
+ }));
560
+ const typesRoot = readRawPart(CONTENT_TYPES_PATH, contentTypes.value)?.root;
561
+ if (typesRoot === void 0 || getLocalName(typesRoot.name) !== "Types" || typesRoot.namespaceUri !== NAMESPACES.ct) return Result.err(unreadable(CONTENT_TYPES_PATH, "The template's content-type registry is not one."));
562
+ parts.set(CONTENT_TYPES_PATH, registerContentTypeParts(contentTypes.value, newContentTypes));
563
+ }
564
+ const patches = plan.numberingPatches ?? [];
565
+ if (patches.length > 0 || resolved.mints.length > 0) {
566
+ const numberingPart = template.numberingPath === null || template.numberingXml === null ? null : readRawPart(template.numberingPath, template.numberingXml);
567
+ if (numberingPart === null) return Result.err(new TemplatePlanError({
568
+ code: "numbering-unknown",
569
+ message: "The template has no numbering part to patch."
570
+ }));
571
+ const numbering = editNumbering(numberingPart, {
572
+ patches,
573
+ mints: resolved.mints
574
+ });
575
+ if (Result.isError(numbering)) return numbering;
576
+ parts.set(numberingPart.path, numbering.value);
577
+ }
578
+ if (resolved.freezeKinds.size > 0) for (const part of headerFooterParts) {
579
+ const { splices } = freezeFields(part, resolved.freezeKinds);
580
+ if (splices.length === 0) continue;
581
+ const frozen = spliceXml(part.xml, splices);
582
+ if (frozen === null) return Result.err(unreadable(part.path, "A header or footer could not be rewritten."));
583
+ parts.set(part.path, frozen);
584
+ }
585
+ const updateOnOpen = plan.fields?.updateOnOpen;
586
+ if (updateOnOpen !== void 0) {
587
+ const settingsPath = pkg.partPath("settings");
588
+ const settingsXml = await readTemplateText(settingsPath);
589
+ if (Result.isError(settingsXml)) return settingsXml;
590
+ if (settingsPath === null || settingsXml.value === null) {
591
+ if (updateOnOpen) return Result.err(new TemplatePlanError({
592
+ code: "part-missing",
593
+ message: "The template has no settings part to set update-on-open in."
594
+ }));
595
+ } else {
596
+ const settings = setUpdateFieldsOnOpen(settingsXml.value, updateOnOpen);
597
+ if (settings === null) return Result.err(unreadable(settingsPath, "The settings part could not be updated."));
598
+ if (settings !== settingsXml.value) parts.set(settingsPath, settings);
599
+ }
600
+ }
601
+ return await Result.tryPromise({
602
+ try: async () => {
603
+ const zip = await ZipArchive.read(pkg.bytes);
604
+ for (const [path, content] of parts) {
605
+ const current = zip.entry(path);
606
+ zip.set(path, content, current === void 0 ? {} : { modified: current.modified });
607
+ }
608
+ return await zip.generate();
609
+ },
610
+ catch: (cause) => new TemplatePlanError({
611
+ code: "archive-unreadable",
612
+ message: "The output package could not be written.",
613
+ cause
614
+ })
615
+ });
616
+ };
617
+ const applyUnguarded = async ({ source, template, plan, options }) => {
618
+ const analyzedSource = await analyzeDocument(source);
619
+ if (Result.isError(analyzedSource)) return analyzedSource;
620
+ const analyzedTemplate = await analyzeDocument(template);
621
+ if (Result.isError(analyzedTemplate)) return analyzedTemplate;
622
+ const resolved = resolvePlan(analyzedSource.value, analyzedTemplate.value, plan);
623
+ if (Result.isError(resolved)) return resolved;
624
+ const written = await writeOutput({
625
+ source: analyzedSource.value,
626
+ template: analyzedTemplate.value,
627
+ plan,
628
+ resolved: resolved.value
629
+ });
630
+ if (Result.isError(written)) return written;
631
+ const report = await reportTemplatePlanOutput({
632
+ source: analyzedSource.value,
633
+ template: analyzedTemplate.value,
634
+ output: written.value,
635
+ plan,
636
+ resolved: resolved.value,
637
+ options
638
+ });
639
+ if (Result.isError(report)) return report;
640
+ if (!report.value.ok) return Result.err(new TemplatePlanError({
641
+ code: "verification-failed",
642
+ message: `The output failed verification: ${report.value.issues.slice(0, 3).map(({ message }) => message).join(" ")}`,
643
+ report: report.value
644
+ }));
645
+ return Result.ok({
646
+ docx: written.value,
647
+ report: report.value
648
+ });
649
+ };
650
+ /**
651
+ * Apply `source` onto `template` as `plan` says and verify the result.
652
+ *
653
+ * The plan names blocks by id and pins them by hash; the text itself always
654
+ * comes from the source. The output is refused, with the report attached,
655
+ * unless every placed block reads back identical.
656
+ */
657
+ const applyTemplatePlan = async (input) => await guarded(async () => await applyUnguarded(input));
658
+ export { applyTemplatePlan };