@stll/folio-core 0.74.0 → 0.76.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 (174) hide show
  1. package/dist/ai-edits/clean-text.d.ts +4 -1
  2. package/dist/ai-edits/clean-text.js +21 -7
  3. package/dist/ai-edits/headless.d.ts +7 -3
  4. package/dist/ai-edits/headless.js +36 -21
  5. package/dist/ai-edits/note-references.d.ts +1 -1
  6. package/dist/ai-edits/note-references.js +1 -1
  7. package/dist/ai-edits/pending-suggestions.d.ts +9 -7
  8. package/dist/ai-edits/pending-suggestions.js +135 -90
  9. package/dist/ai-edits/pendingJoin.d.ts +5 -1
  10. package/dist/ai-edits/pendingJoin.js +6 -2
  11. package/dist/ai-edits/read.js +9 -3
  12. package/dist/ai-edits/retired-comment-receipts.d.ts +2 -2
  13. package/dist/ai-edits/retired-comment-receipts.js +3 -18
  14. package/dist/ai-edits/tracked-batch-fidelity.d.ts +6 -10
  15. package/dist/ai-edits/tracked-batch-fidelity.js +3 -182
  16. package/dist/ai-edits/types.d.ts +9 -4
  17. package/dist/canonical/batchCommentReferences.js +2 -1
  18. package/dist/canonical/canonicalBatchReview.d.ts +4 -1
  19. package/dist/canonical/canonicalBatchReview.js +37 -22
  20. package/dist/canonical/canonicalComments.d.ts +6 -2
  21. package/dist/canonical/canonicalComments.js +16 -6
  22. package/dist/canonical/canonicalCompilerRefusal.d.ts +2 -4
  23. package/dist/canonical/canonicalCompilerRefusal.js +20 -14
  24. package/dist/canonical/canonicalPublicOperations.js +231 -79
  25. package/dist/canonical/canonicalRefusalGrounds.d.ts +4 -0
  26. package/dist/canonical/canonicalRefusalGrounds.js +56 -0
  27. package/dist/canonical/canonicalSession.d.ts +12 -6
  28. package/dist/canonical/canonicalSession.js +119 -122
  29. package/dist/canonical/canonicalTrackedBatchFidelity.js +3 -3
  30. package/dist/compare/inline-atoms.d.ts +35 -41
  31. package/dist/compare/inline-atoms.js +2 -465
  32. package/dist/compare/section-boundary-properties.d.ts +3 -30
  33. package/dist/compare/section-boundary-properties.js +4 -72
  34. package/dist/controller/canonicalClipboard.d.ts +1 -1
  35. package/dist/controller/canonicalClipboard.js +110 -55
  36. package/dist/controller/canonicalComposition.d.ts +1 -1
  37. package/dist/controller/canonicalComposition.js +5 -5
  38. package/dist/controller/canonicalContentControlValue.js +7 -7
  39. package/dist/controller/canonicalInput.d.ts +4 -2
  40. package/dist/controller/canonicalInput.js +33 -16
  41. package/dist/controller/canonicalReview.d.ts +21 -0
  42. package/dist/controller/canonicalReview.js +44 -9
  43. package/dist/controller/canonicalStoryEditor.d.ts +2 -3
  44. package/dist/controller/canonicalStoryEditor.js +43 -25
  45. package/dist/controller/canonicalStructure.d.ts +19 -3
  46. package/dist/controller/canonicalStructure.js +182 -58
  47. package/dist/controller/deferredDisplayListPainter.d.ts +8 -0
  48. package/dist/controller/deferredDisplayListPainter.js +34 -0
  49. package/dist/controller/folioEditor.js +4 -2
  50. package/dist/controller/fontReadiness.js +50 -23
  51. package/dist/controller/headerFooterEditorManager.js +3 -17
  52. package/dist/controller/hiddenEditorApi.d.ts +24 -3
  53. package/dist/controller/hiddenEditorApi.js +2 -0
  54. package/dist/controller/hiddenEditorManager.js +135 -207
  55. package/dist/controller/layoutPipeline.d.ts +4 -86
  56. package/dist/controller/layoutPipeline.js +8 -727
  57. package/dist/controller/layoutPipelineExecution.d.ts +94 -0
  58. package/dist/controller/layoutPipelineExecution.js +730 -0
  59. package/dist/controller/noteEditorManager.js +3 -16
  60. package/dist/docx/blockContentParser.d.ts +1 -3
  61. package/dist/docx/blockContentParser.js +3 -10
  62. package/dist/docx/bulletMarkers.d.ts +8 -0
  63. package/dist/docx/bulletMarkers.js +9 -1
  64. package/dist/docx/canonicalSave.d.ts +4 -3
  65. package/dist/docx/canonicalSave.js +4 -3
  66. package/dist/docx/canonicalSessionInput.js +25 -11
  67. package/dist/docx/ensureParaIds.d.ts +31 -0
  68. package/dist/docx/ensureParaIds.js +57 -32
  69. package/dist/docx/ensureUniqueControlIds.d.ts +13 -0
  70. package/dist/docx/ensureUniqueControlIds.js +47 -29
  71. package/dist/docx/ensureUniqueRevisionIds.d.ts +13 -0
  72. package/dist/docx/ensureUniqueRevisionIds.js +52 -29
  73. package/dist/docx/listMarkerComputation.d.ts +24 -17
  74. package/dist/docx/listMarkerComputation.js +31 -60
  75. package/dist/docx/listModelNormalization.js +8 -15
  76. package/dist/docx/rezip.d.ts +16 -3
  77. package/dist/docx/rezip.js +35 -9
  78. package/dist/docx/selectiveSave.js +13 -5
  79. package/dist/docx/server/templatePlan/apply.js +96 -7
  80. package/dist/docx/server/templatePlan/blocks.d.ts +70 -3
  81. package/dist/docx/server/templatePlan/blocks.js +272 -10
  82. package/dist/docx/server/templatePlan/builders.d.ts +52 -2
  83. package/dist/docx/server/templatePlan/builders.js +224 -5
  84. package/dist/docx/server/templatePlan/effects.d.ts +27 -0
  85. package/dist/docx/server/templatePlan/effects.js +188 -0
  86. package/dist/docx/server/templatePlan/emit.d.ts +4 -1
  87. package/dist/docx/server/templatePlan/emit.js +46 -2
  88. package/dist/docx/server/templatePlan/inspect.js +39 -52
  89. package/dist/docx/server/templatePlan/labels.d.ts +7 -2
  90. package/dist/docx/server/templatePlan/labels.js +120 -23
  91. package/dist/docx/server/templatePlan/plan.d.ts +24 -3
  92. package/dist/docx/server/templatePlan/plan.js +54 -15
  93. package/dist/docx/server/templatePlan/planShape.js +76 -22
  94. package/dist/docx/server/templatePlan/revisions.d.ts +46 -0
  95. package/dist/docx/server/templatePlan/revisions.js +407 -0
  96. package/dist/docx/server/templatePlan/story.d.ts +23 -1
  97. package/dist/docx/server/templatePlan/story.js +60 -2
  98. package/dist/docx/server/templatePlan/types.d.ts +354 -16
  99. package/dist/docx/server/templatePlan/verify.js +164 -14
  100. package/dist/docx/server/templatePlan/xml.d.ts +3 -0
  101. package/dist/docx/server/templatePlan/xml.js +4 -1
  102. package/dist/i18n/messages/ar.gen.js +1 -0
  103. package/dist/i18n/messages/catalogs.gen.d.ts +17 -0
  104. package/dist/i18n/messages/catalogs.gen.js +17 -0
  105. package/dist/i18n/messages/cs.gen.js +1 -0
  106. package/dist/i18n/messages/de.gen.js +1 -0
  107. package/dist/i18n/messages/en.gen.js +1 -0
  108. package/dist/i18n/messages/es.gen.js +1 -0
  109. package/dist/i18n/messages/et.gen.js +1 -0
  110. package/dist/i18n/messages/fr.gen.js +1 -0
  111. package/dist/i18n/messages/he.gen.js +1 -0
  112. package/dist/i18n/messages/hi.gen.js +1 -0
  113. package/dist/i18n/messages/hu.gen.js +1 -0
  114. package/dist/i18n/messages/lt.gen.js +1 -0
  115. package/dist/i18n/messages/lv.gen.js +1 -0
  116. package/dist/i18n/messages/messages.gen.d.ts +1 -0
  117. package/dist/i18n/messages/pl.gen.js +1 -0
  118. package/dist/i18n/messages/pt-BR.gen.js +1 -0
  119. package/dist/i18n/messages/sk.gen.js +1 -0
  120. package/dist/i18n/messages/tr.gen.js +1 -0
  121. package/dist/i18n/messages/zh-CN.gen.js +1 -0
  122. package/dist/internal/revisionResolutionStep.d.ts +2 -31
  123. package/dist/internal/revisionResolutionStep.js +2 -171
  124. package/dist/layout-bridge/convert/toFlowBlocks.js +0 -12
  125. package/dist/layout-bridge/convert/topLevelConversion.js +1 -10
  126. package/dist/prosemirror/commands/comments.d.ts +6 -234
  127. package/dist/prosemirror/commands/comments.js +5 -2464
  128. package/dist/prosemirror/commands/index.d.ts +4 -2
  129. package/dist/prosemirror/commands/index.js +4 -2
  130. package/dist/prosemirror/commands/tableCellMergeResolution.d.ts +1 -11
  131. package/dist/prosemirror/commands/tableCellMergeResolution.js +3 -154
  132. package/dist/prosemirror/extensions/features/ImagePasteExtension.js +1 -1
  133. package/dist/prosemirror/extensions/marks/HyperlinkExtension.js +6 -8
  134. package/dist/prosemirror/hyperlinkRemoval.d.ts +11 -8
  135. package/dist/prosemirror/hyperlinkRemoval.js +24 -15
  136. package/dist/prosemirror/listMarker.d.ts +1 -6
  137. package/dist/prosemirror/listMarker.js +4 -56
  138. package/dist/prosemirror/paraIds.d.ts +1 -14
  139. package/dist/prosemirror/paraIds.js +1 -14
  140. package/dist/prosemirror/paragraphMarkJoin.d.ts +0 -16
  141. package/dist/prosemirror/paragraphMarkJoin.js +3 -46
  142. package/dist/prosemirror/projectionReview.d.ts +49 -0
  143. package/dist/prosemirror/projectionReview.js +292 -0
  144. package/dist/prosemirror/rebaseParagraphRunFormatting.d.ts +1 -13
  145. package/dist/prosemirror/rebaseParagraphRunFormatting.js +1 -16
  146. package/dist/prosemirror/replacedAnnotations.d.ts +2 -5
  147. package/dist/prosemirror/replacedAnnotations.js +1 -10
  148. package/dist/prosemirror/revisionCarriers.d.ts +9 -1
  149. package/dist/prosemirror/revisionCarriers.js +15 -1
  150. package/dist/prosemirror/revisionRangeQueries.d.ts +32 -0
  151. package/dist/prosemirror/revisionRangeQueries.js +76 -0
  152. package/dist/prosemirror/runFormattingMarkNames.d.ts +1 -1
  153. package/dist/prosemirror/runFormattingMarkNames.js +1 -1
  154. package/dist/prosemirror/suggestionQueries.d.ts +114 -0
  155. package/dist/prosemirror/suggestionQueries.js +320 -0
  156. package/dist/prosemirror/tableGridMutation.d.ts +1 -16
  157. package/dist/prosemirror/tableGridMutation.js +1 -78
  158. package/dist/prosemirror/tableRowRevisionOwnership.d.ts +18 -0
  159. package/dist/prosemirror/tableRowRevisionOwnership.js +7 -0
  160. package/dist/prosemirror/utils/extractTrackedChanges.js +14 -4
  161. package/dist/server.d.ts +2 -2
  162. package/dist/types/canonicalCapabilities.d.ts +40 -69
  163. package/dist/types/canonicalCapabilities.js +51 -65
  164. package/dist/types/canonicalComments.d.ts +2 -2
  165. package/dist/types/canonicalSections.d.ts +2 -2
  166. package/dist/utils/clipboard.d.ts +2 -28
  167. package/dist/utils/clipboard.js +1 -96
  168. package/dist/utils/clipboardFiles.d.ts +27 -0
  169. package/dist/utils/clipboardFiles.js +98 -0
  170. package/dist/utils/rulerControl.d.ts +1 -0
  171. package/dist/utils/rulerControl.js +2 -1
  172. package/package.json +2 -2
  173. package/dist/internal/headlessRevisionResolutionGuard.d.ts +0 -3
  174. package/dist/internal/headlessRevisionResolutionGuard.js +0 -18
@@ -53,6 +53,8 @@ const isPlainText = (text) => {
53
53
  }
54
54
  return true;
55
55
  };
56
+ /** A font face as `w:rFonts` names one: plain text, not blank, of a sane length. */
57
+ const isFontName = (value) => isString(value) && value.trim() !== "" && value.length <= 64 && isPlainText(value);
56
58
  const numberingIssue = (value, where) => {
57
59
  if (value === void 0 || value === null) return null;
58
60
  if (!isObject(value)) return `${where} names a malformed list.`;
@@ -64,6 +66,61 @@ const numberingIssue = (value, where) => {
64
66
  if (group !== void 0 && !(isString(group) && group !== "")) return `${where} names a malformed list group.`;
65
67
  return null;
66
68
  };
69
+ const SECTION_STARTS = /* @__PURE__ */ new Set([
70
+ "nextPage",
71
+ "evenPage",
72
+ "oddPage"
73
+ ]);
74
+ const ORIENTATIONS = /* @__PURE__ */ new Set(["portrait", "landscape"]);
75
+ const isTwips = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
76
+ /** Why `section` is not a section of a plan, or null when it is one. */
77
+ const sectionIssue = (section, where) => {
78
+ if (section === void 0) return null;
79
+ if (!isObject(section)) return `${where} describes a malformed section.`;
80
+ const { page, start } = section;
81
+ if (start !== void 0 && !(isString(start) && SECTION_STARTS.has(start))) return `${where} names an unknown section start.`;
82
+ if (page === void 0) return null;
83
+ if (!isObject(page) || !(isString(page["orientation"]) && ORIENTATIONS.has(page["orientation"])) || !isTwips(page["width"]) || !isTwips(page["height"]) || page["width"] === 0 || page["height"] === 0) return `${where} describes a malformed page.`;
84
+ const margins = page["margins"];
85
+ return margins === void 0 || isObject(margins) && [
86
+ "top",
87
+ "right",
88
+ "bottom",
89
+ "left"
90
+ ].every((side) => isTwips(margins[side])) ? null : `${where} describes malformed page margins.`;
91
+ };
92
+ const INDENT_KEYS = /* @__PURE__ */ new Set([
93
+ "left",
94
+ "hanging",
95
+ "firstLine"
96
+ ]);
97
+ /** The widest indent a plan may state: the widest page WordprocessingML allows. */
98
+ const MAX_INDENT = 31680;
99
+ /**
100
+ * Whether `value` is an indent a plan may state: at least one of
101
+ * `left`, `hanging` and `firstLine`, each a whole number of twentieths of a
102
+ * point, and not both a hanging and a first-line indent.
103
+ */
104
+ const isIndent = (value) => {
105
+ if (!isObject(value)) return false;
106
+ const keys = Object.keys(value);
107
+ return keys.length > 0 && keys.every((key) => INDENT_KEYS.has(key) && isCount(value[key]) && value[key] <= MAX_INDENT) && !(value["hanging"] !== void 0 && value["firstLine"] !== void 0);
108
+ };
109
+ /** The most tab stops a plan may give one paragraph. */
110
+ const MAX_TAB_STOPS = 8;
111
+ /**
112
+ * Whether `value` is a list of tab stops a plan may state: one to eight
113
+ * whole numbers of twentieths of a point, above zero and ascending.
114
+ */
115
+ const isTabStops = (value) => Array.isArray(value) && value.length > 0 && value.length <= MAX_TAB_STOPS && value.every((stop, index) => isCount(stop) && stop > 0 && stop <= MAX_INDENT && (index === 0 || stop > value[index - 1]));
116
+ const ALIGNMENTS = /* @__PURE__ */ new Set([
117
+ "left",
118
+ "center",
119
+ "right",
120
+ "both"
121
+ ]);
122
+ /** Whether `value` is an alignment a plan may give a paragraph. */
123
+ const isAlignment = (value) => isString(value) && ALIGNMENTS.has(value);
67
124
  const sourceItemIssue = (item, where) => {
68
125
  if (!isString(item["blockId"]) || !isString(item["hash"])) return `${where} names no source block and hash.`;
69
126
  for (const key of [
@@ -71,9 +128,19 @@ const sourceItemIssue = (item, where) => {
71
128
  "cellStyleId",
72
129
  "stripLabel"
73
130
  ]) if (!isOptionalString(item[key])) return `${where} carries a malformed ${key}.`;
74
- if (!isOptionalBoolean(item["labelAsText"])) return `${where} carries a malformed labelAsText.`;
131
+ for (const key of [
132
+ "labelAsText",
133
+ "pageBreakBefore",
134
+ "keepNext",
135
+ "stripLabelBreak"
136
+ ]) if (!isOptionalBoolean(item[key])) return `${where} carries a malformed ${key}.`;
137
+ if (item["indent"] !== void 0 && !isIndent(item["indent"])) return `${where} carries a malformed indent.`;
138
+ if (item["tabStops"] !== void 0 && !isTabStops(item["tabStops"])) return `${where} carries malformed tab stops.`;
139
+ if (item["alignment"] !== void 0 && !isAlignment(item["alignment"])) return `${where} carries an unknown alignment.`;
75
140
  const merge = item["mergeNext"];
76
141
  if (merge !== void 0 && !(isString(merge) && MERGES.has(merge))) return `${where} names an unknown merge.`;
142
+ const section = sectionIssue(item["endsSection"], where);
143
+ if (section !== null) return section;
77
144
  const numbering = numberingIssue(item["numbering"], where);
78
145
  if (numbering !== null) return numbering;
79
146
  const nested = item["nested"];
@@ -84,7 +151,7 @@ const sourceItemIssue = (item, where) => {
84
151
  if (!isObject(entry) || !isString(entry["blockId"])) return `${where} carries a nested placement without a block.`;
85
152
  if (seen.has(entry["blockId"])) return `${where} places nested block ${entry["blockId"]} twice.`;
86
153
  seen.add(entry["blockId"]);
87
- if (!isOptionalString(entry["styleId"]) || !isOptionalString(entry["stripLabel"]) || !isOptionalBoolean(entry["labelAsText"])) return `${where} carries a malformed nested placement.`;
154
+ if (!isOptionalString(entry["styleId"]) || !isOptionalString(entry["stripLabel"]) || !isOptionalBoolean(entry["labelAsText"]) || !isOptionalBoolean(entry["keepNext"]) || entry["indent"] !== void 0 && !isIndent(entry["indent"]) || entry["tabStops"] !== void 0 && !isTabStops(entry["tabStops"]) || entry["alignment"] !== void 0 && !isAlignment(entry["alignment"])) return `${where} carries a malformed nested placement.`;
88
155
  const nestedNumbering = numberingIssue(entry["numbering"], where);
89
156
  if (nestedNumbering !== null) return nestedNumbering;
90
157
  }
@@ -117,23 +184,6 @@ const omitIssue = (omit) => {
117
184
  for (const entry of omit) if (!isObject(entry) || !isString(entry["blockId"]) || !isString(entry["reason"]) || !OMIT_REASONS.has(entry["reason"])) return "The plan omits a block without an id or for an unknown reason.";
118
185
  return null;
119
186
  };
120
- const INDENT_KEYS = /* @__PURE__ */ new Set([
121
- "left",
122
- "hanging",
123
- "firstLine"
124
- ]);
125
- /** The widest indent a patch may state: the widest page WordprocessingML allows. */
126
- const MAX_INDENT = 31680;
127
- /**
128
- * Whether `value` is a level indent a patch may state: at least one of
129
- * `left`, `hanging` and `firstLine`, each a whole number of twentieths of a
130
- * point, and not both a hanging and a first-line indent.
131
- */
132
- const isLevelIndent = (value) => {
133
- if (!isObject(value)) return false;
134
- const keys = Object.keys(value);
135
- return keys.length > 0 && keys.every((key) => INDENT_KEYS.has(key) && isCount(value[key]) && value[key] <= MAX_INDENT) && !(value["hanging"] !== void 0 && value["firstLine"] !== void 0);
136
- };
137
187
  const patchesIssue = (patches) => {
138
188
  if (patches === void 0) return null;
139
189
  if (!Array.isArray(patches)) return "The plan's numbering patches are malformed.";
@@ -143,8 +193,8 @@ const patchesIssue = (patches) => {
143
193
  const key = `${String(patch["abstractNumId"])}:${String(patch["ilvl"])}`;
144
194
  if (seen.has(key)) return `Two numbering patches change level ${String(patch["ilvl"])} of list definition ${String(patch["abstractNumId"])}.`;
145
195
  seen.add(key);
146
- const { numFmt, lvlText, start, suff, indent } = patch;
147
- if (numFmt !== void 0 && !(isString(numFmt) && NUMBER_FORMATS.has(numFmt)) || lvlText !== void 0 && !(isString(lvlText) && isPlainText(lvlText)) || start !== void 0 && !isCount(start) || suff !== void 0 && !(isString(suff) && SUFFIXES.has(suff)) || indent !== void 0 && !isLevelIndent(indent)) return "A numbering patch carries a malformed value.";
196
+ const { numFmt, lvlText, start, suff, indent, font } = patch;
197
+ if (font !== void 0 && !isFontName(font) || numFmt !== void 0 && !(isString(numFmt) && NUMBER_FORMATS.has(numFmt)) || lvlText !== void 0 && !(isString(lvlText) && isPlainText(lvlText)) || start !== void 0 && !isCount(start) || suff !== void 0 && !(isString(suff) && SUFFIXES.has(suff)) || indent !== void 0 && !isIndent(indent)) return "A numbering patch carries a malformed value.";
148
198
  }
149
199
  return null;
150
200
  };
@@ -172,9 +222,13 @@ const fieldsIssue = (fields) => {
172
222
  if (updateOnOpen !== void 0 && typeof updateOnOpen !== "boolean") return "The plan's update-on-open choice is not a boolean.";
173
223
  return null;
174
224
  };
225
+ const compatIssue = (compat) => {
226
+ if (compat === void 0) return null;
227
+ return isObject(compat) && isOptionalBoolean(compat["doNotExpandShiftReturn"]) ? null : "The plan's compatibility settings are malformed.";
228
+ };
175
229
  /** Why `plan` is not a version 1 template plan, or null when it is one. */
176
230
  const planShapeIssue = (plan) => {
177
231
  if (!isObject(plan) || plan["version"] !== 1 || !isString(plan["sourceSha256"]) || !isString(plan["templateSha256"])) return "The plan is not a version 1 template plan.";
178
- return bodyIssue(plan["body"]) ?? omitIssue(plan["omit"]) ?? patchesIssue(plan["numberingPatches"]) ?? spansIssue(plan) ?? fieldsIssue(plan["fields"]);
232
+ return bodyIssue(plan["body"]) ?? omitIssue(plan["omit"]) ?? patchesIssue(plan["numberingPatches"]) ?? spansIssue(plan) ?? fieldsIssue(plan["fields"]) ?? compatIssue(plan["compat"]) ?? (plan["trackedChanges"] === void 0 || plan["trackedChanges"] === "accept" || plan["trackedChanges"] === "reject" ? null : "The plan names an unknown view of tracked changes.") ?? sectionIssue(plan["lastSection"], "The plan's last section") ?? (plan["textEffects"] === void 0 || plan["textEffects"] === "normalize" || plan["textEffects"] === "keep" ? null : "The plan's choice for text effects is unknown.");
179
233
  };
180
234
  export { OMIT_REASONS, PLAN_HIGHLIGHT_COLORS, isPlainText, planShapeIssue };
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Tracked changes resolved to one view.
3
+ *
4
+ * A document with tracked changes is two texts at once: what it reads with
5
+ * every change accepted, and what it reads with every change rejected. A
6
+ * plan is made for one of them. This module rewrites the story parts of a
7
+ * package into the chosen view: no insertion, deletion, move or recorded
8
+ * formatting change is left, and nothing else of the parts changes.
9
+ *
10
+ * - Accepted: inserted content stays and loses its wrapper, deleted content
11
+ * goes. Rejected: the reverse, and deleted text is ordinary text again.
12
+ * - A paragraph mark that the view removes (deleted and accepted, inserted
13
+ * and rejected) joins its paragraph to the next one of the same container,
14
+ * whose mark, and with it whose properties, the joined paragraph keeps.
15
+ * - A table row that the view removes goes whole; so does a cell.
16
+ * - A recorded formatting change is dropped when accepted. Rejected, the
17
+ * properties it recorded come back.
18
+ */
19
+ import { DocxTrackedChanges, TemplatePlanError, TemplatePlanTrackedView } from "./types.js";
20
+ import { Result } from "better-result";
21
+ type Tally = {
22
+ insertions: number;
23
+ deletions: number;
24
+ moves: number;
25
+ paragraphMarks: number;
26
+ tableRows: number;
27
+ formattingChanges: number;
28
+ authors: Set<string>;
29
+ first: string | null;
30
+ last: string | null;
31
+ };
32
+ /** One part in the chosen view, or null when it cannot be read whole. */
33
+ export declare const resolvePartRevisions: (path: string, xml: string, view: TemplatePlanTrackedView) => {
34
+ xml: string;
35
+ tally: Tally;
36
+ } | null;
37
+ /**
38
+ * A package with the tracked changes of its main document and its notes
39
+ * resolved to `view`, and what was resolved. The bytes are the source's own
40
+ * when it tracks nothing.
41
+ */
42
+ export declare const resolveTrackedChanges: (docx: Uint8Array, view: TemplatePlanTrackedView) => Promise<Result<{
43
+ docx: Uint8Array;
44
+ resolved: DocxTrackedChanges;
45
+ }, TemplatePlanError>>;
46
+ export {};
@@ -0,0 +1,407 @@
1
+ import { spliceXml } from "../../selectiveXmlPatch.js";
2
+ import { loadPackage } from "./package.js";
3
+ import { TemplatePlanError } from "./types.js";
4
+ import { elementChildren, innerRangeOf, rangeOf, readRawPart, wAttr, wChild, wName } from "./xml.js";
5
+ import { Result } from "better-result";
6
+ import { ZipArchive } from "@stll/docx-core/zip";
7
+ // src/docx/server/templatePlan/revisions.ts
8
+ /**
9
+ * Tracked changes resolved to one view.
10
+ *
11
+ * A document with tracked changes is two texts at once: what it reads with
12
+ * every change accepted, and what it reads with every change rejected. A
13
+ * plan is made for one of them. This module rewrites the story parts of a
14
+ * package into the chosen view: no insertion, deletion, move or recorded
15
+ * formatting change is left, and nothing else of the parts changes.
16
+ *
17
+ * - Accepted: inserted content stays and loses its wrapper, deleted content
18
+ * goes. Rejected: the reverse, and deleted text is ordinary text again.
19
+ * - A paragraph mark that the view removes (deleted and accepted, inserted
20
+ * and rejected) joins its paragraph to the next one of the same container,
21
+ * whose mark, and with it whose properties, the joined paragraph keeps.
22
+ * - A table row that the view removes goes whole; so does a cell.
23
+ * - A recorded formatting change is dropped when accepted. Rejected, the
24
+ * properties it recorded come back.
25
+ */
26
+ const INSERTED = /* @__PURE__ */ new Set(["ins", "moveTo"]);
27
+ const DELETED = /* @__PURE__ */ new Set(["del", "moveFrom"]);
28
+ const MOVE_MARKS = /* @__PURE__ */ new Set([
29
+ "moveFromRangeStart",
30
+ "moveFromRangeEnd",
31
+ "moveToRangeStart",
32
+ "moveToRangeEnd"
33
+ ]);
34
+ /** A recorded change of properties, by the properties element it sits in. */
35
+ const PROPERTY_CHANGES = /* @__PURE__ */ new Map([
36
+ ["rPrChange", "rPr"],
37
+ ["pPrChange", "pPr"],
38
+ ["sectPrChange", "sectPr"],
39
+ ["tblPrChange", "tblPr"],
40
+ ["tblGridChange", "tblGrid"],
41
+ ["tblPrExChange", "tblPrEx"],
42
+ ["trPrChange", "trPr"],
43
+ ["tcPrChange", "tcPr"]
44
+ ]);
45
+ const CELL_MARKS = /* @__PURE__ */ new Set([
46
+ "cellIns",
47
+ "cellDel",
48
+ "cellMerge"
49
+ ]);
50
+ const OWN_PROPERTIES = /* @__PURE__ */ new Map([["pPr", /* @__PURE__ */ new Set(["rPr", "sectPr"])], ["sectPr", /* @__PURE__ */ new Set(["headerReference", "footerReference"])]]);
51
+ /** Marks of a range that outlive content a view removes around them: a
52
+ * bookmark or a comment that begins inside a deletion ends outside it. */
53
+ const RANGE_MARKS = /* @__PURE__ */ new Set([
54
+ "bookmarkStart",
55
+ "bookmarkEnd",
56
+ "commentRangeStart",
57
+ "commentRangeEnd",
58
+ "permStart",
59
+ "permEnd"
60
+ ]);
61
+ /** Every element name this module acts on, to skip a subtree without one. */
62
+ const REVISION_NAMES = [
63
+ ...INSERTED,
64
+ ...DELETED,
65
+ ...MOVE_MARKS,
66
+ ...PROPERTY_CHANGES.keys(),
67
+ ...CELL_MARKS,
68
+ "numberingChange",
69
+ "delText",
70
+ "delInstrText"
71
+ ];
72
+ const newTally = () => ({
73
+ insertions: 0,
74
+ deletions: 0,
75
+ moves: 0,
76
+ paragraphMarks: 0,
77
+ tableRows: 0,
78
+ formattingChanges: 0,
79
+ authors: /* @__PURE__ */ new Set(),
80
+ first: null,
81
+ last: null
82
+ });
83
+ /**
84
+ * What a part tracks, whatever view is taken of it: every insertion,
85
+ * deletion, move and recorded formatting change, with who made it and
86
+ * when. A change inside content the view removes is counted all the same.
87
+ */
88
+ const tallyPart = (root, tally) => {
89
+ const stack = [root];
90
+ for (let element = stack.pop(); element !== void 0; element = stack.pop()) {
91
+ const name = wName(element);
92
+ let counted = true;
93
+ if (name === "ins") tally.insertions += 1;
94
+ else if (name === "del") tally.deletions += 1;
95
+ else if (name === "moveFrom" || name === "moveTo") tally.moves += 1;
96
+ else if (name !== null && (PROPERTY_CHANGES.has(name) || CELL_MARKS.has(name) || name === "numberingChange")) tally.formattingChanges += 1;
97
+ else counted = false;
98
+ if (counted) {
99
+ const author = wAttr(element, "author");
100
+ const date = wAttr(element, "date");
101
+ if (author !== null && author !== "") tally.authors.add(author);
102
+ if (date !== null && date !== "") {
103
+ tally.first = tally.first === null || date < tally.first ? date : tally.first;
104
+ tally.last = tally.last === null || date > tally.last ? date : tally.last;
105
+ }
106
+ }
107
+ stack.push(...elementChildren(element));
108
+ }
109
+ };
110
+ const mayHoldRevision = (text) => REVISION_NAMES.some((name) => text.includes(`:${name}`));
111
+ /** The element's source text; the walk is unsound without its range. */
112
+ const sourceOf = (walk, element) => {
113
+ const range = rangeOf(element);
114
+ if (range === null) {
115
+ walk.sound = false;
116
+ return "";
117
+ }
118
+ return walk.xml.slice(range.start, range.end);
119
+ };
120
+ /** The range marks inside content a view removes, as they stand. */
121
+ const rangeMarksIn = (walk, element) => {
122
+ let marks = "";
123
+ const stack = [...elementChildren(element)].toReversed();
124
+ for (let next = stack.pop(); next !== void 0; next = stack.pop()) if (RANGE_MARKS.has(wName(next) ?? "")) marks += sourceOf(walk, next);
125
+ else stack.push(...elementChildren(next).toReversed());
126
+ return marks;
127
+ };
128
+ /** Whether the chosen view keeps content marked `name`. */
129
+ const keeps = (walk, name) => INSERTED.has(name) ? walk.view === "accept" : walk.view === "reject";
130
+ /** Deleted text read as text again: the names of its elements. */
131
+ const asLiveText = (xml) => xml.replaceAll(/<(\/?)([A-Za-z0-9]+:)delText\b/gu, "<$1$2t").replaceAll(/<(\/?)([A-Za-z0-9]+:)delInstrText\b/gu, "<$1$2instrText");
132
+ /** Whether the view removes the paragraph's mark. */
133
+ const losesMark = (walk, paragraph) => {
134
+ const mark = wChild(wChild(paragraph, "pPr"), "rPr");
135
+ return (walk.view === "accept" ? ["del", "moveFrom"] : ["ins", "moveTo"]).some((name) => wChild(mark, name) !== null);
136
+ };
137
+ /** Whether the view removes the row: the marker of `w:trPr`. */
138
+ const losesRow = (walk, row) => {
139
+ const properties = wChild(row, "trPr");
140
+ return wChild(properties, walk.view === "accept" ? "del" : "ins") !== null;
141
+ };
142
+ const losesCell = (walk, cell) => wChild(wChild(cell, "tcPr"), walk.view === "accept" ? "cellDel" : "cellIns") !== null;
143
+ /**
144
+ * The children of `container` in the chosen view, with the text between
145
+ * them as it stands. A paragraph whose mark goes hands its content to the
146
+ * next paragraph of the container.
147
+ */
148
+ const resolveChildren = (walk, container) => {
149
+ const inner = innerRangeOf(walk.xml, container);
150
+ if (inner === null) return "";
151
+ const pieces = [];
152
+ let cursor = inner.start;
153
+ const visit = (element) => {
154
+ const range = rangeOf(element);
155
+ if (range === null) {
156
+ walk.sound = false;
157
+ return;
158
+ }
159
+ pieces.push(walk.xml.slice(cursor, range.start));
160
+ cursor = range.end;
161
+ const name = wName(element);
162
+ if (name !== null && (INSERTED.has(name) || DELETED.has(name))) {
163
+ if (keeps(walk, name)) {
164
+ const kept = resolveChildren(walk, element);
165
+ pieces.push(DELETED.has(name) ? asLiveText(kept) : kept);
166
+ } else pieces.push(rangeMarksIn(walk, element));
167
+ return;
168
+ }
169
+ if (name !== null && MOVE_MARKS.has(name)) return;
170
+ if (name === "numberingChange" || name !== null && CELL_MARKS.has(name)) return;
171
+ if (name !== null && PROPERTY_CHANGES.has(name)) return;
172
+ if (name === "tr" && losesRow(walk, element)) {
173
+ walk.tally.tableRows += 1;
174
+ pieces.push(rangeMarksIn(walk, element));
175
+ return;
176
+ }
177
+ if (name === "tc" && losesCell(walk, element)) {
178
+ pieces.push(rangeMarksIn(walk, element));
179
+ return;
180
+ }
181
+ if (name === "p") {
182
+ pieces.push({
183
+ xml: resolveElement(walk, element),
184
+ paragraph: element,
185
+ carried: losesMark(walk, element)
186
+ });
187
+ return;
188
+ }
189
+ pieces.push(resolveElement(walk, element));
190
+ };
191
+ for (const child of elementChildren(container)) visit(child);
192
+ pieces.push(walk.xml.slice(cursor, inner.end));
193
+ return joinParagraphs(walk, pieces);
194
+ };
195
+ /** The content of a resolved paragraph without its properties. */
196
+ const contentOf = (paragraphXml) => {
197
+ const open = paragraphXml.indexOf(">") + 1;
198
+ const close = paragraphXml.lastIndexOf("</");
199
+ if (paragraphXml.endsWith("/>") || close < open) return "";
200
+ const body = paragraphXml.slice(open, close);
201
+ if (/^\s*<([A-Za-z0-9]+:)?pPr\b/u.exec(body) === null) return body;
202
+ if (/^\s*<([A-Za-z0-9]+:)?pPr\b[^>]*\/>/u.test(body)) return body.slice(body.indexOf("/>") + 2);
203
+ const end = /<\/([A-Za-z0-9]+:)?pPr>/u.exec(body);
204
+ return end === null ? body : body.slice(end.index + end[0].length);
205
+ };
206
+ /** `content` put in front of what a resolved paragraph holds. */
207
+ const withLeadingContent = (paragraphXml, content) => {
208
+ if (content === "") return paragraphXml;
209
+ if (paragraphXml.endsWith("/>")) {
210
+ const name = /^<([^\s/>]+)/u.exec(paragraphXml)?.[1] ?? "w:p";
211
+ return `${paragraphXml.slice(0, -2)}>${content}</${name}>`;
212
+ }
213
+ const open = paragraphXml.indexOf(">") + 1;
214
+ const body = paragraphXml.slice(open);
215
+ const selfClosed = /^\s*<([A-Za-z0-9]+:)?pPr\b[^>]*\/>/u.exec(body);
216
+ if (selfClosed !== null) {
217
+ const at = open + selfClosed[0].length;
218
+ return `${paragraphXml.slice(0, at)}${content}${paragraphXml.slice(at)}`;
219
+ }
220
+ if (/^\s*<([A-Za-z0-9]+:)?pPr\b/u.test(body)) {
221
+ const end = /<\/([A-Za-z0-9]+:)?pPr>/u.exec(body);
222
+ if (end !== null) {
223
+ const at = open + end.index + end[0].length;
224
+ return `${paragraphXml.slice(0, at)}${content}${paragraphXml.slice(at)}`;
225
+ }
226
+ }
227
+ return `${paragraphXml.slice(0, open)}${content}${body}`;
228
+ };
229
+ const joinParagraphs = (walk, pieces) => {
230
+ let out = "";
231
+ /** Content of paragraphs whose mark went, waiting for the next one. */
232
+ let carried = "";
233
+ /** The last such paragraph, kept whole when no paragraph follows. */
234
+ let held = null;
235
+ const flush = () => {
236
+ if (held !== null) {
237
+ out += withLeadingContent(held, carried);
238
+ carried = "";
239
+ held = null;
240
+ }
241
+ };
242
+ for (const piece of pieces) {
243
+ if (typeof piece === "string") {
244
+ out += piece;
245
+ continue;
246
+ }
247
+ if (piece.paragraph === null) {
248
+ flush();
249
+ out += piece.xml;
250
+ continue;
251
+ }
252
+ if (piece.carried) {
253
+ walk.tally.paragraphMarks += 1;
254
+ if (held !== null) carried += contentOf(held);
255
+ held = piece.xml;
256
+ continue;
257
+ }
258
+ if (held !== null) {
259
+ carried += contentOf(held);
260
+ held = null;
261
+ }
262
+ out += withLeadingContent(piece.xml, carried);
263
+ carried = "";
264
+ }
265
+ flush();
266
+ return out;
267
+ };
268
+ /** The properties a recorded change gives back, inside `properties`. */
269
+ const restoredProperties = (walk, properties, name) => {
270
+ const changeName = [...PROPERTY_CHANGES].find(([, owner]) => owner === name)?.[0];
271
+ const change = changeName === void 0 ? null : wChild(properties, changeName);
272
+ if (change === null || walk.view !== "reject") return null;
273
+ const recorded = wChild(change, name);
274
+ const outer = rangeOf(properties);
275
+ const inner = innerRangeOf(walk.xml, properties);
276
+ if (outer === null || inner === null) return null;
277
+ const recordedInner = recorded === null ? null : innerRangeOf(walk.xml, recorded);
278
+ const old = recordedInner === null ? "" : walk.xml.slice(recordedInner.start, recordedInner.end);
279
+ const own = OWN_PROPERTIES.get(name) ?? null;
280
+ const kept = own === null ? "" : elementChildren(properties).filter((child) => own.has(wName(child) ?? "")).map((child) => resolveElement(walk, child)).join("");
281
+ const head = walk.xml.slice(outer.start, inner.start);
282
+ const tail = walk.xml.slice(inner.end, outer.end);
283
+ return name === "sectPr" ? `${head}${kept}${old}${tail}` : `${head}${old}${kept}${tail}`;
284
+ };
285
+ /** `element` in the chosen view; its own text when it holds no revision. */
286
+ const resolveElement = (walk, element) => {
287
+ const source = sourceOf(walk, element);
288
+ if (!mayHoldRevision(source)) return source;
289
+ const name = wName(element);
290
+ if (name !== null && [...PROPERTY_CHANGES.values()].includes(name)) {
291
+ const restored = restoredProperties(walk, element, name);
292
+ if (restored !== null) return restored;
293
+ }
294
+ const outer = rangeOf(element);
295
+ const inner = innerRangeOf(walk.xml, element);
296
+ if (outer === null) {
297
+ walk.sound = false;
298
+ return source;
299
+ }
300
+ if (inner === null) return source;
301
+ const content = resolveChildren(walk, element);
302
+ return `${walk.xml.slice(outer.start, inner.start)}${content}${walk.xml.slice(inner.end, outer.end)}`;
303
+ };
304
+ const summaryOf = (tally) => ({
305
+ insertions: tally.insertions,
306
+ deletions: tally.deletions,
307
+ moves: tally.moves,
308
+ paragraphMarks: tally.paragraphMarks,
309
+ tableRows: tally.tableRows,
310
+ formattingChanges: tally.formattingChanges,
311
+ authors: [...tally.authors].toSorted(),
312
+ first: tally.first,
313
+ last: tally.last
314
+ });
315
+ /** One part in the chosen view, or null when it cannot be read whole. */
316
+ const resolvePartRevisions = (path, xml, view) => {
317
+ const part = readRawPart(path, xml);
318
+ if (part === null) return null;
319
+ const walk = {
320
+ xml,
321
+ view,
322
+ tally: newTally(),
323
+ sound: true
324
+ };
325
+ const outer = rangeOf(part.root);
326
+ if (outer === null) return null;
327
+ tallyPart(part.root, walk.tally);
328
+ const resolved = resolveElement(walk, part.root);
329
+ if (!walk.sound) return null;
330
+ const rewritten = spliceXml(xml, [{
331
+ ...outer,
332
+ newXml: resolved
333
+ }]);
334
+ return rewritten === null ? null : {
335
+ xml: rewritten,
336
+ tally: walk.tally
337
+ };
338
+ };
339
+ const mergeTallies = (tallies) => {
340
+ const total = newTally();
341
+ for (const tally of tallies) {
342
+ total.insertions += tally.insertions;
343
+ total.deletions += tally.deletions;
344
+ total.moves += tally.moves;
345
+ total.paragraphMarks += tally.paragraphMarks;
346
+ total.tableRows += tally.tableRows;
347
+ total.formattingChanges += tally.formattingChanges;
348
+ for (const author of tally.authors) total.authors.add(author);
349
+ for (const date of [tally.first, tally.last]) if (date !== null) {
350
+ total.first = total.first === null || date < total.first ? date : total.first;
351
+ total.last = total.last === null || date > total.last ? date : total.last;
352
+ }
353
+ }
354
+ return total;
355
+ };
356
+ /**
357
+ * A package with the tracked changes of its main document and its notes
358
+ * resolved to `view`, and what was resolved. The bytes are the source's own
359
+ * when it tracks nothing.
360
+ */
361
+ const resolveTrackedChanges = async (docx, view) => {
362
+ const loaded = await loadPackage(docx);
363
+ if (loaded.isErr()) return Result.err(loaded.error);
364
+ const pkg = loaded.value;
365
+ const paths = [
366
+ pkg.documentPath,
367
+ pkg.partPath("footnotes"),
368
+ pkg.partPath("endnotes")
369
+ ].filter((path) => path !== null);
370
+ const rewritten = /* @__PURE__ */ new Map();
371
+ const tallies = [];
372
+ for (const path of paths) {
373
+ const xml = path === pkg.documentPath ? pkg.documentXml : await pkg.readText(path);
374
+ if (xml === null || !mayHoldRevision(xml)) continue;
375
+ const resolved = resolvePartRevisions(path, xml, view);
376
+ if (resolved === null) return Result.err(new TemplatePlanError({
377
+ code: "xml-unreadable",
378
+ message: `The tracked changes of ${path} could not be resolved.`
379
+ }));
380
+ tallies.push(resolved.tally);
381
+ if (resolved.xml !== xml) rewritten.set(path, resolved.xml);
382
+ }
383
+ const resolved = summaryOf(mergeTallies(tallies));
384
+ if (rewritten.size === 0) return Result.ok({
385
+ docx,
386
+ resolved
387
+ });
388
+ return await Result.tryPromise({
389
+ try: async () => {
390
+ const zip = await ZipArchive.read(docx);
391
+ for (const [path, content] of rewritten) {
392
+ const current = zip.entry(path);
393
+ zip.set(path, content, current === void 0 ? {} : { modified: current.modified });
394
+ }
395
+ return {
396
+ docx: await zip.generate(),
397
+ resolved
398
+ };
399
+ },
400
+ catch: (cause) => new TemplatePlanError({
401
+ code: "archive-unreadable",
402
+ message: "The package could not be rewritten without its tracked changes.",
403
+ cause
404
+ })
405
+ });
406
+ };
407
+ export { resolvePartRevisions, resolveTrackedChanges };
@@ -7,7 +7,7 @@ import { XmlElement } from "../../xmlParser.js";
7
7
  import { ParagraphNumberingOverride } from "@stll/docx-core/model";
8
8
  /** The mark a footnote or endnote reference leaves in a block's text. */
9
9
  export declare const NOTE_REFERENCE_MARK = "";
10
- export type AtomKind = "text" | "tab" | "lineBreak" | "pageBreak" | "noBreakHyphen" | "softHyphen" | "symbol" | "footnoteReference" | "endnoteReference" | "object";
10
+ export type AtomKind = "text" | "tab" | "lineBreak" | "pageBreak" | "noBreakHyphen" | "softHyphen" | "symbol" | "footnoteReference" | "endnoteReference" | "selfNumber" | "object";
11
11
  export type AtomLink =
12
12
  /** A link through a relationship; `anchor` is the fragment its element adds. */
13
13
  {
@@ -35,7 +35,11 @@ export type InlineAtom = {
35
35
  element: XmlElement | null;
36
36
  /** Fields whose result the atom is part of, outermost first. */
37
37
  fields: readonly number[];
38
+ /** The code of the field a `selfNumber` atom stands for. */
39
+ instruction?: string;
38
40
  };
41
+ /** Whether a field kind prints a number of its own and caches no text. */
42
+ export declare const isSelfNumberingField: (kind: string) => boolean;
39
43
  export type StoryField = {
40
44
  /** Position among the fields of the story, in begin order. */
41
45
  index: number;
@@ -89,6 +93,8 @@ export type ParagraphRead = {
89
93
  element: XmlElement;
90
94
  ordinal: number;
91
95
  styleId: string | null;
96
+ /** The language the paragraph mark states (`w:pPr/w:rPr/w:lang`), or null. */
97
+ language: string | null;
92
98
  numPr: ParagraphNumberingOverride | undefined;
93
99
  paraId: string | null;
94
100
  outlineLevel: number | null;
@@ -104,9 +110,25 @@ export type ParagraphRead = {
104
110
  /** Names of content the reader has no text for and the transfer cannot carry. */
105
111
  unsupported: string[];
106
112
  hasSectionBreak: boolean;
113
+ /** `w:pageBreakBefore` as the paragraph itself states it; null when it does not. */
114
+ pageBreakBefore: boolean | null;
115
+ /** `w:jc` as the paragraph itself states it, or null. */
116
+ alignment: string | null;
117
+ /** The sides of `w:ind` the paragraph itself states, in twentieths of a
118
+ * point: where its lines start, and what its first line adds to that
119
+ * (negative for a hanging indent). Null for a side it does not state. */
120
+ indent: {
121
+ left: number | null;
122
+ firstLine: number | null;
123
+ };
124
+ /** Whether the paragraph states an indent in characters, which stands
125
+ * over the measured one and cannot be given in twentieths of a point. */
126
+ indentInCharacters: boolean;
107
127
  /** Whether the paragraph mark is a tracked insertion or deletion. */
108
128
  hasTrackedMark: boolean;
109
129
  };
130
+ /** An on/off property as its element states it; null without the element. */
131
+ export declare const toggleOf: (element: XmlElement | null) => boolean | null;
110
132
  /** Read one `w:p`, advancing the story's field and revision state. */
111
133
  export declare const readParagraph: (element: XmlElement, state: StoryState) => ParagraphRead;
112
134
  export type StoryBlockVisitor = {