@stll/folio-core 0.75.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 (92) hide show
  1. package/dist/ai-edits/headless.d.ts +2 -1
  2. package/dist/ai-edits/headless.js +18 -12
  3. package/dist/ai-edits/pending-suggestions.js +2 -3
  4. package/dist/ai-edits/read.js +9 -3
  5. package/dist/ai-edits/types.d.ts +9 -4
  6. package/dist/canonical/batchCommentReferences.js +2 -1
  7. package/dist/canonical/canonicalBatchReview.js +5 -8
  8. package/dist/canonical/canonicalComments.js +8 -2
  9. package/dist/canonical/canonicalCompilerRefusal.d.ts +2 -4
  10. package/dist/canonical/canonicalCompilerRefusal.js +20 -14
  11. package/dist/canonical/canonicalPublicOperations.js +203 -71
  12. package/dist/canonical/canonicalSession.js +3 -1
  13. package/dist/controller/canonicalClipboard.d.ts +1 -1
  14. package/dist/controller/canonicalClipboard.js +71 -17
  15. package/dist/controller/canonicalContentControlValue.js +7 -7
  16. package/dist/controller/canonicalReview.d.ts +21 -0
  17. package/dist/controller/canonicalReview.js +44 -9
  18. package/dist/controller/canonicalStructure.d.ts +1 -2
  19. package/dist/controller/canonicalStructure.js +51 -24
  20. package/dist/controller/fontReadiness.js +50 -23
  21. package/dist/controller/hiddenEditorManager.js +5 -20
  22. package/dist/docx/bulletMarkers.d.ts +8 -0
  23. package/dist/docx/bulletMarkers.js +9 -1
  24. package/dist/docx/canonicalSessionInput.js +25 -11
  25. package/dist/docx/ensureParaIds.d.ts +31 -0
  26. package/dist/docx/ensureParaIds.js +57 -32
  27. package/dist/docx/ensureUniqueControlIds.d.ts +13 -0
  28. package/dist/docx/ensureUniqueControlIds.js +47 -29
  29. package/dist/docx/ensureUniqueRevisionIds.d.ts +13 -0
  30. package/dist/docx/ensureUniqueRevisionIds.js +52 -29
  31. package/dist/docx/server/templatePlan/apply.js +62 -8
  32. package/dist/docx/server/templatePlan/blocks.d.ts +55 -3
  33. package/dist/docx/server/templatePlan/blocks.js +182 -6
  34. package/dist/docx/server/templatePlan/builders.d.ts +16 -1
  35. package/dist/docx/server/templatePlan/builders.js +31 -3
  36. package/dist/docx/server/templatePlan/effects.d.ts +27 -0
  37. package/dist/docx/server/templatePlan/effects.js +188 -0
  38. package/dist/docx/server/templatePlan/emit.d.ts +2 -1
  39. package/dist/docx/server/templatePlan/emit.js +44 -2
  40. package/dist/docx/server/templatePlan/inspect.js +21 -1
  41. package/dist/docx/server/templatePlan/labels.js +16 -1
  42. package/dist/docx/server/templatePlan/plan.d.ts +12 -3
  43. package/dist/docx/server/templatePlan/plan.js +36 -12
  44. package/dist/docx/server/templatePlan/planShape.js +47 -22
  45. package/dist/docx/server/templatePlan/revisions.d.ts +46 -0
  46. package/dist/docx/server/templatePlan/revisions.js +407 -0
  47. package/dist/docx/server/templatePlan/story.d.ts +15 -1
  48. package/dist/docx/server/templatePlan/story.js +50 -2
  49. package/dist/docx/server/templatePlan/types.d.ts +217 -1
  50. package/dist/docx/server/templatePlan/verify.js +117 -8
  51. package/dist/docx/server/templatePlan/xml.d.ts +3 -0
  52. package/dist/docx/server/templatePlan/xml.js +4 -1
  53. package/dist/internal/revisionResolutionStep.d.ts +2 -31
  54. package/dist/internal/revisionResolutionStep.js +2 -171
  55. package/dist/prosemirror/commands/comments.d.ts +6 -234
  56. package/dist/prosemirror/commands/comments.js +5 -2464
  57. package/dist/prosemirror/commands/index.d.ts +4 -2
  58. package/dist/prosemirror/commands/index.js +4 -2
  59. package/dist/prosemirror/commands/tableCellMergeResolution.d.ts +1 -11
  60. package/dist/prosemirror/commands/tableCellMergeResolution.js +3 -154
  61. package/dist/prosemirror/extensions/marks/HyperlinkExtension.js +6 -8
  62. package/dist/prosemirror/hyperlinkRemoval.d.ts +11 -8
  63. package/dist/prosemirror/hyperlinkRemoval.js +24 -15
  64. package/dist/prosemirror/paraIds.d.ts +1 -14
  65. package/dist/prosemirror/paraIds.js +1 -14
  66. package/dist/prosemirror/paragraphMarkJoin.d.ts +0 -16
  67. package/dist/prosemirror/paragraphMarkJoin.js +3 -46
  68. package/dist/prosemirror/projectionReview.d.ts +49 -0
  69. package/dist/prosemirror/projectionReview.js +292 -0
  70. package/dist/prosemirror/rebaseParagraphRunFormatting.d.ts +1 -13
  71. package/dist/prosemirror/rebaseParagraphRunFormatting.js +1 -16
  72. package/dist/prosemirror/replacedAnnotations.d.ts +2 -5
  73. package/dist/prosemirror/replacedAnnotations.js +1 -10
  74. package/dist/prosemirror/revisionCarriers.d.ts +9 -1
  75. package/dist/prosemirror/revisionCarriers.js +15 -1
  76. package/dist/prosemirror/revisionRangeQueries.d.ts +32 -0
  77. package/dist/prosemirror/revisionRangeQueries.js +76 -0
  78. package/dist/prosemirror/runFormattingMarkNames.d.ts +1 -1
  79. package/dist/prosemirror/runFormattingMarkNames.js +1 -1
  80. package/dist/prosemirror/suggestionQueries.d.ts +114 -0
  81. package/dist/prosemirror/suggestionQueries.js +320 -0
  82. package/dist/prosemirror/tableGridMutation.d.ts +1 -16
  83. package/dist/prosemirror/tableGridMutation.js +1 -78
  84. package/dist/prosemirror/tableRowRevisionOwnership.d.ts +18 -0
  85. package/dist/prosemirror/tableRowRevisionOwnership.js +7 -0
  86. package/dist/prosemirror/utils/extractTrackedChanges.js +14 -4
  87. package/dist/server.d.ts +2 -2
  88. package/dist/types/canonicalCapabilities.d.ts +1 -25
  89. package/dist/types/canonicalCapabilities.js +1 -23
  90. package/package.json +2 -2
  91. package/dist/internal/headlessRevisionResolutionGuard.d.ts +0 -3
  92. 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, sectionPropertiesXml, setKeepShiftReturnSpacing, 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()) {
@@ -389,6 +423,7 @@ const writeOutput = async ({ source, template, plan, resolved }) => {
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;
391
425
  const bodySection = wChild(template.body, "sectPr");
426
+ const inherited = bodySection === null ? [] : inheritedReferencesXml(template.document.xml, template.body, bodySection);
392
427
  const sectionEnds = resolved.items.flatMap((item) => item.kind === "paragraph" && item.paragraph.endsSection !== null ? [item.paragraph] : []);
393
428
  const sectionXmlOf = /* @__PURE__ */ new Map();
394
429
  for (const [position, paragraph] of sectionEnds.entries()) {
@@ -396,7 +431,8 @@ const writeOutput = async ({ source, template, plan, resolved }) => {
396
431
  const xml = bodySection === null || section === null ? null : sectionPropertiesXml(template.document.xml, bodySection, documentContext.prefixes.w, {
397
432
  first: position === 0,
398
433
  page: section.page,
399
- start: position === 0 ? null : section.start ?? "nextPage"
434
+ start: position === 0 ? null : section.start ?? "nextPage",
435
+ inherited
400
436
  });
401
437
  if (xml === null) return Result.err(unreadable(pkg.documentPath, "A section could not be built."));
402
438
  sectionXmlOf.set(paragraph, xml);
@@ -486,10 +522,11 @@ const writeOutput = async ({ source, template, plan, resolved }) => {
486
522
  }
487
523
  if (bodySection !== null) {
488
524
  const { lastSection } = plan;
489
- const rebuilt = sectionEnds.length > 0 || lastSection !== void 0 ? sectionPropertiesXml(template.document.xml, bodySection, documentContext.prefixes.w, {
525
+ const rebuilt = sectionEnds.length > 0 || lastSection !== void 0 || inherited.length > 0 ? sectionPropertiesXml(template.document.xml, bodySection, documentContext.prefixes.w, {
490
526
  first: sectionEnds.length === 0,
491
527
  page: lastSection?.page,
492
- start: sectionEnds.length === 0 ? null : lastSection?.start ?? null
528
+ start: sectionEnds.length === 0 ? null : lastSection?.start ?? null,
529
+ inherited
493
530
  }) : null;
494
531
  const section = rebuilt === null ? keptXml(bodySection) : Result.ok(rebuilt);
495
532
  if (Result.isError(section)) return section;
@@ -633,6 +670,23 @@ const writeOutput = async ({ source, template, plan, resolved }) => {
633
670
  if (settings === null) return Result.err(unreadable(settingsPath, "The settings part could not be updated."));
634
671
  if (settings !== settingsXml.value) parts.set(settingsPath, settings);
635
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
+ }
636
690
  return await Result.tryPromise({
637
691
  try: async () => {
638
692
  const zip = await ZipArchive.read(pkg.bytes);
@@ -650,7 +704,7 @@ const writeOutput = async ({ source, template, plan, resolved }) => {
650
704
  });
651
705
  };
652
706
  const applyUnguarded = async ({ source, template, plan, options }) => {
653
- const analyzedSource = await analyzeDocument(source);
707
+ const analyzedSource = await analyzeSource(source, viewOf(plan));
654
708
  if (Result.isError(analyzedSource)) return analyzedSource;
655
709
  const analyzedTemplate = await analyzeDocument(template);
656
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, DocxSection, 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;
@@ -46,13 +46,50 @@ type StoryResources = {
46
46
  numbering: NumberingMap | null;
47
47
  /** The alignment each paragraph style states for itself (`w:jc`). */
48
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;
49
53
  };
50
54
  /** The heading level a style outlines its paragraphs at, 0 being the highest. */
51
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
+ };
52
60
  /** The alignment each style of a styles part states for itself (`w:jc`). */
53
61
  export declare const statedAlignments: (stylesPath: string | null, stylesXml: string | null) => Map<string, string>;
54
62
  /** The alignment of the nearest style in the `basedOn` chain that states one. */
55
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
+ };
56
93
  /**
57
94
  * The sections of a story with what each states. A body without section
58
95
  * properties of its own still ends in a section, which states nothing.
@@ -104,9 +141,24 @@ export type AnalyzedDocument = {
104
141
  };
105
142
  /** Open a package and analyse its main story, notes, styles and numbering. */
106
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>>;
107
155
  /**
108
156
  * Read a DOCX into the blocks a template plan addresses: ids, visible text,
109
- * 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.
110
160
  */
111
- 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>>;
112
164
  export {};
@@ -5,9 +5,10 @@ import { keepsShiftReturnSpacing } from "./builders.js";
5
5
  import { defaultsBaseline } from "./emphasis.js";
6
6
  import { createLabelCounter } from "./labels.js";
7
7
  import { guarded, loadPackage, readPartText, sha256Hex } from "./package.js";
8
- import { createStoryState, endStory, readParagraph, walkBlocks } from "./story.js";
8
+ import { resolveTrackedChanges } from "./revisions.js";
9
+ import { createStoryState, endStory, readParagraph, toggleOf, walkBlocks } from "./story.js";
9
10
  import { TemplatePlanError } from "./types.js";
10
- import { elementChildren, isW, readRawPart, wAttr, wChild, wChildVal, wChildren } from "./xml.js";
11
+ import { elementChildren, halfPointsOrNull, integerOrNull, isW, readRawPart, twipsOrNull, wAttr, wChild, wChildVal, wChildren } from "./xml.js";
11
12
  import { Result } from "better-result";
12
13
  // src/docx/server/templatePlan/blocks.ts
13
14
  /** The block manifest of a DOCX: its main story as addressable, hash-pinned blocks. */
@@ -39,6 +40,65 @@ const sectionOf = (sectPr, index) => {
39
40
  columns: properties.columnCount ?? 1
40
41
  };
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
+ };
42
102
  /** The alignment each style of a styles part states for itself (`w:jc`). */
43
103
  const statedAlignments = (stylesPath, stylesXml) => {
44
104
  const alignments = /* @__PURE__ */ new Map();
@@ -62,6 +122,59 @@ const styleAlignment = (styleId, styles, stated) => {
62
122
  }
63
123
  return null;
64
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
+ };
65
178
  /**
66
179
  * The sections of a story with what each states. A body without section
67
180
  * properties of its own still ends in a section, which states nothing.
@@ -87,6 +200,16 @@ const storySections = ({ sections, hasBodySection }) => {
87
200
  };
88
201
  /** Page breaks among a paragraph's runs; a column break is not one. */
89
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
+ };
90
213
  /** Read the blocks under `container` into ids, text, labels and hashes. */
91
214
  const analyzeStory = ({ container, resources, counter = createLabelCounter(resources) }) => {
92
215
  const state = createStoryState();
@@ -147,10 +270,17 @@ const analyzeStory = ({ container, resources, counter = createLabelCounter(resou
147
270
  };
148
271
  const pageBreaks = pageBreaksOf(read);
149
272
  if (pageBreaks > 0) block.pageBreaks = pageBreaks;
273
+ const selfNumbers = selfNumbersOf(read);
274
+ if (selfNumbers.length > 0) block.selfNumbers = selfNumbers;
150
275
  if (read.pageBreakBefore ?? style?.pPr?.pageBreakBefore === true) block.pageBreakBefore = true;
151
276
  if (read.hasSectionBreak) block.endsSection = true;
152
277
  const alignment = read.alignment ?? (resources.alignments === void 0 ? null : styleAlignment(styleId ?? resources.defaultStyleId, resources.styles, resources.alignments));
153
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;
154
284
  index += 1;
155
285
  const analyzed = {
156
286
  block,
@@ -386,7 +516,9 @@ const analyzeDocument = async (bytes) => {
386
516
  defaultStyleId,
387
517
  defaultLanguage: stylesPackage?.styleDefinitions.docDefaults?.rPr?.language?.val ?? null,
388
518
  numbering,
389
- alignments: statedAlignments(stylesPath, stylesXml)
519
+ alignments: statedAlignments(stylesPath, stylesXml),
520
+ levelIndents: statedLevelIndents(numberingPath, numberingXml),
521
+ defaultIndent: statedDefaultIndent(stylesPath, stylesXml)
390
522
  }
391
523
  }),
392
524
  footnotes: analyzeNotes("footnotes", footnotesPath, footnotesXml),
@@ -433,9 +565,53 @@ const analyzeDocument = async (bytes) => {
433
565
  manifest
434
566
  });
435
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
+ };
436
610
  /**
437
611
  * Read a DOCX into the blocks a template plan addresses: ids, visible text,
438
- * 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.
439
615
  */
440
- const analyzeDocxBlocks = async (docx) => await guarded(async () => (await analyzeDocument(docx)).map(({ manifest }) => manifest));
441
- export { analyzeDocument, analyzeDocxBlocks, analyzeStory, blockHash, statedAlignments, storySections, styleAlignment, 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 };
@@ -78,14 +78,29 @@ export type SectionRewrite = {
78
78
  page: TemplatePlanSectionPage | undefined;
79
79
  /** How the section begins; null keeps what the template states. */
80
80
  start: string | null;
81
+ /**
82
+ * Header and footer references the section takes over from the sections
83
+ * in front of it and does not state itself, as markup. Left out, the
84
+ * section is written with its own alone.
85
+ */
86
+ inherited?: readonly string[];
81
87
  };
88
+ /**
89
+ * The header and footer references a body's last section takes over from
90
+ * the sections in front of it: a section that states no header of a kind
91
+ * shows the one of the section before. An output built from the last
92
+ * section alone would lose them, so they are stated on it. Each is the
93
+ * reference of the nearest earlier section that states that kind, as it is
94
+ * written in `xml`; kinds the last section states itself are left out.
95
+ */
96
+ export declare const inheritedReferencesXml: (xml: string, body: XmlElement, last: XmlElement) => string[];
82
97
  /**
83
98
  * A `w:sectPr` built from the template's: the same children in the same
84
99
  * order, with the page, the start and the first-section properties changed
85
100
  * as `rewrite` says. `xml` is the part `sectPr` was read from. Null when a
86
101
  * child cannot be read back.
87
102
  */
88
- export declare const sectionPropertiesXml: (xml: string, sectPr: XmlElement, w: string, { first, page, start }: SectionRewrite) => string | null;
103
+ export declare const sectionPropertiesXml: (xml: string, sectPr: XmlElement, w: string, { first, page, start, inherited }: SectionRewrite) => string | null;
89
104
  export type FrozenFieldCount = {
90
105
  kind: string;
91
106
  count: number;
@@ -256,15 +256,43 @@ const MARGINS_KEPT = [
256
256
  "gutter"
257
257
  ];
258
258
  /**
259
+ * The header and footer references a body's last section takes over from
260
+ * the sections in front of it: a section that states no header of a kind
261
+ * shows the one of the section before. An output built from the last
262
+ * section alone would lose them, so they are stated on it. Each is the
263
+ * reference of the nearest earlier section that states that kind, as it is
264
+ * written in `xml`; kinds the last section states itself are left out.
265
+ */
266
+ const inheritedReferencesXml = (xml, body, last) => {
267
+ const keyOf = (reference) => {
268
+ const name = wName(reference);
269
+ return name === "headerReference" || name === "footerReference" ? `${name}:${wAttr(reference, "type") ?? "default"}` : null;
270
+ };
271
+ const referencesOf = (sectPr) => elementChildren(sectPr).flatMap((child) => {
272
+ const key = keyOf(child);
273
+ return key === null ? [] : [[key, child]];
274
+ });
275
+ const inEffect = /* @__PURE__ */ new Map();
276
+ for (const block of elementChildren(body)) {
277
+ const sectPr = wName(block) === "p" ? wChild(wChild(block, "pPr"), "sectPr") : null;
278
+ for (const [key, reference] of referencesOf(sectPr)) inEffect.set(key, reference);
279
+ }
280
+ const own = new Set(referencesOf(last).map(([key]) => key));
281
+ return [...inEffect].flatMap(([key, reference]) => {
282
+ const range = own.has(key) ? null : rangeOf(reference);
283
+ return range === null ? [] : [xml.slice(range.start, range.end)];
284
+ });
285
+ };
286
+ /**
259
287
  * A `w:sectPr` built from the template's: the same children in the same
260
288
  * order, with the page, the start and the first-section properties changed
261
289
  * as `rewrite` says. `xml` is the part `sectPr` was read from. Null when a
262
290
  * child cannot be read back.
263
291
  */
264
- const sectionPropertiesXml = (xml, sectPr, w, { first, page, start }) => {
292
+ const sectionPropertiesXml = (xml, sectPr, w, { first, page, start, inherited = [] }) => {
265
293
  const attributes = (element, names) => names.map((name) => [name, wAttr(element, name)]).filter(([, value]) => value !== null).map(([name, value]) => ` ${w}:${name}="${escapeXmlAttribute(value ?? "")}"`).join("");
266
294
  const type = start === null ? "" : `<${w}:type ${w}:val="${start}"/>`;
267
- const out = [];
295
+ const out = [...inherited];
268
296
  let typeWritten = type === "";
269
297
  for (const child of elementChildren(sectPr)) {
270
298
  const name = wName(child);
@@ -425,4 +453,4 @@ const freezeFields = (part, kinds) => {
425
453
  }))
426
454
  };
427
455
  };
428
- export { applyRefCaseFormat, bookmarkEndXml, bookmarkIdsOf, bookmarkStartXml, complexFieldXml, fieldBookmarkOf, freezeFields, keepsShiftReturnSpacing, mintRefBookmarkName, refCaseFormat, refFieldInstruction, sectionPropertiesXml, setKeepShiftReturnSpacing, setUpdateFieldsOnOpen, withoutContained, wrapParagraphContentInBookmark };
456
+ export { applyRefCaseFormat, bookmarkEndXml, bookmarkIdsOf, bookmarkStartXml, complexFieldXml, fieldBookmarkOf, freezeFields, inheritedReferencesXml, keepsShiftReturnSpacing, mintRefBookmarkName, refCaseFormat, refFieldInstruction, sectionPropertiesXml, setKeepShiftReturnSpacing, setUpdateFieldsOnOpen, withoutContained, wrapParagraphContentInBookmark };
@@ -0,0 +1,27 @@
1
+ import { DocxTextEffect, DocxTextEffectOwner } from "./types.js";
2
+ import { RawPart, XmlRange } from "./xml.js";
3
+ export type TextEffect = DocxTextEffect;
4
+ export type TextEffectOwner = DocxTextEffectOwner;
5
+ export declare const TEXT_EFFECTS: readonly TextEffect[];
6
+ export type InvisibleEffect = {
7
+ effect: TextEffect;
8
+ owner: TextEffectOwner;
9
+ range: XmlRange;
10
+ };
11
+ /** Every text effect of a part that shows nothing, in document order. */
12
+ export declare const findInvisibleEffects: ({ root }: RawPart) => InvisibleEffect[];
13
+ /**
14
+ * `part` without its text effects that show nothing; every other byte
15
+ * stays. `xml` is the part as it stands when nothing qualifies. Null when
16
+ * the part cannot be rewritten.
17
+ */
18
+ export declare const removeInvisibleEffects: (part: RawPart) => {
19
+ xml: string;
20
+ removed: InvisibleEffect[];
21
+ } | null;
22
+ /** How many of each effect a part lost, for a report. */
23
+ export declare const countEffects: (part: string, effects: readonly InvisibleEffect[]) => {
24
+ part: string;
25
+ effect: TextEffect;
26
+ count: number;
27
+ }[];