@stll/folio-core 0.66.1 → 0.67.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 (170) hide show
  1. package/dist/ai-edits/apply.d.ts +13 -1
  2. package/dist/ai-edits/apply.js +572 -140
  3. package/dist/ai-edits/batch-claims.d.ts +26 -0
  4. package/dist/ai-edits/batch-claims.js +32 -5
  5. package/dist/ai-edits/clean-text.js +4 -1
  6. package/dist/ai-edits/headless.d.ts +6 -0
  7. package/dist/ai-edits/headless.js +25 -3
  8. package/dist/ai-edits/newListNumbering.d.ts +4 -1
  9. package/dist/ai-edits/newListNumbering.js +4 -2
  10. package/dist/ai-edits/read.js +6 -4
  11. package/dist/ai-edits/snapshot.js +24 -14
  12. package/dist/ai-edits/table-cell-mutations.js +3 -2
  13. package/dist/ai-edits/table-row-column-mutations.js +20 -6
  14. package/dist/ai-edits/types.d.ts +1 -1
  15. package/dist/controller/canonicalComposition.d.ts +1 -1
  16. package/dist/controller/canonicalComposition.js +76 -18
  17. package/dist/controller/canonicalInput.d.ts +0 -1
  18. package/dist/controller/canonicalInput.js +19 -1
  19. package/dist/controller/canonicalSession.js +1 -2
  20. package/dist/controller/hiddenEditorManager.d.ts +6 -0
  21. package/dist/controller/hiddenEditorManager.js +3 -1
  22. package/dist/controller/layoutPipeline.d.ts +2 -0
  23. package/dist/controller/layoutPipeline.js +7 -3
  24. package/dist/controller/layoutSession.d.ts +1 -0
  25. package/dist/display-list/build/tablePrimitives.d.ts +3 -1
  26. package/dist/display-list/build/tablePrimitives.js +29 -13
  27. package/dist/document-operations.d.ts +13 -1
  28. package/dist/document-operations.js +11 -4
  29. package/dist/docx/chartPreview.d.ts +4 -1
  30. package/dist/docx/chartPreview.js +26 -15
  31. package/dist/docx/listNumberingInstances.d.ts +6 -4
  32. package/dist/docx/listNumberingInstances.js +12 -11
  33. package/dist/docx/mainDocumentPart.d.ts +6 -0
  34. package/dist/docx/mainDocumentPart.js +65 -0
  35. package/dist/docx/numberingIds.d.ts +10 -0
  36. package/dist/docx/numberingIds.js +5 -1
  37. package/dist/docx/packageParts.d.ts +1 -1
  38. package/dist/docx/packageParts.js +10 -4
  39. package/dist/docx/paragraphParser.js +16 -3
  40. package/dist/docx/paragraphProperties.js +2 -1
  41. package/dist/docx/previewBudget.d.ts +6 -0
  42. package/dist/docx/previewBudget.js +7 -1
  43. package/dist/docx/rezip.js +4 -4
  44. package/dist/docx/serializer/paragraphSerializer.js +86 -66
  45. package/dist/docx/shapeAlternateContent.js +19 -0
  46. package/dist/docx/unzip.js +2 -0
  47. package/dist/i18n/messages/ar.gen.js +2 -0
  48. package/dist/i18n/messages/catalogs.gen.d.ts +34 -0
  49. package/dist/i18n/messages/catalogs.gen.js +34 -0
  50. package/dist/i18n/messages/cs.gen.js +2 -0
  51. package/dist/i18n/messages/de.gen.js +2 -0
  52. package/dist/i18n/messages/en.gen.js +2 -0
  53. package/dist/i18n/messages/es.gen.js +2 -0
  54. package/dist/i18n/messages/et.gen.js +2 -0
  55. package/dist/i18n/messages/fr.gen.js +2 -0
  56. package/dist/i18n/messages/he.gen.js +2 -0
  57. package/dist/i18n/messages/hi.gen.js +2 -0
  58. package/dist/i18n/messages/hu.gen.js +2 -0
  59. package/dist/i18n/messages/lt.gen.js +2 -0
  60. package/dist/i18n/messages/lv.gen.js +2 -0
  61. package/dist/i18n/messages/messages.gen.d.ts +2 -0
  62. package/dist/i18n/messages/pl.gen.js +2 -0
  63. package/dist/i18n/messages/pt-BR.gen.js +2 -0
  64. package/dist/i18n/messages/sk.gen.js +2 -0
  65. package/dist/i18n/messages/tr.gen.js +2 -0
  66. package/dist/i18n/messages/zh-CN.gen.js +2 -0
  67. package/dist/internal/wholeStoryRevisionResolution.d.ts +1 -1
  68. package/dist/internal/wholeStoryRevisionResolution.js +81 -21
  69. package/dist/layout-bridge/convert/altChunkPlaceholder.d.ts +10 -0
  70. package/dist/layout-bridge/convert/altChunkPlaceholder.js +70 -0
  71. package/dist/layout-bridge/convert/fixedTableColumnWidths.js +2 -1
  72. package/dist/layout-bridge/convert/flowConversionShared.d.ts +10 -0
  73. package/dist/layout-bridge/convert/flowConversionShared.js +11 -1
  74. package/dist/layout-bridge/convert/footnoteLayout.d.ts +1 -0
  75. package/dist/layout-bridge/convert/footnoteLayout.js +4 -1
  76. package/dist/layout-bridge/convert/headerFooterLayout.d.ts +1 -0
  77. package/dist/layout-bridge/convert/headerFooterLayout.js +6 -1
  78. package/dist/layout-bridge/convert/runMarkFormatting.js +1 -0
  79. package/dist/layout-bridge/convert/tableConversion.js +6 -2
  80. package/dist/layout-bridge/convert/toFlowBlocks.js +4 -0
  81. package/dist/layout-bridge/engine/clickToPosition.js +5 -1
  82. package/dist/layout-engine/measure/tableCellFloating.d.ts +2 -0
  83. package/dist/layout-engine/measure/tableCellFloating.js +1 -0
  84. package/dist/layout-engine/measure/tableVisibleBand.d.ts +16 -0
  85. package/dist/layout-engine/measure/tableVisibleBand.js +28 -0
  86. package/dist/layout-engine/tableLayout.js +7 -4
  87. package/dist/layout-engine/tableRowBreak.d.ts +10 -0
  88. package/dist/layout-engine/tableRowBreak.js +151 -36
  89. package/dist/layout-engine/types.d.ts +7 -2
  90. package/dist/layout-painter/previewSvg.d.ts +8 -0
  91. package/dist/layout-painter/previewSvg.js +47 -0
  92. package/dist/layout-painter/renderImage.js +2 -1
  93. package/dist/layout-painter/renderPage.d.ts +1 -0
  94. package/dist/layout-painter/renderPage.js +6 -3
  95. package/dist/layout-painter/renderParagraph.js +3 -2
  96. package/dist/layout-painter/renderTable.d.ts +5 -2
  97. package/dist/layout-painter/renderTable.js +33 -19
  98. package/dist/markdown/renderRuns.js +68 -12
  99. package/dist/prosemirror/anchoredTextBoxes.d.ts +2 -1
  100. package/dist/prosemirror/commands/comments.js +22 -7
  101. package/dist/prosemirror/commands/deleteBesideInlineAnchor.d.ts +9 -0
  102. package/dist/prosemirror/commands/deleteBesideInlineAnchor.js +36 -0
  103. package/dist/prosemirror/commands/pastePlainText.d.ts +6 -0
  104. package/dist/prosemirror/commands/pastePlainText.js +13 -3
  105. package/dist/prosemirror/commands/resolveAllTableChanges.js +30 -2
  106. package/dist/prosemirror/commands/resolveParagraphProperties.js +15 -2
  107. package/dist/prosemirror/commentReferenceIntegrity.d.ts +8 -2
  108. package/dist/prosemirror/commentReferenceIntegrity.js +19 -4
  109. package/dist/prosemirror/conversion/fromProseDoc.js +94 -22
  110. package/dist/prosemirror/conversion/hyphenTextCarriers.d.ts +23 -1
  111. package/dist/prosemirror/conversion/hyphenTextCarriers.js +46 -1
  112. package/dist/prosemirror/conversion/toProseDoc.js +21 -13
  113. package/dist/prosemirror/extensions/StarterKit.js +1 -1
  114. package/dist/prosemirror/extensions/core/ParagraphExtension.d.ts +3 -1
  115. package/dist/prosemirror/extensions/core/ParagraphExtension.js +8 -9
  116. package/dist/prosemirror/extensions/features/AutoBidiDetectionExtension.js +46 -11
  117. package/dist/prosemirror/extensions/features/BaseKeymapExtension.js +3 -2
  118. package/dist/prosemirror/extensions/features/BidiShortcutExtension.js +2 -3
  119. package/dist/prosemirror/extensions/features/ListExtension.js +22 -1
  120. package/dist/prosemirror/extensions/features/pasteCleanup.js +6 -0
  121. package/dist/prosemirror/extensions/features/pastedHtmlLists.js +2 -1
  122. package/dist/prosemirror/extensions/markRegistry.d.ts +3 -1
  123. package/dist/prosemirror/extensions/markRegistry.js +3 -0
  124. package/dist/prosemirror/extensions/marks/HyperlinkExtension.js +5 -0
  125. package/dist/prosemirror/extensions/marks/HyphenElementExtension.d.ts +6 -0
  126. package/dist/prosemirror/extensions/marks/HyphenElementExtension.js +54 -0
  127. package/dist/prosemirror/extensions/marks/TextColorExtension.js +1 -1
  128. package/dist/prosemirror/extensions/marks/TrackedChangeExtensions.js +8 -4
  129. package/dist/prosemirror/extensions/nodes/BookmarkBoundaryExtension.js +5 -1
  130. package/dist/prosemirror/extensions/nodes/CommentRangeBoundaryExtension.js +2 -1
  131. package/dist/prosemirror/extensions/nodes/CommentReferenceExtension.js +4 -3
  132. package/dist/prosemirror/extensions/nodes/MoveRangeBoundaryExtension.js +2 -1
  133. package/dist/prosemirror/extensions/nodes/NoteMarkerExtension.js +2 -1
  134. package/dist/prosemirror/extensions/nodes/RangeAnchorExtension.js +2 -1
  135. package/dist/prosemirror/extensions/nodes/RenderedPageBreakExtension.js +2 -1
  136. package/dist/prosemirror/extensions/nodes/TableExtension.js +87 -7
  137. package/dist/prosemirror/extensions/nodes/inlineAnchorDom.d.ts +11 -0
  138. package/dist/prosemirror/extensions/nodes/inlineAnchorDom.js +21 -0
  139. package/dist/prosemirror/fieldRepresentation.js +2 -1
  140. package/dist/prosemirror/hyphenElementAttrs.d.ts +10 -0
  141. package/dist/prosemirror/hyphenElementAttrs.js +32 -0
  142. package/dist/prosemirror/keptRangeBoundaries.d.ts +2 -0
  143. package/dist/prosemirror/keptRangeBoundaries.js +1 -1
  144. package/dist/prosemirror/listNumbering.js +3 -2
  145. package/dist/prosemirror/paragraphIndentation.js +2 -1
  146. package/dist/prosemirror/paragraphPropertyCarry.d.ts +1 -14
  147. package/dist/prosemirror/paragraphPropertyCarry.js +4 -28
  148. package/dist/prosemirror/plugins/suggestionMode.d.ts +0 -8
  149. package/dist/prosemirror/plugins/suggestionMode.js +194 -27
  150. package/dist/prosemirror/replacedAnnotations.d.ts +1 -0
  151. package/dist/prosemirror/replacedAnnotations.js +1 -0
  152. package/dist/prosemirror/rowGridOmissions.d.ts +11 -0
  153. package/dist/prosemirror/rowGridOmissions.js +21 -0
  154. package/dist/prosemirror/sectionCarrier.d.ts +8 -0
  155. package/dist/prosemirror/sectionCarrier.js +29 -1
  156. package/dist/prosemirror/styles/paragraphStyleCascade.d.ts +10 -0
  157. package/dist/prosemirror/styles/paragraphStyleCascade.js +12 -2
  158. package/dist/prosemirror/tableGridMutation.d.ts +19 -2
  159. package/dist/prosemirror/tableGridMutation.js +118 -15
  160. package/dist/prosemirror/tablePositionedBookmarks.d.ts +2 -0
  161. package/dist/prosemirror/tablePositionedBookmarks.js +80 -0
  162. package/dist/prosemirror/tableRunIn.d.ts +24 -9
  163. package/dist/prosemirror/tableRunIn.js +107 -21
  164. package/dist/prosemirror/textInput.js +3 -1
  165. package/dist/prosemirror/validation.js +7 -1
  166. package/dist/utils/createDocument.js +11 -8
  167. package/dist/utils/formatToStyle.js +2 -2
  168. package/dist/utils/units.d.ts +5 -0
  169. package/dist/utils/units.js +6 -1
  170. package/package.json +3 -3
@@ -257,12 +257,33 @@ const chartPart = (drawing, rels, media) => {
257
257
  path
258
258
  } : null;
259
259
  };
260
- /** Describe a supported cached chart. AlternateContent fallbacks are resolved by the run parser. */
260
+ /**
261
+ * Describe a chart: the marks of a supported cached chart, or an empty frame of
262
+ * the same size. AlternateContent fallbacks are resolved by the run parser.
263
+ */
261
264
  const parseChartPreview = (drawing, rels, media) => {
265
+ const size = extentOf(drawing);
266
+ if (!isChartDrawing(drawing) || size.width <= 0 || size.height <= 0) return null;
267
+ return {
268
+ type: "image",
269
+ preview: {
270
+ kind: "chart",
271
+ extent: size,
272
+ shapes: chartMarks(drawing, size, rels, media) ?? []
273
+ },
274
+ size,
275
+ wrap: { type: "inline" }
276
+ };
277
+ };
278
+ const isChartDrawing = (drawing) => {
279
+ const graphicData = firstDescendant(drawing, DRAWINGML, "graphicData");
280
+ return graphicData !== null && CHART.has(getAttribute(graphicData, null, "uri") ?? "") && firstDescendant(graphicData, CHART, "chart") !== null;
281
+ };
282
+ /** The marks a chart's cached data draws, or null when it cannot draw them. */
283
+ const chartMarks = (drawing, size, rels, media) => {
262
284
  if (!rels || !media) return null;
263
285
  const part = chartPart(drawing, rels, media);
264
- const size = extentOf(drawing);
265
- if (!part || size.width <= 0 || size.height <= 0) return null;
286
+ if (!part) return null;
266
287
  const plotArea = firstDescendant(part.root, CHART, "plotArea");
267
288
  if (!plotArea) return null;
268
289
  const supported = getChildElements(plotArea).find((item) => [
@@ -281,21 +302,11 @@ const parseChartPreview = (drawing, rels, media) => {
281
302
  else shapes = pieShapes(supported, series, size.width, size.height, kind === "doughnutChart");
282
303
  if (shapes.length === 0) return null;
283
304
  if (shapes.reduce((total, shape) => total + (shape.type === "polygon" || shape.type === "polyline" ? shape.points.length : 0), 0) > 512) return null;
284
- if (!shapes.every((shape) => shape.type === "polygon" || shape.type === "polyline" ? shape.points.every(({ x, y }) => Number.isFinite(x) && Number.isFinite(y)) : [
305
+ return shapes.every((shape) => shape.type === "polygon" || shape.type === "polyline" ? shape.points.every(({ x, y }) => Number.isFinite(x) && Number.isFinite(y)) : [
285
306
  shape.x,
286
307
  shape.y,
287
308
  shape.width,
288
309
  shape.height
289
- ].every(Number.isFinite))) return null;
290
- return {
291
- type: "image",
292
- preview: {
293
- kind: "chart",
294
- extent: size,
295
- shapes
296
- },
297
- size,
298
- wrap: { type: "inline" }
299
- };
310
+ ].every(Number.isFinite)) ? shapes : null;
300
311
  };
301
312
  export { parseChartPreview };
@@ -1,3 +1,4 @@
1
+ import { NumberingIdsInUse } from "./numberingIds.js";
1
2
  import { document_d_exports } from "../types/document.js";
2
3
  /** The two kinds of list a command can create. */
3
4
  export declare const LIST_KINDS: readonly ["bullet", "numbered"];
@@ -23,10 +24,11 @@ type MintedListInstance = {
23
24
  /**
24
25
  * Define a new list: a new `w:abstractNum` of the requested kind and the
25
26
  * `w:num` naming it. `definitions` must already hold every instance the
26
- * document references (see {@link completeListNumbering}), so the new ids
27
- * collide with none of them.
27
+ * story references (see {@link completeListNumbering}), and `elsewhere` the
28
+ * ids the package's other stories define, so the new ids collide with none of
29
+ * them.
28
30
  */
29
- export declare const mintListInstance: (definitions: document_d_exports.NumberingDefinitions | null | undefined, { kind, format, start }: NewListDefinition) => MintedListInstance;
31
+ export declare const mintListInstance: (definitions: document_d_exports.NumberingDefinitions | null | undefined, { kind, format, start }: NewListDefinition, elsewhere: NumberingIdsInUse) => MintedListInstance;
30
32
  type RestartListInstanceOptions = {
31
33
  abstractNumId: number;
32
34
  ilvl: number;
@@ -38,7 +40,7 @@ type RestartListInstanceOptions = {
38
40
  * makes a consumer count the instance on its own rather than continue the
39
41
  * other instances of the same definition.
40
42
  */
41
- export declare const restartListInstance: (definitions: document_d_exports.NumberingDefinitions | null | undefined, { abstractNumId, ilvl, start }: RestartListInstanceOptions) => MintedListInstance;
43
+ export declare const restartListInstance: (definitions: document_d_exports.NumberingDefinitions | null | undefined, { abstractNumId, ilvl, start }: RestartListInstanceOptions, elsewhere: NumberingIdsInUse) => MintedListInstance;
42
44
  /** One paragraph's numbering reference and the rendering it resolved to. */
43
45
  export type ListInstanceReference = {
44
46
  numId: number;
@@ -117,25 +117,26 @@ const EMPTY_DEFINITIONS = {
117
117
  nums: []
118
118
  };
119
119
  /** A fresh `w:numId` for `definitions`; zero is reserved for "no numbering". */
120
- const nextNumId = (definitions) => mintNumberingId({
120
+ const nextNumId = (definitions, elsewhere) => mintNumberingId({
121
121
  kind: "num",
122
- existingIds: (definitions?.nums ?? []).map(({ numId }) => numId)
122
+ existingIds: [...(definitions?.nums ?? []).map(({ numId }) => numId), ...elsewhere.numIds]
123
123
  });
124
124
  /** A fresh `w:abstractNumId` for `definitions`. */
125
- const nextAbstractNumId = (definitions) => mintNumberingId({
125
+ const nextAbstractNumId = (definitions, elsewhere) => mintNumberingId({
126
126
  kind: "abstract",
127
- existingIds: (definitions?.abstractNums ?? []).map(({ abstractNumId }) => abstractNumId)
127
+ existingIds: [...(definitions?.abstractNums ?? []).map(({ abstractNumId }) => abstractNumId), ...elsewhere.abstractNumIds]
128
128
  });
129
129
  /**
130
130
  * Define a new list: a new `w:abstractNum` of the requested kind and the
131
131
  * `w:num` naming it. `definitions` must already hold every instance the
132
- * document references (see {@link completeListNumbering}), so the new ids
133
- * collide with none of them.
132
+ * story references (see {@link completeListNumbering}), and `elsewhere` the
133
+ * ids the package's other stories define, so the new ids collide with none of
134
+ * them.
134
135
  */
135
- const mintListInstance = (definitions, { kind, format, start }) => {
136
+ const mintListInstance = (definitions, { kind, format, start }, elsewhere) => {
136
137
  const current = definitions ?? EMPTY_DEFINITIONS;
137
- const numId = nextNumId(current);
138
- const abstractNumId = nextAbstractNumId(current);
138
+ const numId = nextNumId(current, elsewhere);
139
+ const abstractNumId = nextAbstractNumId(current, elsewhere);
139
140
  const levelOverrides = levelZeroStart(start);
140
141
  const instance = {
141
142
  numId,
@@ -161,9 +162,9 @@ const mintListInstance = (definitions, { kind, format, start }) => {
161
162
  * makes a consumer count the instance on its own rather than continue the
162
163
  * other instances of the same definition.
163
164
  */
164
- const restartListInstance = (definitions, { abstractNumId, ilvl, start }) => {
165
+ const restartListInstance = (definitions, { abstractNumId, ilvl, start }, elsewhere) => {
165
166
  const current = definitions ?? EMPTY_DEFINITIONS;
166
- const numId = nextNumId(current);
167
+ const numId = nextNumId(current, elsewhere);
167
168
  const instance = {
168
169
  numId,
169
170
  abstractNumId,
@@ -0,0 +1,6 @@
1
+ import { ZipArchive } from "@stll/docx-core/zip";
2
+ /**
3
+ * Moves the main document to the standard path. Returns whether it moved.
4
+ * What is not a word processing main part, a theme package say, stays put.
5
+ */
6
+ export declare const moveMainDocumentToStandardPath: (zip: ZipArchive) => Promise<boolean>;
@@ -0,0 +1,65 @@
1
+ import { resolvePackageRelationshipTarget } from "./packageParts.js";
2
+ // src/docx/mainDocumentPart.ts
3
+ const STANDARD_PATH = "word/document.xml";
4
+ const STANDARD_RELATIONSHIPS_PATH = "word/_rels/document.xml.rels";
5
+ const PACKAGE_RELATIONSHIPS_PATH = "_rels/.rels";
6
+ const CONTENT_TYPES_PATH = "[content_types].xml";
7
+ const OFFICE_DOCUMENT_TYPE = /\/officeDocument["']/u;
8
+ const WORD_MAIN_CONTENT_TYPE = /wordprocessingml\.[a-z.]*main\+xml/iu;
9
+ const entryNamed = (zip, lowerPath) => zip.paths().find((path) => path.toLowerCase() === lowerPath);
10
+ const relationshipsPathOf = (part) => {
11
+ const slash = part.lastIndexOf("/");
12
+ return `${part.slice(0, slash + 1)}_rels/${part.slice(slash + 1)}.rels`;
13
+ };
14
+ /** A relationship's relative target as an absolute part name. */
15
+ const absolutePartPath = (directory, relative) => {
16
+ const segments = [];
17
+ for (const segment of `${directory}${relative}`.split("/")) if (segment === "..") segments.pop();
18
+ else if (segment !== "" && segment !== ".") segments.push(segment);
19
+ return `/${segments.join("/")}`;
20
+ };
21
+ const escapeForRegExp = (text) => text.replaceAll(/[.*+?^${}()|[\]\\]/gu, String.raw`\$&`);
22
+ const targetOf = (element) => /\bTarget\s*=\s*["']([^"']+)["']/u.exec(element)?.[1] ?? null;
23
+ /**
24
+ * Moves the main document to the standard path. Returns whether it moved.
25
+ * What is not a word processing main part, a theme package say, stays put.
26
+ */
27
+ const moveMainDocumentToStandardPath = async (zip) => {
28
+ const packagePath = entryNamed(zip, PACKAGE_RELATIONSHIPS_PATH);
29
+ const contentTypesPath = entryNamed(zip, CONTENT_TYPES_PATH);
30
+ if (packagePath === void 0 || contentTypesPath === void 0) return false;
31
+ const packageXml = await zip.entry(packagePath)?.text();
32
+ const contentTypes = await zip.entry(contentTypesPath)?.text();
33
+ if (packageXml === void 0 || contentTypes === void 0) return false;
34
+ const relationship = [...packageXml.matchAll(/<(?:\w+:)?Relationship\b[^>]*>/gu)].map(([element]) => element).find((element) => OFFICE_DOCUMENT_TYPE.test(element));
35
+ const target = relationship && targetOf(relationship);
36
+ if (!relationship || !target) return false;
37
+ const lowerPath = resolvePackageRelationshipTarget(target, PACKAGE_RELATIONSHIPS_PATH);
38
+ if (lowerPath === void 0 || lowerPath === STANDARD_PATH) return false;
39
+ const part = entryNamed(zip, lowerPath);
40
+ if (part === void 0) return false;
41
+ const override = new RegExp(String.raw`<(?:\w+:)?Override\b[^>]*PartName\s*=\s*["']/${escapeForRegExp(part)}["'][^>]*>`, "iu");
42
+ const declared = override.exec(contentTypes)?.[0];
43
+ if (declared === void 0 || !WORD_MAIN_CONTENT_TYPE.test(declared)) return false;
44
+ const bytes = await zip.entry(part)?.bytes();
45
+ if (bytes === void 0) return false;
46
+ const relationshipsPath = entryNamed(zip, relationshipsPathOf(part).toLowerCase());
47
+ const relationships = relationshipsPath === void 0 ? void 0 : await zip.entry(relationshipsPath)?.text();
48
+ const directory = part.slice(0, part.lastIndexOf("/") + 1);
49
+ const anchored = relationships === void 0 || directory === "word/" ? relationships : relationships.replaceAll(/<(?:\w+:)?Relationship\b[^>]*>/gu, (element) => /TargetMode\s*=\s*["']External["']/iu.test(element) ? element : element.replace(/\bTarget\s*=\s*(["'])(?!\/)([^"']+)\1/u, (_match, quote, relative) => {
50
+ return `Target=${quote}${absolutePartPath(directory, relative)}${quote}`;
51
+ }));
52
+ zip.delete(part);
53
+ if (relationshipsPath !== void 0) zip.delete(relationshipsPath);
54
+ const replaced = entryNamed(zip, STANDARD_PATH);
55
+ if (replaced !== void 0) zip.delete(replaced);
56
+ const replacedRelationships = entryNamed(zip, STANDARD_RELATIONSHIPS_PATH);
57
+ if (replacedRelationships !== void 0) zip.delete(replacedRelationships);
58
+ zip.set(STANDARD_PATH, bytes);
59
+ if (anchored !== void 0) zip.set(STANDARD_RELATIONSHIPS_PATH, anchored);
60
+ zip.set(packagePath, packageXml.replace(relationship, relationship.replace(/\bTarget\s*=\s*(["'])[^"']+\1/u, `Target="${STANDARD_PATH}"`)));
61
+ const standardOverride = new RegExp(String.raw`<(?:\w+:)?Override\b[^>]*PartName\s*=\s*["']/${escapeForRegExp(STANDARD_PATH)}["'][^>]*>`, "iu");
62
+ zip.set(contentTypesPath, contentTypes.replace(standardOverride, "").replace(override, declared.replace(/PartName\s*=\s*(["'])[^"']+\1/u, `PartName="/${STANDARD_PATH}"`)));
63
+ return true;
64
+ };
65
+ export { moveMainDocumentToStandardPath };
@@ -1,4 +1,14 @@
1
1
  type NumberingKind = "num" | "abstract";
2
+ /**
3
+ * Numbering ids (`w:num`, `w:abstractNum`) defined outside the numbering a
4
+ * caller allocates against: the lists the package's other stories define. The
5
+ * ids are package-wide, so a list minted in one story takes none of them.
6
+ */
7
+ export type NumberingIdsInUse = {
8
+ numIds: ReadonlySet<number>;
9
+ abstractNumIds: ReadonlySet<number>;
10
+ };
11
+ export declare const NO_NUMBERING_IDS_IN_USE: NumberingIdsInUse;
2
12
  type MintNumberingIdOptions = {
3
13
  kind: NumberingKind;
4
14
  existingIds: Iterable<number>;
@@ -1,5 +1,9 @@
1
1
  import { createNumericIdAllocator } from "./numericIdAllocator.js";
2
2
  // src/docx/numberingIds.ts
3
+ const NO_NUMBERING_IDS_IN_USE = {
4
+ numIds: /* @__PURE__ */ new Set(),
5
+ abstractNumIds: /* @__PURE__ */ new Set()
6
+ };
3
7
  /** Independent offline packages can allocate deterministically without retaining realm state. */
4
8
  const createNumberingIdAllocator = (kind, existingIds) => {
5
9
  const allocator = createNumericIdAllocator({
@@ -12,4 +16,4 @@ const createNumberingIdAllocator = (kind, existingIds) => {
12
16
  const mintNumberingId = ({ kind, existingIds }) => {
13
17
  return createNumberingIdAllocator(kind, existingIds).next();
14
18
  };
15
- export { createNumberingIdAllocator, mintNumberingId };
19
+ export { NO_NUMBERING_IDS_IN_USE, createNumberingIdAllocator, mintNumberingId };
@@ -41,7 +41,7 @@ export type PackageReferenceRepair = {
41
41
  * already-reconciled package therefore reports nothing and changes nothing,
42
42
  * which is what the repack tests assert about their own output.
43
43
  */
44
- export declare const reconcilePackageReferences: (zip: ZipArchive, compressionLevel: number) => Promise<PackageReferenceRepair>;
44
+ export declare const reconcilePackageReferences: (zip: ZipArchive, compressionLevel: number, source?: ZipArchive) => Promise<PackageReferenceRepair>;
45
45
  /**
46
46
  * What {@link checkPackageIntegrity} found wrong with a package. Both fields
47
47
  * are empty for a package where every internal relationship resolves and
@@ -102,7 +102,11 @@ const removeUnsafeEntries = (zip) => {
102
102
  };
103
103
  const presentPartPaths = (zip) => {
104
104
  const present = /* @__PURE__ */ new Set();
105
- for (const path of zip.paths()) present.add(normalizePartPath(path));
105
+ for (const path of zip.paths()) {
106
+ present.add(normalizePartPath(path));
107
+ const decoded = decodePartName(path);
108
+ if (decoded !== void 0) present.add(normalizePartPath(decoded));
109
+ }
106
110
  return present;
107
111
  };
108
112
  const isPresent = (present, partPath) => present.has(normalizePartPath(partPath)) || present.has(normalizePartPath(decodePartName(partPath) ?? ""));
@@ -143,8 +147,10 @@ const writePart = ({ zip, path, xml, compressionLevel }) => {
143
147
  * already-reconciled package therefore reports nothing and changes nothing,
144
148
  * which is what the repack tests assert about their own output.
145
149
  */
146
- const reconcilePackageReferences = async (zip, compressionLevel) => {
150
+ const reconcilePackageReferences = async (zip, compressionLevel, source) => {
147
151
  const present = presentPartPaths(zip);
152
+ const sourceParts = source ? presentPartPaths(source) : null;
153
+ const danglingInSource = (partPath) => sourceParts !== null && partPath !== "" && !isPresent(sourceParts, partPath);
148
154
  const repair = {
149
155
  danglingRelationships: [],
150
156
  danglingOverrides: [],
@@ -155,7 +161,7 @@ const reconcilePackageReferences = async (zip, compressionLevel) => {
155
161
  let dropped = false;
156
162
  const pruned = xml.replaceAll(RELATIONSHIP_ELEMENT, (element) => {
157
163
  const target = relationshipTarget(element, path);
158
- if (target === null || present.has(target)) return element;
164
+ if (target === null || isPresent(present, target) || danglingInSource(target)) return element;
159
165
  repair.danglingRelationships.push(target || TARGET_ATTRIBUTE.exec(element)?.groups?.["value"] || "");
160
166
  dropped = true;
161
167
  const id = RELATIONSHIP_ID_ATTRIBUTE.exec(element)?.groups?.["value"];
@@ -201,7 +207,7 @@ const reconcilePackageReferences = async (zip, compressionLevel) => {
201
207
  let droppedOverride = false;
202
208
  const prunedContentTypes = (await contentTypes.bytes().then((bytes) => decodeText(bytes, { ignoreBOM: true }))).replaceAll(CONTENT_TYPE_ELEMENT, (element) => {
203
209
  const partName = PART_NAME_ATTRIBUTE.exec(element)?.groups?.["value"];
204
- if (partName === void 0 || isPresent(present, partName)) return element;
210
+ if (partName === void 0 || isPresent(present, partName) || danglingInSource(partName)) return element;
205
211
  repair.danglingOverrides.push(normalizePartPath(decodePartName(partName) ?? partName));
206
212
  droppedOverride = true;
207
213
  return "";
@@ -168,6 +168,19 @@ function paragraphStartsWithRenderedPageBreak(node) {
168
168
  if (outcome === "forced") return sawRenderedPageBreak;
169
169
  return outcome === "visible" && sawRenderedPageBreak;
170
170
  }
171
+ /**
172
+ * How each revision's content is read. A deletion's runs spell their text
173
+ * `w:delText` (ISO/IEC 29500-1 §17.3.3.7), read here as the text it stands
174
+ * for. A move source's runs spell it `w:t` (§17.13.5.22), which that reading
175
+ * leaves as it is; it also accepts the `w:delText` some writers put there, so
176
+ * both spellings give the same model, which the serializer writes as `w:t`.
177
+ */
178
+ const TRACKED_CHANGE_PARSE_CONTEXT = {
179
+ insertion: "default",
180
+ deletion: "deletion",
181
+ moveFrom: "deletion",
182
+ moveTo: "default"
183
+ };
171
184
  function replaceLocalName(name, localName) {
172
185
  if (!name) return `w:${localName}`;
173
186
  const colonIndex = name.indexOf(":");
@@ -405,7 +418,7 @@ const linkedRevisionContent = (wrapped, linkOver) => {
405
418
  return content;
406
419
  };
407
420
  const hoistRevision = (wrapper) => (child, { styles, theme, rels, media, previews, inScopeXmlns, items, linkOver }) => {
408
- const wrapped = parseParagraphContents(child, styles, theme, null, rels, media, previews, wrapper === "deletion" || wrapper === "moveFrom" ? "deletion" : "default", inScopeXmlns, "hyperlink");
421
+ const wrapped = parseParagraphContents(child, styles, theme, null, rels, media, previews, TRACKED_CHANGE_PARSE_CONTEXT[wrapper], inScopeXmlns, "hyperlink");
409
422
  const content = linkedRevisionContent(wrapped, linkOver);
410
423
  items.push({
411
424
  type: "hoistedRevision",
@@ -537,7 +550,7 @@ const fieldInlineWrapper = (element) => (child, context) => {
537
550
  };
538
551
  /** Read a field's revision with the same ownership rules as a paragraph revision. */
539
552
  const fieldTrackedChange = (type) => (child, { push, styles, theme, rels, media, previews, inScopeXmlns }) => {
540
- const parsedContent = parseParagraphContents(child, styles, theme, null, rels, media, previews, type === "deletion" || type === "moveFrom" ? "deletion" : "default", inScopeXmlns);
553
+ const parsedContent = parseParagraphContents(child, styles, theme, null, rels, media, previews, TRACKED_CHANGE_PARSE_CONTEXT[type], inScopeXmlns);
541
554
  if (parsedContent.length === 0 || !parsedContent.every(isTrackedChangeWrapperChild)) {
542
555
  push(preserveInlineChild(child));
543
556
  return;
@@ -901,7 +914,7 @@ const PARAGRAPH_CONTENT_UNDECLARED_NAMESPACES = { [OMML_NAMESPACE]: (child, { co
901
914
  /** All revision wrappers retain typed review ownership while parsing their children. */
902
915
  const trackedParagraphRevision = (type) => (child, { contents, styles, theme, rels, media, previews, inScopeXmlns, inlineScope }) => {
903
916
  const resolutionJoins = parseResolutionJoins(child);
904
- const parsedContent = parseParagraphContents(child, styles, theme, null, rels, media, previews, type === "deletion" || type === "moveFrom" ? "deletion" : "default", inScopeXmlns, inlineScope);
917
+ const parsedContent = parseParagraphContents(child, styles, theme, null, rels, media, previews, TRACKED_CHANGE_PARSE_CONTEXT[type], inScopeXmlns, inlineScope);
905
918
  pushTrackedChangeSegments({
906
919
  contents,
907
920
  type,
@@ -1,3 +1,4 @@
1
+ import { hangingFirstLineIndent } from "../utils/units.js";
1
2
  import { readAttributeBag } from "./attributeRemainder.js";
2
3
  import { parseBorderSpec } from "./borderParser.js";
3
4
  import { CAPTURE, dispatchChildrenWithContext, ownedElsewhere, sequencePositions } from "./containerChildren.js";
@@ -296,7 +297,7 @@ const readParagraphIndentation = (ind, formatting) => {
296
297
  if (firstLine !== void 0) formatting.indentFirstLine = firstLine;
297
298
  const hanging = parseNumericAttribute(ind, "w", "hanging");
298
299
  if (hanging !== void 0) {
299
- formatting.indentFirstLine = -hanging;
300
+ formatting.indentFirstLine = hangingFirstLineIndent(hanging);
300
301
  formatting.hangingIndent = true;
301
302
  }
302
303
  if (!(left !== void 0 || right !== void 0 || firstLine !== void 0 || hanging !== void 0)) return false;
@@ -1,5 +1,11 @@
1
1
  import { document_d_exports } from "../types/document.js";
2
2
  type PreviewKindName = "vmlShape" | "wpGroup" | "smartArt";
3
+ /**
4
+ * A drawn preview as an `<img>` source. It is derived from a descriptor the
5
+ * ledger already charged and held only while a painter uses it, so it is not a
6
+ * second retained preview.
7
+ */
8
+ export declare const svgPreviewDataUrl: (svg: string) => string;
3
9
  declare const PREVIEW_KINDS: {
4
10
  /** A VML shape folio renders rather than projects (`v:shape`, `v:rect`, ...). */
5
11
  readonly vmlShape: {
@@ -2,6 +2,12 @@
2
2
  /** Both SVG producers encode their drawing into the URL rather than base64. */
3
3
  const SVG_PREVIEW_DATA_URL_PREFIX = "data:image/svg+xml;charset=utf-8,";
4
4
  /**
5
+ * A drawn preview as an `<img>` source. It is derived from a descriptor the
6
+ * ledger already charged and held only while a painter uses it, so it is not a
7
+ * second retained preview.
8
+ */
9
+ const svgPreviewDataUrl = (svg) => `${SVG_PREVIEW_DATA_URL_PREFIX}${encodeURIComponent(svg)}`;
10
+ /**
5
11
  * Eight times what a producer may spend on one drawing, which is a package
6
12
  * holding a handful of the largest previews folio will build.
7
13
  */
@@ -109,4 +115,4 @@ const createPackagePreviewBudget = () => {
109
115
  * whose previews no package budget charges.
110
116
  */
111
117
  const standalonePreviewLedger = () => createPackagePreviewBudget().ledger;
112
- export { createPackagePreviewBudget, standalonePreviewLedger };
118
+ export { createPackagePreviewBudget, standalonePreviewLedger, svgPreviewDataUrl };
@@ -698,8 +698,8 @@ const normalizePackageOnSave = async (zip, compressionLevel) => {
698
698
  * at each caller so no save path can emit a package whose relationships or
699
699
  * content types name a part it does not hold.
700
700
  */
701
- const generateDocxZip = async (zip, compressionLevel) => {
702
- await reconcilePackageReferences(zip, compressionLevel);
701
+ const generateDocxZip = async (zip, compressionLevel, source) => {
702
+ await reconcilePackageReferences(zip, compressionLevel, source);
703
703
  await normalizePackageOnSave(zip, compressionLevel);
704
704
  return zip.generate({ level: compressionLevel }).then((bytes) => bytes.buffer);
705
705
  };
@@ -829,7 +829,7 @@ const finishRepack = async ({ document: sourceDocument, originalZip, outputZip,
829
829
  });
830
830
  outputZip.set("docProps/core.xml", updatedCoreProperties, { level: compressionLevel });
831
831
  }
832
- return generateDocxZip(outputZip, compressionLevel);
832
+ return generateDocxZip(outputZip, compressionLevel, originalZip);
833
833
  };
834
834
  async function repackDocxWithSectionEndpointRemoval({ document: doc, options, sectionEndpointRemoval, sectionReferenceRemovals }) {
835
835
  if (!doc.originalBuffer) panic("Cannot repack document: no original buffer for round-trip. Use createDocx() for new documents.");
@@ -937,7 +937,7 @@ async function repackDocxFromRaw(doc, rawContent, options = {}) {
937
937
  });
938
938
  newZip.set("docProps/core.xml", updatedCoreProps, { level: compressionLevel });
939
939
  }
940
- return generateDocxZip(newZip, compressionLevel);
940
+ return generateDocxZip(newZip, compressionLevel, rawContent.originalZip);
941
941
  }
942
942
  const COMMENTS_CONTENT_TYPE = "application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml";
943
943
  const COMMENTS_EXTENDED_CONTENT_TYPE = "application/vnd.openxmlformats-officedocument.wordprocessingml.commentsExtended+xml";