@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
@@ -3,8 +3,9 @@ import { RELATIONSHIP_TYPES } from "../../relsParser.js";
3
3
  import { spliceXml } from "../../selectiveXmlPatch.js";
4
4
  import { NAMESPACES, getLocalName } from "../../xmlParser.js";
5
5
  import { appendToXmlRoot } from "../../xmlRootInsertion.js";
6
- import { analyzeDocument } from "./blocks.js";
7
- import { freezeFields, setUpdateFieldsOnOpen, withoutContained } from "./builders.js";
6
+ import { analyzeDocument, analyzeSource, viewOf } from "./blocks.js";
7
+ import { freezeFields, inheritedReferencesXml, sectionPropertiesXml, setKeepShiftReturnSpacing, setUpdateFieldsOnOpen, withoutContained } from "./builders.js";
8
+ import { removeInvisibleEffects } from "./effects.js";
8
9
  import { createRelationshipsEditor, noteXml, paragraphContentXml, paragraphXml, tableXml, templateCharacterStyles } from "./emit.js";
9
10
  import { readHeaderFooterParts } from "./inspect.js";
10
11
  import { styleNumbering } from "./labels.js";
@@ -159,6 +160,32 @@ const levelPropertiesXml = ({ part, level, w, indent }) => {
159
160
  const at = (later === void 0 || later === null ? null : rangeOf(later))?.start ?? inner.end;
160
161
  return `${part.xml.slice(range.start, at)}${indentXml}${part.xml.slice(at, range.end)}`;
161
162
  };
163
+ /**
164
+ * The `w:rPr` of a level with its label set in `font`. Whatever else the
165
+ * level's run properties state is kept; the face is named for every script
166
+ * a label is written in, and no theme face is left to override it.
167
+ */
168
+ const levelRunPropertiesXml = ({ part, level, w, font }) => {
169
+ const face = escapeXmlAttribute(font);
170
+ const fontsXml = `<${w}:rFonts ${w}:ascii="${face}" ${w}:hAnsi="${face}" ${w}:eastAsia="${face}" ${w}:cs="${face}" ${w}:hint="default"/>`;
171
+ const properties = wChild(level, "rPr");
172
+ const range = properties === null ? null : rangeOf(properties);
173
+ if (properties === null || range === null) return `<${w}:rPr>${fontsXml}</${w}:rPr>`;
174
+ const existing = wChild(properties, "rFonts");
175
+ const existingRange = existing === null ? null : rangeOf(existing);
176
+ if (existingRange !== null) return sliceWithSplices(part.xml, range, [{
177
+ ...existingRange,
178
+ newXml: fontsXml
179
+ }]);
180
+ const inner = innerRangeOf(part.xml, properties);
181
+ if (inner === null) {
182
+ const name = properties.name ?? `${w}:rPr`;
183
+ return `${part.xml.slice(range.start, range.end - 2).trimEnd()}>${fontsXml}</${name}>`;
184
+ }
185
+ const style = wChild(properties, "rStyle");
186
+ const at = (style === null ? null : rangeOf(style))?.end ?? inner.start;
187
+ return `${part.xml.slice(range.start, at)}${fontsXml}${part.xml.slice(at, range.end)}`;
188
+ };
162
189
  /** The template numbering part with level patches and new list instances. */
163
190
  const editNumbering = (part, { patches, mints }) => {
164
191
  const prefixes = partPrefixes(part.root);
@@ -188,13 +215,20 @@ const editNumbering = (part, { patches, mints }) => {
188
215
  w,
189
216
  indent: patch.indent
190
217
  });
191
- if (properties === null) return Result.err(unreadable(part.path, "The numbering part could not be patched."));
218
+ const runProperties = patch.font === void 0 ? void 0 : levelRunPropertiesXml({
219
+ part,
220
+ level,
221
+ w,
222
+ font: patch.font
223
+ });
224
+ if (properties === null || runProperties === null) return Result.err(unreadable(part.path, "The numbering part could not be patched."));
192
225
  const planned = {
193
226
  ...patch.start === void 0 ? {} : { start: valued("start", String(patch.start)) },
194
227
  ...patch.numFmt === void 0 ? {} : { numFmt: valued("numFmt", patch.numFmt) },
195
228
  ...patch.suff === void 0 ? {} : { suff: valued("suff", patch.suff) },
196
229
  ...patch.lvlText === void 0 ? {} : { lvlText: valued("lvlText", patch.lvlText) },
197
- ...properties === void 0 ? {} : { pPr: properties }
230
+ ...properties === void 0 ? {} : { pPr: properties },
231
+ ...runProperties === void 0 ? {} : { rPr: runProperties }
198
232
  };
199
233
  const inner = innerRangeOf(part.xml, level);
200
234
  for (const [index, name] of LEVEL_CHILD_ORDER.entries()) {
@@ -388,9 +422,25 @@ const writeOutput = async ({ source, template, plan, resolved }) => {
388
422
  };
389
423
  const instructions = new Map(resolved.references.map(({ reference, instruction }) => [reference, instruction]));
390
424
  const instructionOf = (segment) => segment.kind === "reference" ? instructions.get(segment.reference) ?? null : null;
425
+ const bodySection = wChild(template.body, "sectPr");
426
+ const inherited = bodySection === null ? [] : inheritedReferencesXml(template.document.xml, template.body, bodySection);
427
+ const sectionEnds = resolved.items.flatMap((item) => item.kind === "paragraph" && item.paragraph.endsSection !== null ? [item.paragraph] : []);
428
+ const sectionXmlOf = /* @__PURE__ */ new Map();
429
+ for (const [position, paragraph] of sectionEnds.entries()) {
430
+ const section = paragraph.endsSection;
431
+ const xml = bodySection === null || section === null ? null : sectionPropertiesXml(template.document.xml, bodySection, documentContext.prefixes.w, {
432
+ first: position === 0,
433
+ page: section.page,
434
+ start: position === 0 ? null : section.start ?? "nextPage",
435
+ inherited
436
+ });
437
+ if (xml === null) return Result.err(unreadable(pkg.documentPath, "A section could not be built."));
438
+ sectionXmlOf.set(paragraph, xml);
439
+ }
391
440
  const emitOf = (paragraph) => ({
392
441
  paragraph,
393
442
  bookmark: resolved.bookmarks.get(paragraph),
443
+ sectionXml: sectionXmlOf.get(paragraph) ?? null,
394
444
  instructionOf,
395
445
  styleBindsList: styleNumbering(paragraph.styleId ?? template.defaultStyleId, template.styles, template.numbering)?.kind === "reference"
396
446
  });
@@ -424,7 +474,6 @@ const writeOutput = async ({ source, template, plan, resolved }) => {
424
474
  end: inner.end
425
475
  });
426
476
  }
427
- const bodySection = wChild(template.body, "sectPr");
428
477
  const keptElements = [
429
478
  ...resolved.keptTemplateBlocks.map(({ element }) => element),
430
479
  ...resolved.items.flatMap((item) => item.kind === "slot" ? [item.templateBlock.element] : []),
@@ -453,6 +502,9 @@ const writeOutput = async ({ source, template, plan, resolved }) => {
453
502
  case "paragraph":
454
503
  xml = paragraphXml(emitOf(item.paragraph), documentContext);
455
504
  break;
505
+ case "separator":
506
+ xml = Result.ok(`<${documentContext.prefixes.w}:p/>`);
507
+ break;
456
508
  case "table":
457
509
  xml = tableXml({
458
510
  table: item.block.element,
@@ -469,7 +521,14 @@ const writeOutput = async ({ source, template, plan, resolved }) => {
469
521
  body.push(xml.value);
470
522
  }
471
523
  if (bodySection !== null) {
472
- const section = keptXml(bodySection);
524
+ const { lastSection } = plan;
525
+ const rebuilt = sectionEnds.length > 0 || lastSection !== void 0 || inherited.length > 0 ? sectionPropertiesXml(template.document.xml, bodySection, documentContext.prefixes.w, {
526
+ first: sectionEnds.length === 0,
527
+ page: lastSection?.page,
528
+ start: sectionEnds.length === 0 ? null : lastSection?.start ?? null,
529
+ inherited
530
+ }) : null;
531
+ const section = rebuilt === null ? keptXml(bodySection) : Result.ok(rebuilt);
473
532
  if (Result.isError(section)) return section;
474
533
  body.push(section.value);
475
534
  }
@@ -598,6 +657,36 @@ const writeOutput = async ({ source, template, plan, resolved }) => {
598
657
  if (settings !== settingsXml.value) parts.set(settingsPath, settings);
599
658
  }
600
659
  }
660
+ if (plan.compat?.doNotExpandShiftReturn === true) {
661
+ const settingsPath = pkg.partPath("settings");
662
+ const written = settingsPath === null ? void 0 : parts.get(settingsPath);
663
+ const settingsXml = typeof written === "string" ? Result.ok(written) : await readTemplateText(settingsPath);
664
+ if (Result.isError(settingsXml)) return settingsXml;
665
+ if (settingsPath === null || settingsXml.value === null) return Result.err(new TemplatePlanError({
666
+ code: "part-missing",
667
+ message: "The template has no settings part to set a compatibility setting in."
668
+ }));
669
+ const settings = setKeepShiftReturnSpacing(settingsXml.value);
670
+ if (settings === null) return Result.err(unreadable(settingsPath, "The settings part could not be updated."));
671
+ if (settings !== settingsXml.value) parts.set(settingsPath, settings);
672
+ }
673
+ if (plan.textEffects !== "keep") {
674
+ const kept = [
675
+ [pkg.documentPath, documentXml],
676
+ [template.numberingPath, template.numberingXml],
677
+ [template.stylesPath, template.stylesXml],
678
+ ...headerFooterParts.map(({ path, xml }) => [path, xml])
679
+ ];
680
+ for (const [path, original] of kept) {
681
+ const written = path === null ? void 0 : parts.get(path);
682
+ const xml = typeof written === "string" ? written : original;
683
+ if (path === null || xml === null) continue;
684
+ const part = readRawPart(path, xml);
685
+ const plain = part === null ? null : removeInvisibleEffects(part);
686
+ if (plain === null) return Result.err(unreadable(path, "A part could not be read for its text effects."));
687
+ if (plain.removed.length > 0) parts.set(path, plain.xml);
688
+ }
689
+ }
601
690
  return await Result.tryPromise({
602
691
  try: async () => {
603
692
  const zip = await ZipArchive.read(pkg.bytes);
@@ -615,7 +704,7 @@ const writeOutput = async ({ source, template, plan, resolved }) => {
615
704
  });
616
705
  };
617
706
  const applyUnguarded = async ({ source, template, plan, options }) => {
618
- const analyzedSource = await analyzeDocument(source);
707
+ const analyzedSource = await analyzeSource(source, viewOf(plan));
619
708
  if (Result.isError(analyzedSource)) return analyzedSource;
620
709
  const analyzedTemplate = await analyzeDocument(template);
621
710
  if (Result.isError(analyzedTemplate)) return analyzedTemplate;
@@ -7,7 +7,7 @@ import { Emphasis } from "./emphasis.js";
7
7
  import { LabelCounter, ParagraphLabel } from "./labels.js";
8
8
  import { LoadedPackage } from "./package.js";
9
9
  import { ParagraphRead, StoryState } from "./story.js";
10
- import { DocxBlock, DocxBlockManifest, TemplatePlanError } from "./types.js";
10
+ import { DocxBlock, DocxBlockManifest, DocxSection, TemplatePlanError, TemplatePlanTrackedView } from "./types.js";
11
11
  import { RawPart } from "./xml.js";
12
12
  import { Result } from "better-result";
13
13
  export declare const blockHash: (text: string, label: string | null) => string;
@@ -32,6 +32,8 @@ export type AnalyzedStory = {
32
32
  state: StoryState;
33
33
  /** `w:sectPr` elements in document order, the body's own last. */
34
34
  sections: XmlElement[];
35
+ /** Whether the body states section properties of its own. */
36
+ hasBodySection: boolean;
35
37
  /** Names of block-level elements the walk has no reading for. */
36
38
  unreadBlocks: string[];
37
39
  warnings: string[];
@@ -39,10 +41,60 @@ export type AnalyzedStory = {
39
41
  type StoryResources = {
40
42
  styles: StyleMap;
41
43
  defaultStyleId: string | null;
44
+ /** The language the document defaults give every run, or null. */
45
+ defaultLanguage: string | null;
42
46
  numbering: NumberingMap | null;
47
+ /** The alignment each paragraph style states for itself (`w:jc`). */
48
+ alignments?: ReadonlyMap<string, string>;
49
+ /** The indent each list level states, by definition and level. */
50
+ levelIndents?: ReadonlyMap<string, IndentSides>;
51
+ /** The indent the document's defaults give every paragraph. */
52
+ defaultIndent?: IndentSides;
43
53
  };
44
54
  /** The heading level a style outlines its paragraphs at, 0 being the highest. */
45
55
  export declare const styleOutlineLevel: (style: document_d_exports.Style | undefined) => number | null;
56
+ type IndentSides = {
57
+ left: number | null;
58
+ firstLine: number | null;
59
+ };
60
+ /** The alignment each style of a styles part states for itself (`w:jc`). */
61
+ export declare const statedAlignments: (stylesPath: string | null, stylesXml: string | null) => Map<string, string>;
62
+ /** The alignment of the nearest style in the `basedOn` chain that states one. */
63
+ export declare const styleAlignment: (styleId: string | null, styles: StyleMap, stated: ReadonlyMap<string, string>) => string | null;
64
+ /** What a style states of the look of its text; null where it states
65
+ * nothing. */
66
+ type StatedLook = {
67
+ bold: boolean | null;
68
+ /** In half-points. */
69
+ size: number | null;
70
+ keepNext: boolean | null;
71
+ /** In twentieths of a point. */
72
+ indentLeft: number | null;
73
+ };
74
+ /** The look each style of the styles part states itself, by style id, and
75
+ * the look the document's defaults state. */
76
+ export declare const statedLooks: (stylesPath: string | null, stylesXml: string | null) => {
77
+ styles: Map<string, StatedLook>;
78
+ defaults: StatedLook;
79
+ };
80
+ /**
81
+ * The look a style gives its text: each property from the nearest style in
82
+ * the `basedOn` chain that states it, then from the document's defaults.
83
+ * Without a statement text is not bold and a paragraph is not kept with the
84
+ * next; the size and the left indent stay null, which leaves the size to
85
+ * the application and the indent to a list level, if the style has one.
86
+ */
87
+ export declare const styleLook: (styleId: string | null, styles: StyleMap, { styles: stated, defaults }: ReturnType<typeof statedLooks>) => {
88
+ bold: boolean;
89
+ size: number | null;
90
+ keepNext: boolean;
91
+ indentLeft: number | null;
92
+ };
93
+ /**
94
+ * The sections of a story with what each states. A body without section
95
+ * properties of its own still ends in a section, which states nothing.
96
+ */
97
+ export declare const storySections: ({ sections, hasBodySection }: AnalyzedStory) => DocxSection[];
46
98
  type AnalyzeStoryOptions = {
47
99
  container: XmlElement;
48
100
  resources: StoryResources;
@@ -89,9 +141,24 @@ export type AnalyzedDocument = {
89
141
  };
90
142
  /** Open a package and analyse its main story, notes, styles and numbering. */
91
143
  export declare const analyzeDocument: (bytes: Uint8Array) => Promise<Result<AnalyzedDocument, TemplatePlanError>>;
144
+ /** The view a plan states, when what was handed in is shaped like a plan
145
+ * at all; its shape is checked where the plan is resolved. */
146
+ export declare const viewOf: (plan: unknown) => TemplatePlanTrackedView | undefined;
147
+ /**
148
+ * Analyse a source in the view a caller chose of its tracked changes, or
149
+ * as it stands. In a view, the package that is analysed is the resolved
150
+ * one, while the manifest keeps the hash of the bytes that were given: a
151
+ * plan pins the file, not a rewriting of it. Without a view, a document
152
+ * that tracks changes says what it tracks.
153
+ */
154
+ export declare const analyzeSource: (bytes: Uint8Array, view: TemplatePlanTrackedView | undefined) => Promise<Result<AnalyzedDocument, TemplatePlanError>>;
92
155
  /**
93
156
  * Read a DOCX into the blocks a template plan addresses: ids, visible text,
94
- * rendered list labels, styles and a hash per block, plus its notes.
157
+ * rendered list labels, styles and a hash per block, plus its notes. With
158
+ * `trackedChanges`, the blocks are those of that view of a document with
159
+ * tracked changes.
95
160
  */
96
- export declare const analyzeDocxBlocks: (docx: Uint8Array) => Promise<Result<DocxBlockManifest, TemplatePlanError>>;
161
+ export declare const analyzeDocxBlocks: (docx: Uint8Array, options?: {
162
+ trackedChanges?: TemplatePlanTrackedView;
163
+ }) => Promise<Result<DocxBlockManifest, TemplatePlanError>>;
97
164
  export {};
@@ -1,11 +1,14 @@
1
1
  import { parseNumbering } from "../../numberingParser.js";
2
+ import { parseSectionProperties } from "../../sectionParser.js";
2
3
  import { parseStylesPackage } from "../../styleParser.js";
4
+ import { keepsShiftReturnSpacing } from "./builders.js";
3
5
  import { defaultsBaseline } from "./emphasis.js";
4
6
  import { createLabelCounter } from "./labels.js";
5
7
  import { guarded, loadPackage, readPartText, sha256Hex } from "./package.js";
6
- import { createStoryState, endStory, readParagraph, walkBlocks } from "./story.js";
8
+ import { resolveTrackedChanges } from "./revisions.js";
9
+ import { createStoryState, endStory, readParagraph, toggleOf, walkBlocks } from "./story.js";
7
10
  import { TemplatePlanError } from "./types.js";
8
- import { elementChildren, isW, readRawPart, wAttr, wChild } from "./xml.js";
11
+ import { elementChildren, halfPointsOrNull, integerOrNull, isW, readRawPart, twipsOrNull, wAttr, wChild, wChildVal, wChildren } from "./xml.js";
9
12
  import { Result } from "better-result";
10
13
  // src/docx/server/templatePlan/blocks.ts
11
14
  /** The block manifest of a DOCX: its main story as addressable, hash-pinned blocks. */
@@ -17,6 +20,196 @@ const styleOutlineLevel = (style) => {
17
20
  return outline?.kind === "heading" ? outline.level : null;
18
21
  };
19
22
  const styleNameOf = (style) => style?.name ?? null;
23
+ /** A section's page and how it begins, as its `w:sectPr` states them. */
24
+ const sectionOf = (sectPr, index) => {
25
+ const properties = parseSectionProperties(sectPr);
26
+ return {
27
+ index,
28
+ start: properties.sectionStart ?? "nextPage",
29
+ orientation: properties.orientation ?? "portrait",
30
+ size: {
31
+ width: properties.pageWidth ?? null,
32
+ height: properties.pageHeight ?? null
33
+ },
34
+ margins: {
35
+ top: properties.marginTop ?? null,
36
+ right: properties.marginRight ?? null,
37
+ bottom: properties.marginBottom ?? null,
38
+ left: properties.marginLeft ?? null
39
+ },
40
+ columns: properties.columnCount ?? 1
41
+ };
42
+ };
43
+ const NO_INDENT = {
44
+ left: null,
45
+ firstLine: null
46
+ };
47
+ const levelKey = (abstractNumId, ilvl) => `${String(abstractNumId)}:${String(ilvl)}`;
48
+ /** The sides a `w:ind` states; a hanging indent is a negative first line. */
49
+ const statedIndent = (indent) => {
50
+ const hanging = twipsOrNull(wAttr(indent, "hanging"));
51
+ return {
52
+ left: twipsOrNull(wAttr(indent, "left") ?? wAttr(indent, "start")),
53
+ firstLine: hanging === null ? twipsOrNull(wAttr(indent, "firstLine")) : -hanging
54
+ };
55
+ };
56
+ /**
57
+ * The indent each level of a numbering part states, by list definition and
58
+ * level, read off the part itself. An override a list instance makes of a
59
+ * level is not followed.
60
+ */
61
+ const statedLevelIndents = (numberingPath, numberingXml) => {
62
+ const indents = /* @__PURE__ */ new Map();
63
+ const part = numberingPath === null || numberingXml === null ? null : readRawPart(numberingPath, numberingXml);
64
+ for (const definition of wChildren(part?.root, "abstractNum")) {
65
+ const abstractNumId = integerOrNull(wAttr(definition, "abstractNumId"));
66
+ for (const level of wChildren(definition, "lvl")) {
67
+ const ilvl = integerOrNull(wAttr(level, "ilvl"));
68
+ if (abstractNumId !== null && ilvl !== null) indents.set(levelKey(abstractNumId, ilvl), statedIndent(wChild(wChild(level, "pPr"), "ind")));
69
+ }
70
+ }
71
+ return indents;
72
+ };
73
+ /** The indent the document's defaults give every paragraph. */
74
+ const statedDefaultIndent = (stylesPath, stylesXml) => {
75
+ const part = stylesPath === null || stylesXml === null ? null : readRawPart(stylesPath, stylesXml);
76
+ const defaults = wChild(wChild(part?.root, "docDefaults"), "pPrDefault");
77
+ return statedIndent(wChild(wChild(defaults, "pPr"), "ind"));
78
+ };
79
+ /** The sides a style states, as the document model holds them: a hanging
80
+ * indent is a negative first line. */
81
+ const modelIndent = (formatting) => {
82
+ const first = formatting?.indentFirstLine;
83
+ let firstLine = null;
84
+ if (first !== void 0) firstLine = formatting?.hangingIndent === true ? -Math.abs(first) : first;
85
+ return {
86
+ left: formatting?.indentLeft ?? null,
87
+ firstLine
88
+ };
89
+ };
90
+ /**
91
+ * The indent in effect: each side from the first of `sources` that states
92
+ * it. Null when none of them states a side.
93
+ */
94
+ const indentInEffect = (...sources) => {
95
+ const left = sources.find((source) => source.left !== null)?.left ?? null;
96
+ const firstLine = sources.find((source) => source.firstLine !== null)?.firstLine ?? null;
97
+ return left === null && firstLine === null ? null : {
98
+ left: left ?? 0,
99
+ firstLine: firstLine ?? 0
100
+ };
101
+ };
102
+ /** The alignment each style of a styles part states for itself (`w:jc`). */
103
+ const statedAlignments = (stylesPath, stylesXml) => {
104
+ const alignments = /* @__PURE__ */ new Map();
105
+ const part = stylesPath === null || stylesXml === null ? null : readRawPart(stylesPath, stylesXml);
106
+ for (const style of wChildren(part?.root, "style")) {
107
+ const styleId = wAttr(style, "styleId");
108
+ const alignment = wChildVal(wChild(style, "pPr"), "jc");
109
+ if (styleId !== null && alignment !== null) alignments.set(styleId, alignment);
110
+ }
111
+ return alignments;
112
+ };
113
+ /** The alignment of the nearest style in the `basedOn` chain that states one. */
114
+ const styleAlignment = (styleId, styles, stated) => {
115
+ const seen = /* @__PURE__ */ new Set();
116
+ let cursor = styleId ?? void 0;
117
+ while (cursor !== void 0 && !seen.has(cursor)) {
118
+ seen.add(cursor);
119
+ const alignment = stated.get(cursor);
120
+ if (alignment !== void 0) return alignment;
121
+ cursor = styles.get(cursor)?.basedOn;
122
+ }
123
+ return null;
124
+ };
125
+ const statedLook = (paragraph, run) => ({
126
+ bold: toggleOf(wChild(run, "b")),
127
+ size: halfPointsOrNull(wChildVal(run, "sz")),
128
+ keepNext: toggleOf(wChild(paragraph, "keepNext")),
129
+ indentLeft: twipsOrNull(wAttr(wChild(paragraph, "ind"), "left") ?? wAttr(wChild(paragraph, "ind"), "start"))
130
+ });
131
+ /** The look each style of the styles part states itself, by style id, and
132
+ * the look the document's defaults state. */
133
+ const statedLooks = (stylesPath, stylesXml) => {
134
+ const styles = /* @__PURE__ */ new Map();
135
+ const part = stylesPath === null || stylesXml === null ? null : readRawPart(stylesPath, stylesXml);
136
+ for (const style of wChildren(part?.root, "style")) {
137
+ const styleId = wAttr(style, "styleId");
138
+ if (styleId !== null) styles.set(styleId, statedLook(wChild(style, "pPr"), wChild(style, "rPr")));
139
+ }
140
+ const defaults = wChild(part?.root, "docDefaults");
141
+ return {
142
+ styles,
143
+ defaults: statedLook(wChild(wChild(defaults, "pPrDefault"), "pPr"), wChild(wChild(defaults, "rPrDefault"), "rPr"))
144
+ };
145
+ };
146
+ /**
147
+ * The look a style gives its text: each property from the nearest style in
148
+ * the `basedOn` chain that states it, then from the document's defaults.
149
+ * Without a statement text is not bold and a paragraph is not kept with the
150
+ * next; the size and the left indent stay null, which leaves the size to
151
+ * the application and the indent to a list level, if the style has one.
152
+ */
153
+ const styleLook = (styleId, styles, { styles: stated, defaults }) => {
154
+ const look = {
155
+ bold: null,
156
+ size: null,
157
+ keepNext: null,
158
+ indentLeft: null
159
+ };
160
+ const seen = /* @__PURE__ */ new Set();
161
+ let cursor = styleId ?? void 0;
162
+ while (cursor !== void 0 && !seen.has(cursor)) {
163
+ seen.add(cursor);
164
+ const own = stated.get(cursor);
165
+ look.bold ??= own?.bold ?? null;
166
+ look.size ??= own?.size ?? null;
167
+ look.keepNext ??= own?.keepNext ?? null;
168
+ look.indentLeft ??= own?.indentLeft ?? null;
169
+ cursor = styles.get(cursor)?.basedOn;
170
+ }
171
+ return {
172
+ bold: look.bold ?? defaults.bold ?? false,
173
+ size: look.size ?? defaults.size,
174
+ keepNext: look.keepNext ?? defaults.keepNext ?? false,
175
+ indentLeft: look.indentLeft ?? defaults.indentLeft
176
+ };
177
+ };
178
+ /**
179
+ * The sections of a story with what each states. A body without section
180
+ * properties of its own still ends in a section, which states nothing.
181
+ */
182
+ const storySections = ({ sections, hasBodySection }) => {
183
+ const stated = sections.map(sectionOf);
184
+ return hasBodySection ? stated : [...stated, {
185
+ index: stated.length,
186
+ start: "nextPage",
187
+ orientation: "portrait",
188
+ size: {
189
+ width: null,
190
+ height: null
191
+ },
192
+ margins: {
193
+ top: null,
194
+ right: null,
195
+ bottom: null,
196
+ left: null
197
+ },
198
+ columns: 1
199
+ }];
200
+ };
201
+ /** Page breaks among a paragraph's runs; a column break is not one. */
202
+ const pageBreaksOf = ({ atoms }) => atoms.filter(({ kind, element }) => kind === "pageBreak" && wAttr(element, "type") === "page").length;
203
+ /** Where in a paragraph's text its self-numbering fields stand. */
204
+ const selfNumbersOf = ({ atoms }) => {
205
+ const offsets = [];
206
+ let at = 0;
207
+ for (const { kind, text } of atoms) {
208
+ if (kind === "selfNumber") offsets.push(at);
209
+ at += text.length;
210
+ }
211
+ return offsets;
212
+ };
20
213
  /** Read the blocks under `container` into ids, text, labels and hashes. */
21
214
  const analyzeStory = ({ container, resources, counter = createLabelCounter(resources) }) => {
22
215
  const state = createStoryState();
@@ -27,6 +220,7 @@ const analyzeStory = ({ container, resources, counter = createLabelCounter(resou
27
220
  paragraphs: [],
28
221
  state,
29
222
  sections: [],
223
+ hasBodySection: false,
30
224
  unreadBlocks: [],
31
225
  warnings: []
32
226
  };
@@ -55,7 +249,8 @@ const analyzeStory = ({ container, resources, counter = createLabelCounter(resou
55
249
  const style = resources.styles.get(styleId ?? resources.defaultStyleId ?? "");
56
250
  const label = counter.next({
57
251
  styleId,
58
- numPr: read.numPr
252
+ numPr: read.numPr,
253
+ language: read.language
59
254
  });
60
255
  const id = `p${index}`;
61
256
  const block = {
@@ -73,6 +268,19 @@ const analyzeStory = ({ container, resources, counter = createLabelCounter(resou
73
268
  ...read.paraId === null ? {} : { paraId: read.paraId },
74
269
  inlineObjects: read.inlineObjects
75
270
  };
271
+ const pageBreaks = pageBreaksOf(read);
272
+ if (pageBreaks > 0) block.pageBreaks = pageBreaks;
273
+ const selfNumbers = selfNumbersOf(read);
274
+ if (selfNumbers.length > 0) block.selfNumbers = selfNumbers;
275
+ if (read.pageBreakBefore ?? style?.pPr?.pageBreakBefore === true) block.pageBreakBefore = true;
276
+ if (read.hasSectionBreak) block.endsSection = true;
277
+ const alignment = read.alignment ?? (resources.alignments === void 0 ? null : styleAlignment(styleId ?? resources.defaultStyleId, resources.styles, resources.alignments));
278
+ if (alignment !== null) block.alignment = alignment;
279
+ const ofLevel = (label.numbering === null ? void 0 : resources.levelIndents?.get(levelKey(label.numbering.abstractNumId, label.numbering.ilvl))) ?? NO_INDENT;
280
+ const ofStyle = modelIndent(style?.pPr);
281
+ const ofDefaults = resources.defaultIndent ?? NO_INDENT;
282
+ const indent = read.numPr === void 0 ? indentInEffect(read.indent, ofStyle, ofLevel, ofDefaults) : indentInEffect(read.indent, ofLevel, ofStyle, ofDefaults);
283
+ if (indent !== null && !read.indentInCharacters) block.indent = indent;
76
284
  index += 1;
77
285
  const analyzed = {
78
286
  block,
@@ -166,7 +374,10 @@ const analyzeStory = ({ container, resources, counter = createLabelCounter(resou
166
374
  }
167
375
  });
168
376
  const bodySection = wChild(container, "sectPr");
169
- if (bodySection !== null) story.sections.push(bodySection);
377
+ if (bodySection !== null) {
378
+ story.sections.push(bodySection);
379
+ story.hasBodySection = true;
380
+ }
170
381
  for (const [name, count] of unread) {
171
382
  story.unreadBlocks.push(name);
172
383
  story.warnings.push(`${count} block-level ${name} element(s) are not read as blocks.`);
@@ -278,13 +489,14 @@ const analyzeDocument = async (bytes) => {
278
489
  numberingPath,
279
490
  footnotesPath,
280
491
  endnotesPath,
281
- pkg.partPath("comments")
492
+ pkg.partPath("comments"),
493
+ pkg.partPath("settings")
282
494
  ]) {
283
495
  const text = await readPartText(pkg, path);
284
496
  if (Result.isError(text)) return text;
285
497
  texts.push(text.value);
286
498
  }
287
- const [stylesXml = null, numberingXml = null, footnotesXml = null, endnotesXml = null, commentsXml = null] = texts;
499
+ const [stylesXml = null, numberingXml = null, footnotesXml = null, endnotesXml = null, commentsXml = null, settingsXml = null] = texts;
288
500
  const read = Result.try({
289
501
  try: () => {
290
502
  const stylesPackage = stylesXml === null ? null : parseStylesPackage(stylesXml, null);
@@ -302,7 +514,11 @@ const analyzeDocument = async (bytes) => {
302
514
  resources: {
303
515
  styles,
304
516
  defaultStyleId,
305
- numbering
517
+ defaultLanguage: stylesPackage?.styleDefinitions.docDefaults?.rPr?.language?.val ?? null,
518
+ numbering,
519
+ alignments: statedAlignments(stylesPath, stylesXml),
520
+ levelIndents: statedLevelIndents(numberingPath, numberingXml),
521
+ defaultIndent: statedDefaultIndent(stylesPath, stylesXml)
306
522
  }
307
523
  }),
308
524
  footnotes: analyzeNotes("footnotes", footnotesPath, footnotesXml),
@@ -323,6 +539,8 @@ const analyzeDocument = async (bytes) => {
323
539
  const manifest = {
324
540
  sha256: pkg.sha256,
325
541
  blocks: story.topLevel.map(({ block }) => block),
542
+ sections: storySections(story),
543
+ compat: { doNotExpandShiftReturn: settingsXml !== null && keepsShiftReturnSpacing(settingsXml) },
326
544
  footnotes: noteList(footnotes),
327
545
  endnotes: noteList(endnotes),
328
546
  comments: countComments(commentsXml),
@@ -347,9 +565,53 @@ const analyzeDocument = async (bytes) => {
347
565
  manifest
348
566
  });
349
567
  };
568
+ /** The view a plan states, when what was handed in is shaped like a plan
569
+ * at all; its shape is checked where the plan is resolved. */
570
+ const viewOf = (plan) => {
571
+ const view = typeof plan === "object" && plan !== null && "trackedChanges" in plan ? plan.trackedChanges : void 0;
572
+ return view === "accept" || view === "reject" ? view : void 0;
573
+ };
574
+ /**
575
+ * Analyse a source in the view a caller chose of its tracked changes, or
576
+ * as it stands. In a view, the package that is analysed is the resolved
577
+ * one, while the manifest keeps the hash of the bytes that were given: a
578
+ * plan pins the file, not a rewriting of it. Without a view, a document
579
+ * that tracks changes says what it tracks.
580
+ */
581
+ const analyzeSource = async (bytes, view) => {
582
+ if (view === void 0) {
583
+ const analyzed = await analyzeDocument(bytes);
584
+ if (Result.isError(analyzed) || analyzed.value.manifest.trackedChanges === 0) return analyzed;
585
+ const tracked = await resolveTrackedChanges(bytes, "accept");
586
+ return Result.isError(tracked) ? analyzed : Result.ok({
587
+ ...analyzed.value,
588
+ manifest: {
589
+ ...analyzed.value.manifest,
590
+ revisions: tracked.value.resolved
591
+ }
592
+ });
593
+ }
594
+ const resolved = await resolveTrackedChanges(bytes, view);
595
+ if (Result.isError(resolved)) return resolved;
596
+ const analyzed = await analyzeDocument(resolved.value.docx);
597
+ if (Result.isError(analyzed)) return analyzed;
598
+ return Result.ok({
599
+ ...analyzed.value,
600
+ manifest: {
601
+ ...analyzed.value.manifest,
602
+ sha256: sha256Hex(bytes),
603
+ trackedChangesResolved: {
604
+ view,
605
+ ...resolved.value.resolved
606
+ }
607
+ }
608
+ });
609
+ };
350
610
  /**
351
611
  * Read a DOCX into the blocks a template plan addresses: ids, visible text,
352
- * rendered list labels, styles and a hash per block, plus its notes.
612
+ * rendered list labels, styles and a hash per block, plus its notes. With
613
+ * `trackedChanges`, the blocks are those of that view of a document with
614
+ * tracked changes.
353
615
  */
354
- const analyzeDocxBlocks = async (docx) => await guarded(async () => (await analyzeDocument(docx)).map(({ manifest }) => manifest));
355
- export { analyzeDocument, analyzeDocxBlocks, analyzeStory, blockHash, styleOutlineLevel };
616
+ const analyzeDocxBlocks = async (docx, options = {}) => await guarded(async () => (await analyzeSource(docx, options.trackedChanges)).map(({ manifest }) => manifest));
617
+ export { analyzeDocument, analyzeDocxBlocks, analyzeSource, analyzeStory, blockHash, statedAlignments, statedLooks, storySections, styleAlignment, styleLook, styleOutlineLevel, viewOf };