@stll/folio-core 0.72.0 → 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 (192) hide show
  1. package/README.md +12 -6
  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 -3
  39. package/dist/compat/eigenpal.js +2 -3
  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/hiddenEditorApi.d.ts +1 -1
  50. package/dist/controller/hiddenEditorManager.d.ts +4 -3
  51. package/dist/controller/hiddenEditorManager.js +75 -15
  52. package/dist/document-operations-apply.d.ts +15 -0
  53. package/dist/document-operations-apply.js +280 -0
  54. package/dist/document-operations.d.ts +1 -14
  55. package/dist/document-operations.js +2 -279
  56. package/dist/docx/modelValidation.js +1 -1
  57. package/dist/docx/paragraphParser.js +2 -2
  58. package/dist/docx/paragraphPropertySource.d.ts +1 -1
  59. package/dist/docx/reviewResolutionProvenance.d.ts +3 -2
  60. package/dist/docx/reviewResolutionProvenance.js +32 -9
  61. package/dist/docx/revisionIdNormalization.js +30 -7
  62. package/dist/docx/rezip.js +1 -1
  63. package/dist/docx/serializer/borderSerializer.js +1 -1
  64. package/dist/docx/serializer/commentSerializer.js +1 -1
  65. package/dist/docx/serializer/documentSerializer.js +1 -1
  66. package/dist/docx/serializer/paragraphSerializer.js +3 -3
  67. package/dist/docx/serializer/runSerializer.js +1 -1
  68. package/dist/docx/serializer/sectionPropertiesSerializer.js +1 -1
  69. package/dist/docx/serializer/tableSerializer.js +5 -37
  70. package/dist/docx/serializer/textFormattingSerializer.js +1 -1
  71. package/dist/docx/serializer/trackedChangeAttributes.js +1 -1
  72. package/dist/docx/server/templatePlan/apply.d.ts +15 -0
  73. package/dist/docx/server/templatePlan/apply.js +600 -0
  74. package/dist/docx/server/templatePlan/blocks.d.ts +97 -0
  75. package/dist/docx/server/templatePlan/blocks.js +355 -0
  76. package/dist/docx/server/templatePlan/builders.d.ts +72 -0
  77. package/dist/docx/server/templatePlan/builders.js +237 -0
  78. package/dist/docx/server/templatePlan/emit.d.ts +118 -0
  79. package/dist/docx/server/templatePlan/emit.js +466 -0
  80. package/dist/docx/server/templatePlan/emphasis.d.ts +62 -0
  81. package/dist/docx/server/templatePlan/emphasis.js +173 -0
  82. package/dist/docx/server/templatePlan/inspect.d.ts +22 -0
  83. package/dist/docx/server/templatePlan/inspect.js +177 -0
  84. package/dist/docx/server/templatePlan/labels.d.ts +36 -0
  85. package/dist/docx/server/templatePlan/labels.js +126 -0
  86. package/dist/docx/server/templatePlan/package.d.ts +34 -0
  87. package/dist/docx/server/templatePlan/package.js +99 -0
  88. package/dist/docx/server/templatePlan/plan.d.ts +143 -0
  89. package/dist/docx/server/templatePlan/plan.js +841 -0
  90. package/dist/docx/server/templatePlan/planShape.d.ts +9 -0
  91. package/dist/docx/server/templatePlan/planShape.js +161 -0
  92. package/dist/docx/server/templatePlan/resources.d.ts +41 -0
  93. package/dist/docx/server/templatePlan/resources.js +136 -0
  94. package/dist/docx/server/templatePlan/story.d.ts +128 -0
  95. package/dist/docx/server/templatePlan/story.js +440 -0
  96. package/dist/docx/server/templatePlan/types.d.ts +406 -0
  97. package/dist/docx/server/templatePlan/types.js +28 -0
  98. package/dist/docx/server/templatePlan/verify.d.ts +40 -0
  99. package/dist/docx/server/templatePlan/verify.js +968 -0
  100. package/dist/docx/server/templatePlan/xml.d.ts +69 -0
  101. package/dist/docx/server/templatePlan/xml.js +119 -0
  102. package/dist/docx/settingsHeaderFooterUpdate.d.ts +9 -0
  103. package/dist/docx/settingsHeaderFooterUpdate.js +45 -10
  104. package/dist/docx/storyBlockReplay.js +1 -1
  105. package/dist/docx/structuralXmlPatch.js +9 -1
  106. package/dist/docx/tableGridXml.d.ts +30 -0
  107. package/dist/docx/tableGridXml.js +54 -0
  108. package/dist/docx/tableParser.js +7 -0
  109. package/dist/docx/xmlParser.js +1 -1
  110. package/dist/index.d.ts +3 -3
  111. package/dist/index.js +2 -3
  112. package/dist/internal/paragraphFormattingSerialization.js +1 -1
  113. package/dist/internal/wholeStoryRevisionResolution.js +1 -1
  114. package/dist/managers/ContextMenuManager.js +2 -1
  115. package/dist/managers/editorShortcuts.d.ts +1 -1
  116. package/dist/prosemirror/anchoredTextBoxes.d.ts +1 -1
  117. package/dist/prosemirror/canonicalCommands.d.ts +1 -1
  118. package/dist/prosemirror/canonicalSelectionRange.d.ts +1 -1
  119. package/dist/prosemirror/canonicalTableCommands.js +2 -2
  120. package/dist/prosemirror/commands/comments.js +3 -3
  121. package/dist/prosemirror/commands/contentControls.d.ts +1 -1
  122. package/dist/prosemirror/commands/formatPainter.d.ts +1 -1
  123. package/dist/prosemirror/commands/formatting.d.ts +1 -1
  124. package/dist/prosemirror/commands/pastePlainText.d.ts +1 -1
  125. package/dist/prosemirror/commands/sectionBreak.js +1 -1
  126. package/dist/prosemirror/commands/tableCellMergeResolution.d.ts +1 -1
  127. package/dist/prosemirror/commands/tableMergeFoldDecisions.d.ts +1 -1
  128. package/dist/prosemirror/commentRecords.d.ts +1 -1
  129. package/dist/prosemirror/contentControlRevisions.d.ts +1 -1
  130. package/dist/prosemirror/conversion/fromProseDoc.js +1 -1
  131. package/dist/prosemirror/documentStructureCounts.d.ts +24 -0
  132. package/dist/prosemirror/documentStructureCounts.js +76 -0
  133. package/dist/prosemirror/extensions/ExtensionManager.d.ts +1 -1
  134. package/dist/prosemirror/extensions/StarterKit.d.ts +1 -1
  135. package/dist/prosemirror/extensions/core/HistoryExtension.d.ts +1 -7
  136. package/dist/prosemirror/extensions/core/HistoryExtension.js +5 -13
  137. package/dist/prosemirror/extensions/core/ParagraphExtension.js +1 -1
  138. package/dist/prosemirror/extensions/core/historyCommands.d.ts +16 -0
  139. package/dist/prosemirror/extensions/core/historyCommands.js +19 -0
  140. package/dist/prosemirror/extensions/features/AutoBidiDetectionExtension.js +1 -1
  141. package/dist/prosemirror/extensions/features/ParaIdAllocatorExtension.d.ts +2 -35
  142. package/dist/prosemirror/extensions/features/ParaIdAllocatorExtension.js +4 -142
  143. package/dist/prosemirror/extensions/features/ParagraphChangeTrackerExtension.d.ts +3 -87
  144. package/dist/prosemirror/extensions/features/ParagraphChangeTrackerExtension.js +7 -162
  145. package/dist/prosemirror/extensions/features/pastedCellSections.d.ts +1 -1
  146. package/dist/prosemirror/extensions/features/pastedHeadingStyles.js +1 -1
  147. package/dist/prosemirror/extensions/marks/markUtils.d.ts +1 -1
  148. package/dist/prosemirror/extensions/nodes/TableExtension.d.ts +1 -1
  149. package/dist/prosemirror/extensions/nodes/TableExtension.js +2 -2
  150. package/dist/prosemirror/extensions/types.d.ts +1 -1
  151. package/dist/prosemirror/findReplaceSelection.d.ts +1 -1
  152. package/dist/prosemirror/hyperlinkRemoval.d.ts +1 -1
  153. package/dist/prosemirror/index.d.ts +1 -1
  154. package/dist/prosemirror/index.js +1 -1
  155. package/dist/prosemirror/insertionGaps.d.ts +1 -1
  156. package/dist/prosemirror/keptRangeBoundaries.d.ts +1 -1
  157. package/dist/prosemirror/listNumbering.d.ts +1 -1
  158. package/dist/prosemirror/lockedControls.d.ts +1 -1
  159. package/dist/prosemirror/markupViewProjection.d.ts +1 -1
  160. package/dist/prosemirror/noteReferenceOccurrences.d.ts +1 -1
  161. package/dist/prosemirror/noteReferenceReview.js +1 -1
  162. package/dist/prosemirror/paraIds.d.ts +46 -0
  163. package/dist/prosemirror/paraIds.js +152 -0
  164. package/dist/prosemirror/paragraphChangeTrackerMeta.d.ts +97 -0
  165. package/dist/prosemirror/paragraphChangeTrackerMeta.js +87 -0
  166. package/dist/prosemirror/paragraphMarkJoin.d.ts +1 -1
  167. package/dist/prosemirror/paragraphPropertyCarry.d.ts +1 -1
  168. package/dist/prosemirror/pastedCommentCopies.d.ts +1 -1
  169. package/dist/prosemirror/pastedCommentCopies.js +1 -1
  170. package/dist/prosemirror/plugins/createDocScanPlugin.d.ts +1 -1
  171. package/dist/prosemirror/plugins/documentNumbering.d.ts +1 -1
  172. package/dist/prosemirror/plugins/suggestionMode.d.ts +1 -1
  173. package/dist/prosemirror/plugins/templateDirectives.d.ts +1 -1
  174. package/dist/prosemirror/rebaseParagraphRunFormatting.d.ts +1 -1
  175. package/dist/prosemirror/rebaseParagraphRuns.d.ts +1 -1
  176. package/dist/prosemirror/rejoinRunCarriers.d.ts +1 -1
  177. package/dist/prosemirror/replacedAnnotations.d.ts +1 -1
  178. package/dist/prosemirror/replacedAnnotations.js +16 -1
  179. package/dist/prosemirror/revisionCarriers.d.ts +1 -1
  180. package/dist/prosemirror/runFormattingInlineCarriers.d.ts +1 -1
  181. package/dist/prosemirror/sectionMarkEdits.d.ts +1 -1
  182. package/dist/prosemirror/selectionBounds.d.ts +10 -0
  183. package/dist/prosemirror/selectionBounds.js +22 -0
  184. package/dist/prosemirror/storyListNumbering.d.ts +1 -1
  185. package/dist/prosemirror/tableCellPaste.d.ts +1 -1
  186. package/dist/prosemirror/tableGridMutation.d.ts +1 -1
  187. package/dist/prosemirror/textInput.d.ts +1 -1
  188. package/dist/server.d.ts +7 -2
  189. package/dist/server.js +6 -1
  190. package/dist/types/canonicalCapabilities.d.ts +8 -41
  191. package/dist/types/canonicalCapabilities.js +6 -34
  192. package/package.json +4 -4
@@ -0,0 +1,173 @@
1
+ import { wAttr, wChild, wChildVal, wChildren } from "./xml.js";
2
+ // src/docx/server/templatePlan/emphasis.ts
3
+ /**
4
+ * In `CT_RPr` order. Bold and italic for complex scripts are properties of
5
+ * their own: a run may state one and not the other.
6
+ */
7
+ const TOGGLES = [
8
+ "b",
9
+ "bCs",
10
+ "i",
11
+ "iCs",
12
+ "caps",
13
+ "smallCaps",
14
+ "strike",
15
+ "dstrike",
16
+ "vanish"
17
+ ];
18
+ const NO_EMPHASIS = Object.freeze({
19
+ b: false,
20
+ bCs: false,
21
+ i: false,
22
+ iCs: false,
23
+ caps: false,
24
+ smallCaps: false,
25
+ strike: false,
26
+ dstrike: false,
27
+ vanish: false,
28
+ u: null,
29
+ vertAlign: null,
30
+ highlight: null
31
+ });
32
+ /** Toggle properties: stated on at two style tiers, they cancel (ECMA-376 §17.7.3). */
33
+ const XOR_TOGGLES = /* @__PURE__ */ new Set([
34
+ "b",
35
+ "bCs",
36
+ "i",
37
+ "iCs",
38
+ "caps",
39
+ "smallCaps",
40
+ "strike",
41
+ "vanish"
42
+ ]);
43
+ const formattingToggle = (rPr, toggle) => {
44
+ switch (toggle) {
45
+ case "b": return rPr?.bold;
46
+ case "bCs": return rPr?.boldCs;
47
+ case "i": return rPr?.italic;
48
+ case "iCs": return rPr?.italicCs;
49
+ case "caps": return rPr?.allCaps;
50
+ case "smallCaps": return rPr?.smallCaps;
51
+ case "strike": return rPr?.strike;
52
+ case "dstrike": return rPr?.doubleStrike;
53
+ case "vanish": return rPr?.hidden;
54
+ default: return toggle;
55
+ }
56
+ };
57
+ const underlineOf = (value) => value === void 0 || value === null || value === "none" ? null : value;
58
+ const vertAlignOf = (value) => value === "superscript" || value === "subscript" ? value : null;
59
+ const highlightOf = (value) => value === void 0 || value === null || value === "none" ? null : value;
60
+ /** `base` under one more style tier's resolved run formatting. */
61
+ const withStyleTier = (base, rPr) => {
62
+ if (rPr === void 0) return base;
63
+ const next = { ...base };
64
+ for (const toggle of TOGGLES) {
65
+ const stated = formattingToggle(rPr, toggle);
66
+ if (XOR_TOGGLES.has(toggle)) {
67
+ if (stated === true) next[toggle] = !base[toggle];
68
+ } else if (stated !== void 0) next[toggle] = stated;
69
+ }
70
+ if (rPr.underline !== void 0) next.u = underlineOf(rPr.underline.style);
71
+ if (rPr.vertAlign !== void 0) next.vertAlign = vertAlignOf(rPr.vertAlign);
72
+ if (rPr.highlight !== void 0) next.highlight = highlightOf(rPr.highlight);
73
+ return next;
74
+ };
75
+ /** The emphasis the document defaults give every run. */
76
+ const defaultsBaseline = (rPr) => withStyleTier(NO_EMPHASIS, rPr);
77
+ /**
78
+ * The emphasis every run of a paragraph starts from: the document defaults
79
+ * under the paragraph's style.
80
+ */
81
+ const paragraphBaseline = (style, defaults) => withStyleTier(defaults, style?.rPr);
82
+ /** `base` under a character style. */
83
+ const withCharacterStyle = (base, style) => withStyleTier(base, style?.rPr);
84
+ const OFF_VALUES = /* @__PURE__ */ new Set([
85
+ "0",
86
+ "false",
87
+ "off"
88
+ ]);
89
+ /** What a `w:rPr` states directly. */
90
+ const readDirectEmphasis = (rPr) => {
91
+ const override = {};
92
+ if (!rPr) return override;
93
+ for (const toggle of TOGGLES) {
94
+ const stated = wChildren(rPr, toggle).at(-1);
95
+ if (stated !== void 0) override[toggle] = !OFF_VALUES.has(wAttr(stated, "val") ?? "");
96
+ }
97
+ if (wChild(rPr, "u") !== null) override.u = underlineOf(wChildVal(rPr, "u") ?? "single");
98
+ if (wChild(rPr, "vertAlign") !== null) override.vertAlign = vertAlignOf(wChildVal(rPr, "vertAlign"));
99
+ if (wChild(rPr, "highlight") !== null) override.highlight = highlightOf(wChildVal(rPr, "highlight"));
100
+ return override;
101
+ };
102
+ const withOverride = (base, override) => ({
103
+ ...base,
104
+ ...override
105
+ });
106
+ /** The part of `effective` that differs from `baseline`, stated explicitly. */
107
+ const emphasisDeviation = (effective, baseline) => {
108
+ const deviation = {};
109
+ for (const toggle of TOGGLES) if (effective[toggle] !== baseline[toggle]) deviation[toggle] = effective[toggle];
110
+ if (effective.u !== baseline.u) deviation.u = effective.u;
111
+ if (effective.vertAlign !== baseline.vertAlign) deviation.vertAlign = effective.vertAlign;
112
+ if (effective.highlight !== baseline.highlight) deviation.highlight = effective.highlight;
113
+ return deviation;
114
+ };
115
+ const SIGNATURE_SEPARATOR = ";";
116
+ /** One canonical string per override; the empty string states nothing. */
117
+ const emphasisSignature = (override) => {
118
+ const parts = [];
119
+ for (const toggle of TOGGLES) {
120
+ const stated = override[toggle];
121
+ if (stated !== void 0) parts.push(`${toggle}=${stated ? "1" : "0"}`);
122
+ }
123
+ if (override.highlight !== void 0) parts.push(`highlight=${override.highlight ?? "none"}`);
124
+ if (override.u !== void 0) parts.push(`u=${override.u ?? "none"}`);
125
+ if (override.vertAlign !== void 0) parts.push(`vertAlign=${override.vertAlign ?? "baseline"}`);
126
+ return parts.join(SIGNATURE_SEPARATOR);
127
+ };
128
+ /** The highlight a signature states, or null when it states none. */
129
+ const signatureHighlight = (signature) => {
130
+ const color = signature.split(SIGNATURE_SEPARATOR).find((entry) => entry.startsWith("highlight="))?.slice(10);
131
+ return color === void 0 || color === "none" ? null : color;
132
+ };
133
+ /** A signature without its highlight entry. */
134
+ const signatureWithoutHighlight = (signature) => signature.split(SIGNATURE_SEPARATOR).filter((entry) => entry !== "" && !entry.startsWith("highlight=")).join(SIGNATURE_SEPARATOR);
135
+ /** Whether a signature states anything besides a highlight. */
136
+ const signatureHasEmphasis = (signature) => signature.split(SIGNATURE_SEPARATOR).some((entry) => entry !== "" && !entry.startsWith("highlight="));
137
+ const withSignatureHighlight = (signature, color) => {
138
+ const parts = signature.split(SIGNATURE_SEPARATOR).filter((entry) => entry !== "" && !entry.startsWith("highlight="));
139
+ const toggles = parts.filter((entry) => !/^(?:u|vertAlign)=/u.test(entry));
140
+ const rest = parts.filter((entry) => /^(?:u|vertAlign)=/u.test(entry));
141
+ return [
142
+ ...toggles,
143
+ `highlight=${color}`,
144
+ ...rest
145
+ ].join(SIGNATURE_SEPARATOR);
146
+ };
147
+ const onOff = (prefix, name, value) => value ? `<${prefix}:${name}/>` : `<${prefix}:${name} ${prefix}:val="0"/>`;
148
+ /**
149
+ * The `w:rPr` for a signature, children in `CT_RPr` order; the empty string
150
+ * when there is nothing to state.
151
+ */
152
+ const runPropertiesXml = ({ prefix, signature, rStyle, escapeAttribute }) => {
153
+ const stated = new Map(signature.split(SIGNATURE_SEPARATOR).filter((entry) => entry !== "").map((entry) => {
154
+ const equals = entry.indexOf("=");
155
+ return [entry.slice(0, equals), entry.slice(equals + 1)];
156
+ }));
157
+ const out = [];
158
+ if (rStyle) out.push(`<${prefix}:rStyle ${prefix}:val="${escapeAttribute(rStyle)}"/>`);
159
+ for (const name of TOGGLES) {
160
+ const value = stated.get(name);
161
+ if (value !== void 0) out.push(onOff(prefix, name, value === "1"));
162
+ }
163
+ for (const name of [
164
+ "highlight",
165
+ "u",
166
+ "vertAlign"
167
+ ]) {
168
+ const value = stated.get(name);
169
+ if (value !== void 0) out.push(`<${prefix}:${name} ${prefix}:val="${escapeAttribute(value)}"/>`);
170
+ }
171
+ return out.length === 0 ? "" : `<${prefix}:rPr>${out.join("")}</${prefix}:rPr>`;
172
+ };
173
+ export { NO_EMPHASIS, defaultsBaseline, emphasisDeviation, emphasisSignature, paragraphBaseline, readDirectEmphasis, runPropertiesXml, signatureHasEmphasis, signatureHighlight, signatureWithoutHighlight, withCharacterStyle, withOverride, withSignatureHighlight };
@@ -0,0 +1,22 @@
1
+ /** A template's inventory: what a plan may name when it places blocks onto it. */
2
+ import { AnalyzedDocument } from "./blocks.js";
3
+ import { StoryField } from "./story.js";
4
+ import { DocxTemplateInspection, TemplatePlanError } from "./types.js";
5
+ import { RawPart } from "./xml.js";
6
+ import { Result } from "better-result";
7
+ /** The fields of a part other than the main document, read as one story. */
8
+ export declare const partFields: (part: RawPart) => StoryField[];
9
+ /** The header and footer parts the main document names, in relationship order. */
10
+ export declare const headerFooterPaths: ({ pkg }: AnalyzedDocument) => string[];
11
+ /**
12
+ * The header and footer parts of a package, read. A part the document names
13
+ * that has no readable root is a refusal: skipping it would hide its fields.
14
+ */
15
+ export declare const readHeaderFooterParts: (analyzed: AnalyzedDocument) => Promise<Result<RawPart[], TemplatePlanError>>;
16
+ /** Build the inspection of an analysed template. */
17
+ export declare const inspectAnalyzedTemplate: (analyzed: AnalyzedDocument) => Promise<Result<DocxTemplateInspection, TemplatePlanError>>;
18
+ /**
19
+ * Read a template into what a plan may name: the block manifest plus its
20
+ * styles, numbering definitions, fields, sections and bookmarks.
21
+ */
22
+ export declare const inspectDocxTemplate: (docx: Uint8Array) => Promise<Result<DocxTemplateInspection, TemplatePlanError>>;
@@ -0,0 +1,177 @@
1
+ import { RELATIONSHIP_TYPES } from "../../relsParser.js";
2
+ import { parseSectionProperties } from "../../sectionParser.js";
3
+ import { analyzeDocument, styleOutlineLevel } from "./blocks.js";
4
+ import { styleNumbering } from "./labels.js";
5
+ import { guarded, readPartText } from "./package.js";
6
+ import { createStoryState, endStory, readParagraph, walkBlocks } from "./story.js";
7
+ import { TemplatePlanError } from "./types.js";
8
+ import { isW, readRawPart, wAttr, walkElements } from "./xml.js";
9
+ import { Result } from "better-result";
10
+ // src/docx/server/templatePlan/inspect.ts
11
+ /** A template's inventory: what a plan may name when it places blocks onto it. */
12
+ const DEFAULT_LEVEL_START = 1;
13
+ const inspectStyles = ({ styles, numbering }) => [...styles.values()].map((style) => {
14
+ const bound = styleNumbering(style.styleId, styles, numbering);
15
+ return {
16
+ styleId: style.styleId,
17
+ name: style.name ?? null,
18
+ type: style.type,
19
+ basedOn: style.basedOn ?? null,
20
+ numPr: bound?.kind === "reference" ? {
21
+ numId: bound.numId,
22
+ ilvl: bound.ilvl ?? 0
23
+ } : null,
24
+ outlineLvl: styleOutlineLevel(style),
25
+ isDefault: style.default === true
26
+ };
27
+ });
28
+ const inspectNumbering = ({ numbering }) => ({
29
+ abstractNums: (numbering?.definitions.abstractNums ?? []).map(({ abstractNumId, levels }) => ({
30
+ abstractNumId,
31
+ levels: levels.map((level) => ({
32
+ ilvl: level.ilvl,
33
+ numFmt: level.numFmt,
34
+ lvlText: level.lvlText,
35
+ start: level.start ?? DEFAULT_LEVEL_START,
36
+ suff: level.suffix ?? "tab",
37
+ pStyle: level.pStyle ?? null
38
+ }))
39
+ })),
40
+ nums: (numbering?.definitions.nums ?? []).map(({ numId, abstractNumId, levelOverrides }) => ({
41
+ numId,
42
+ abstractNumId,
43
+ overrides: (levelOverrides ?? []).map(({ ilvl, startOverride }) => ({
44
+ ilvl,
45
+ startOverride: startOverride ?? null
46
+ }))
47
+ }))
48
+ });
49
+ const inspectSections = ({ story, pkg }) => story.sections.map((sectPr, index) => {
50
+ const properties = parseSectionProperties(sectPr);
51
+ const partOf = (rId) => {
52
+ const relationship = pkg.documentRelationships.get(rId);
53
+ return relationship === void 0 ? null : pkg.resolveDocumentTarget(relationship.target);
54
+ };
55
+ return {
56
+ index,
57
+ orientation: properties.orientation ?? "portrait",
58
+ size: {
59
+ width: properties.pageWidth ?? null,
60
+ height: properties.pageHeight ?? null
61
+ },
62
+ margins: {
63
+ top: properties.marginTop ?? null,
64
+ right: properties.marginRight ?? null,
65
+ bottom: properties.marginBottom ?? null,
66
+ left: properties.marginLeft ?? null
67
+ },
68
+ headers: (properties.headerReferences ?? []).map(({ type, rId }) => ({
69
+ type,
70
+ part: partOf(rId)
71
+ })),
72
+ footers: (properties.footerReferences ?? []).map(({ type, rId }) => ({
73
+ type,
74
+ part: partOf(rId)
75
+ }))
76
+ };
77
+ });
78
+ const fieldOf = (part, { instruction, kind, result }) => ({
79
+ part,
80
+ instruction: instruction.trim(),
81
+ kind,
82
+ result
83
+ });
84
+ /** The fields of a part other than the main document, read as one story. */
85
+ const partFields = (part) => {
86
+ const state = createStoryState();
87
+ const readUnder = (container) => {
88
+ walkBlocks(container, {
89
+ paragraph: (paragraph) => {
90
+ readParagraph(paragraph, state);
91
+ },
92
+ tableStart: () => {},
93
+ cellStart: () => {},
94
+ tableEnd: () => {},
95
+ unread: () => {},
96
+ tracked: () => {}
97
+ });
98
+ };
99
+ if (isW(part.root, "footnotes") || isW(part.root, "endnotes")) {
100
+ for (const note of part.root.elements ?? []) if (note.type === "element") {
101
+ readUnder(note);
102
+ endStory(state);
103
+ }
104
+ } else readUnder(part.root);
105
+ return state.fields;
106
+ };
107
+ const bookmarksOf = (part) => {
108
+ const bookmarks = [];
109
+ walkElements(part.root, (element) => {
110
+ if (isW(element, "bookmarkStart")) bookmarks.push({
111
+ name: wAttr(element, "name") ?? "",
112
+ id: wAttr(element, "id") ?? "",
113
+ part: part.path
114
+ });
115
+ });
116
+ return bookmarks;
117
+ };
118
+ /** The header and footer parts the main document names, in relationship order. */
119
+ const headerFooterPaths = ({ pkg }) => [...pkg.documentRelationships.values()].filter(({ type, targetMode }) => (type === RELATIONSHIP_TYPES.header || type === RELATIONSHIP_TYPES.footer) && targetMode !== "External").map(({ target }) => pkg.resolveDocumentTarget(target)).filter((path) => pkg.paths.has(path));
120
+ /**
121
+ * The header and footer parts of a package, read. A part the document names
122
+ * that has no readable root is a refusal: skipping it would hide its fields.
123
+ */
124
+ const readHeaderFooterParts = async (analyzed) => {
125
+ const parts = [];
126
+ for (const path of headerFooterPaths(analyzed)) {
127
+ const xml = await readPartText(analyzed.pkg, path);
128
+ if (Result.isError(xml)) return xml;
129
+ const part = xml.value === null ? null : readRawPart(path, xml.value);
130
+ if (part === null) return Result.err(new TemplatePlanError({
131
+ message: `The part ${path} could not be read.`,
132
+ code: "xml-unreadable",
133
+ part: path
134
+ }));
135
+ parts.push(part);
136
+ }
137
+ return Result.ok(parts);
138
+ };
139
+ /** Build the inspection of an analysed template. */
140
+ const inspectAnalyzedTemplate = async (analyzed) => {
141
+ const { pkg, story, document, footnotes, endnotes, manifest } = analyzed;
142
+ const fields = story.state.fields.map((field) => {
143
+ const inspected = fieldOf(pkg.documentPath, field);
144
+ const block = story.paragraphs[field.paragraphOrdinal];
145
+ if (block !== void 0) inspected.blockId = block.topLevelId;
146
+ const endBlock = story.paragraphs[field.endParagraphOrdinal];
147
+ if (endBlock !== void 0 && field.closed) inspected.endBlockId = endBlock.topLevelId;
148
+ return inspected;
149
+ });
150
+ const bookmarks = bookmarksOf(document);
151
+ const headersAndFooters = await readHeaderFooterParts(analyzed);
152
+ if (Result.isError(headersAndFooters)) return headersAndFooters;
153
+ const others = [...headersAndFooters.value];
154
+ for (const notes of [footnotes, endnotes]) if (notes.part !== null) others.push(notes.part);
155
+ for (const part of others) {
156
+ fields.push(...partFields(part).map((field) => fieldOf(part.path, field)));
157
+ bookmarks.push(...bookmarksOf(part));
158
+ }
159
+ return Result.ok({
160
+ ...manifest,
161
+ styles: inspectStyles(analyzed),
162
+ numbering: inspectNumbering(analyzed),
163
+ fields,
164
+ sections: inspectSections(analyzed),
165
+ bookmarks
166
+ });
167
+ };
168
+ /**
169
+ * Read a template into what a plan may name: the block manifest plus its
170
+ * styles, numbering definitions, fields, sections and bookmarks.
171
+ */
172
+ const inspectDocxTemplate = async (docx) => await guarded(async () => {
173
+ const analyzed = await analyzeDocument(docx);
174
+ if (Result.isError(analyzed)) return Result.err(analyzed.error);
175
+ return await inspectAnalyzedTemplate(analyzed.value);
176
+ });
177
+ export { headerFooterPaths, inspectAnalyzedTemplate, inspectDocxTemplate, partFields, readHeaderFooterParts };
@@ -0,0 +1,36 @@
1
+ import { NumberingMap } from "../../numberingParser.js";
2
+ import { StyleMap } from "../../styleParser.js";
3
+ import { DocxBlockNumbering } from "./types.js";
4
+ import { ParagraphNumberingOverride } from "@stll/docx-core/model";
5
+ export type ParagraphLabel = {
6
+ label: string | null;
7
+ numbering: DocxBlockNumbering | null;
8
+ /**
9
+ * The label as a `REF \n \t` field shows it: number parts and delimiters,
10
+ * without the words of the level text and without a trailing period.
11
+ */
12
+ numberOnly: string | null;
13
+ /** The label as a `REF \n` field shows it: without a trailing period. */
14
+ paragraphNumber: string | null;
15
+ };
16
+ /**
17
+ * The numbering a style binds its paragraphs to. A style that names a list
18
+ * without a level takes the level of that list which names the style back
19
+ * (`w:pStyle`), as the consumer that wrote it does.
20
+ */
21
+ export declare const styleNumbering: (styleId: string | null, styles: StyleMap, numbering: NumberingMap | null) => ParagraphNumberingOverride | undefined;
22
+ export type LabelCounter = {
23
+ next: (paragraph: {
24
+ styleId: string | null;
25
+ numPr: ParagraphNumberingOverride | undefined;
26
+ }) => ParagraphLabel;
27
+ };
28
+ type LabelCounterOptions = {
29
+ numbering: NumberingMap | null;
30
+ styles: StyleMap;
31
+ /** The style a paragraph without `w:pStyle` takes. */
32
+ defaultStyleId: string | null;
33
+ };
34
+ /** A counter over one story; call `next` for every paragraph in document order. */
35
+ export declare const createLabelCounter: ({ numbering, styles, defaultStyleId }: LabelCounterOptions) => LabelCounter;
36
+ export {};
@@ -0,0 +1,126 @@
1
+ import { computeListMarker } from "../../listMarkerComputation.js";
2
+ import { resolveListTemplateWithComponents } from "../../listTemplate.js";
3
+ import { computeListRendering } from "../../numberingParser.js";
4
+ import { mergeParagraphNumbering, paragraphNumberingReference, resolveParagraphNumbering } from "../../numberingReference.js";
5
+ import { finalizeParagraphFormatting } from "@stll/docx-core";
6
+ // src/docx/server/templatePlan/labels.ts
7
+ /**
8
+ * The automatic list label each paragraph of a story renders, counted with
9
+ * the same marker code the document parser uses.
10
+ */
11
+ const NO_LABEL = {
12
+ label: null,
13
+ numbering: null,
14
+ numberOnly: null,
15
+ paragraphNumber: null
16
+ };
17
+ /**
18
+ * The numbering a style binds its paragraphs to. A style that names a list
19
+ * without a level takes the level of that list which names the style back
20
+ * (`w:pStyle`), as the consumer that wrote it does.
21
+ */
22
+ const styleNumbering = (styleId, styles, numbering) => {
23
+ if (styleId === null) return;
24
+ const stated = styles.get(styleId)?.pPr?.numPr;
25
+ if (stated === void 0 || stated.kind !== "reference" || stated.ilvl !== void 0 || numbering === null) return stated;
26
+ const abstractNumId = numbering.getAbstractNumId(stated.numId);
27
+ const abstract = abstractNumId === null ? null : numbering.getAbstract(abstractNumId);
28
+ const levelByStyle = new Map((abstract?.levels ?? []).flatMap(({ pStyle, ilvl }) => pStyle === void 0 ? [] : [[pStyle, ilvl]]));
29
+ let cursor = styleId;
30
+ const seen = /* @__PURE__ */ new Set();
31
+ while (cursor !== void 0 && !seen.has(cursor)) {
32
+ seen.add(cursor);
33
+ const ilvl = levelByStyle.get(cursor);
34
+ if (ilvl !== void 0) return paragraphNumberingReference({
35
+ numId: stated.numId,
36
+ ilvl
37
+ });
38
+ cursor = styles.get(cursor)?.basedOn;
39
+ }
40
+ return stated;
41
+ };
42
+ const stripTrailingPeriods = (value) => value.replace(/\.+$/u, "");
43
+ /** Drop the literal runs of a level text that hold a letter; keep delimiters. */
44
+ const numberOnlyLabel = ({ template, counters, levelFormats, forceDecimal }) => {
45
+ const { value, components } = resolveListTemplateWithComponents({
46
+ template,
47
+ counters,
48
+ levelFormats,
49
+ forceDecimal
50
+ });
51
+ let out = "";
52
+ let cursor = 0;
53
+ const literal = (text) => /\p{L}/u.test(text) ? "" : text;
54
+ for (const { start, end } of components) {
55
+ out += literal(value.slice(cursor, start)) + value.slice(start, end);
56
+ cursor = end;
57
+ }
58
+ out += literal(value.slice(cursor));
59
+ return stripTrailingPeriods(out.trim());
60
+ };
61
+ /** A counter over one story; call `next` for every paragraph in document order. */
62
+ const createLabelCounter = ({ numbering, styles, defaultStyleId }) => {
63
+ const counters = {
64
+ numbering,
65
+ listCounters: /* @__PURE__ */ new Map(),
66
+ abstractCounters: /* @__PURE__ */ new Map(),
67
+ restartedNumIds: /* @__PURE__ */ new Set(),
68
+ previousList: {
69
+ abstractNumId: null,
70
+ fromStyle: false,
71
+ numId: null
72
+ }
73
+ };
74
+ return { next: ({ styleId, numPr }) => {
75
+ const fromStyle = styleNumbering(styleId ?? defaultStyleId, styles, numbering);
76
+ const inherits = fromStyle !== void 0 && (numPr === void 0 || numPr.kind === "levelOnly");
77
+ const effective = inherits ? mergeParagraphNumbering(fromStyle, numPr) : numPr;
78
+ const resolved = resolveParagraphNumbering(effective);
79
+ const listRendering = numbering !== null && resolved.kind === "reference" ? computeListRendering({
80
+ numId: resolved.numId,
81
+ ilvl: resolved.ilvl
82
+ }, numbering) : null;
83
+ const formatting = finalizeParagraphFormatting({
84
+ ...numPr === void 0 ? {} : { numPr },
85
+ ...inherits ? { numPrFromStyle: fromStyle } : {}
86
+ });
87
+ const paragraph = {
88
+ type: "paragraph",
89
+ content: [],
90
+ ...formatting === void 0 ? {} : { formatting },
91
+ ...listRendering === null ? {} : { listRendering }
92
+ };
93
+ const template = listRendering?.marker ?? "";
94
+ const advance = computeListMarker(paragraph, counters);
95
+ if (advance === null || listRendering === null || numbering === null || resolved.kind !== "reference") return NO_LABEL;
96
+ const abstractNumId = numbering.getAbstractNumId(resolved.numId);
97
+ const label = listRendering.marker;
98
+ const numberingInfo = abstractNumId === null ? null : {
99
+ numId: resolved.numId,
100
+ ilvl: resolved.ilvl,
101
+ abstractNumId
102
+ };
103
+ if (listRendering.markerHidden === true) return {
104
+ ...NO_LABEL,
105
+ numbering: numberingInfo
106
+ };
107
+ if (listRendering.isBullet) return {
108
+ label,
109
+ numbering: numberingInfo,
110
+ numberOnly: null,
111
+ paragraphNumber: null
112
+ };
113
+ return {
114
+ label,
115
+ numbering: numberingInfo,
116
+ paragraphNumber: stripTrailingPeriods(label.trim()),
117
+ numberOnly: numberOnlyLabel({
118
+ template,
119
+ counters: advance.counters,
120
+ levelFormats: listRendering.levelNumFmts,
121
+ forceDecimal: listRendering.isLegal === true
122
+ })
123
+ };
124
+ } };
125
+ };
126
+ export { createLabelCounter, styleNumbering };
@@ -0,0 +1,34 @@
1
+ /** A DOCX package opened for reading: its parts, and the parts its main document names. */
2
+ import { document_d_exports } from "../../../types/document.js";
3
+ import { TemplatePlanError } from "./types.js";
4
+ import { Result } from "better-result";
5
+ export declare const sha256Hex: (bytes: Uint8Array | string) => string;
6
+ export declare const relationshipsPathFor: (partPath: string) => string;
7
+ export type DocumentPartKind = "styles" | "numbering" | "footnotes" | "endnotes" | "settings" | "comments";
8
+ export type LoadedPackage = {
9
+ bytes: Uint8Array;
10
+ sha256: string;
11
+ paths: ReadonlySet<string>;
12
+ readText: (path: string) => Promise<string | null>;
13
+ readBytes: (path: string) => Promise<Uint8Array | null>;
14
+ documentPath: string;
15
+ documentXml: string;
16
+ documentRelationshipsPath: string;
17
+ documentRelationships: document_d_exports.RelationshipMap;
18
+ /** The path of the part the main document names for `kind`, when it names one. */
19
+ partPath: (kind: DocumentPartKind) => string | null;
20
+ /** The path the main document names for `kind` when the package holds no such entry. */
21
+ missingPartPath: (kind: DocumentPartKind) => string | null;
22
+ /** The package path a relationship of the main document points at. */
23
+ resolveDocumentTarget: (target: string) => string;
24
+ };
25
+ /** Open `bytes` within folio's archive and XML limits. */
26
+ export declare const loadPackage: (bytes: Uint8Array) => Promise<Result<LoadedPackage, TemplatePlanError>>;
27
+ /** Read an XML part, refusing one the archive could not hand out. */
28
+ export declare const readPartText: (pkg: LoadedPackage, path: string | null) => Promise<Result<string | null, TemplatePlanError>>;
29
+ /**
30
+ * Run one public entry of the module. Whatever a hostile or malformed
31
+ * package makes a shared helper throw comes back as a typed refusal, so no
32
+ * caller has to guard the call.
33
+ */
34
+ export declare const guarded: <Value>(run: () => Promise<Result<Value, TemplatePlanError>>) => Promise<Result<Value, TemplatePlanError>>;
@@ -0,0 +1,99 @@
1
+ import { RELATIONSHIP_TYPES, parseRelationships, resolveRelativePath } from "../../relsParser.js";
2
+ import { loadDocxArchive } from "../boundedArchive.js";
3
+ import { TemplatePlanError } from "./types.js";
4
+ import { Result } from "better-result";
5
+ import { createHash } from "node:crypto";
6
+ // src/docx/server/templatePlan/package.ts
7
+ /** A DOCX package opened for reading: its parts, and the parts its main document names. */
8
+ const sha256Hex = (bytes) => createHash("sha256").update(bytes).digest("hex");
9
+ const relationshipsPathFor = (partPath) => {
10
+ const slash = partPath.lastIndexOf("/");
11
+ return `${slash === -1 ? "" : `${partPath.slice(0, slash)}/`}_rels/${partPath.slice(slash + 1)}.rels`;
12
+ };
13
+ const PACKAGE_RELATIONSHIPS_PATH = "_rels/.rels";
14
+ const DEFAULT_DOCUMENT_PATH = "word/document.xml";
15
+ /** Open `bytes` within folio's archive and XML limits. */
16
+ const loadPackage = async (bytes) => {
17
+ const opened = await Result.tryPromise({
18
+ try: async () => {
19
+ const archive = await loadDocxArchive(bytes);
20
+ const paths = new Set(archive.entries);
21
+ const officeDocument = [...parseRelationships(await archive.readEntryString(PACKAGE_RELATIONSHIPS_PATH) ?? "").values()].find(({ type }) => type === RELATIONSHIP_TYPES.officeDocument);
22
+ const documentPath = officeDocument === void 0 ? DEFAULT_DOCUMENT_PATH : resolveRelativePath(PACKAGE_RELATIONSHIPS_PATH, officeDocument.target);
23
+ const documentXml = await archive.readEntryString(documentPath);
24
+ const documentRelationshipsPath = relationshipsPathFor(documentPath);
25
+ return {
26
+ archive,
27
+ paths,
28
+ documentPath,
29
+ documentXml,
30
+ documentRelationshipsPath,
31
+ documentRelationships: parseRelationships(await archive.readEntryString(documentRelationshipsPath) ?? "")
32
+ };
33
+ },
34
+ catch: (cause) => new TemplatePlanError({
35
+ message: "The DOCX package could not be read.",
36
+ code: "archive-unreadable",
37
+ cause
38
+ })
39
+ });
40
+ if (Result.isError(opened)) return opened;
41
+ const { archive, paths, documentPath, documentXml, documentRelationshipsPath, documentRelationships } = opened.value;
42
+ if (documentXml === null) return Result.err(new TemplatePlanError({
43
+ message: "The DOCX package has no main document part.",
44
+ code: "part-missing",
45
+ part: documentPath
46
+ }));
47
+ const resolveDocumentTarget = (target) => resolveRelativePath(documentRelationshipsPath, target);
48
+ const declaredPath = (kind) => {
49
+ const relationship = [...documentRelationships.values()].find(({ type, targetMode }) => type === RELATIONSHIP_TYPES[kind] && targetMode !== "External");
50
+ return relationship === void 0 ? null : resolveDocumentTarget(relationship.target);
51
+ };
52
+ return Result.ok({
53
+ bytes,
54
+ sha256: sha256Hex(bytes),
55
+ paths,
56
+ readText: async (path) => await archive.readEntryString(path),
57
+ readBytes: async (path) => await archive.readEntryUint8(path),
58
+ documentPath,
59
+ documentXml,
60
+ documentRelationshipsPath,
61
+ documentRelationships,
62
+ partPath: (kind) => {
63
+ const path = declaredPath(kind);
64
+ return path !== null && paths.has(path) ? path : null;
65
+ },
66
+ missingPartPath: (kind) => {
67
+ const path = declaredPath(kind);
68
+ return path === null || paths.has(path) ? null : path;
69
+ },
70
+ resolveDocumentTarget
71
+ });
72
+ };
73
+ /** Read an XML part, refusing one the archive could not hand out. */
74
+ const readPartText = async (pkg, path) => {
75
+ if (path === null) return Result.ok(null);
76
+ return await Result.tryPromise({
77
+ try: async () => await pkg.readText(path),
78
+ catch: (cause) => new TemplatePlanError({
79
+ message: `The part ${path} could not be read.`,
80
+ code: "xml-unreadable",
81
+ part: path,
82
+ cause
83
+ })
84
+ });
85
+ };
86
+ /**
87
+ * Run one public entry of the module. Whatever a hostile or malformed
88
+ * package makes a shared helper throw comes back as a typed refusal, so no
89
+ * caller has to guard the call.
90
+ */
91
+ const guarded = async (run) => Result.flatten(await Result.tryPromise({
92
+ try: run,
93
+ catch: (cause) => cause instanceof TemplatePlanError ? cause : new TemplatePlanError({
94
+ message: "The package could not be processed.",
95
+ code: "xml-unreadable",
96
+ cause
97
+ })
98
+ }));
99
+ export { guarded, loadPackage, readPartText, relationshipsPathFor, sha256Hex };