@stll/folio-core 0.75.0 → 0.77.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 (143) hide show
  1. package/dist/ai-edits/headless.d.ts +8 -5
  2. package/dist/ai-edits/headless.js +49 -26
  3. package/dist/ai-edits/pending-suggestions.d.ts +9 -0
  4. package/dist/ai-edits/pending-suggestions.js +13 -3
  5. package/dist/ai-edits/read.js +33 -4
  6. package/dist/ai-edits/table-geometry.js +12 -4
  7. package/dist/ai-edits/types.d.ts +9 -4
  8. package/dist/canonical/batchCommentReferences.js +2 -1
  9. package/dist/canonical/canonicalBatchReview.js +5 -8
  10. package/dist/canonical/canonicalComments.js +8 -2
  11. package/dist/canonical/canonicalCompilerRefusal.d.ts +2 -4
  12. package/dist/canonical/canonicalCompilerRefusal.js +20 -14
  13. package/dist/canonical/canonicalInlineProjection.d.ts +2 -2
  14. package/dist/canonical/canonicalInlineProjection.js +2 -2
  15. package/dist/canonical/canonicalProjectionBlocks.d.ts +10 -1
  16. package/dist/canonical/canonicalPublicOperations.js +214 -107
  17. package/dist/canonical/canonicalSeedContent.d.ts +18 -3
  18. package/dist/canonical/canonicalSeedContent.js +28 -15
  19. package/dist/canonical/canonicalSession.d.ts +22 -12
  20. package/dist/canonical/canonicalSession.js +181 -187
  21. package/dist/controller/canonicalClipboard.d.ts +3 -2
  22. package/dist/controller/canonicalClipboard.js +377 -58
  23. package/dist/controller/canonicalComposition.js +67 -14
  24. package/dist/controller/canonicalContentControlValue.js +7 -7
  25. package/dist/controller/canonicalReview.d.ts +21 -0
  26. package/dist/controller/canonicalReview.js +44 -9
  27. package/dist/controller/canonicalStoryEditor.js +2 -0
  28. package/dist/controller/canonicalStructure.d.ts +1 -2
  29. package/dist/controller/canonicalStructure.js +51 -24
  30. package/dist/controller/fontReadiness.js +50 -23
  31. package/dist/controller/hiddenEditorManager.js +7 -20
  32. package/dist/docx/bulletMarkers.d.ts +8 -0
  33. package/dist/docx/bulletMarkers.js +9 -1
  34. package/dist/docx/canonicalSessionInput.js +25 -11
  35. package/dist/docx/ensureParaIds.d.ts +31 -0
  36. package/dist/docx/ensureParaIds.js +57 -32
  37. package/dist/docx/ensureUniqueControlIds.d.ts +13 -0
  38. package/dist/docx/ensureUniqueControlIds.js +47 -29
  39. package/dist/docx/ensureUniqueRevisionIds.d.ts +13 -0
  40. package/dist/docx/ensureUniqueRevisionIds.js +52 -29
  41. package/dist/docx/importedIdCollisions.js +29 -4
  42. package/dist/docx/server/templatePlan/apply.js +108 -9
  43. package/dist/docx/server/templatePlan/blocks.d.ts +77 -5
  44. package/dist/docx/server/templatePlan/blocks.js +281 -14
  45. package/dist/docx/server/templatePlan/builders.d.ts +22 -1
  46. package/dist/docx/server/templatePlan/builders.js +37 -3
  47. package/dist/docx/server/templatePlan/effects.d.ts +27 -0
  48. package/dist/docx/server/templatePlan/effects.js +188 -0
  49. package/dist/docx/server/templatePlan/emit.d.ts +4 -1
  50. package/dist/docx/server/templatePlan/emit.js +152 -8
  51. package/dist/docx/server/templatePlan/inspect.js +21 -1
  52. package/dist/docx/server/templatePlan/labels.js +16 -1
  53. package/dist/docx/server/templatePlan/plan.d.ts +35 -3
  54. package/dist/docx/server/templatePlan/plan.js +197 -20
  55. package/dist/docx/server/templatePlan/planShape.js +58 -22
  56. package/dist/docx/server/templatePlan/revisions.d.ts +101 -0
  57. package/dist/docx/server/templatePlan/revisions.js +681 -0
  58. package/dist/docx/server/templatePlan/story.d.ts +61 -2
  59. package/dist/docx/server/templatePlan/story.js +175 -13
  60. package/dist/docx/server/templatePlan/types.d.ts +313 -1
  61. package/dist/docx/server/templatePlan/verify.js +175 -12
  62. package/dist/docx/server/templatePlan/xml.d.ts +3 -0
  63. package/dist/docx/server/templatePlan/xml.js +4 -1
  64. package/dist/docx/settingsHeaderFooterUpdate.d.ts +1 -1
  65. package/dist/docx/tableGridXml.d.ts +3 -7
  66. package/dist/docx/tableGridXml.js +5 -13
  67. package/dist/layout-bridge/convert/footnoteLayout.js +34 -8
  68. package/dist/prosemirror/canonicalMarkupDocument.d.ts +20 -0
  69. package/dist/prosemirror/canonicalMarkupDocument.js +73 -0
  70. package/dist/prosemirror/canonicalTableCommands.d.ts +1 -1
  71. package/dist/prosemirror/canonicalTableCommands.js +1 -3
  72. package/dist/prosemirror/commands/comments.d.ts +6 -234
  73. package/dist/prosemirror/commands/comments.js +5 -2464
  74. package/dist/prosemirror/commands/index.d.ts +4 -2
  75. package/dist/prosemirror/commands/index.js +4 -2
  76. package/dist/prosemirror/conversion/markupViewSource.d.ts +17 -0
  77. package/dist/prosemirror/conversion/markupViewSource.js +11 -0
  78. package/dist/prosemirror/conversion/toProseDoc.d.ts +3 -0
  79. package/dist/prosemirror/conversion/toProseDoc.js +31 -14
  80. package/dist/prosemirror/extensions/marks/HyperlinkExtension.js +6 -8
  81. package/dist/prosemirror/hyperlinkRemoval.d.ts +11 -8
  82. package/dist/prosemirror/hyperlinkRemoval.js +24 -15
  83. package/dist/prosemirror/independentMarkupProjection.d.ts +27 -0
  84. package/dist/prosemirror/independentMarkupProjection.js +147 -0
  85. package/dist/prosemirror/markupViewNotes.d.ts +1 -1
  86. package/dist/prosemirror/markupViewNotes.js +24 -27
  87. package/dist/prosemirror/markupViewPositionMap.d.ts +16 -0
  88. package/dist/prosemirror/markupViewPositionMap.js +316 -0
  89. package/dist/prosemirror/markupViewProjection.d.ts +3 -46
  90. package/dist/prosemirror/markupViewProjection.js +90 -17
  91. package/dist/prosemirror/paraIds.d.ts +1 -14
  92. package/dist/prosemirror/paraIds.js +1 -14
  93. package/dist/prosemirror/paragraphMarkJoin.d.ts +0 -16
  94. package/dist/prosemirror/paragraphMarkJoin.js +3 -46
  95. package/dist/prosemirror/projectionReview.d.ts +49 -0
  96. package/dist/prosemirror/projectionReview.js +292 -0
  97. package/dist/prosemirror/rebaseParagraphRunFormatting.d.ts +1 -13
  98. package/dist/prosemirror/rebaseParagraphRunFormatting.js +1 -16
  99. package/dist/prosemirror/replacedAnnotations.d.ts +6 -83
  100. package/dist/prosemirror/replacedAnnotations.js +11 -203
  101. package/dist/prosemirror/revisionCarriers.d.ts +9 -1
  102. package/dist/prosemirror/revisionCarriers.js +15 -1
  103. package/dist/prosemirror/revisionRangeQueries.d.ts +32 -0
  104. package/dist/prosemirror/revisionRangeQueries.js +76 -0
  105. package/dist/prosemirror/runFormattingMarkNames.d.ts +1 -1
  106. package/dist/prosemirror/runFormattingMarkNames.js +1 -1
  107. package/dist/prosemirror/styles/styleResolver.d.ts +1 -0
  108. package/dist/prosemirror/styles/styleResolver.js +4 -1
  109. package/dist/prosemirror/suggestionQueries.d.ts +114 -0
  110. package/dist/prosemirror/suggestionQueries.js +320 -0
  111. package/dist/prosemirror/tableGridMutation.d.ts +1 -16
  112. package/dist/prosemirror/tableGridMutation.js +1 -78
  113. package/dist/prosemirror/tableRowRevisionOwnership.d.ts +18 -0
  114. package/dist/prosemirror/tableRowRevisionOwnership.js +7 -0
  115. package/dist/prosemirror/utils/extractTrackedChanges.js +14 -4
  116. package/dist/server.d.ts +2 -2
  117. package/dist/types/canonicalCapabilities.d.ts +4 -35
  118. package/dist/types/canonicalCapabilities.js +4 -33
  119. package/package.json +2 -2
  120. package/dist/internal/headlessRevisionResolutionGuard.d.ts +0 -3
  121. package/dist/internal/headlessRevisionResolutionGuard.js +0 -18
  122. package/dist/internal/revisionResolutionEdits.d.ts +0 -11
  123. package/dist/internal/revisionResolutionEdits.js +0 -18
  124. package/dist/internal/revisionResolutionInline.d.ts +0 -24
  125. package/dist/internal/revisionResolutionInline.js +0 -302
  126. package/dist/internal/revisionResolutionStep.d.ts +0 -32
  127. package/dist/internal/revisionResolutionStep.js +0 -282
  128. package/dist/internal/revisionResolutionTracking.d.ts +0 -9
  129. package/dist/internal/revisionResolutionTracking.js +0 -124
  130. package/dist/internal/wholeStoryRevisionResolution.d.ts +0 -56
  131. package/dist/internal/wholeStoryRevisionResolution.js +0 -783
  132. package/dist/prosemirror/commands/resolveAllTableChanges.d.ts +0 -38
  133. package/dist/prosemirror/commands/resolveAllTableChanges.js +0 -642
  134. package/dist/prosemirror/commands/resolveNodePropertyChangeAttrs.d.ts +0 -13
  135. package/dist/prosemirror/commands/resolveNodePropertyChangeAttrs.js +0 -45
  136. package/dist/prosemirror/commands/tableCellMergeResolution.d.ts +0 -18
  137. package/dist/prosemirror/commands/tableCellMergeResolution.js +0 -207
  138. package/dist/prosemirror/commands/tableMergeFoldDecisions.d.ts +0 -60
  139. package/dist/prosemirror/commands/tableMergeFoldDecisions.js +0 -78
  140. package/dist/prosemirror/rejoinRunCarriers.d.ts +0 -42
  141. package/dist/prosemirror/rejoinRunCarriers.js +0 -65
  142. package/dist/prosemirror/runPropertyChangeResolution.d.ts +0 -15
  143. package/dist/prosemirror/runPropertyChangeResolution.js +0 -34
@@ -15,11 +15,11 @@ import { canonicalSelectionRange } from "../prosemirror/canonicalSelectionRange.
15
15
  import { registerClipboardIntentHandler } from "../prosemirror/clipboardIntent.js";
16
16
  import { pasteWithoutFormatting } from "../prosemirror/commands/pastePlainText.js";
17
17
  import { createCommentRecordsPlugin, isCommentRecordsSync } from "../prosemirror/commentRecords.js";
18
+ import { retainMarkupViewSource } from "../prosemirror/conversion/markupViewSource.js";
18
19
  import { createEmptyDoc, toProseDoc } from "../prosemirror/conversion/toProseDoc.js";
19
20
  import { registerEditorCommandOwner } from "../prosemirror/executeEditorCommand.js";
20
21
  import { ensureBaseDirectionInState } from "../prosemirror/extensions/features/AutoBidiDetectionExtension.js";
21
22
  import { toggleMarkForAllScripts, toggleUnderlineMark } from "../prosemirror/extensions/marks/markUtils.js";
22
- import { HyperlinkRemovalRefusal } from "../prosemirror/hyperlinkRemoval.js";
23
23
  import { REVISION_MARK_NAMES } from "../prosemirror/keptRangeBoundaries.js";
24
24
  import { adoptNativeSelection, createNativeNavigationPlugin, createNativeSelectionRefreshPlugin, isCompositionKeyDown } from "../prosemirror/nativeSelection.js";
25
25
  import { NoteReferenceReplayDefect, noteReferenceTransactionIssue } from "../prosemirror/noteReferenceOccurrences.js";
@@ -27,7 +27,7 @@ import { ensureParaIdsInDoc } from "../prosemirror/paraIds.js";
27
27
  import { createDocumentNumberingPlugin } from "../prosemirror/plugins/documentNumbering.js";
28
28
  import { createDocumentStyleContextPlugin, createDocumentStylesPlugin } from "../prosemirror/plugins/documentStyles.js";
29
29
  import { schema } from "../prosemirror/schema/index.js";
30
- import { CANONICAL_CONDITION, CANONICAL_GAP, CANONICAL_RULE } from "../types/canonicalCapabilities.js";
30
+ import { CANONICAL_CONDITION, CANONICAL_RULE } from "../types/canonicalCapabilities.js";
31
31
  import { readModel } from "../types/documentModel.js";
32
32
  import { INTERNAL_CLIPBOARD_TYPE } from "../utils/clipboardFiles.js";
33
33
  import { NO_ANONYMIZATION_TERMS, createAnonymizationHighlights } from "./anonymizationHighlights.js";
@@ -497,21 +497,7 @@ const createHiddenEditorManager = (hostDeps) => {
497
497
  refuse("Composition must finish before formatting.", { condition: CANONICAL_CONDITION.composing });
498
498
  return false;
499
499
  }
500
- const commandState = view.state;
501
- const described = Result.try({
502
- try: () => getCanonicalCommandIntents(command, commandState),
503
- catch: (error) => error
504
- });
505
- if (described.isErr()) {
506
- if (!(described.error instanceof HyperlinkRemovalRefusal)) throw described.error;
507
- const refusal = new CanonicalSessionRefusalError({
508
- ground: { gap: CANONICAL_GAP.commands },
509
- message: described.error.message
510
- });
511
- refuse(refusal.message, refusal.ground);
512
- return false;
513
- }
514
- const intents = described.value;
500
+ const intents = getCanonicalCommandIntents(command, view.state);
515
501
  if (intents === void 0) return void 0;
516
502
  if (intents.length > 0 && intents.every((intent) => intent.type === "selection")) return command(view.state, (transaction) => view?.dispatch(transaction), view);
517
503
  syncCanonicalMode();
@@ -616,7 +602,7 @@ const createHiddenEditorManager = (hostDeps) => {
616
602
  if (mark !== void 0) command = name === "toggleUnderline" ? toggleUnderlineMark(mark) : toggleMarkForAllScripts(mark, name === "toggleBold" ? "bold" : "italic");
617
603
  }
618
604
  if (command === void 0) {
619
- refuse("The formatting command is unavailable.", { gap: CANONICAL_GAP.commands });
605
+ refuse("The formatting command is unavailable.", { condition: CANONICAL_CONDITION.invalidRequest });
620
606
  return;
621
607
  }
622
608
  if (executeCanonicalCommand(command) === void 0) command(view.state, (transaction) => view?.dispatch(transaction), view);
@@ -626,7 +612,7 @@ const createHiddenEditorManager = (hostDeps) => {
626
612
  syncCanonicalMode();
627
613
  if (type === "deleteTable") {
628
614
  const command = deps.getExtensionManager()?.getCommand("deleteTable")?.();
629
- if (command === void 0) refuse("Deleting the table is unavailable.", { gap: CANONICAL_GAP.commands });
615
+ if (command === void 0) refuse("Deleting the table is unavailable.", { condition: CANONICAL_CONDITION.invalidRequest });
630
616
  else executeCanonicalCommand(command);
631
617
  return;
632
618
  }
@@ -747,6 +733,7 @@ const createHiddenEditorManager = (hostDeps) => {
747
733
  return;
748
734
  }
749
735
  const documentEdits = applied.transactions.filter((appliedTransaction) => appliedTransaction.docChanged && !isCommentRecordsSync(appliedTransaction));
736
+ retainMarkupViewSource(view.state, applied.state);
750
737
  view.updateState(applied.state);
751
738
  const docChanged = documentEdits.length > 0;
752
739
  const selectionChanged = applied.transactions.some((appliedTransaction) => appliedTransaction.selectionSet || appliedTransaction.docChanged && !isCommentRecordsSync(appliedTransaction));
@@ -1391,7 +1378,7 @@ const createHiddenEditorManager = (hostDeps) => {
1391
1378
  const command = deps.getExtensionManager()?.getCommand("deleteTable")?.();
1392
1379
  const intents = command === void 0 ? void 0 : getCanonicalCommandIntents(command, storyView.state);
1393
1380
  if (intents === void 0) {
1394
- refuse("Deleting the table is unavailable.", { gap: CANONICAL_GAP.commands });
1381
+ refuse("Deleting the table is unavailable.", { condition: CANONICAL_CONDITION.invalidRequest });
1395
1382
  return false;
1396
1383
  }
1397
1384
  prepared = prepareCanonicalCommands(session, storyView.state, intents, story);
@@ -20,4 +20,12 @@ export declare const bulletMarkerFontName: (formatting: {
20
20
  * symbol-font code.
21
21
  */
22
22
  export declare const convertBulletToUnicode: (bulletChar: string, fontName?: string) => string;
23
+ /**
24
+ * The text face a bullet level's mark is a character of, when it is one: the
25
+ * mark then looks as it does only in that face (the customary `o` of a
26
+ * monospace face). Undefined for a level that names no face, for a symbol
27
+ * face, and for a code a text face has no character for, which is read as
28
+ * the shape it stands in for.
29
+ */
30
+ export declare const bulletTextFace: (bulletChar: string, fontName: string | undefined) => string | undefined;
23
31
  export {};
@@ -23,4 +23,12 @@ const convertBulletToUnicode = (bulletChar, fontName) => {
23
23
  if (charCode < 32 || charCode >= 127 && charCode < 160) return "•";
24
24
  return bulletChar;
25
25
  };
26
- export { bulletMarkerFontName, convertBulletToUnicode };
26
+ /**
27
+ * The text face a bullet level's mark is a character of, when it is one: the
28
+ * mark then looks as it does only in that face (the customary `o` of a
29
+ * monospace face). Undefined for a level that names no face, for a symbol
30
+ * face, and for a code a text face has no character for, which is read as
31
+ * the shape it stands in for.
32
+ */
33
+ const bulletTextFace = (bulletChar, fontName) => fontName !== void 0 && !isOoxmlSymbolFont(fontName) && bulletChar !== "" && convertBulletToUnicode(bulletChar, fontName) === bulletChar ? fontName : void 0;
34
+ export { bulletMarkerFontName, bulletTextFace, convertBulletToUnicode };
@@ -1,8 +1,8 @@
1
1
  import { toArrayBuffer } from "../utils/docxInput.js";
2
2
  import { DOCX_CONTAINER_TYPES, detectDocxContainerType } from "./encryption/containerFormat.js";
3
- import { ensureParaIds } from "./ensureParaIds.js";
4
- import { ensureUniqueControlIds } from "./ensureUniqueControlIds.js";
5
- import { ensureUniqueRevisionIds } from "./ensureUniqueRevisionIds.js";
3
+ import { isDigitallySignedPackage, planPackageParaIds, signedPackageMutationError, writePackageParts } from "./ensureParaIds.js";
4
+ import { uniqueControlIdUpdates } from "./ensureUniqueControlIds.js";
5
+ import { uniqueRevisionIdUpdates } from "./ensureUniqueRevisionIds.js";
6
6
  import { keepNormalizedSourceParts } from "./normalizedSourceParts.js";
7
7
  import { MalformedPackageRelationshipsError } from "./packageRelationshipsRoot.js";
8
8
  import { parseDocx } from "./parser.js";
@@ -30,6 +30,27 @@ const prepareCanonicalDocxInput = async (input) => {
30
30
  const source = await prepareCanonicalDocxSource(input);
31
31
  return source.isErr() ? Result.err(source.error) : Result.ok(source.value.docx);
32
32
  };
33
+ /**
34
+ * Every id normalization of a package over one read of its parts: paragraph
35
+ * ids, then content control ids, then revision ids, each pass reading the
36
+ * texts the one before wrote. The package is written once, if at all.
37
+ */
38
+ const normalizeCanonicalPackage = async (bytes) => {
39
+ const paragraphs = await planPackageParaIds(bytes);
40
+ const signed = isDigitallySignedPackage(paragraphs.entries);
41
+ if (signed && paragraphs.updates.size > 0) throw signedPackageMutationError();
42
+ const texts = new Map(paragraphs.partTexts);
43
+ const updates = new Map(paragraphs.updates);
44
+ for (const [path, text] of updates) texts.set(path, text);
45
+ if (!signed) for (const pass of [uniqueControlIdUpdates, uniqueRevisionIdUpdates]) for (const [path, text] of pass(texts)?.updates ?? []) {
46
+ texts.set(path, text);
47
+ updates.set(path, text);
48
+ }
49
+ return {
50
+ docx: updates.size === 0 ? new Uint8Array(bytes) : await writePackageParts(bytes, updates),
51
+ mintedParaIds: new Set(paragraphs.mintedParaIds)
52
+ };
53
+ };
33
54
  /** {@link prepareCanonicalDocxInput}, with the paragraph ids it minted. */
34
55
  const prepareCanonicalDocxSource = async (input) => {
35
56
  const bytes = await Result.tryPromise({
@@ -42,14 +63,7 @@ const prepareCanonicalDocxSource = async (input) => {
42
63
  if (bytes.isErr()) return Result.err(bytes.error);
43
64
  if (detectDocxContainerType(bytes.value) === DOCX_CONTAINER_TYPES.CFB) return Result.err(new CanonicalDocxInputError({ message: "Password-protected documents are unavailable in the experimental canonical session." }));
44
65
  return Result.tryPromise({
45
- try: async () => {
46
- const paragraphs = await ensureParaIds(bytes.value);
47
- const { docx } = await ensureUniqueRevisionIds((await ensureUniqueControlIds(paragraphs.docx)).docx);
48
- return {
49
- docx,
50
- mintedParaIds: new Set(paragraphs.mintedParaIds)
51
- };
52
- },
66
+ try: () => normalizeCanonicalPackage(bytes.value),
53
67
  catch: (cause) => malformedPartCause(cause) ?? new CanonicalDocxInputError({
54
68
  message: cause instanceof Error ? cause.message : "Canonical document normalization failed.",
55
69
  cause
@@ -74,6 +74,8 @@ export declare const paragraphMintKeys: (xml: string) => readonly string[] | und
74
74
  * keyed on the ordinal alone.
75
75
  */
76
76
  export declare const mintParaId: (context: MintContext, partPath: string, ordinal: number, keys: readonly string[] | undefined) => string;
77
+ /** Whether a package with these part paths carries a digital signature. */
78
+ export declare const isDigitallySignedPackage: (entries: readonly string[]) => boolean;
77
79
  type PackageStoryPartsOptions = {
78
80
  documentPartName: string;
79
81
  /** The main part's relationships part, when the package has one. */
@@ -108,6 +110,35 @@ export type UnnamedParagraphIds = {
108
110
  * it. A repeated authored id is left for its readers to judge.
109
111
  */
110
112
  export declare const assignPackageParaIds: (options: AssignPackageParaIdsOptions) => ReadonlyMap<string, UnnamedParagraphIds>;
113
+ /**
114
+ * A package's XML parts as one bounded read decoded them, and the texts that
115
+ * write the paragraph ids {@link ensureParaIds} would write.
116
+ */
117
+ export type PackageParaIdPlan = {
118
+ /** The package's part paths. */
119
+ entries: readonly string[];
120
+ /** Each XML part the read decoded, by path, as the package holds it. */
121
+ partTexts: ReadonlyMap<string, string>;
122
+ /** The part texts that write the ids, by path. */
123
+ updates: ReadonlyMap<string, string>;
124
+ /** Every id the texts write, in scan order. */
125
+ mintedParaIds: readonly string[];
126
+ assigned: number;
127
+ deduplicated: number;
128
+ };
129
+ /**
130
+ * Read a `.docx` buffer's XML parts once and plan the paragraph ids
131
+ * {@link ensureParaIds} writes, without writing them. Failures are surfaced
132
+ * as {@link EnsureParaIdsError}, as {@link ensureParaIds} surfaces them.
133
+ */
134
+ export declare const planPackageParaIds: (docx: Uint8Array | ArrayBuffer) => Promise<PackageParaIdPlan>;
135
+ /** The error for a normalization that would invalidate a package's signatures. */
136
+ export declare const signedPackageMutationError: () => EnsureParaIdsError;
137
+ /**
138
+ * `docx` with each part of `updates` written as its text, in one write of the
139
+ * package. Every other entry keeps its stored bytes.
140
+ */
141
+ export declare const writePackageParts: (docx: Uint8Array | ArrayBuffer, updates: ReadonlyMap<string, string>) => Promise<Uint8Array>;
111
142
  /**
112
143
  * Backfill `w14:paraId` on every paragraph of a `.docx` buffer. All package,
113
144
  * XML, and compression failures are surfaced as {@link EnsureParaIdsError}.
@@ -538,7 +538,8 @@ const relatedStoryParts = (rels, relsPath, entries) => {
538
538
  /** OPC part names are case-insensitive; compare lowercased. */
539
539
  const matchesTargetPattern = (path) => TARGET_PART_PATTERNS.some((pattern) => pattern.test(path.toLowerCase()));
540
540
  const toUint8Array = (docx) => docx instanceof Uint8Array ? docx : new Uint8Array(docx);
541
- const hasDigitalSignatureParts = (zip) => zip.entries().some(({ path }) => path.toLowerCase().startsWith(DIGITAL_SIGNATURE_PART_PREFIX));
541
+ /** Whether a package with these part paths carries a digital signature. */
542
+ const isDigitallySignedPackage = (entries) => entries.some((path) => path.toLowerCase().startsWith(DIGITAL_SIGNATURE_PART_PREFIX));
542
543
  /** The parts besides the main one whose paragraphs get ids. */
543
544
  const packageStoryParts = ({ documentPartName, documentRels, entries }) => {
544
545
  const storyParts = relatedStoryParts(documentRels, relationshipsPathFor(documentPartName), entries);
@@ -618,12 +619,7 @@ const packageParaIdUpdates = (partTexts, parts) => {
618
619
  deduplicated
619
620
  };
620
621
  };
621
- /**
622
- * Backfill `w14:paraId` on every paragraph of a `.docx` buffer. See the
623
- * module doc for the exact contract. Throws {@link EnsureParaIdsError} when
624
- * the buffer is not a WordprocessingML package or a part is malformed.
625
- */
626
- const ensureParaIdsInternal = async (docx, options) => {
622
+ const planPackageParaIdsInternal = async (docx) => {
627
623
  const archive = await loadDocxArchive(docx);
628
624
  const relsPath = archive.entries.find((name) => name.toLowerCase() === PACKAGE_RELATIONSHIPS_PART);
629
625
  const rels = relsPath === void 0 ? null : await archive.readEntryString(relsPath);
@@ -646,30 +642,67 @@ const ensureParaIdsInternal = async (docx, options) => {
646
642
  const text = await archive.readEntryString(name);
647
643
  if (text !== null) partTexts.set(name, text);
648
644
  }
649
- const { updates, mintedParaIds, assigned, deduplicated } = packageParaIdUpdates(partTexts, scanPackageParaIds({
645
+ return {
646
+ entries: archive.entries,
650
647
  partTexts,
651
- documentPartName,
652
- isTargetPart
653
- }));
654
- if (updates.size === 0) return {
655
- docx: toUint8Array(docx),
656
- assigned: 0,
657
- deduplicated: 0,
658
- alreadyComplete: true,
659
- mintedParaIds: []
648
+ ...packageParaIdUpdates(partTexts, scanPackageParaIds({
649
+ partTexts,
650
+ documentPartName,
651
+ isTargetPart
652
+ }))
660
653
  };
654
+ };
655
+ /** Run `normalize`, surfacing every failure as an {@link EnsureParaIdsError}. */
656
+ const withEnsureParaIdsErrors = async (normalize) => {
657
+ try {
658
+ return await normalize();
659
+ } catch (error) {
660
+ if (error instanceof EnsureParaIdsError) throw error;
661
+ const message = error instanceof Error ? error.message : String(error);
662
+ throw createEnsureParaIdsError(`Failed to normalize paragraph IDs: ${message}`, error);
663
+ }
664
+ };
665
+ /**
666
+ * Read a `.docx` buffer's XML parts once and plan the paragraph ids
667
+ * {@link ensureParaIds} writes, without writing them. Failures are surfaced
668
+ * as {@link EnsureParaIdsError}, as {@link ensureParaIds} surfaces them.
669
+ */
670
+ const planPackageParaIds = (docx) => withEnsureParaIdsErrors(() => planPackageParaIdsInternal(docx));
671
+ /** The error for a normalization that would invalidate a package's signatures. */
672
+ const signedPackageMutationError = () => new EnsureParaIdsError({
673
+ reason: ENSURE_PARA_IDS_REASONS.SIGNED_PACKAGE,
674
+ message: "Refusing to normalize a digitally signed package because rewriting OOXML invalidates its signatures. Warn the user and pass allowSignedPackageMutation only if invalidation is acceptable."
675
+ });
676
+ /**
677
+ * `docx` with each part of `updates` written as its text, in one write of the
678
+ * package. Every other entry keeps its stored bytes.
679
+ */
680
+ const writePackageParts = async (docx, updates) => {
661
681
  const zip = await ZipArchive.read(docx);
662
- if (hasDigitalSignatureParts(zip) && options.allowSignedPackageMutation !== true) throw new EnsureParaIdsError({
663
- reason: ENSURE_PARA_IDS_REASONS.SIGNED_PACKAGE,
664
- message: "Refusing to normalize a digitally signed package because rewriting OOXML invalidates its signatures. Warn the user and pass allowSignedPackageMutation only if invalidation is acceptable."
665
- });
666
682
  for (const [partPath, content] of updates) {
667
683
  const sourceEntry = zip.entry(partPath);
668
684
  if (sourceEntry === void 0) throw createEnsureParaIdsError(`Package part disappeared during normalization: ${partPath}`);
669
685
  zip.set(partPath, content, { modified: sourceEntry.modified });
670
686
  }
687
+ return await zip.generate({ level: 6 });
688
+ };
689
+ /**
690
+ * Backfill `w14:paraId` on every paragraph of a `.docx` buffer. See the
691
+ * module doc for the exact contract. Throws {@link EnsureParaIdsError} when
692
+ * the buffer is not a WordprocessingML package or a part is malformed.
693
+ */
694
+ const ensureParaIdsInternal = async (docx, options) => {
695
+ const { entries, updates, mintedParaIds, assigned, deduplicated } = await planPackageParaIdsInternal(docx);
696
+ if (updates.size === 0) return {
697
+ docx: toUint8Array(docx),
698
+ assigned: 0,
699
+ deduplicated: 0,
700
+ alreadyComplete: true,
701
+ mintedParaIds: []
702
+ };
703
+ if (isDigitallySignedPackage(entries) && options.allowSignedPackageMutation !== true) throw signedPackageMutationError();
671
704
  return {
672
- docx: await zip.generate({ level: 6 }),
705
+ docx: await writePackageParts(docx, updates),
673
706
  assigned,
674
707
  deduplicated,
675
708
  alreadyComplete: false,
@@ -680,13 +713,5 @@ const ensureParaIdsInternal = async (docx, options) => {
680
713
  * Backfill `w14:paraId` on every paragraph of a `.docx` buffer. All package,
681
714
  * XML, and compression failures are surfaced as {@link EnsureParaIdsError}.
682
715
  */
683
- const ensureParaIds = async (docx, options = {}) => {
684
- try {
685
- return await ensureParaIdsInternal(docx, options);
686
- } catch (error) {
687
- if (error instanceof EnsureParaIdsError) throw error;
688
- const message = error instanceof Error ? error.message : String(error);
689
- throw createEnsureParaIdsError(`Failed to normalize paragraph IDs: ${message}`, error);
690
- }
691
- };
692
- export { ENSURE_PARA_IDS_REASONS, EnsureParaIdsError, assignPackageParaIds, collectExistingParaIds, ensureParaIds, isWordprocessingElement, mintParaId, packageStoryParts, paragraphMintKeys, storyParagraphSlots };
716
+ const ensureParaIds = (docx, options = {}) => withEnsureParaIdsErrors(() => ensureParaIdsInternal(docx, options));
717
+ export { ENSURE_PARA_IDS_REASONS, EnsureParaIdsError, assignPackageParaIds, collectExistingParaIds, ensureParaIds, isDigitallySignedPackage, isWordprocessingElement, mintParaId, packageStoryParts, paragraphMintKeys, planPackageParaIds, signedPackageMutationError, storyParagraphSlots, writePackageParts };
@@ -12,6 +12,19 @@
12
12
  * under the same ids for older readers, and the parser reads one of the two,
13
13
  * so a fallback's ids are reserved but never counted as a repeat.
14
14
  */
15
+ /** Part texts that renumber repeated ids, and how many they renumber. */
16
+ export type PackageControlIdUpdates = {
17
+ /** The rewritten text of each part that repeats an id, by path. */
18
+ updates: Map<string, string>;
19
+ reminted: number;
20
+ };
21
+ /**
22
+ * The part texts that give each content control after the first carrying an
23
+ * id an id of its own; `undefined` when a part does not scan, since it may
24
+ * hold ids a new one would repeat. The body's controls win the
25
+ * first-occurrence rule.
26
+ */
27
+ export declare const uniqueControlIdUpdates: (partTexts: ReadonlyMap<string, string>) => PackageControlIdUpdates | undefined;
15
28
  export type EnsureUniqueControlIdsResult = {
16
29
  /** The normalized `.docx`; the input bytes when nothing repeated. */
17
30
  docx: Uint8Array;
@@ -46,33 +46,25 @@ const controlIdsIn = (xml) => {
46
46
  }
47
47
  }).status === "scanned" ? out : void 0;
48
48
  };
49
+ /** The story parts of `paths`, the body first, then the rest in a fixed order. */
50
+ const storyPartsInOrder = (paths) => [...paths].filter((path) => STORY_PART_PATTERN.test(path)).sort((a, b) => {
51
+ const body = (path) => path.toLowerCase() === "word/document.xml" ? 0 : 1;
52
+ return body(a) - body(b) || a.localeCompare(b);
53
+ });
49
54
  /**
50
- * Give each content control after the first carrying an id an id of its own.
51
- * A signed package, or a part that does not scan, is left as it is.
55
+ * The part texts that give each content control after the first carrying an
56
+ * id an id of its own; `undefined` when a part does not scan, since it may
57
+ * hold ids a new one would repeat. The body's controls win the
58
+ * first-occurrence rule.
52
59
  */
53
- const ensureUniqueControlIds = async (docx) => {
54
- const zip = await ZipArchive.read(docx);
55
- const entries = zip.entries();
56
- if (entries.some(({ path }) => path.toLowerCase().startsWith(DIGITAL_SIGNATURE_PART_PREFIX))) return {
57
- docx,
58
- reminted: 0
59
- };
60
- const parts = entries.map(({ path }) => path).filter((path) => STORY_PART_PATTERN.test(path)).sort((a, b) => {
61
- const body = (path) => path.toLowerCase() === "word/document.xml" ? 0 : 1;
62
- return body(a) - body(b) || a.localeCompare(b);
63
- });
64
- const texts = /* @__PURE__ */ new Map();
60
+ const uniqueControlIdUpdates = (partTexts) => {
65
61
  const ids = /* @__PURE__ */ new Map();
66
62
  const taken = /* @__PURE__ */ new Set();
67
- for (const path of parts) {
68
- const xml = await zip.entry(path)?.text();
69
- if (xml === void 0 || !xml.includes("sdtPr")) continue;
63
+ for (const path of storyPartsInOrder(partTexts.keys())) {
64
+ const xml = partTexts.get(path);
65
+ if (!xml.includes("sdtPr")) continue;
70
66
  const found = controlIdsIn(xml);
71
- if (found === void 0) return {
72
- docx,
73
- reminted: 0
74
- };
75
- texts.set(path, xml);
67
+ if (found === void 0) return void 0;
76
68
  ids.set(path, found);
77
69
  for (const { value } of found) taken.add(value);
78
70
  }
@@ -83,6 +75,7 @@ const ensureUniqueControlIds = async (docx) => {
83
75
  return next;
84
76
  };
85
77
  const seen = /* @__PURE__ */ new Set();
78
+ const updates = /* @__PURE__ */ new Map();
86
79
  let reminted = 0;
87
80
  for (const [path, found] of ids) {
88
81
  const edits = [];
@@ -99,19 +92,44 @@ const ensureUniqueControlIds = async (docx) => {
99
92
  });
100
93
  }
101
94
  if (edits.length === 0) continue;
102
- const patched = spliceXml(texts.get(path), edits);
95
+ const patched = spliceXml(partTexts.get(path), edits);
103
96
  if (patched === null) continue;
104
- const source = zip.entry(path);
105
- zip.set(path, patched, source ? { modified: source.modified } : {});
97
+ updates.set(path, patched);
106
98
  reminted += edits.length;
107
99
  }
108
- if (reminted === 0) return {
109
- docx,
100
+ return {
101
+ updates,
110
102
  reminted
111
103
  };
104
+ };
105
+ /**
106
+ * Give each content control after the first carrying an id an id of its own.
107
+ * A signed package, or a part that does not scan, is left as it is.
108
+ */
109
+ const ensureUniqueControlIds = async (docx) => {
110
+ const zip = await ZipArchive.read(docx);
111
+ const entries = zip.entries();
112
+ if (entries.some(({ path }) => path.toLowerCase().startsWith(DIGITAL_SIGNATURE_PART_PREFIX))) return {
113
+ docx,
114
+ reminted: 0
115
+ };
116
+ const texts = /* @__PURE__ */ new Map();
117
+ for (const path of storyPartsInOrder(entries.map((entry) => entry.path))) {
118
+ const xml = await zip.entry(path)?.text();
119
+ if (xml !== void 0) texts.set(path, xml);
120
+ }
121
+ const found = uniqueControlIdUpdates(texts);
122
+ if (found === void 0 || found.reminted === 0) return {
123
+ docx,
124
+ reminted: 0
125
+ };
126
+ for (const [path, patched] of found.updates) {
127
+ const source = zip.entry(path);
128
+ zip.set(path, patched, source ? { modified: source.modified } : {});
129
+ }
112
130
  return {
113
131
  docx: await zip.generate({ level: 6 }),
114
- reminted
132
+ reminted: found.reminted
115
133
  };
116
134
  };
117
- export { ensureUniqueControlIds };
135
+ export { ensureUniqueControlIds, uniqueControlIdUpdates };
@@ -15,6 +15,19 @@
15
15
  * under the same ids for older readers, and the parser reads one of the two,
16
16
  * so a fallback's ids are reserved but never counted as a repeat.
17
17
  */
18
+ /** Part texts that renumber repeated ids, and how many they renumber. */
19
+ export type PackageRevisionIdUpdates = {
20
+ /** The rewritten text of each part that repeats an id, by path. */
21
+ updates: Map<string, string>;
22
+ reminted: number;
23
+ };
24
+ /**
25
+ * The part texts that give each revision record after the first carrying an
26
+ * id an id of its own; `undefined` when a part does not scan, since it may
27
+ * hold ids a new one would repeat. The body's records win the
28
+ * first-occurrence rule.
29
+ */
30
+ export declare const uniqueRevisionIdUpdates: (partTexts: ReadonlyMap<string, string>) => PackageRevisionIdUpdates | undefined;
18
31
  export type EnsureUniqueRevisionIdsResult = {
19
32
  /** The normalized `.docx`; the input bytes when nothing repeated. */
20
33
  docx: Uint8Array;
@@ -69,33 +69,30 @@ const revisionIdsIn = (xml) => {
69
69
  }).status === "scanned" ? out : void 0;
70
70
  };
71
71
  /**
72
- * Give each revision record after the first carrying an id an id of its own.
73
- * A signed package, or a part that does not scan, is left as it is.
72
+ * A start tag naming a revision record under any prefix. A part none matches
73
+ * holds no record, so it needs no scan.
74
74
  */
75
- const ensureUniqueRevisionIds = async (docx) => {
76
- const zip = await ZipArchive.read(docx);
77
- const entries = zip.entries();
78
- if (entries.some(({ path }) => path.toLowerCase().startsWith(DIGITAL_SIGNATURE_PART_PREFIX))) return {
79
- docx,
80
- reminted: 0
81
- };
82
- const parts = entries.map(({ path }) => path).filter((path) => STORY_PART_PATTERN.test(path)).sort((a, b) => {
83
- const body = (path) => path.toLowerCase() === "word/document.xml" ? 0 : 1;
84
- return body(a) - body(b) || a.localeCompare(b);
85
- });
86
- const texts = /* @__PURE__ */ new Map();
75
+ const REVISION_RECORD_TAG = new RegExp(`<(?:[^\\s/>:]+:)?(?:${[...REVISION_RECORDS].join("|")})[\\s/>]`, "u");
76
+ /** The story parts of `paths`, the body first, then the rest in a fixed order. */
77
+ const storyPartsInOrder = (paths) => [...paths].filter((path) => STORY_PART_PATTERN.test(path)).sort((a, b) => {
78
+ const body = (path) => path.toLowerCase() === "word/document.xml" ? 0 : 1;
79
+ return body(a) - body(b) || a.localeCompare(b);
80
+ });
81
+ /**
82
+ * The part texts that give each revision record after the first carrying an
83
+ * id an id of its own; `undefined` when a part does not scan, since it may
84
+ * hold ids a new one would repeat. The body's records win the
85
+ * first-occurrence rule.
86
+ */
87
+ const uniqueRevisionIdUpdates = (partTexts) => {
87
88
  const ids = /* @__PURE__ */ new Map();
88
89
  const taken = /* @__PURE__ */ new Set();
89
- for (const path of parts) {
90
- const xml = await zip.entry(path)?.text();
91
- if (xml === void 0) continue;
90
+ for (const path of storyPartsInOrder(partTexts.keys())) {
91
+ const xml = partTexts.get(path);
92
+ if (!REVISION_RECORD_TAG.test(xml)) continue;
92
93
  const found = revisionIdsIn(xml);
93
- if (found === void 0) return {
94
- docx,
95
- reminted: 0
96
- };
94
+ if (found === void 0) return void 0;
97
95
  if (found.length === 0) continue;
98
- texts.set(path, xml);
99
96
  ids.set(path, found);
100
97
  for (const { value } of found) taken.add(value);
101
98
  }
@@ -106,6 +103,7 @@ const ensureUniqueRevisionIds = async (docx) => {
106
103
  return next;
107
104
  };
108
105
  const seen = /* @__PURE__ */ new Set();
106
+ const updates = /* @__PURE__ */ new Map();
109
107
  let reminted = 0;
110
108
  for (const [path, found] of ids) {
111
109
  const edits = [];
@@ -122,19 +120,44 @@ const ensureUniqueRevisionIds = async (docx) => {
122
120
  });
123
121
  }
124
122
  if (edits.length === 0) continue;
125
- const patched = spliceXml(texts.get(path), edits);
123
+ const patched = spliceXml(partTexts.get(path), edits);
126
124
  if (patched === null) continue;
127
- const source = zip.entry(path);
128
- zip.set(path, patched, source ? { modified: source.modified } : {});
125
+ updates.set(path, patched);
129
126
  reminted += edits.length;
130
127
  }
131
- if (reminted === 0) return {
132
- docx,
128
+ return {
129
+ updates,
133
130
  reminted
134
131
  };
132
+ };
133
+ /**
134
+ * Give each revision record after the first carrying an id an id of its own.
135
+ * A signed package, or a part that does not scan, is left as it is.
136
+ */
137
+ const ensureUniqueRevisionIds = async (docx) => {
138
+ const zip = await ZipArchive.read(docx);
139
+ const entries = zip.entries();
140
+ if (entries.some(({ path }) => path.toLowerCase().startsWith(DIGITAL_SIGNATURE_PART_PREFIX))) return {
141
+ docx,
142
+ reminted: 0
143
+ };
144
+ const texts = /* @__PURE__ */ new Map();
145
+ for (const path of storyPartsInOrder(entries.map((entry) => entry.path))) {
146
+ const xml = await zip.entry(path)?.text();
147
+ if (xml !== void 0) texts.set(path, xml);
148
+ }
149
+ const found = uniqueRevisionIdUpdates(texts);
150
+ if (found === void 0 || found.reminted === 0) return {
151
+ docx,
152
+ reminted: 0
153
+ };
154
+ for (const [path, patched] of found.updates) {
155
+ const source = zip.entry(path);
156
+ zip.set(path, patched, source ? { modified: source.modified } : {});
157
+ }
135
158
  return {
136
159
  docx: await zip.generate({ level: 6 }),
137
- reminted
160
+ reminted: found.reminted
138
161
  };
139
162
  };
140
- export { ensureUniqueRevisionIds };
163
+ export { ensureUniqueRevisionIds, uniqueRevisionIdUpdates };
@@ -151,6 +151,31 @@ const IMPORTED_ID_COLLISION_REGISTRY = {
151
151
  encoding: "string"
152
152
  }
153
153
  };
154
+ /**
155
+ * The rules naming each element local name, in registry order, each with the
156
+ * namespaces it names that local name in: most elements of a part are named by
157
+ * no rule, and are passed over without resolving their namespace.
158
+ */
159
+ const RULES_BY_LOCAL_NAME = (() => {
160
+ const index = /* @__PURE__ */ new Map();
161
+ for (const rule of Object.values(IMPORTED_ID_COLLISION_REGISTRY)) for (const site of rule.sites) for (const localName of site.elements) {
162
+ let rules = index.get(localName);
163
+ if (rules === void 0) {
164
+ rules = [];
165
+ index.set(localName, rules);
166
+ }
167
+ let entry = rules.find((candidate) => candidate.rule === rule);
168
+ if (entry === void 0) {
169
+ entry = {
170
+ rule,
171
+ namespaces: /* @__PURE__ */ new Set()
172
+ };
173
+ rules.push(entry);
174
+ }
175
+ entry.namespaces.add(site.namespace);
176
+ }
177
+ return index;
178
+ })();
154
179
  const normalizedIdentity = (value, encoding) => {
155
180
  if (encoding === "string") return value;
156
181
  if (encoding === "hex") return /^[0-9a-f]{8}$/iu.test(value) ? value.toUpperCase() : void 0;
@@ -161,18 +186,18 @@ const normalizedIdentity = (value, encoding) => {
161
186
  };
162
187
  /** Reports repeated source definitions without changing the package or choosing a winner. */
163
188
  const diagnoseImportedIdCollisions = (parts, context) => {
164
- const rules = Object.values(IMPORTED_ID_COLLISION_REGISTRY);
165
189
  const packageSeen = /* @__PURE__ */ new Map();
166
190
  for (const [part, xml] of parts) {
167
191
  const partSeen = /* @__PURE__ */ new Map();
168
192
  const scoped = context.scoped({ part });
169
193
  scanSelectedStreamingXmlElements(xml, ({ element, attributeValueSpans }) => {
170
194
  if (element.name === void 0) return;
195
+ const candidates = RULES_BY_LOCAL_NAME.get(getLocalName(element.name));
196
+ if (candidates === void 0) return;
171
197
  const namespace = toTransitionalNamespaceUri(getNamespaceUri(element) ?? "");
172
- const localName = getLocalName(element.name);
173
- for (const rule of rules) {
198
+ for (const { rule, namespaces } of candidates) {
174
199
  const kind = rule.kind;
175
- if (!rule.sites.some((site) => namespace === site.namespace && site.elements.has(localName))) continue;
200
+ if (!namespaces.has(namespace)) continue;
176
201
  const paragraphIdentity = paragraphIdentityForKind(kind, element);
177
202
  const seen = rule.scope === "package" ? packageSeen : partSeen;
178
203
  for (const [name, rawValue] of Object.entries(element.attributes ?? {})) {