From 7907016816ab5264e25701366f52ac0e9674f287 Mon Sep 17 00:00:00 2001 From: Dolan Date: Sat, 17 Oct 2026 09:44:22 +0100 Subject: [PATCH] fix: read and write XML without xml and xml-js, which are no longer maintained (#3779) --- package-lock.json | 62 +---- package.json | 5 +- scripts/check-api.ts | 2 +- scripts/compare-layout.ts | 14 +- scripts/generate-preset-shape-geometry.ts | 4 +- scripts/layout-probes/demo-lines.ts | 10 +- scripts/layout-probes/guess-lines.ts | 4 +- scripts/layout-probes/stops2/layout-stops.ts | 2 +- src/charts/chart-data-patch.spec.ts | 4 +- src/charts/chart-data-patch.ts | 3 +- src/charts/chart-elements.spec.ts | 22 +- src/charts/chart-schema.spec.ts | 9 +- src/charts/chart-space.spec.ts | 7 +- src/charts/chart-style.spec.ts | 4 +- src/charts/chart-text.spec.ts | 14 +- src/charts/index.spec.ts | 4 +- src/charts/plot-area/area-chart.spec.ts | 5 +- src/charts/plot-area/axes.spec.ts | 21 +- src/charts/plot-area/bar-chart.spec.ts | 7 +- src/charts/plot-area/bubble-chart.spec.ts | 9 +- src/charts/plot-area/category-chart.spec.ts | 11 +- src/charts/plot-area/data-labels.spec.ts | 11 +- src/charts/plot-area/error-bars.spec.ts | 7 +- src/charts/plot-area/line-chart.spec.ts | 9 +- src/charts/plot-area/pie-chart.spec.ts | 9 +- src/charts/plot-area/plot-area.spec.ts | 9 +- src/charts/plot-area/radar-chart.spec.ts | 13 +- src/charts/plot-area/scatter-chart.spec.ts | 5 +- src/charts/plot-area/series.spec.ts | 4 +- src/charts/plot-area/stock-chart.spec.ts | 7 +- src/charts/plot-area/trendline.spec.ts | 7 +- src/charts/template/patch-chart.spec.ts | 9 +- src/charts/template/patch-chart.ts | 3 +- src/charts/template/template-chart.spec.ts | 5 +- src/charts/template/template-chart.ts | 3 +- src/charts/template/template-series.spec.ts | 7 +- src/charts/template/template-series.ts | 3 +- src/charts/template/template-xml.spec.ts | 7 +- src/charts/template/template-xml.ts | 4 +- src/charts/workbook/workbook.spec.ts | 4 +- src/export/packer/next-compiler.ts | 56 ++-- src/export/packer/package-part-writer.ts | 4 +- src/file/styles/external-styles-factory.ts | 4 +- .../imported-xml-component.spec.ts | 4 +- .../xml-components/imported-xml-component.ts | 22 +- src/html/math.spec.ts | 4 +- src/layout/imported-documents.spec.ts | 5 +- src/layout/imported-documents.ts | 3 +- src/layout/read-docx.spec.ts | 4 +- src/layout/read-docx.ts | 9 +- src/math/latex-to-math.spec.ts | 4 +- src/math/math-accent.spec.ts | 4 +- src/math/math-bar.spec.ts | 4 +- src/math/math-box.spec.ts | 4 +- src/math/math-brace.spec.ts | 4 +- src/math/math-brackets.spec.ts | 6 +- src/math/math-cases.spec.ts | 4 +- src/math/math-equation-array.spec.ts | 4 +- src/math/math-large-operator.spec.ts | 4 +- src/math/math-matrix.spec.ts | 4 +- src/math/math-phantom.spec.ts | 4 +- src/math/math-schema.spec.ts | 9 +- src/patcher/bookmark-ids.spec.ts | 3 +- src/patcher/bookmark-ids.ts | 2 +- src/patcher/content-types-manager.ts | 3 +- src/patcher/drawing-ids.spec.ts | 3 +- src/patcher/drawing-ids.ts | 2 +- src/patcher/drawing-patch.spec.ts | 2 +- src/patcher/drawing-patch.ts | 5 +- src/patcher/from-docx.ts | 38 +-- src/patcher/notes.ts | 5 +- src/patcher/numbering.ts | 5 +- src/patcher/page-numbers.spec.ts | 11 +- src/patcher/page-numbers.ts | 8 +- src/patcher/paragraph-split-inject.ts | 3 +- src/patcher/paragraph-token-replacer.ts | 3 +- src/patcher/relationship-manager.ts | 2 +- src/patcher/replacer.spec.ts | 2 +- src/patcher/replacer.ts | 5 +- src/patcher/run-renderer.ts | 3 +- src/patcher/styles.ts | 5 +- src/patcher/table-rows.spec.ts | 6 +- src/patcher/table-rows.ts | 3 +- src/patcher/theme-colors.ts | 2 +- src/patcher/traverser.ts | 3 +- src/patcher/util.ts | 7 +- src/tests/html.ts | 8 +- src/util/index.ts | 1 + src/util/xml/corpus.spec.ts | 142 ++++++++++ src/util/xml/index.ts | 8 + src/util/xml/parse.spec.ts | 177 ++++++++++++ src/util/xml/parse.ts | 263 ++++++++++++++++++ src/util/xml/stringify.spec.ts | 136 +++++++++ src/util/xml/stringify.ts | 191 +++++++++++++ src/util/xml/types.ts | 47 ++++ vite.config.ts | 2 + 96 files changed, 1241 insertions(+), 384 deletions(-) create mode 100644 src/util/xml/corpus.spec.ts create mode 100644 src/util/xml/index.ts create mode 100644 src/util/xml/parse.spec.ts create mode 100644 src/util/xml/parse.ts create mode 100644 src/util/xml/stringify.spec.ts create mode 100644 src/util/xml/stringify.ts create mode 100644 src/util/xml/types.ts diff --git a/package-lock.json b/package-lock.json index 0f57af05b1..5da5bdceec 100644 --- a/package-lock.json +++ b/package-lock.json @@ -12,16 +12,13 @@ "@types/node": "^26.6.2", "hash.js": "^1.1.7", "jszip": "^3.10.1", - "nanoid": "^6.0.1", - "xml": "^1.0.1", - "xml-js": "^1.6.8" + "nanoid": "^6.0.1" }, "devDependencies": { "@eslint/js": "^10.0.1", "@microsoft/api-extractor": "^7.58.7", "@types/pngjs": "^6.0.5", "@types/unzipper": "^0.10.4", - "@types/xml": "^1.0.8", "@typescript-eslint/eslint-plugin": "^8.8.1", "@typescript-eslint/parser": "^8.8.1", "@typescript/native": "npm:typescript@7.0.2", @@ -3029,15 +3026,6 @@ "@types/node": "*" } }, - "node_modules/@types/xml": { - "version": "1.0.11", - "resolved": "https://registry.npmjs.org/@types/xml/-/xml-1.0.11.tgz", - "integrity": "sha512-9gktTjxBWoz4+X8ZOS+QRFM2/liMQgBv8Z36wuNnomK5jtXFq4IJa7Az4Hzoy+rYux343NkH9Dq+nzIdejVrjw==", - "dev": true, - "dependencies": { - "@types/node": "*" - } - }, "node_modules/@typescript-eslint/eslint-plugin": { "version": "8.71.2", "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.71.2.tgz", @@ -10567,11 +10555,6 @@ "dev": true, "license": "MIT" }, - "node_modules/sax": { - "version": "1.2.4", - "resolved": "https://registry.npmjs.org/sax/-/sax-1.2.4.tgz", - "integrity": "sha512-NqVDv9TpANUjFm0N8uM5GxL36UgKi9/atZw+x7YFnQ8ckwFGKrl4xX4yWtrey3UJm5nP1kUbnYgLopqWNSRhWw==" - }, "node_modules/saxes": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz", @@ -12361,22 +12344,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/xml": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/xml/-/xml-1.0.1.tgz", - "integrity": "sha1-eLpyAgApxbyHuKgaPPzXS0ovweU=" - }, - "node_modules/xml-js": { - "version": "1.6.11", - "resolved": "https://registry.npmjs.org/xml-js/-/xml-js-1.6.11.tgz", - "integrity": "sha512-7rVi2KMfwfWFl+GpPg6m80IVMWXLRjO+PxTq7V2CDhoGak0wzYzFgUY2m4XJ47OGdXd8eLE8EmwfAmdjw7lC1g==", - "dependencies": { - "sax": "^1.2.4" - }, - "bin": { - "xml-js": "bin/cli.js" - } - }, "node_modules/xml-name-validator": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz", @@ -14340,15 +14307,6 @@ "@types/node": "*" } }, - "@types/xml": { - "version": "1.0.11", - "resolved": "https://registry.npmjs.org/@types/xml/-/xml-1.0.11.tgz", - "integrity": "sha512-9gktTjxBWoz4+X8ZOS+QRFM2/liMQgBv8Z36wuNnomK5jtXFq4IJa7Az4Hzoy+rYux343NkH9Dq+nzIdejVrjw==", - "dev": true, - "requires": { - "@types/node": "*" - } - }, "@typescript-eslint/eslint-plugin": { "version": "8.71.2", "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.71.2.tgz", @@ -19136,11 +19094,6 @@ "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", "dev": true }, - "sax": { - "version": "1.2.4", - "resolved": "https://registry.npmjs.org/sax/-/sax-1.2.4.tgz", - "integrity": "sha512-NqVDv9TpANUjFm0N8uM5GxL36UgKi9/atZw+x7YFnQ8ckwFGKrl4xX4yWtrey3UJm5nP1kUbnYgLopqWNSRhWw==" - }, "saxes": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz", @@ -20270,19 +20223,6 @@ "integrity": "sha512-GCPAHLvrIH13+c0SuacwvRYj2SxJXQ4kaVTT5xgL3kPrz56XxkF21IGhjSE1+W0aw7gpBWRGXLCPnPby6lSpmQ==", "dev": true }, - "xml": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/xml/-/xml-1.0.1.tgz", - "integrity": "sha1-eLpyAgApxbyHuKgaPPzXS0ovweU=" - }, - "xml-js": { - "version": "1.6.11", - "resolved": "https://registry.npmjs.org/xml-js/-/xml-js-1.6.11.tgz", - "integrity": "sha512-7rVi2KMfwfWFl+GpPg6m80IVMWXLRjO+PxTq7V2CDhoGak0wzYzFgUY2m4XJ47OGdXd8eLE8EmwfAmdjw7lC1g==", - "requires": { - "sax": "^1.2.4" - } - }, "xml-name-validator": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz", diff --git a/package.json b/package.json index 29807a90c8..a459a45549 100644 --- a/package.json +++ b/package.json @@ -145,9 +145,7 @@ "@types/node": "^26.6.2", "hash.js": "^1.1.7", "jszip": "^3.10.1", - "nanoid": "^6.0.1", - "xml": "^1.0.1", - "xml-js": "^1.6.8" + "nanoid": "^6.0.1" }, "author": "Dolan Miu", "license": "MIT", @@ -160,7 +158,6 @@ "@microsoft/api-extractor": "^7.58.7", "@types/pngjs": "^6.0.5", "@types/unzipper": "^0.10.4", - "@types/xml": "^1.0.8", "@typescript-eslint/eslint-plugin": "^8.8.1", "@typescript-eslint/parser": "^8.8.1", "@typescript/native": "npm:typescript@7.0.2", diff --git a/scripts/check-api.ts b/scripts/check-api.ts index 57d734fb50..321c5ca4e1 100644 --- a/scripts/check-api.ts +++ b/scripts/check-api.ts @@ -42,7 +42,7 @@ type PackageJson = { }; const ROOT = resolve(import.meta.dirname, ".."); -// Inside the repository, so the declarations' imports of jszip, xml-js and Node's types resolve +// Inside the repository, so the declarations' imports of jszip and Node's types resolve const WORK = join(ROOT, "build", "api-check"); const readPackage = (directory: string): PackageJson => JSON.parse(readFileSync(join(directory, "package.json"), "utf8")) as PackageJson; diff --git a/scripts/compare-layout.ts b/scripts/compare-layout.ts index ecd4bf9604..f51361ddc0 100644 --- a/scripts/compare-layout.ts +++ b/scripts/compare-layout.ts @@ -26,7 +26,7 @@ import { existsSync, readFileSync, readdirSync } from "node:fs"; import { join } from "node:path"; import JSZip from "jszip"; -import { type Element, xml2js } from "xml-js"; +import { type XmlElement as Element, parseXml } from "../src/util/xml"; import { estimatePageNumbers } from "../src/layout/estimate-page-numbers"; @@ -55,7 +55,7 @@ const paragraphsIn = (element: Element): readonly Element[] => /** Each entry of the document's tables of contents: its heading's text, and the page number written for it */ const entriesOf = async (path: string): Promise => { const zip = await JSZip.loadAsync(readFileSync(path)); - const document = xml2js(await zip.file("word/document.xml")!.async("string"), { compact: false }) as Element; + const document = parseXml(await zip.file("word/document.xml")!.async("string")); return paragraphsIn(document) .filter((paragraph) => JSON.stringify(paragraph).includes("PAGEREF _Toc")) .map((paragraph) => { @@ -96,7 +96,7 @@ const pageCountsOf = async (path: string): Promise => { } }; for (const part of parts) { - read(xml2js(await zip.file(part)!.async("string"), { compact: false }) as Element); + read(parseXml(await zip.file(part)!.async("string"))); } return results; }; @@ -113,13 +113,7 @@ const partsOf = async (path: string): Promise> => { const paths = Object.keys(zip.files).filter((file) => file.endsWith(".xml") || file.endsWith(".rels")); return new Map( await Promise.all( - paths.map( - async (file) => - [ - file, - xml2js(await zip.file(file)!.async("string"), { compact: false, captureSpacesBetweenElements: true }) as Element, - ] as const, - ), + paths.map(async (file) => [file, parseXml(await zip.file(file)!.async("string"), { keepWhitespaceText: true })] as const), ), ); }; diff --git a/scripts/generate-preset-shape-geometry.ts b/scripts/generate-preset-shape-geometry.ts index e04ed9d98f..dcd2507a78 100644 --- a/scripts/generate-preset-shape-geometry.ts +++ b/scripts/generate-preset-shape-geometry.ts @@ -15,7 +15,7 @@ import { execSync } from "node:child_process"; import { readFileSync, writeFileSync } from "node:fs"; -import { type Element, xml2js } from "xml-js"; +import { type XmlElement as Element, parseXml } from "../src/util/xml"; import { PRESET_SHAPE_OOXML_NAMES } from "../src/shapes/preset-shape/preset-shape-type"; @@ -51,7 +51,7 @@ const guides = (shape: Element, list: string): readonly (readonly [string, strin children(child(shape, list), "gd").map((guide) => [attribute(guide, "name"), attribute(guide, "fmla")] as const); const main = async (): Promise => { - const document = xml2js(await loadDefinitions(process.argv[2]), { compact: false }) as Element; + const document = parseXml(await loadDefinitions(process.argv[2])); const root = children(document)[0]; const shapes = new Map(children(root).map((shape) => [shape.name!, shape])); const lines: string[] = []; diff --git a/scripts/layout-probes/demo-lines.ts b/scripts/layout-probes/demo-lines.ts index 526024c662..0d4f70d595 100644 --- a/scripts/layout-probes/demo-lines.ts +++ b/scripts/layout-probes/demo-lines.ts @@ -22,7 +22,7 @@ import { readFileSync } from "node:fs"; import JSZip from "jszip"; -import { type Element, xml2js } from "xml-js"; +import { type XmlElement as Element, parseXml } from "../../src/util/xml"; import type { BlockLayout } from "../../src/layout"; import { layOutPasses } from "../../src/layout/layout-passes"; @@ -65,13 +65,7 @@ const parts = new Map( await Promise.all( Object.keys(zip.files) .filter((file) => file.endsWith(".xml") || file.endsWith(".rels")) - .map( - async (file) => - [ - file, - xml2js(await zip.file(file)!.async("string"), { compact: false, captureSpacesBetweenElements: true }) as Element, - ] as const, - ), + .map(async (file) => [file, parseXml(await zip.file(file)!.async("string"), { keepWhitespaceText: true })] as const), ), ); diff --git a/scripts/layout-probes/guess-lines.ts b/scripts/layout-probes/guess-lines.ts index e364fb11cb..bb041ea895 100644 --- a/scripts/layout-probes/guess-lines.ts +++ b/scripts/layout-probes/guess-lines.ts @@ -14,7 +14,7 @@ import { readFileSync } from "node:fs"; import JSZip from "jszip"; -import { type Element, xml2js } from "xml-js"; +import { type XmlElement as Element, parseXml } from "../../src/util/xml"; import type { BlockLayout } from "../../src/layout"; import { layOutPasses } from "../../src/layout/layout-passes"; @@ -60,7 +60,7 @@ for (const [path, file] of Object.entries(zip.files)) { continue; } if (path.endsWith(".xml") || path.endsWith(".rels")) { - parts.set(path, xml2js(await file.async("string"), { compact: false, captureSpacesBetweenElements: true }) as Element); + parts.set(path, parseXml(await file.async("string"), { keepWhitespaceText: true })); } else { binaryParts.set(path, await file.async("uint8array")); } diff --git a/scripts/layout-probes/stops2/layout-stops.ts b/scripts/layout-probes/stops2/layout-stops.ts index 288d78dfbf..9663c8b7f2 100644 --- a/scripts/layout-probes/stops2/layout-stops.ts +++ b/scripts/layout-probes/stops2/layout-stops.ts @@ -10,7 +10,7 @@ */ import { readFileSync } from "node:fs"; -import type { Element } from "xml-js"; +import type { XmlElement as Element } from "../../../src/util/xml"; import { patchDocument } from "../../../src/index"; import { layOutPasses } from "../../../src/layout/layout-passes"; diff --git a/src/charts/chart-data-patch.spec.ts b/src/charts/chart-data-patch.spec.ts index a36a98e5a2..44730231bb 100644 --- a/src/charts/chart-data-patch.spec.ts +++ b/src/charts/chart-data-patch.spec.ts @@ -1,8 +1,8 @@ /* eslint-disable @typescript-eslint/naming-convention -- The keys of objects here are paths of parts in a package */ import JSZip from "jszip"; import { describe, expect, it } from "vitest"; -import { type Element, xml2js } from "xml-js"; +import { type XmlElement as Element, parseXml } from "@util/xml"; import { Document, DrawingPatch, @@ -41,7 +41,7 @@ import { attributeOf, childOf, childrenOf, descendantsOf, elementsOf, textOf, va // --------------------------------------------------------------------------------------------------------------------- // Parsed with the spaces in text, such as a category that is a space -const parse = (text: string): Element => xml2js(text, { compact: false, captureSpacesBetweenElements: true }) as Element; +const parse = (text: string): Element => parseXml(text, { keepWhitespaceText: true }); const readText = async (zip: JSZip, path: string): Promise => (await zip.file(path)?.async("text")) ?? ""; diff --git a/src/charts/chart-data-patch.ts b/src/charts/chart-data-patch.ts index 9633eb3beb..6ff4fabe16 100644 --- a/src/charts/chart-data-patch.ts +++ b/src/charts/chart-data-patch.ts @@ -4,9 +4,8 @@ * @module */ // cspell:ignore descr -import type { Element } from "xml-js"; -import { DrawingPatch, type TemplateDrawing, type TemplatePackage } from "docx"; +import { DrawingPatch, type XmlElement as Element, type TemplateDrawing, type TemplatePackage } from "docx"; import { leafCategoriesOf } from "./chart-categories"; import { TYPE_NAMES, checkChartOptions } from "./chart-checks"; diff --git a/src/charts/chart-elements.spec.ts b/src/charts/chart-elements.spec.ts index 2973c55c32..b7a200f579 100644 --- a/src/charts/chart-elements.spec.ts +++ b/src/charts/chart-elements.spec.ts @@ -1,28 +1,30 @@ import { describe, expect, it } from "vitest"; -import xml from "xml"; import { Formatter } from "@export/formatter"; +import { stringifyXmlable } from "@util/xml"; import { createElement, createText, createValue } from "./chart-elements"; describe("chart elements", () => { it("should write an element's attributes in order, leaving out undefined ones, and its children", () => { - expect(xml(new Formatter().format(createElement("c:numFmt", { formatCode: "0%", skipped: undefined, sourceLinked: 1 })))).to.equal( - '', - ); - expect(xml(new Formatter().format(createElement("c:layout")))).to.equal(""); - expect(xml(new Formatter().format(createElement("c:scaling", {}, [createValue("c:orientation", "minMax")])))).to.equal( + expect( + stringifyXmlable(new Formatter().format(createElement("c:numFmt", { formatCode: "0%", skipped: undefined, sourceLinked: 1 }))), + ).to.equal(''); + expect(stringifyXmlable(new Formatter().format(createElement("c:layout")))).to.equal(""); + expect(stringifyXmlable(new Formatter().format(createElement("c:scaling", {}, [createValue("c:orientation", "minMax")])))).to.equal( '', ); }); it("should write a boolean value as 1 or 0", () => { - expect(xml(new Formatter().format(createValue("c:varyColors", true)))).to.equal(''); - expect(xml(new Formatter().format(createValue("c:varyColors", false)))).to.equal(''); - expect(xml(new Formatter().format(createValue("c:gapWidth", 219)))).to.equal(''); + expect(stringifyXmlable(new Formatter().format(createValue("c:varyColors", true)))).to.equal(''); + expect(stringifyXmlable(new Formatter().format(createValue("c:varyColors", false)))).to.equal(''); + expect(stringifyXmlable(new Formatter().format(createValue("c:gapWidth", 219)))).to.equal(''); }); it("should write text, escaped", () => { - expect(xml(new Formatter().format(createText("c:v", "Sales & ")))).to.equal("Sales & <costs>"); + expect(stringifyXmlable(new Formatter().format(createText("c:v", "Sales & ")))).to.equal( + "Sales & <costs>", + ); }); }); diff --git a/src/charts/chart-schema.spec.ts b/src/charts/chart-schema.spec.ts index d9d400b1e9..c70769ed75 100644 --- a/src/charts/chart-schema.spec.ts +++ b/src/charts/chart-schema.spec.ts @@ -1,10 +1,9 @@ import { describe, expect, it } from "vitest"; -import xml from "xml"; -import { type Element, xml2js } from "xml-js"; import { Formatter } from "@export/formatter"; import { File } from "@file/file"; import { Relationships } from "@file/relationships"; +import { type XmlElement as Element, parseXml, stringifyXmlable } from "@util/xml"; import { type IContext, PackagePart } from "docx"; import { createChartData } from "./chart-data"; @@ -15,7 +14,7 @@ import chartSchema from "../../ooxml-schemas/ISO-IEC29500-4_2016/dml-chart.xsd?r // The chart schema, which every chart part's elements are checked against: each element's children are ones its type // has, in its type's order. The Open XML SDK validator checks this too, for the demos only -const schema = xml2js(chartSchema as string) as Element; +const schema = parseXml(chartSchema as string); const definitions = new Map( schema @@ -103,14 +102,14 @@ const workbook = new PackagePart({ const chartSpaceOf = (options: ChartRunOptions): Element => { const component = createChartSpace(options, createChartData(options), workbook); - const written = xml( + const written = stringifyXmlable( new Formatter().format(component, { file: new File({ sections: [] }), viewWrapper: { View: component, Relationships: new Relationships() }, stack: [], } as IContext), ); - return (xml2js(written) as Element).elements![0]; + return parseXml(written).elements![0]; }; const problemsOf = (options: ChartRunOptions): readonly string[] => problemsIn(chartSpaceOf(options), "CT_ChartSpace", "c:chartSpace"); diff --git a/src/charts/chart-space.spec.ts b/src/charts/chart-space.spec.ts index dc8d785185..bde074ccd0 100644 --- a/src/charts/chart-space.spec.ts +++ b/src/charts/chart-space.spec.ts @@ -1,10 +1,9 @@ import { describe, expect, it } from "vitest"; -import xml from "xml"; -import { type Element, xml2js } from "xml-js"; import { Formatter } from "@export/formatter"; import { File } from "@file/file"; import { Relationships } from "@file/relationships"; +import { type XmlElement as Element, parseXml, stringifyXmlable } from "@util/xml"; import { type IContext, PackagePart, type XmlComponent } from "docx"; import { createChartData } from "./chart-data"; @@ -21,7 +20,7 @@ const workbook = new PackagePart({ }); const format = (component: XmlComponent, relationships = new Relationships()): string => - xml( + stringifyXmlable( new Formatter().format(component, { file: new File({ sections: [] }), viewWrapper: { View: component, Relationships: relationships }, @@ -31,7 +30,7 @@ const format = (component: XmlComponent, relationships = new Relationships()): s const chartSpace = (options: Partial = {}): Element => { const full = { type: "column", categories: ["A"], series: [{ name: "S", values: [1] }], ...options } as ChartRunOptions; - return (xml2js(format(createChartSpace(full, createChartData(full), workbook))) as Element).elements![0]; + return parseXml(format(createChartSpace(full, createChartData(full), workbook))).elements![0]; }; const names = (element: Element): readonly string[] => (element.elements ?? []).map(({ name }) => name!); const child = (element: Element, name: string): Element => element.elements!.find((one) => one.name === name)!; diff --git a/src/charts/chart-style.spec.ts b/src/charts/chart-style.spec.ts index 38da7680d6..3b54a7dbe9 100644 --- a/src/charts/chart-style.spec.ts +++ b/src/charts/chart-style.spec.ts @@ -1,8 +1,8 @@ // cspell:ignore cmpd prst import { describe, expect, it } from "vitest"; -import xml from "xml"; import { Formatter } from "@export/formatter"; +import { stringifyXmlable } from "@util/xml"; import type { XmlComponent } from "docx"; import { @@ -23,7 +23,7 @@ import { createTextProperties, } from "./chart-style"; -const toXml = (component: XmlComponent): string => xml(new Formatter().format(component)); +const toXml = (component: XmlComponent): string => stringifyXmlable(new Formatter().format(component)); const ACCENT1 = ''; const FILL = `${ACCENT1}`; diff --git a/src/charts/chart-text.spec.ts b/src/charts/chart-text.spec.ts index e7f9648436..06caf05803 100644 --- a/src/charts/chart-text.spec.ts +++ b/src/charts/chart-text.spec.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from "vitest"; -import xml from "xml"; import { Formatter } from "@export/formatter"; +import { stringifyXmlable } from "@util/xml"; import { createAxisTitle, createChartTitle, fontOf, titleOf } from "./chart-text"; @@ -13,7 +13,7 @@ const BODY = (rotation: number): string => describe("createChartTitle", () => { it("should write the title as Office does: 14 point text in the theme's body font, not over the plot", () => { const properties = `${TEXT_COLOR}${FONTS}`; - expect(xml(new Formatter().format(createChartTitle("Sales")))).to.equal( + expect(stringifyXmlable(new Formatter().format(createChartTitle("Sales")))).to.equal( "" + `${BODY(0)}${properties}Sales` + '' + @@ -24,30 +24,30 @@ describe("createChartTitle", () => { }); it("should write each line of the title as a paragraph", () => { - const title = xml(new Formatter().format(createChartTitle("Sales\nby month"))); + const title = stringifyXmlable(new Formatter().format(createChartTitle("Sales\nby month"))); expect(title.match(/[^<]*<\/a:t>/g)).to.deep.equal(["Sales", "by month"]); }); }); describe("createAxisTitle", () => { it("should write 10 point text, reading from bottom to top on a vertical axis", () => { - const vertical = xml(new Formatter().format(createAxisTitle("Units", true))); + const vertical = stringifyXmlable(new Formatter().format(createAxisTitle("Units", true))); expect(vertical).to.contain(BODY(-5400000)); expect(vertical).to.contain(''); expect(vertical).to.contain("Units"); - expect(xml(new Formatter().format(createAxisTitle("Month", false)))).to.contain(BODY(0)); + expect(stringifyXmlable(new Formatter().format(createAxisTitle("Month", false)))).to.contain(BODY(0)); }); }); describe("titles with fonts", () => { it("should write a title's own font over the chart's", () => { - const title = xml( + const title = stringifyXmlable( new Formatter().format(createChartTitle({ text: "Sales", font: { size: 18, bold: true } }, { name: "Arial", bold: false })), ); expect(title).to.contain(''); - expect(xml(new Formatter().format(createAxisTitle({ text: "Units", font: { italics: true } }, true)))).to.contain( + expect(stringifyXmlable(new Formatter().format(createAxisTitle({ text: "Units", font: { italics: true } }, true)))).to.contain( 'sz="1000" b="0" i="1"', ); }); diff --git a/src/charts/index.spec.ts b/src/charts/index.spec.ts index e786e3bceb..3840f0751f 100644 --- a/src/charts/index.spec.ts +++ b/src/charts/index.spec.ts @@ -1,7 +1,7 @@ import JSZip from "jszip"; import { describe, expect, it } from "vitest"; -import { type Element, xml2js } from "xml-js"; +import { type XmlElement as Element, parseXml } from "@util/xml"; import { Document, Footer, FootnoteReferenceRun, Header, Packer, Paragraph, Run, Table, TableCell, TableRow, TextRun } from "docx"; import { ChartRun, type ChartRunOptions } from "."; @@ -95,7 +95,7 @@ const paragraphWith = (options: ChartRunOptions): Paragraph => new Paragraph({ c const read = async (zip: JSZip, path: string): Promise => (await zip.file(path)?.async("text")) ?? ""; -const parse = (text: string): Element => xml2js(text) as Element; +const parse = (text: string): Element => parseXml(text); const descendants = (element: Element, name: string): readonly Element[] => (element.elements ?? []).flatMap((child) => [...(child.name === name ? [child] : []), ...descendants(child, name)]); diff --git a/src/charts/plot-area/area-chart.spec.ts b/src/charts/plot-area/area-chart.spec.ts index 913b2180aa..6efcec665e 100644 --- a/src/charts/plot-area/area-chart.spec.ts +++ b/src/charts/plot-area/area-chart.spec.ts @@ -1,15 +1,14 @@ import { describe, expect, it } from "vitest"; -import xml from "xml"; -import { type Element, xml2js } from "xml-js"; import { Formatter } from "@export/formatter"; +import { type XmlElement as Element, parseXml, stringifyXmlable } from "@util/xml"; import type { XmlComponent } from "docx"; import { createChartData } from "../chart-data"; import type { AreaChartOptions } from "../chart-options"; import { createCategoryCharts } from "./category-chart"; -const parse = (component: XmlComponent): Element => (xml2js(xml(new Formatter().format(component))) as Element).elements![0]; +const parse = (component: XmlComponent): Element => parseXml(stringifyXmlable(new Formatter().format(component))).elements![0]; const names = (element: Element): readonly string[] => (element.elements ?? []).map(({ name }) => name!); const children = (element: Element, name: string): readonly Element[] => element.elements!.filter((one) => one.name === name); const value = (element: Element, name: string): unknown => children(element, name)[0]?.attributes?.val; diff --git a/src/charts/plot-area/axes.spec.ts b/src/charts/plot-area/axes.spec.ts index fbc74f6388..06d5167f75 100644 --- a/src/charts/plot-area/axes.spec.ts +++ b/src/charts/plot-area/axes.spec.ts @@ -1,14 +1,13 @@ // cspell:ignore cmpd import { describe, expect, it } from "vitest"; -import xml from "xml"; -import { type Element, xml2js } from "xml-js"; import { Formatter } from "@export/formatter"; +import { type XmlElement as Element, parseXml, stringifyXmlable } from "@util/xml"; import type { XmlComponent } from "docx"; import { PRIMARY_AXES, createCategoryAxis, createPointAxes, createValueAxis } from "./axes"; -const parse = (component: XmlComponent): Element => (xml2js(xml(new Formatter().format(component))) as Element).elements![0]; +const parse = (component: XmlComponent): Element => parseXml(stringifyXmlable(new Formatter().format(component))).elements![0]; const names = (element: Element): readonly string[] => (element.elements ?? []).map(({ name }) => name!); const child = (element: Element, name: string): Element => element.elements!.find((one) => one.name === name)!; const value = (element: Element, name: string): unknown => child(element, name)?.attributes?.val; @@ -63,7 +62,7 @@ describe("createCategoryAxis", () => { ]); expect(value(axis, "c:delete")).to.equal("1"); // The title of an axis on the left reads from bottom to top - expect(xml(new Formatter().format(createCategoryAxis({ ...CATEGORY, position: "l" }, { title: "Month" })))).to.contain( + expect(stringifyXmlable(new Formatter().format(createCategoryAxis({ ...CATEGORY, position: "l" }, { title: "Month" })))).to.contain( 'rot="-5400000"', ); }); @@ -90,7 +89,7 @@ describe("createCategoryAxis", () => { }); it("should turn the labels as asked, in 60,000ths of a degree, in the font given over the chart's", () => { - const written = xml( + const written = stringifyXmlable( new Formatter().format( createCategoryAxis( { ...CATEGORY, font: { name: "Arial", bold: true } }, @@ -103,7 +102,7 @@ describe("createCategoryAxis", () => { expect(written).to.contain(''); // Office's automatic rotation otherwise - expect(xml(new Formatter().format(createCategoryAxis(CATEGORY)))).to.contain(' { @@ -214,10 +213,12 @@ describe("createValueAxis", () => { expect(value(units, "c:builtInUnit")).to.equal("thousands"); expect(names(child(units, "c:dispUnitsLbl"))).to.deep.equal(["c:layout", "c:spPr", "c:txPr"]); // Upright beside a vertical axis, and level beside a horizontal one - expect(xml(new Formatter().format(createValueAxis(VALUE, { displayUnits: "millions" })))).to.contain( + expect(stringifyXmlable(new Formatter().format(createValueAxis(VALUE, { displayUnits: "millions" })))).to.contain( ' { }); it("should give a radar chart's value axis a line and tick marks", () => { - const written = xml(new Formatter().format(createValueAxis({ ...VALUE, radar: true }))); + const written = stringifyXmlable(new Formatter().format(createValueAxis({ ...VALUE, radar: true }))); expect(written).to.contain(''); expect(written).to.contain( @@ -240,7 +241,7 @@ describe("createValueAxis", () => { const axis = parse(createValueAxis({ ...VALUE, crossBetween: "midCat", scatter: true })); expect(value(axis, "c:crossBetween")).to.equal("midCat"); - expect(xml(new Formatter().format(createValueAxis({ ...VALUE, crossBetween: "midCat", scatter: true })))).to.contain( + expect(stringifyXmlable(new Formatter().format(createValueAxis({ ...VALUE, crossBetween: "midCat", scatter: true })))).to.contain( '', ); }); diff --git a/src/charts/plot-area/bar-chart.spec.ts b/src/charts/plot-area/bar-chart.spec.ts index b3f60b7a50..5d4ae17bfe 100644 --- a/src/charts/plot-area/bar-chart.spec.ts +++ b/src/charts/plot-area/bar-chart.spec.ts @@ -1,15 +1,14 @@ import { describe, expect, it } from "vitest"; -import xml from "xml"; -import { type Element, xml2js } from "xml-js"; import { Formatter } from "@export/formatter"; +import { type XmlElement as Element, parseXml, stringifyXmlable } from "@util/xml"; import type { XmlComponent } from "docx"; import { createChartData } from "../chart-data"; import type { BarChartOptions, ColumnChartOptions } from "../chart-options"; import { createCategoryCharts } from "./category-chart"; -const parse = (component: XmlComponent): Element => (xml2js(xml(new Formatter().format(component))) as Element).elements![0]; +const parse = (component: XmlComponent): Element => parseXml(stringifyXmlable(new Formatter().format(component))).elements![0]; const names = (element: Element): readonly string[] => (element.elements ?? []).map(({ name }) => name!); const children = (element: Element, name: string): readonly Element[] => element.elements!.filter((one) => one.name === name); const value = (element: Element, name: string): unknown => children(element, name)[0]?.attributes?.val; @@ -67,7 +66,7 @@ describe("createBarChart", () => { ]); expect(value(series[0], "c:invertIfNegative")).to.equal("0"); expect( - xml( + stringifyXmlable( new Formatter().format( createCategoryCharts( { diff --git a/src/charts/plot-area/bubble-chart.spec.ts b/src/charts/plot-area/bubble-chart.spec.ts index 1f7e28f29a..62848c2b45 100644 --- a/src/charts/plot-area/bubble-chart.spec.ts +++ b/src/charts/plot-area/bubble-chart.spec.ts @@ -1,15 +1,14 @@ import { describe, expect, it } from "vitest"; -import xml from "xml"; -import { type Element, xml2js } from "xml-js"; import { Formatter } from "@export/formatter"; +import { type XmlElement as Element, parseXml, stringifyXmlable } from "@util/xml"; import type { XmlComponent } from "docx"; import { createChartData } from "../chart-data"; import type { BubbleChartOptions } from "../chart-options"; import { createBubbleChart } from "./bubble-chart"; -const parse = (component: XmlComponent): Element => (xml2js(xml(new Formatter().format(component))) as Element).elements![0]; +const parse = (component: XmlComponent): Element => parseXml(stringifyXmlable(new Formatter().format(component))).elements![0]; const names = (element: Element): readonly string[] => (element.elements ?? []).map(({ name }) => name!); const children = (element: Element, name: string): readonly Element[] => element.elements!.filter((one) => one.name === name); const value = (element: Element, name: string): unknown => children(element, name)[0]?.attributes?.val; @@ -69,14 +68,14 @@ describe("createBubbleChart", () => { "c:bubble3D", ]); expect(value(series, "c:bubble3D")).to.equal("0"); - const sizes = xml(new Formatter().format(create().group)); + const sizes = stringifyXmlable(new Formatter().format(create().group)); expect(sizes).to.contain( 'Sheet1!$C$2:$C$3General1020', ); }); it("should fill bubbles with the series' colour at 75% opacity, without a line", () => { - const written = xml(new Formatter().format(create().group)); + const written = stringifyXmlable(new Formatter().format(create().group)); expect(written).to.contain( '', diff --git a/src/charts/plot-area/category-chart.spec.ts b/src/charts/plot-area/category-chart.spec.ts index 54c79c2875..2fbfe18a1f 100644 --- a/src/charts/plot-area/category-chart.spec.ts +++ b/src/charts/plot-area/category-chart.spec.ts @@ -1,8 +1,7 @@ import { describe, expect, it } from "vitest"; -import xml from "xml"; -import { type Element, xml2js } from "xml-js"; import { Formatter } from "@export/formatter"; +import { type XmlElement as Element, parseXml, stringifyXmlable } from "@util/xml"; import type { XmlComponent } from "docx"; import { createChartData } from "../chart-data"; @@ -11,7 +10,7 @@ import { createCategoryCharts } from "./category-chart"; type Options = ColumnChartOptions | BarChartOptions | LineChartOptions | AreaChartOptions; -const parse = (component: XmlComponent): Element => (xml2js(xml(new Formatter().format(component))) as Element).elements![0]; +const parse = (component: XmlComponent): Element => parseXml(stringifyXmlable(new Formatter().format(component))).elements![0]; const names = (element: Element): readonly string[] => (element.elements ?? []).map(({ name }) => name!); const children = (element: Element, name: string): readonly Element[] => element.elements!.filter((one) => one.name === name); const value = (element: Element, name: string): unknown => children(element, name)[0]?.attributes?.val; @@ -223,7 +222,7 @@ describe("createCategoryCharts", () => { it("should write the chart's font on its axes", () => { const full: ColumnChartOptions = { type: "column", categories: ["A"], series: [{ name: "A", values: [1] }] }; const written = createCategoryCharts(full, createChartData(full), { name: "Arial" }) - .axes.map((axis) => xml(new Formatter().format(axis))) + .axes.map((axis) => stringifyXmlable(new Formatter().format(axis))) .join(""); expect(written.match(//g)).to.have.length(2); @@ -238,7 +237,7 @@ describe("createCategoryCharts' series", () => { const point = children(series, "c:dPt")[0]; expect(names(point)).to.deep.equal(["c:idx", "c:invertIfNegative", "c:bubble3D", "c:spPr"]); expect(value(point, "c:idx")).to.equal("1"); - expect(xml(new Formatter().format(createCategoryCharts(...colored()).groups[0]))).to.contain( + expect(stringifyXmlable(new Formatter().format(createCategoryCharts(...colored()).groups[0]))).to.contain( '', ); }); @@ -315,7 +314,7 @@ describe("createCategoryCharts' series", () => { expect(value(marker, "c:symbol")).to.equal("square"); expect(value(marker, "c:size")).to.equal("8"); expect(value(series, "c:smooth")).to.equal("1"); - expect(xml(new Formatter().format(createCategoryCharts(...dashed()).groups[0]))).to.contain( + expect(stringifyXmlable(new Formatter().format(createCategoryCharts(...dashed()).groups[0]))).to.contain( '', ); }); diff --git a/src/charts/plot-area/data-labels.spec.ts b/src/charts/plot-area/data-labels.spec.ts index 1c27d1f18d..4b19d14ceb 100644 --- a/src/charts/plot-area/data-labels.spec.ts +++ b/src/charts/plot-area/data-labels.spec.ts @@ -1,14 +1,13 @@ import { describe, expect, it } from "vitest"; -import xml from "xml"; -import { type Element, xml2js } from "xml-js"; import { Formatter } from "@export/formatter"; +import { type XmlElement as Element, parseXml, stringifyXmlable } from "@util/xml"; import type { XmlComponent } from "docx"; import type { ChartDataLabelPosition } from "../chart-options"; import { type LabelledShape, createGroupDataLabels, createSeriesDataLabels } from "./data-labels"; -const parse = (component: XmlComponent): Element => (xml2js(xml(new Formatter().format(component))) as Element).elements![0]; +const parse = (component: XmlComponent): Element => parseXml(stringifyXmlable(new Formatter().format(component))).elements![0]; const names = (element: Element): readonly string[] => (element.elements ?? []).map(({ name }) => name!); const values = (element: Element): Readonly> => Object.fromEntries( @@ -116,7 +115,7 @@ describe("createSeriesDataLabels' formats and fonts", () => { }); it("should write the labels' font over the chart's, over Office's 9 point grey", () => { - const written = xml( + const written = stringifyXmlable( new Formatter().format( createSeriesDataLabels( { value: true, font: { color: "FFFFFF", bold: true } }, @@ -207,7 +206,7 @@ describe("createSeriesDataLabels' labels of single points", () => { "c:showBubbleSize", ]); expect(values(point)).to.include({ "c:dLblPos": "ctr", "c:showVal": "1" }); - const written = xml( + const written = stringifyXmlable( new Formatter().format(createSeriesDataLabels(undefined, { ...BARS, pointLabels: [{ text: "Record\nhigh" }] })[0]), ); expect(written).to.contain("Record"); @@ -260,7 +259,7 @@ describe("createSeriesDataLabels' labels of single points", () => { // Its own flags replace the series', and its own number format and font replace theirs expect(values(own)).to.include({ "c:dLblPos": "inEnd", "c:showVal": "0", "c:showCatName": "1" }); expect(own.elements!.find(({ name }) => name === "c:numFmt")!.attributes!.formatCode).to.equal("0.0"); - const written = xml( + const written = stringifyXmlable( new Formatter().format(createSeriesDataLabels(series, { ...BARS, pointLabels: [{ font: { bold: true } }] })[0]), ); expect(written).to.contain(' xml(new Formatter().format(component)); -const parse = (component: XmlComponent): Element => (xml2js(write(component)) as Element).elements![0]; +const write = (component: XmlComponent): string => stringifyXmlable(new Formatter().format(component)); +const parse = (component: XmlComponent): Element => parseXml(write(component)).elements![0]; const names = (element: Element): readonly string[] => (element.elements ?? []).map(({ name }) => name!); const value = (element: Element, name: string): unknown => element.elements!.find((one) => one.name === name)?.attributes?.val; diff --git a/src/charts/plot-area/line-chart.spec.ts b/src/charts/plot-area/line-chart.spec.ts index 4838073c2f..2cbc2f9e54 100644 --- a/src/charts/plot-area/line-chart.spec.ts +++ b/src/charts/plot-area/line-chart.spec.ts @@ -1,15 +1,14 @@ import { describe, expect, it } from "vitest"; -import xml from "xml"; -import { type Element, xml2js } from "xml-js"; import { Formatter } from "@export/formatter"; +import { type XmlElement as Element, parseXml, stringifyXmlable } from "@util/xml"; import type { XmlComponent } from "docx"; import { createChartData } from "../chart-data"; import type { LineChartOptions } from "../chart-options"; import { createCategoryCharts } from "./category-chart"; -const parse = (component: XmlComponent): Element => (xml2js(xml(new Formatter().format(component))) as Element).elements![0]; +const parse = (component: XmlComponent): Element => parseXml(stringifyXmlable(new Formatter().format(component))).elements![0]; const names = (element: Element): readonly string[] => (element.elements ?? []).map(({ name }) => name!); const children = (element: Element, name: string): readonly Element[] => element.elements!.filter((one) => one.name === name); const value = (element: Element, name: string): unknown => children(element, name)[0]?.attributes?.val; @@ -40,7 +39,7 @@ describe("createLineChart", () => { expect(value(children(series, "c:marker")[0], "c:symbol")).to.equal("none"); expect(value(series, "c:smooth")).to.equal("0"); expect( - xml( + stringifyXmlable( new Formatter().format( createCategoryCharts( { type: "line", categories: ["A"], series: [{ name: "A", values: [1] }] }, @@ -57,7 +56,7 @@ describe("createLineChart", () => { expect(names(group)).to.deep.equal(["c:grouping", "c:varyColors", "c:ser", "c:dLbls", "c:marker", "c:axId", "c:axId"]); expect(value(group, "c:marker")).to.equal("1"); - const marker = xml( + const marker = stringifyXmlable( new Formatter().format( createCategoryCharts( { type: "line", markers: true, categories: ["A"], series: [{ name: "Red", values: [1], color: "FF0000" }] }, diff --git a/src/charts/plot-area/pie-chart.spec.ts b/src/charts/plot-area/pie-chart.spec.ts index 9cab8dfc19..1f9a2c22ad 100644 --- a/src/charts/plot-area/pie-chart.spec.ts +++ b/src/charts/plot-area/pie-chart.spec.ts @@ -1,16 +1,15 @@ // cspell:ignore cmpd cust import { describe, expect, it } from "vitest"; -import xml from "xml"; -import { type Element, xml2js } from "xml-js"; import { Formatter } from "@export/formatter"; +import { type XmlElement as Element, parseXml, stringifyXmlable } from "@util/xml"; import type { XmlComponent } from "docx"; import { createChartData } from "../chart-data"; import type { BarOfPieChartOptions, DoughnutChartOptions, PieChartOptions, PieOfPieChartOptions } from "../chart-options"; import { createPieChart } from "./pie-chart"; -const parse = (component: XmlComponent): Element => (xml2js(xml(new Formatter().format(component))) as Element).elements![0]; +const parse = (component: XmlComponent): Element => parseXml(stringifyXmlable(new Formatter().format(component))).elements![0]; const names = (element: Element): readonly string[] => (element.elements ?? []).map(({ name }) => name!); const children = (element: Element, name: string): readonly Element[] => element.elements!.filter((one) => one.name === name); const value = (element: Element, name: string): unknown => children(element, name)[0]?.attributes?.val; @@ -219,7 +218,9 @@ describe("createPieChart for a pie of pie or bar of pie chart", () => { const element = split({ secondPlotSize: 150.4, gapWidth: 250.6 }); expect([value(element, "c:secondPieSize"), value(element, "c:gapWidth")]).to.deep.equal(["150", "251"]); const written = (options: Partial): string => - xml(new Formatter().format(create({ type: "pieOfPie", categories, series: [{ name: "S", values: [1] }], ...options }).group)); + stringifyXmlable( + new Formatter().format(create({ type: "pieOfPie", categories, series: [{ name: "S", values: [1] }], ...options }).group), + ); expect(written({})).to.contain( '', ); diff --git a/src/charts/plot-area/plot-area.spec.ts b/src/charts/plot-area/plot-area.spec.ts index 844899e590..826698b285 100644 --- a/src/charts/plot-area/plot-area.spec.ts +++ b/src/charts/plot-area/plot-area.spec.ts @@ -1,16 +1,15 @@ // cspell:ignore cmpd import { describe, expect, it } from "vitest"; -import xml from "xml"; -import { type Element, xml2js } from "xml-js"; import { Formatter } from "@export/formatter"; +import { type XmlElement as Element, parseXml, stringifyXmlable } from "@util/xml"; import { createChartData } from "../chart-data"; import type { ChartRunOptions } from "../chart-options"; import { createPlotArea } from "./plot-area"; const plotArea = (options: ChartRunOptions): Element => - (xml2js(xml(new Formatter().format(createPlotArea(options, createChartData(options))))) as Element).elements![0]; + parseXml(stringifyXmlable(new Formatter().format(createPlotArea(options, createChartData(options))))).elements![0]; const names = (element: Element): readonly string[] => (element.elements ?? []).map(({ name }) => name!); const children = (element: Element, name: string): readonly Element[] => element.elements!.filter((one) => one.name === name); const value = (element: Element, name: string): unknown => children(element, name)[0]?.attributes?.val; @@ -87,7 +86,7 @@ describe("createPlotArea's data table", () => { "1", "1", ]); - const written = xml( + const written = stringifyXmlable( new Formatter().format( createPlotArea( { type: "column", categories, series, dataTable: true }, @@ -115,7 +114,7 @@ describe("createPlotArea's data table", () => { "0", "0", ]); - const written = xml(new Formatter().format(createPlotArea(options, createChartData(options)))); + const written = stringifyXmlable(new Formatter().format(createPlotArea(options, createChartData(options)))); expect(written).to.contain(''); }); diff --git a/src/charts/plot-area/radar-chart.spec.ts b/src/charts/plot-area/radar-chart.spec.ts index 6fdfd1ab37..b34375f609 100644 --- a/src/charts/plot-area/radar-chart.spec.ts +++ b/src/charts/plot-area/radar-chart.spec.ts @@ -1,15 +1,14 @@ import { describe, expect, it } from "vitest"; -import xml from "xml"; -import { type Element, xml2js } from "xml-js"; import { Formatter } from "@export/formatter"; +import { type XmlElement as Element, parseXml, stringifyXmlable } from "@util/xml"; import type { XmlComponent } from "docx"; import { createChartData } from "../chart-data"; import type { RadarChartOptions } from "../chart-options"; import { createRadarChart } from "./radar-chart"; -const parse = (component: XmlComponent): Element => (xml2js(xml(new Formatter().format(component))) as Element).elements![0]; +const parse = (component: XmlComponent): Element => parseXml(stringifyXmlable(new Formatter().format(component))).elements![0]; const names = (element: Element): readonly string[] => (element.elements ?? []).map(({ name }) => name!); const children = (element: Element, name: string): readonly Element[] => element.elements!.filter((one) => one.name === name); const value = (element: Element, name: string): unknown => children(element, name)[0]?.attributes?.val; @@ -39,7 +38,7 @@ describe("createRadarChart", () => { expect(value(group, "c:varyColors")).to.equal("0"); expect(names(series)).to.deep.equal(["c:idx", "c:order", "c:tx", "c:spPr", "c:marker", "c:cat", "c:val"]); expect(value(children(series, "c:marker")[0], "c:symbol")).to.equal("none"); - expect(xml(new Formatter().format(create().group))).to.contain( + expect(stringifyXmlable(new Formatter().format(create().group))).to.contain( '', ); }); @@ -58,9 +57,9 @@ describe("createRadarChart", () => { const symbols = children(group, "c:ser").map((series) => value(children(series, "c:marker")[0], "c:symbol")); expect(symbols).to.deep.equal(["diamond", "circle", "none"]); - expect(xml(new Formatter().format(create({ series: [{ name: "A", values: [1], line: { dash: "dot" } }] }).group))).to.contain( - '', - ); + expect( + stringifyXmlable(new Formatter().format(create({ series: [{ name: "A", values: [1], line: { dash: "dot" } }] }).group)), + ).to.contain(''); }); it("should fill the series of a filled radar chart, without lines or markers", () => { diff --git a/src/charts/plot-area/scatter-chart.spec.ts b/src/charts/plot-area/scatter-chart.spec.ts index 6605cad694..44bdcf78c6 100644 --- a/src/charts/plot-area/scatter-chart.spec.ts +++ b/src/charts/plot-area/scatter-chart.spec.ts @@ -1,15 +1,14 @@ import { describe, expect, it } from "vitest"; -import xml from "xml"; -import { type Element, xml2js } from "xml-js"; import { Formatter } from "@export/formatter"; +import { type XmlElement as Element, parseXml, stringifyXmlable } from "@util/xml"; import type { XmlComponent } from "docx"; import { createChartData } from "../chart-data"; import type { ScatterChartOptions } from "../chart-options"; import { createScatterChart } from "./scatter-chart"; -const parse = (component: XmlComponent): Element => (xml2js(xml(new Formatter().format(component))) as Element).elements![0]; +const parse = (component: XmlComponent): Element => parseXml(stringifyXmlable(new Formatter().format(component))).elements![0]; const names = (element: Element): readonly string[] => (element.elements ?? []).map(({ name }) => name!); const children = (element: Element, name: string): readonly Element[] => element.elements!.filter((one) => one.name === name); const value = (element: Element, name: string): unknown => children(element, name)[0]?.attributes?.val; diff --git a/src/charts/plot-area/series.spec.ts b/src/charts/plot-area/series.spec.ts index 83836fa4f0..6022d33b70 100644 --- a/src/charts/plot-area/series.spec.ts +++ b/src/charts/plot-area/series.spec.ts @@ -1,12 +1,12 @@ import { describe, expect, it } from "vitest"; -import xml from "xml"; import { Formatter } from "@export/formatter"; +import { stringifyXmlable } from "@util/xml"; import type { XmlComponent } from "docx"; import { createCategoriesAndValues, createDataSource, createSeriesStart, formatNumber } from "./series"; -const toXml = (component: XmlComponent): string => xml(new Formatter().format(component)); +const toXml = (component: XmlComponent): string => stringifyXmlable(new Formatter().format(component)); describe("series", () => { it("should write numbers in JavaScript's shortest form that reads back as the same number", () => { diff --git a/src/charts/plot-area/stock-chart.spec.ts b/src/charts/plot-area/stock-chart.spec.ts index 6788ac4a21..d6afbdec5d 100644 --- a/src/charts/plot-area/stock-chart.spec.ts +++ b/src/charts/plot-area/stock-chart.spec.ts @@ -1,17 +1,16 @@ // cspell:ignore cmpd import { describe, expect, it } from "vitest"; -import xml from "xml"; -import { type Element, xml2js } from "xml-js"; import { Formatter } from "@export/formatter"; +import { type XmlElement as Element, parseXml, stringifyXmlable } from "@util/xml"; import type { XmlComponent } from "docx"; import { createChartData } from "../chart-data"; import type { StockChartOptions } from "../chart-options"; import { createStockChart } from "./stock-chart"; -const write = (component: XmlComponent): string => xml(new Formatter().format(component)); -const parse = (component: XmlComponent): Element => (xml2js(write(component)) as Element).elements![0]; +const write = (component: XmlComponent): string => stringifyXmlable(new Formatter().format(component)); +const parse = (component: XmlComponent): Element => parseXml(write(component)).elements![0]; const names = (element: Element): readonly string[] => (element.elements ?? []).map(({ name }) => name!); const children = (element: Element, name: string): readonly Element[] => element.elements!.filter((one) => one.name === name); const value = (element: Element, name: string): unknown => children(element, name)[0]?.attributes?.val; diff --git a/src/charts/plot-area/trendline.spec.ts b/src/charts/plot-area/trendline.spec.ts index 7cc8af712b..d1c382cf3c 100644 --- a/src/charts/plot-area/trendline.spec.ts +++ b/src/charts/plot-area/trendline.spec.ts @@ -1,16 +1,15 @@ import { describe, expect, it } from "vitest"; -import xml from "xml"; -import { type Element, xml2js } from "xml-js"; import { Formatter } from "@export/formatter"; +import { type XmlElement as Element, parseXml, stringifyXmlable } from "@util/xml"; import type { XmlComponent } from "docx"; import type { ChartTrendline } from "../chart-options"; import { createSeriesColor } from "../chart-style"; import { createTrendlines } from "./trendline"; -const write = (component: XmlComponent): string => xml(new Formatter().format(component)); -const parse = (component: XmlComponent): Element => (xml2js(write(component)) as Element).elements![0]; +const write = (component: XmlComponent): string => stringifyXmlable(new Formatter().format(component)); +const parse = (component: XmlComponent): Element => parseXml(write(component)).elements![0]; const names = (element: Element): readonly string[] => (element.elements ?? []).map(({ name }) => name!); const value = (element: Element, name: string): unknown => element.elements!.find((one) => one.name === name)?.attributes?.val; diff --git a/src/charts/template/patch-chart.spec.ts b/src/charts/template/patch-chart.spec.ts index 12e3015510..4f48621496 100644 --- a/src/charts/template/patch-chart.spec.ts +++ b/src/charts/template/patch-chart.spec.ts @@ -1,8 +1,7 @@ import { describe, expect, it, vi } from "vitest"; -import xml from "xml"; -import { type Element, js2xml, xml2js } from "xml-js"; import { Formatter } from "@export/formatter"; +import { type XmlElement as Element, parseXml, stringifyElement, stringifyXmlable } from "@util/xml"; import type { XmlComponent } from "docx"; import { createChartData } from "../chart-data"; @@ -21,12 +20,12 @@ import { childOf, childrenOf, descendantsOf, textOf } from "./template-xml"; // cspell:ignore dLbls dLbl dPt varyColors barDir axId crossAx valAx catAx dateAx baseTimeUnit majorTimeUnit legendEntry schemeClr srgbClr lumMod // cspell:ignore numCache strCache ptCount strRef numRef formatCode datalabelsRange trendlineLbl errBars sqref externalData autoUpdate userShapes -const parse = (text: string): Element => (xml2js(text, { compact: false, captureSpacesBetweenElements: true }) as Element).elements![0]; +const parse = (text: string): Element => parseXml(text, { keepWhitespaceText: true }).elements![0]; -const write = (element: Element | undefined): string => (element === undefined ? "" : js2xml({ elements: [element] })); +const write = (element: Element | undefined): string => (element === undefined ? "" : stringifyElement({ elements: [element] })); const formatter = new Formatter(); -const format = (content: XmlComponent): Element => parse(xml(formatter.format(content))); +const format = (content: XmlComponent): Element => parse(stringifyXmlable(formatter.format(content))); const NAMESPACES = 'xmlns:c="http://schemas.openxmlformats.org/drawingml/2006/chart" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" ' + diff --git a/src/charts/template/patch-chart.ts b/src/charts/template/patch-chart.ts index 8519059d0b..80391d9cd9 100644 --- a/src/charts/template/patch-chart.ts +++ b/src/charts/template/patch-chart.ts @@ -5,9 +5,8 @@ * @module */ // cspell:ignore sqref -import type { Element } from "xml-js"; -import type { XmlComponent } from "docx"; +import type { XmlElement as Element, XmlComponent } from "docx"; import type { ChartData, ChartSeriesData } from "../chart-data"; import type { TimeUnit } from "../chart-dates"; diff --git a/src/charts/template/template-chart.spec.ts b/src/charts/template/template-chart.spec.ts index 0282cffa55..c75e856cf1 100644 --- a/src/charts/template/template-chart.spec.ts +++ b/src/charts/template/template-chart.spec.ts @@ -1,11 +1,12 @@ import { describe, expect, it } from "vitest"; -import { type Element, xml2js } from "xml-js"; + +import { type XmlElement as Element, parseXml } from "@util/xml"; import { formatCodeOf, isDateFormat, pointCountOf, readTemplateChart } from "./template-chart"; // cspell:ignore varyColors barDir radarStyle scatterStyle ofPieType ofPie dLbls strRef numRef numCache formatCode ptCount pivotSource -const parse = (text: string): Element => (xml2js(text, { compact: false, captureSpacesBetweenElements: true }) as Element).elements![0]; +const parse = (text: string): Element => parseXml(text, { keepWhitespaceText: true }).elements![0]; // A series, with its order, or null for none const series = (index: number, order: number | null = index): string => diff --git a/src/charts/template/template-chart.ts b/src/charts/template/template-chart.ts index f4d6ad42cb..ed265a6864 100644 --- a/src/charts/template/template-chart.ts +++ b/src/charts/template/template-chart.ts @@ -5,7 +5,8 @@ * @module */ // cspell:ignore dmyhs -import type { Element } from "xml-js"; + +import type { XmlElement as Element } from "docx"; import type { ChartType } from "../chart-options"; import { childOf, childrenOf, descendantsOf, elementsOf, nameOf, numberOf, textOf, valueOf } from "./template-xml"; diff --git a/src/charts/template/template-series.spec.ts b/src/charts/template/template-series.spec.ts index 57a3c531ee..b361ed17dc 100644 --- a/src/charts/template/template-series.spec.ts +++ b/src/charts/template/template-series.spec.ts @@ -1,5 +1,6 @@ import { describe, expect, it } from "vitest"; -import { type Element, js2xml, xml2js } from "xml-js"; + +import { type XmlElement as Element, parseXml, stringifyElement } from "@util/xml"; import { CHART_SPACE_ORDER } from "./patch-chart"; import { @@ -17,9 +18,9 @@ import { // cspell:ignore srgbClr schemeClr lumMod lumOff dLbls dLbl dPt extLst errBars trendline uniqueId spPr gradFill gsLst prstClr sysClr -const parse = (text: string): Element => (xml2js(text, { compact: false, captureSpacesBetweenElements: true }) as Element).elements![0]; +const parse = (text: string): Element => parseXml(text, { keepWhitespaceText: true }).elements![0]; -const write = (element: Element | undefined): string => (element === undefined ? "" : js2xml({ elements: [element] })); +const write = (element: Element | undefined): string => (element === undefined ? "" : stringifyElement({ elements: [element] })); // The children of each type in ooxml-schemas/ISO-IEC29500-4_2016/dml-chart.xsd, in order, with the children of the // groups it refers to (EG_SerShared) in their places diff --git a/src/charts/template/template-series.ts b/src/charts/template/template-series.ts index 3c74d2c779..2b6392d0d5 100644 --- a/src/charts/template/template-series.ts +++ b/src/charts/template/template-series.ts @@ -4,7 +4,8 @@ * * @module */ -import type { Element } from "xml-js"; + +import type { XmlElement as Element } from "docx"; import { childOf, diff --git a/src/charts/template/template-xml.spec.ts b/src/charts/template/template-xml.spec.ts index 5da0a5de60..a7a7128b90 100644 --- a/src/charts/template/template-xml.spec.ts +++ b/src/charts/template/template-xml.spec.ts @@ -1,5 +1,6 @@ import { describe, expect, it } from "vitest"; -import { type Element, js2xml, xml2js } from "xml-js"; + +import { type XmlElement as Element, parseXml, stringifyElement } from "@util/xml"; import { attributeOf, @@ -21,9 +22,9 @@ import { } from "./template-xml"; // Parsed as patchDocument parses a template's parts, with the spaces between elements -const parse = (text: string): Element => (xml2js(text, { compact: false, captureSpacesBetweenElements: true }) as Element).elements![0]; +const parse = (text: string): Element => parseXml(text, { keepWhitespaceText: true }).elements![0]; -const write = (element: Element): string => js2xml({ elements: [element] }); +const write = (element: Element): string => stringifyElement({ elements: [element] }); describe("template-xml", () => { describe("nameOf", () => { diff --git a/src/charts/template/template-xml.ts b/src/charts/template/template-xml.ts index f62adbc305..6676f188be 100644 --- a/src/charts/template/template-xml.ts +++ b/src/charts/template/template-xml.ts @@ -1,10 +1,10 @@ /** - * Small helpers for reading and changing a template's XML, as `patchDocument` parses it (xml-js elements). Changes make + * Small helpers for reading and changing a template's XML, as `patchDocument` parses it (`XmlElement`s). Changes make * new elements rather than changing the template's, and keep its text, comments and elements they don't know. * * @module */ -import type { Element } from "xml-js"; +import type { XmlElement as Element } from "docx"; /** * An element's name, such as "c:ser", or "" for text and comments, which have none. diff --git a/src/charts/workbook/workbook.spec.ts b/src/charts/workbook/workbook.spec.ts index dda4bb4521..1686a136f7 100644 --- a/src/charts/workbook/workbook.spec.ts +++ b/src/charts/workbook/workbook.spec.ts @@ -1,13 +1,13 @@ // cspell:ignore Fmts import { describe, expect, it } from "vitest"; -import xml from "xml"; import { Formatter } from "@export/formatter"; +import { stringifyXmlable } from "@util/xml"; import type { EmbeddedPackageFile, XmlComponent } from "docx"; import { createWorkbookFiles } from "./workbook"; -const toXml = (component: EmbeddedPackageFile["content"]): string => xml(new Formatter().format(component as XmlComponent)); +const toXml = (component: EmbeddedPackageFile["content"]): string => stringifyXmlable(new Formatter().format(component as XmlComponent)); const files = (sheet: Parameters[0]): Readonly> => Object.fromEntries(createWorkbookFiles(sheet).map(({ path, content }) => [path, toXml(content)])); diff --git a/src/export/packer/next-compiler.ts b/src/export/packer/next-compiler.ts index 6ecc88e679..67af9686dc 100644 --- a/src/export/packer/next-compiler.ts +++ b/src/export/packer/next-compiler.ts @@ -4,12 +4,12 @@ * @module */ import JSZip from "jszip"; -import xml from "xml"; import type { File } from "@file/file"; import { obfuscate } from "@file/fonts/obfuscate-ttf-to-odttf"; import { Relationships } from "@file/relationships"; import { encodeUtf8 } from "@util/convenience-functions"; +import { stringifyXmlable } from "@util/xml"; import { Formatter } from "../formatter"; import { ImageReplacer } from "./image-replacer"; @@ -181,7 +181,7 @@ export class Compiler { } private xmlifyFile(file: File, prettify?: (typeof PrettifyType)[keyof typeof PrettifyType]): IXmlifyedFileMapping { - const documentXmlData = xml( + const documentXmlData = stringifyXmlable( this.formatter.format(file.Document.View, { viewWrapper: file.Document, file, @@ -196,7 +196,7 @@ export class Compiler { }, ); - const commentXmlData = xml( + const commentXmlData = stringifyXmlable( this.formatter.format(file.Comments, { viewWrapper: { View: file.Comments, @@ -214,7 +214,7 @@ export class Compiler { }, ); - const footnoteXmlData = xml( + const footnoteXmlData = stringifyXmlable( this.formatter.format(file.FootNotes.View, { viewWrapper: file.FootNotes, file, @@ -229,7 +229,7 @@ export class Compiler { }, ); - const endnoteXmlData = xml( + const endnoteXmlData = stringifyXmlable( this.formatter.format(file.Endnotes.View, { viewWrapper: file.Endnotes, file, @@ -274,7 +274,7 @@ export class Compiler { "fontTable.xml", ); - return xml( + return stringifyXmlable( this.formatter.format(relationships, { viewWrapper: file.Document, file, @@ -300,7 +300,7 @@ export class Compiler { }, Styles: { data: (() => { - const xmlStyles = xml( + const xmlStyles = stringifyXmlable( this.formatter.format(file.Styles, { viewWrapper: file.Document, file, @@ -320,7 +320,7 @@ export class Compiler { path: "word/styles.xml", }, Properties: { - data: xml( + data: stringifyXmlable( this.formatter.format(file.CoreProperties, { viewWrapper: file.Document, file, @@ -337,7 +337,7 @@ export class Compiler { path: "docProps/core.xml", }, FileRelationships: { - data: xml( + data: stringifyXmlable( this.formatter.format(file.FileRelationships, { viewWrapper: file.Document, file, @@ -353,7 +353,7 @@ export class Compiler { path: "_rels/.rels", }, HeaderRelationships: file.Headers.map((headerWrapper, index) => { - const xmlData = xml( + const xmlData = stringifyXmlable( this.formatter.format(headerWrapper.View, { viewWrapper: headerWrapper, file, @@ -379,7 +379,7 @@ export class Compiler { }); return { - data: xml( + data: stringifyXmlable( this.formatter.format(relationships, { viewWrapper: headerWrapper, file, @@ -396,7 +396,7 @@ export class Compiler { }; }), FooterRelationships: file.Footers.map((footerWrapper, index) => { - const xmlData = xml( + const xmlData = stringifyXmlable( this.formatter.format(footerWrapper.View, { viewWrapper: footerWrapper, file, @@ -422,7 +422,7 @@ export class Compiler { }); return { - data: xml( + data: stringifyXmlable( this.formatter.format(relationships, { viewWrapper: footerWrapper, file, @@ -439,7 +439,7 @@ export class Compiler { }; }), Headers: file.Headers.map((headerWrapper, index) => { - const tempXmlData = xml( + const tempXmlData = stringifyXmlable( this.formatter.format(headerWrapper.View, { viewWrapper: headerWrapper, file, @@ -464,7 +464,7 @@ export class Compiler { }; }), Footers: file.Footers.map((footerWrapper, index) => { - const tempXmlData = xml( + const tempXmlData = stringifyXmlable( this.formatter.format(footerWrapper.View, { viewWrapper: footerWrapper, file, @@ -489,7 +489,7 @@ export class Compiler { }; }), CustomProperties: { - data: xml( + data: stringifyXmlable( this.formatter.format(file.CustomProperties, { viewWrapper: file.Document, file, @@ -506,7 +506,7 @@ export class Compiler { path: "docProps/custom.xml", }, AppProperties: { - data: xml( + data: stringifyXmlable( this.formatter.format(file.AppProperties, { viewWrapper: file.Document, file, @@ -541,7 +541,7 @@ export class Compiler { `media/${mediaData.fileName}`, ); }); - return xml( + return stringifyXmlable( this.formatter.format(relationships, { viewWrapper: file.FootNotes, file, @@ -576,7 +576,7 @@ export class Compiler { `media/${mediaData.fileName}`, ); }); - return xml( + return stringifyXmlable( this.formatter.format(relationships, { viewWrapper: file.Endnotes, file, @@ -593,7 +593,7 @@ export class Compiler { path: "word/_rels/endnotes.xml.rels", }, Settings: { - data: xml( + data: stringifyXmlable( this.formatter.format(file.Settings, { viewWrapper: file.Document, file, @@ -631,7 +631,7 @@ export class Compiler { `media/${mediaData.fileName}`, ); }); - return xml( + return stringifyXmlable( this.formatter.format(relationships, { viewWrapper: { View: file.Comments, @@ -654,7 +654,7 @@ export class Compiler { ...(file.CommentsExtended ? { CommentsExtended: { - data: xml( + data: stringifyXmlable( this.formatter.format(file.CommentsExtended, { viewWrapper: { View: file.CommentsExtended, @@ -678,7 +678,7 @@ export class Compiler { ...(file.CommentsIds ? { CommentsIds: { - data: xml( + data: stringifyXmlable( this.formatter.format(file.CommentsIds, { viewWrapper: { View: file.CommentsIds, @@ -700,7 +700,7 @@ export class Compiler { } : {}), FontTable: { - data: xml( + data: stringifyXmlable( this.formatter.format(file.FontTable.View, { viewWrapper: file.Document, file, @@ -718,7 +718,7 @@ export class Compiler { }, FontTableRelationships: { data: (() => - xml( + stringifyXmlable( this.formatter.format(file.FontTable.Relationships, { viewWrapper: file.Document, file, @@ -734,7 +734,7 @@ export class Compiler { path: "word/_rels/fontTable.xml.rels", }, Theme: { - data: xml( + data: stringifyXmlable( this.formatter.format(file.Theme, { viewWrapper: file.Document, file, @@ -755,7 +755,7 @@ export class Compiler { // After every part that can have lists, such as headers and footers, as the lists they use are added to the // numbering while they're written Numbering: { - data: xml( + data: stringifyXmlable( this.formatter.format(file.Numbering, { viewWrapper: file.Document, file, @@ -773,7 +773,7 @@ export class Compiler { }, // Last, as parts are added to the package, with their content types, while the others are written ContentTypes: { - data: xml( + data: stringifyXmlable( this.formatter.format(file.ContentTypes, { viewWrapper: file.Document, file, diff --git a/src/export/packer/package-part-writer.ts b/src/export/packer/package-part-writer.ts index 3166da49c3..17b3c82cf3 100644 --- a/src/export/packer/package-part-writer.ts +++ b/src/export/packer/package-part-writer.ts @@ -5,13 +5,13 @@ * @module */ import JSZip from "jszip"; -import xml from "xml"; import type { File } from "@file/file"; import type { PackagePart } from "@file/package-part/package-part"; import { Relationships } from "@file/relationships"; import type { XmlComponent } from "@file/xml-components"; import { encodeUtf8 } from "@util/convenience-functions"; +import { stringifyXmlable } from "@util/xml"; import { Formatter } from "../formatter"; import type { PrettifyType } from "./packer"; @@ -33,7 +33,7 @@ const formatter = new Formatter(); * Formats a part's XML, with the relationships that anything in it that refers to other parts adds to. */ const xmlifyPart = (file: File, content: XmlComponent, prettify: Prettify, relationships: Relationships, standalone = true): string => - xml(formatter.format(content, { viewWrapper: { View: content, Relationships: relationships }, file, stack: [] }), { + stringifyXmlable(formatter.format(content, { viewWrapper: { View: content, Relationships: relationships }, file, stack: [] }), { indent: prettify, declaration: standalone ? { standalone: "yes", encoding: "UTF-8" } : { encoding: "UTF-8" }, }); diff --git a/src/file/styles/external-styles-factory.ts b/src/file/styles/external-styles-factory.ts index 01bfff4f56..29d9a484ad 100644 --- a/src/file/styles/external-styles-factory.ts +++ b/src/file/styles/external-styles-factory.ts @@ -7,9 +7,9 @@ * * @module */ -import { type Element as XMLElement, xml2js } from "xml-js"; import { ImportedRootElementAttributes, type ImportedXmlComponent, convertToXmlComponent } from "@file/xml-components"; +import { type XmlElement as XMLElement, parseXml } from "@util/xml"; import type { IStylesOptions } from "./styles"; @@ -54,7 +54,7 @@ export class ExternalStylesFactory { * @throws Error if styles element cannot be found in the XML */ public newInstance(xmlData: string): IStylesOptions { - const xmlObj = xml2js(xmlData, { compact: false }) as XMLElement; + const xmlObj = parseXml(xmlData); let stylesXmlElement: XMLElement | undefined; for (const xmlElm of xmlObj.elements || []) { diff --git a/src/file/xml-components/imported-xml-component.spec.ts b/src/file/xml-components/imported-xml-component.spec.ts index 2baf8b235f..b65c5c762b 100644 --- a/src/file/xml-components/imported-xml-component.spec.ts +++ b/src/file/xml-components/imported-xml-component.spec.ts @@ -1,7 +1,7 @@ import { beforeEach, describe, expect, it } from "vitest"; -import { type Element, xml2js } from "xml-js"; import { EMPTY_OBJECT } from "@file/xml-components"; +import { type XmlElement as Element, parseXml } from "@util/xml"; import type { IContext } from "./base"; import { ImportedRootElementAttributes, ImportedXmlComponent, convertToXmlComponent } from "./imported-xml-component"; @@ -85,7 +85,7 @@ describe("ImportedXmlComponent", () => { describe("convertToXmlComponent", () => { it("should convert to xml component", () => { - const xmlObj = xml2js(xmlString, { compact: false }) as Element; + const xmlObj = parseXml(xmlString); const converted = convertToXmlComponent(xmlObj); expect(JSON.parse(JSON.stringify(converted))).to.deep.equal(convertedXmlElement); }); diff --git a/src/file/xml-components/imported-xml-component.ts b/src/file/xml-components/imported-xml-component.ts index ce3289cdb9..1fe85a4ce8 100644 --- a/src/file/xml-components/imported-xml-component.ts +++ b/src/file/xml-components/imported-xml-component.ts @@ -7,26 +7,28 @@ * * @module */ -import { type Element as XmlElement, xml2js } from "xml-js"; import { type IXmlableObject, XmlAttributeComponent, XmlComponent } from "@file/xml-components"; +import { type XmlElement, parseXml } from "@util/xml"; import type { IContext } from "./base"; /** - * Converts an xml-js Element into an XmlComponent tree. + * Converts an XML element, in the shape of xml-js's non-compact `Element`, into an XmlComponent tree. * - * This function recursively processes XML elements in JSON format (from xml-js) - * and creates a tree of ImportedXmlComponent objects that match the structure - * of the original XML. + * This function recursively processes the element and creates a tree of + * ImportedXmlComponent objects that match the structure of the original XML. * - * @param element - The XML element in JSON representation from xml-js + * @param element - The XML element as an {@link XmlElement} * @returns An ImportedXmlComponent tree, text string, or undefined * * @example * ```typescript - * const xmlElement = xml2js('Hello'); - * const component = convertToXmlComponent(xmlElement); + * const component = convertToXmlComponent({ + * type: "element", + * name: "w:p", + * elements: [{ type: "element", name: "w:r", elements: [{ type: "element", name: "w:t", elements: [{ type: "text", text: "Hello" }] }] }], + * }); * ``` */ export const convertToXmlComponent = (element: XmlElement): ImportedXmlComponent | string | undefined => { @@ -85,7 +87,7 @@ export class ImportedXmlComponent extends XmlComponent { * Parses an XML string and converts it to an ImportedXmlComponent tree. * * This static method is the primary way to import external XML content. - * It uses xml-js to parse the XML string into a JSON representation, + * It parses the XML string into an {@link XmlElement} tree, * then converts that into a tree of XmlComponent objects. * * @param importedContent - The XML content as a string @@ -98,7 +100,7 @@ export class ImportedXmlComponent extends XmlComponent { * ``` */ public static fromXmlString(importedContent: string): ImportedXmlComponent { - const xmlObj = xml2js(importedContent, { compact: false }) as XmlElement; + const xmlObj = parseXml(importedContent); return convertToXmlComponent(xmlObj) as ImportedXmlComponent; } diff --git a/src/html/math.spec.ts b/src/html/math.spec.ts index 16980cad84..3b21b8cb26 100644 --- a/src/html/math.spec.ts +++ b/src/html/math.spec.ts @@ -2,9 +2,9 @@ import type { Element } from "domhandler"; import { parse } from "parse5"; import { adapter } from "parse5-htmlparser2-tree-adapter"; import { describe, expect, it } from "vitest"; -import xml from "xml"; import { Formatter } from "@export/formatter"; +import { stringifyXmlable } from "@util/xml"; import { Math, type MathComponent, @@ -34,7 +34,7 @@ const elementIn = (html: string, name: string): Element => { return find(document)!; }; -const written = (...children: readonly MathComponent[]): string => xml(new Formatter().format(new Math({ children }))); +const written = (...children: readonly MathComponent[]): string => stringifyXmlable(new Formatter().format(new Math({ children }))); const read = (mathMl: string): string => written(...mathOf(elementIn(`${mathMl}`, "math"))); const run = (text: string, options: Omit[0] & object, "text"> = {}): MathRun => new MathRun({ text, ...options }); diff --git a/src/layout/imported-documents.spec.ts b/src/layout/imported-documents.spec.ts index 84584cf4e3..a78a58c1d8 100644 --- a/src/layout/imported-documents.spec.ts +++ b/src/layout/imported-documents.spec.ts @@ -1,13 +1,14 @@ // cspell:ignore endedi import { describe, expect, it } from "vitest"; -import { type Element, xml2js } from "xml-js"; + +import { type XmlElement as Element, parseXml } from "@util/xml"; import type { DocxPackage } from "./imported-documents"; import { type Block, type DocumentContent, type ParagraphBlock } from "./read-document"; import { readDocx } from "./read-docx"; /** Parses XML as patchDocument parses a template's parts */ -const parse = (xml: string): Element => xml2js(xml, { compact: false, captureSpacesBetweenElements: true }) as Element; +const parse = (xml: string): Element => parseXml(xml, { keepWhitespaceText: true }); const W = 'xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"'; const R = 'xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"'; diff --git a/src/layout/imported-documents.ts b/src/layout/imported-documents.ts index cd062ecc03..ae40740c84 100644 --- a/src/layout/imported-documents.ts +++ b/src/layout/imported-documents.ts @@ -33,7 +33,8 @@ * * @module */ -import type { Element } from "xml-js"; + +import type { XmlElement as Element } from "docx"; import { type FontFace, diff --git a/src/layout/read-docx.spec.ts b/src/layout/read-docx.spec.ts index 7d3a4ad94e..32fb687149 100644 --- a/src/layout/read-docx.spec.ts +++ b/src/layout/read-docx.spec.ts @@ -1,8 +1,8 @@ import JSZip from "jszip"; import { describe, expect, it } from "vitest"; -import { type Element, xml2js } from "xml-js"; import { obfuscate } from "@file/fonts/obfuscate-ttf-to-odttf"; +import { type XmlElement as Element, parseXml } from "@util/xml"; import { AlignmentType, Document, @@ -31,7 +31,7 @@ import { type DocumentContent, type ParagraphBlock, readDocument } from "./read- import { readDocx } from "./read-docx"; /** Parses XML as patchDocument parses a template's parts */ -const parse = (xml: string): Element => xml2js(xml, { compact: false, captureSpacesBetweenElements: true }) as Element; +const parse = (xml: string): Element => parseXml(xml, { keepWhitespaceText: true }); /** The XML parts of a .docx, parsed, by their paths */ const partsOf = async (buffer: Buffer): Promise> => { diff --git a/src/layout/read-docx.ts b/src/layout/read-docx.ts index f071f0344d..503abdf53a 100644 --- a/src/layout/read-docx.ts +++ b/src/layout/read-docx.ts @@ -5,7 +5,8 @@ * * @module */ -import type { Element } from "xml-js"; + +import type { XmlElement as Element } from "docx"; import { type XmlObject, attributesOf, childrenOf, find, readTextStyles, readThemeFonts, stringOf, withoutUndefined } from "../text-layout"; import type { DataStores } from "./bound-controls"; @@ -26,7 +27,7 @@ type Relationship = { const DEFAULT_DOCUMENT = "word/document.xml"; /** - * An element as xml-js parses it, formatted as docx formats elements: `{ "w:p": [{ _attr: {...} }, ...content] }`, with + * An element as `parseXml` reads it, formatted as docx formats elements: `{ "w:p": [{ _attr: {...} }, ...content] }`, with * text as strings. */ const formatted = (element: Element): unknown => { @@ -250,8 +251,8 @@ const dataStoresOf = (parts: ReadonlyMap, documentPath: string) * Reads a .docx's main document, with the parts it refers to, and the documents it imports (`w:altChunk`) as Word turns * them into its own paragraphs and tables when it opens it (see `imported-documents.ts`). * - * @param parts - The XML parts of its package, parsed by xml-js's `xml2js`, not compact and keeping the spaces between - * elements, by their paths, such as "word/document.xml" + * @param parts - The XML parts of its package, read by `parseXml` keeping the text that is only whitespace, by their + * paths, such as "word/document.xml" * @param binaryParts - Its other parts, such as the fonts it embeds, by their paths * @param options - How it is read: to be laid out with a guess, or not * @param importedDocuments - The .docx files it imports, by their paths, each read as it is diff --git a/src/math/latex-to-math.spec.ts b/src/math/latex-to-math.spec.ts index 8ade94b81c..4ba4d8ea07 100644 --- a/src/math/latex-to-math.spec.ts +++ b/src/math/latex-to-math.spec.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from "vitest"; -import xml from "xml"; import { Formatter } from "@export/formatter"; +import { stringifyXmlable } from "@util/xml"; import { Math, type MathComponent, @@ -29,7 +29,7 @@ import { MathLargeOperator } from "./math-large-operator"; import { MathMatrix } from "./math-matrix"; import { MathPhantom } from "./math-phantom"; -const written = (...children: readonly MathComponent[]): string => xml(new Formatter().format(new Math({ children }))); +const written = (...children: readonly MathComponent[]): string => stringifyXmlable(new Formatter().format(new Math({ children }))); /** The math the LaTeX is read as, written, to compare with the same math built by hand */ const read = (latex: string): string => written(...latexToMath(latex)); diff --git a/src/math/math-accent.spec.ts b/src/math/math-accent.spec.ts index 7eec813523..87b1dc35b0 100644 --- a/src/math/math-accent.spec.ts +++ b/src/math/math-accent.spec.ts @@ -1,12 +1,12 @@ import { describe, expect, it } from "vitest"; -import xml from "xml"; import { Formatter } from "@export/formatter"; +import { stringifyXmlable } from "@util/xml"; import { Math, MathRun } from "docx"; import { MathAccent, type MathAccentName } from "./math-accent"; -const toXml = (component: MathAccent): string => xml(new Formatter().format(component)); +const toXml = (component: MathAccent): string => stringifyXmlable(new Formatter().format(component)); const x = "x"; diff --git a/src/math/math-bar.spec.ts b/src/math/math-bar.spec.ts index 4b097053fe..c811e12257 100644 --- a/src/math/math-bar.spec.ts +++ b/src/math/math-bar.spec.ts @@ -1,12 +1,12 @@ import { describe, expect, it } from "vitest"; -import xml from "xml"; import { Formatter } from "@export/formatter"; +import { stringifyXmlable } from "@util/xml"; import { Math, MathRun } from "docx"; import { MathBar } from "./math-bar"; -const toXml = (component: MathBar): string => xml(new Formatter().format(component)); +const toXml = (component: MathBar): string => stringifyXmlable(new Formatter().format(component)); describe("MathBar", () => { it("puts a line above its children by default, writing the position, as the schema's default is below", () => { diff --git a/src/math/math-box.spec.ts b/src/math/math-box.spec.ts index 4cb2668ce3..dfb933231e 100644 --- a/src/math/math-box.spec.ts +++ b/src/math/math-box.spec.ts @@ -1,12 +1,12 @@ import { describe, expect, it } from "vitest"; -import xml from "xml"; import { Formatter } from "@export/formatter"; +import { stringifyXmlable } from "@util/xml"; import { Math, MathRun } from "docx"; import { MathBox } from "./math-box"; -const toXml = (component: MathBox): string => xml(new Formatter().format(component)); +const toXml = (component: MathBox): string => stringifyXmlable(new Formatter().format(component)); describe("MathBox", () => { it("draws a box around its children, with no properties, as all four sides are drawn by default", () => { diff --git a/src/math/math-brace.spec.ts b/src/math/math-brace.spec.ts index befce8eb63..8a64510435 100644 --- a/src/math/math-brace.spec.ts +++ b/src/math/math-brace.spec.ts @@ -1,12 +1,12 @@ import { describe, expect, it } from "vitest"; -import xml from "xml"; import { Formatter } from "@export/formatter"; +import { stringifyXmlable } from "@util/xml"; import { Math, MathRun } from "docx"; import { MathBrace } from "./math-brace"; -const toXml = (component: MathBrace): string => xml(new Formatter().format(component)); +const toXml = (component: MathBrace): string => stringifyXmlable(new Formatter().format(component)); const e = "a+b"; diff --git a/src/math/math-brackets.spec.ts b/src/math/math-brackets.spec.ts index 9fa2031cc6..baa58b2783 100644 --- a/src/math/math-brackets.spec.ts +++ b/src/math/math-brackets.spec.ts @@ -1,13 +1,13 @@ import { describe, expect, it } from "vitest"; -import xml from "xml"; import { Formatter } from "@export/formatter"; +import { stringifyXmlable } from "@util/xml"; import { Math, MathFraction, MathRun, Paragraph, TextRun } from "docx"; import { MathBrackets } from "./math-brackets"; import { MathMatrix } from "./math-matrix"; -const toXml = (component: MathBrackets): string => xml(new Formatter().format(component)); +const toXml = (component: MathBrackets): string => stringifyXmlable(new Formatter().format(component)); const x = "x"; @@ -104,7 +104,7 @@ describe("MathBrackets", () => { numerator: [new MathBrackets({ open: "|", close: "|", children: [new MathRun("x")] })], denominator: [new MathRun("2")], }); - expect(xml(new Formatter().format(fraction))).toContain(''); + expect(stringifyXmlable(new Formatter().format(fraction))).toContain(''); expect(toXml(new MathBrackets({ children: [new MathMatrix({ rows: [[[new MathRun("1")]]] })] }))).toContain(""); }); }); diff --git a/src/math/math-cases.spec.ts b/src/math/math-cases.spec.ts index 1dc4fb6576..792f03b0b4 100644 --- a/src/math/math-cases.spec.ts +++ b/src/math/math-cases.spec.ts @@ -1,13 +1,13 @@ import { describe, expect, it } from "vitest"; -import xml from "xml"; import { Formatter } from "@export/formatter"; +import { stringifyXmlable } from "@util/xml"; import { Math, MathRun } from "docx"; import { type MathCase, MathCases } from "./math-cases"; import { MathMatrix } from "./math-matrix"; -const toXml = (component: MathCases): string => xml(new Formatter().format(component)); +const toXml = (component: MathCases): string => stringifyXmlable(new Formatter().format(component)); const e = (text: string): string => `${text}`; const EMPTY = '\u200B'; diff --git a/src/math/math-equation-array.spec.ts b/src/math/math-equation-array.spec.ts index 0fa67cdb66..7d217b6b56 100644 --- a/src/math/math-equation-array.spec.ts +++ b/src/math/math-equation-array.spec.ts @@ -1,13 +1,13 @@ import { describe, expect, it } from "vitest"; -import xml from "xml"; import { Formatter } from "@export/formatter"; +import { stringifyXmlable } from "@util/xml"; import { Math, MathRun, MathSuperScript, TextRun } from "docx"; import { MathCases } from "./math-cases"; import { MathEquationArray, type MathEquationArrayOptions, type MathEquationArrayRow } from "./math-equation-array"; -const toXml = (component: MathEquationArray | MathCases): string => xml(new Formatter().format(component)); +const toXml = (component: MathEquationArray | MathCases): string => stringifyXmlable(new Formatter().format(component)); const r = (text: string): string => `${text}`; const AMP = r("&"); diff --git a/src/math/math-large-operator.spec.ts b/src/math/math-large-operator.spec.ts index 14ccdafb65..371cdff48e 100644 --- a/src/math/math-large-operator.spec.ts +++ b/src/math/math-large-operator.spec.ts @@ -1,12 +1,12 @@ import { describe, expect, it } from "vitest"; -import xml from "xml"; import { Formatter } from "@export/formatter"; +import { stringifyXmlable } from "@util/xml"; import { Math, MathRun } from "docx"; import { LARGE_OPERATORS, MathLargeOperator, type MathLargeOperatorName } from "./math-large-operator"; -const toXml = (component: MathLargeOperator): string => xml(new Formatter().format(component)); +const toXml = (component: MathLargeOperator): string => stringifyXmlable(new Formatter().format(component)); describe("MathLargeOperator", () => { it("writes the operator with its limits above and below, and what it applies to", () => { diff --git a/src/math/math-matrix.spec.ts b/src/math/math-matrix.spec.ts index f2891d2120..aea0b3b0bb 100644 --- a/src/math/math-matrix.spec.ts +++ b/src/math/math-matrix.spec.ts @@ -1,12 +1,12 @@ import { describe, expect, it } from "vitest"; -import xml from "xml"; import { Formatter } from "@export/formatter"; +import { stringifyXmlable } from "@util/xml"; import { Math, type MathComponent, MathFraction, MathRun } from "docx"; import { type MathColumnAlignment, MathMatrix, type MathMatrixBrackets, type MathMatrixOptions } from "./math-matrix"; -const toXml = (component: MathMatrix | MathFraction): string => xml(new Formatter().format(component)); +const toXml = (component: MathMatrix | MathFraction): string => stringifyXmlable(new Formatter().format(component)); const cell = (text: string): readonly MathComponent[] => [new MathRun(text)]; const e = (text: string): string => `${text}`; diff --git a/src/math/math-phantom.spec.ts b/src/math/math-phantom.spec.ts index ee223062ce..001352d623 100644 --- a/src/math/math-phantom.spec.ts +++ b/src/math/math-phantom.spec.ts @@ -1,12 +1,12 @@ import { describe, expect, it } from "vitest"; -import xml from "xml"; import { Formatter } from "@export/formatter"; +import { stringifyXmlable } from "@util/xml"; import { Math, MathRun } from "docx"; import { MathPhantom } from "./math-phantom"; -const toXml = (component: MathPhantom): string => xml(new Formatter().format(component)); +const toXml = (component: MathPhantom): string => stringifyXmlable(new Formatter().format(component)); describe("MathPhantom", () => { it("hides its children, which still take up their room, by default", () => { diff --git a/src/math/math-schema.spec.ts b/src/math/math-schema.spec.ts index 4c037177f5..56ed43ef80 100644 --- a/src/math/math-schema.spec.ts +++ b/src/math/math-schema.spec.ts @@ -1,8 +1,7 @@ import { describe, expect, it } from "vitest"; -import xml from "xml"; -import { type Element, xml2js } from "xml-js"; import { Formatter } from "@export/formatter"; +import { type XmlElement as Element, parseXml, stringifyXmlable } from "@util/xml"; import { Math, type MathComponent, MathFraction, MathIntegral, MathRun, MathSum, MathSuperScript } from "docx"; import { latexToMath } from "./latex-to-math"; @@ -21,7 +20,7 @@ import mathSchema from "../../ooxml-schemas/ISO-IEC29500-4_2016/shared-math.xsd? // The math schema, which docx/math's elements are checked against: each element's children are ones its type has, in // its type's order. The Open XML SDK validator checks this too, for the demos only -const schema = xml2js(mathSchema as string) as Element; +const schema = parseXml(mathSchema as string); const definitions = new Map( schema @@ -103,8 +102,8 @@ const problemsIn = (element: Element, type: string, path: string): readonly stri }; const problemsOf = (children: readonly MathComponent[]): readonly string[] => { - const written = xml(new Formatter().format(new Math({ children }))); - return problemsIn((xml2js(written) as Element).elements![0], "CT_OMath", "m:oMath"); + const written = stringifyXmlable(new Formatter().format(new Math({ children }))); + return problemsIn(parseXml(written).elements![0], "CT_OMath", "m:oMath"); }; const run = (text: string): MathRun => new MathRun(text); diff --git a/src/patcher/bookmark-ids.spec.ts b/src/patcher/bookmark-ids.spec.ts index 32569a19de..8d62e7eebe 100644 --- a/src/patcher/bookmark-ids.spec.ts +++ b/src/patcher/bookmark-ids.spec.ts @@ -1,5 +1,6 @@ import { describe, expect, it } from "vitest"; -import type { Element } from "xml-js"; + +import type { XmlElement as Element } from "@util/xml"; import { findBookmarkIds, renumberBookmarksAvoiding } from "./bookmark-ids"; import { toJson } from "./util"; diff --git a/src/patcher/bookmark-ids.ts b/src/patcher/bookmark-ids.ts index dd15d72b35..196d32e8fc 100644 --- a/src/patcher/bookmark-ids.ts +++ b/src/patcher/bookmark-ids.ts @@ -3,7 +3,7 @@ * * @module */ -import type { Element } from "xml-js"; +import type { XmlElement as Element } from "@util/xml"; /** * Renumbers the bookmarks in content that is about to be inserted into a document. diff --git a/src/patcher/content-types-manager.ts b/src/patcher/content-types-manager.ts index a73c3a81a0..ed9ca8b6cc 100644 --- a/src/patcher/content-types-manager.ts +++ b/src/patcher/content-types-manager.ts @@ -3,7 +3,8 @@ * * @module */ -import type { Element } from "xml-js"; + +import type { XmlElement as Element } from "@util/xml"; import { getFirstLevelElements } from "./util"; diff --git a/src/patcher/drawing-ids.spec.ts b/src/patcher/drawing-ids.spec.ts index b638dfe7ce..82e91be370 100644 --- a/src/patcher/drawing-ids.spec.ts +++ b/src/patcher/drawing-ids.spec.ts @@ -1,5 +1,6 @@ import { describe, expect, it } from "vitest"; -import type { Element } from "xml-js"; + +import type { XmlElement as Element } from "@util/xml"; import { findDrawingIds, renumberDrawingsAvoiding } from "./drawing-ids"; import { toJson } from "./util"; diff --git a/src/patcher/drawing-ids.ts b/src/patcher/drawing-ids.ts index 7e52fa89d0..65b75f9e85 100644 --- a/src/patcher/drawing-ids.ts +++ b/src/patcher/drawing-ids.ts @@ -3,7 +3,7 @@ * * @module */ -import type { Element } from "xml-js"; +import type { XmlElement as Element } from "@util/xml"; /** * Renumbers the drawings in content that is about to be inserted into a document. diff --git a/src/patcher/drawing-patch.spec.ts b/src/patcher/drawing-patch.spec.ts index 25abf7f9b6..1089a51309 100644 --- a/src/patcher/drawing-patch.spec.ts +++ b/src/patcher/drawing-patch.spec.ts @@ -1,11 +1,11 @@ /* eslint-disable @typescript-eslint/naming-convention -- The keys of objects here are paths of parts in a package */ import JSZip from "jszip"; import { describe, expect, it } from "vitest"; -import type { Element } from "xml-js"; import { PackagePart } from "@file/package-part"; import { ExternalHyperlink, ImageRun, TextRun } from "@file/paragraph"; import { BuilderElement } from "@file/xml-components"; +import type { XmlElement as Element } from "@util/xml"; import { DrawingPatch, diff --git a/src/patcher/drawing-patch.ts b/src/patcher/drawing-patch.ts index 77243aea99..23e0cc10cd 100644 --- a/src/patcher/drawing-patch.ts +++ b/src/patcher/drawing-patch.ts @@ -7,13 +7,12 @@ * @module */ // cspell:ignore descr -import xml from "xml"; -import type { Element } from "xml-js"; import { Formatter } from "@export/formatter"; import type { File } from "@file/file"; import type { PackagePart } from "@file/package-part"; import type { IContext, XmlComponent } from "@file/xml-components"; +import { type XmlElement as Element, stringifyXmlable } from "@util/xml"; import { removeContentTypeOverride } from "./content-types-manager"; import { PatchType } from "./patch-type"; @@ -320,7 +319,7 @@ const createTemplatePackage = ( return String(relationship.attributes.Id); }, - format: (content) => toJson(xml(formatter.format(content, context))).elements![0], + format: (content) => toJson(stringifyXmlable(formatter.format(content, context))).elements![0], }; }; diff --git a/src/patcher/from-docx.ts b/src/patcher/from-docx.ts index d5ce52406d..fcaaba1d65 100644 --- a/src/patcher/from-docx.ts +++ b/src/patcher/from-docx.ts @@ -7,7 +7,6 @@ * @module */ import JSZip from "jszip"; -import { type Element, js2xml } from "xml-js"; import { ImageReplacer } from "@export/packer/image-replacer"; import { xmlifyPackageParts } from "@export/packer/package-part-writer"; @@ -25,6 +24,7 @@ import { type RelationshipType, TargetModeType } from "@file/relationships/relat import type { IContext } from "@file/xml-components"; import { encodeUtf8, uniqueId } from "@util/convenience-functions"; import type { OutputByType, OutputType } from "@util/output-type"; +import { type XmlElement as Element, stringifyElement } from "@util/xml"; import { findBookmarkIds, renumberBookmarksAvoiding } from "./bookmark-ids"; import { appendContentType, appendContentTypeOverride } from "./content-types-manager"; @@ -643,7 +643,7 @@ export const patchDocument = async ({ - ...element, - ...(element.attributes === undefined - ? {} - : { - attributes: Object.fromEntries( - Object.entries(element.attributes).map(([key, value]) => [ - key, - value === undefined ? value : String(value).replace(/&/g, "&"), - ]), - ), - }), - ...(element.elements === undefined - ? {} - : { - elements: element.elements.map((child) => - child.type === "text" ? { ...child, text: String(child.text).replace(/&/g, "&") } : withAmpersandsEscaped(child), - ), - }), -}); - -const toXml = (jsonObj: Element): string => { - const output = js2xml(withAmpersandsEscaped(jsonObj), { - // xml-js has already escaped the quotes, and withAmpersandsEscaped each "&" - attributeValueFn: (str) => String(str).replace(//g, ">").replace(/'/g, "'"), // cspell:words apos - }); - return output; -}; diff --git a/src/patcher/notes.ts b/src/patcher/notes.ts index ea5749ea0a..acd43cf8a0 100644 --- a/src/patcher/notes.ts +++ b/src/patcher/notes.ts @@ -3,8 +3,6 @@ * * @module */ -import xml from "xml"; -import type { Element } from "xml-js"; import { Formatter } from "@export/formatter"; import { EndnoteRefRun } from "@file/endnotes/endnote/run/endnote-ref-run"; @@ -23,6 +21,7 @@ import { } from "@file/styles/style/default-styles"; import type { IContext, XmlComponent } from "@file/xml-components"; import { uniqueId } from "@util/convenience-functions"; +import { type XmlElement as Element, stringifyXmlable } from "@util/xml"; import type { RenumberBookmarks } from "./bookmark-ids"; import type { RenumberDrawings } from "./drawing-ids"; @@ -127,7 +126,7 @@ export type NotesPatcher = { }; const formatElement = (component: XmlComponent, context: IContext): Element => - toJson(xml(formatter.format(component, context))).elements![0]; + toJson(stringifyXmlable(formatter.format(component, context))).elements![0]; const findIds = (element: Element, names: readonly string[]): readonly number[] => { const id = names.includes(element.name ?? "") ? Number(element.attributes?.["w:id"]) : NaN; diff --git a/src/patcher/numbering.ts b/src/patcher/numbering.ts index ed2060bbdb..33076292bb 100644 --- a/src/patcher/numbering.ts +++ b/src/patcher/numbering.ts @@ -3,13 +3,12 @@ * * @module */ -import xml from "xml"; -import type { Element } from "xml-js"; import { Formatter } from "@export/formatter"; import type { ConcreteNumbering, Numbering } from "@file/numbering"; import type { IContext, XmlComponent } from "@file/xml-components"; import { uniqueId } from "@util/convenience-functions"; +import { type XmlElement as Element, stringifyXmlable } from "@util/xml"; import { relationshipsPathOf, relativeTarget, resolveTarget } from "./drawing-patch"; import { getFirstLevelElements, toJson } from "./util"; @@ -53,7 +52,7 @@ export type NumberingPatcher = { }; const formatElement = (component: XmlComponent, context: IContext): Element => - toJson(xml(formatter.format(component, context))).elements![0]; + toJson(stringifyXmlable(formatter.format(component, context))).elements![0]; const highestOf = (ids: readonly number[]): number => ids.reduce((highest, id) => Math.max(highest, id), 0); diff --git a/src/patcher/page-numbers.spec.ts b/src/patcher/page-numbers.spec.ts index a43c25d1a0..fd49a38f14 100644 --- a/src/patcher/page-numbers.spec.ts +++ b/src/patcher/page-numbers.spec.ts @@ -1,6 +1,7 @@ import JSZip from "jszip"; import { describe, expect, it, vi } from "vitest"; -import { type Element, js2xml } from "xml-js"; + +import { type XmlElement as Element, stringifyElement } from "@util/xml"; import { type PatchedTemplate, fillTemplatePageNumbers } from "./page-numbers"; import { toJson } from "./util"; @@ -23,7 +24,7 @@ const sectionEnd = (references: string): string => `${refe /** The text of a part, with each field's result where it is */ const textOf = (part: Element): string => - js2xml(part) + stringifyElement(part) .replace(/]*>[^<]*<\/w:instrText>/g, "") .replace(/]*>([^<]*)<\/w:t>|]*\/>|<[^>]+>/g, "$1"); @@ -101,7 +102,7 @@ describe("fillTemplatePageNumbers", () => { ], ]); await fillTemplatePageNumbers(parts, () => ({ bookmarks: new Map([["_Toc1", "3"]]) })); - const document = js2xml(parts.get("word/document.xml")!); + const document = stringifyElement(parts.get("word/document.xml")!); expect(document.match(/]*w:fldCharType="begin"[^>]*\/>/g)).to.deep.equal([ '', '', @@ -140,7 +141,7 @@ describe("fillTemplatePageNumbers", () => { const outer = await zipOf( new Map([ ["word/document.xml", ``], - ["word/_rels/document.xml.rels", js2xml(relationships(["rId1", "inner.docx"]))], + ["word/_rels/document.xml.rels", stringifyElement(relationships(["rId1", "inner.docx"]))], ["word/inner.docx", ""], ["word/media/image1.png", "png"], ["word/folder/", ""], @@ -186,7 +187,7 @@ describe("fillTemplatePageNumbers", () => { const inner = await zipOf(new Map([["word/document.xml", ``]])); const outer = new JSZip(); outer.file("word/document.xml", ``); - outer.file("word/_rels/document.xml.rels", js2xml(relationships(["rId1", "inner.docx"]))); + outer.file("word/_rels/document.xml.rels", stringifyElement(relationships(["rId1", "inner.docx"]))); outer.file("word/inner.docx", inner); const parts = new Map([ ["word/document.xml", toJson(``)], diff --git a/src/patcher/page-numbers.ts b/src/patcher/page-numbers.ts index 9fc24359d2..42cc2b750e 100644 --- a/src/patcher/page-numbers.ts +++ b/src/patcher/page-numbers.ts @@ -5,10 +5,10 @@ * @module */ import JSZip from "jszip"; -import type { Element } from "xml-js"; import { type ElementTree, fillBodyFields, fillPartFields } from "@file/document/body/page-number-fields"; import type { EstimatedPageNumbers } from "@file/document/body/page-numbers"; +import type { XmlElement as Element } from "@util/xml"; import { relationshipsPathOf, resolveTarget, sourceOfRelationships } from "./drawing-patch"; import { toJson } from "./util"; @@ -21,8 +21,8 @@ import { toJson } from "./util"; export type PatchedTemplate = { /** * Each XML part of the template's package, by its path in the package, such as "word/document.xml". Each is parsed as - * `patchDocument` parses it, with xml-js's `xml2js`, not compact, and keeping the spaces between elements - * (`captureSpacesBetweenElements`), as the spaces in a text element are its text + * `patchDocument` parses it, with `parseXml` keeping the text that is only whitespace (`keepWhitespaceText`), as the + * spaces in a text element are its text */ readonly parts: ReadonlyMap; /** Each of its other parts, such as its pictures and the fonts it embeds, by its path in the package, as bytes */ @@ -45,7 +45,7 @@ export type PatchedTemplate = { */ export type TemplatePageNumberEstimator = (template: PatchedTemplate) => EstimatedPageNumbers; -/** The elements of a template, as xml-js parses them */ +/** The elements of a template, as `parseXml` reads them */ const PARSED: ElementTree = { nameOf: (element) => (element.type === "element" ? element.name : undefined), contentOf: (element) => element.elements, diff --git a/src/patcher/paragraph-split-inject.ts b/src/patcher/paragraph-split-inject.ts index e46baba3d0..be4f2dd162 100644 --- a/src/patcher/paragraph-split-inject.ts +++ b/src/patcher/paragraph-split-inject.ts @@ -3,7 +3,8 @@ * * @module */ -import type { Element } from "xml-js"; + +import type { XmlElement as Element } from "@util/xml"; import { createTextElementContents, patchSpaceAttribute } from "./util"; diff --git a/src/patcher/paragraph-token-replacer.ts b/src/patcher/paragraph-token-replacer.ts index 5629716601..4d1e7ecbef 100644 --- a/src/patcher/paragraph-token-replacer.ts +++ b/src/patcher/paragraph-token-replacer.ts @@ -3,7 +3,8 @@ * * @module */ -import type { Element } from "xml-js"; + +import type { XmlElement as Element } from "@util/xml"; import type { IRenderedParagraphNode } from "./run-renderer"; import { createTextElementContents, patchSpaceAttribute } from "./util"; diff --git a/src/patcher/relationship-manager.ts b/src/patcher/relationship-manager.ts index dc3abb4a35..f57ad67ed6 100644 --- a/src/patcher/relationship-manager.ts +++ b/src/patcher/relationship-manager.ts @@ -3,9 +3,9 @@ * * @module */ -import type { Element } from "xml-js"; import type { RelationshipType, TargetModeType } from "@file/relationships/relationship/relationship"; +import type { XmlElement as Element } from "@util/xml"; import { getFirstLevelElements } from "./util"; diff --git a/src/patcher/replacer.spec.ts b/src/patcher/replacer.spec.ts index 1197ecdaea..12eb3e7650 100644 --- a/src/patcher/replacer.spec.ts +++ b/src/patcher/replacer.spec.ts @@ -1,5 +1,4 @@ import { describe, expect, it, vi } from "vitest"; -import type { Element } from "xml-js"; import type { IViewWrapper } from "@file/document-wrapper"; import type { File } from "@file/file"; @@ -8,6 +7,7 @@ import { FootnoteReferenceRun } from "@file/footnotes/footnote/run/reference-run import { Bookmark, ConcreteHyperlink, Paragraph, type ParagraphChild, TextRun } from "@file/paragraph"; import { WpsShapeRun } from "@file/paragraph/run/wps-shape-run"; import { Table, TableCell, TableRow } from "@file/table"; +import type { XmlElement as Element } from "@util/xml"; import { PatchType } from "./from-docx"; import { replacer } from "./replacer"; diff --git a/src/patcher/replacer.ts b/src/patcher/replacer.ts index e6f08bd01a..da9974f298 100644 --- a/src/patcher/replacer.ts +++ b/src/patcher/replacer.ts @@ -3,10 +3,9 @@ * * @module */ -import xml from "xml"; -import type { Element } from "xml-js"; import type { IContext, XmlComponent } from "@file/xml-components"; +import { type XmlElement as Element, stringifyXmlable } from "@util/xml"; import { type IPatch, PatchType } from "./from-docx"; import { findRunElementIndexWithToken, splitRunElement } from "./paragraph-split-inject"; @@ -134,7 +133,7 @@ const formatChildren = (patch: IPatch, context: IContext, renumberIds: RenumberI // A child written as nothing in this part, such as a footnote's reference in a header, is left out .flatMap((c) => { const formatted = c.prepForXml(context); - return formatted ? [toJson(xml(formatted)).elements![0]] : []; + return formatted ? [toJson(stringifyXmlable(formatted)).elements![0]] : []; }), ); diff --git a/src/patcher/run-renderer.ts b/src/patcher/run-renderer.ts index 006641a8a0..ec41b2f4a3 100644 --- a/src/patcher/run-renderer.ts +++ b/src/patcher/run-renderer.ts @@ -3,7 +3,8 @@ * * @module */ -import type { Element } from "xml-js"; + +import type { XmlElement as Element } from "@util/xml"; import type { ElementWrapper } from "./traverser"; diff --git a/src/patcher/styles.ts b/src/patcher/styles.ts index 6f5278932f..c9329adb02 100644 --- a/src/patcher/styles.ts +++ b/src/patcher/styles.ts @@ -3,12 +3,11 @@ * * @module */ -import xml from "xml"; -import type { Element } from "xml-js"; import { Formatter } from "@export/formatter"; import { createDefaultStyles } from "@file/styles/factory"; import type { IContext } from "@file/xml-components"; +import { type XmlElement as Element, stringifyXmlable } from "@util/xml"; import { getFirstLevelElements, toJson } from "./util"; @@ -43,7 +42,7 @@ const nameOf = (style: Element): string | undefined => { const formatDefaultStyles = (context: IContext): ReadonlyMap => new Map( Object.values(createDefaultStyles()) - .map((style) => toJson(xml(formatter.format(style, context))).elements![0]) + .map((style) => toJson(stringifyXmlable(formatter.format(style, context))).elements![0]) // Rather than the document's defaults, which aren't a style .filter((style) => style.name === "w:style") .map((style) => [idOf(style), style]), diff --git a/src/patcher/table-rows.spec.ts b/src/patcher/table-rows.spec.ts index ed4da81720..6d09d1445d 100644 --- a/src/patcher/table-rows.spec.ts +++ b/src/patcher/table-rows.spec.ts @@ -1,9 +1,9 @@ import { describe, expect, it } from "vitest"; -import { js2xml } from "xml-js"; import type { IViewWrapper } from "@file/document-wrapper"; import type { File } from "@file/file"; import { Paragraph, TextRun } from "@file/paragraph"; +import { stringifyElement } from "@util/xml"; import { findDrawingIds, renumberDrawingsAvoiding } from "./drawing-ids"; import type { IPatch, TableRowsPatch } from "./from-docx"; @@ -50,7 +50,7 @@ const tablesOf = (json: ReturnType): readonly (readonly (readonly t.elements!.filter((e) => e.name === "w:tr").map((r) => r.elements!.map((c) => traverse({ elements: [c] })[0]?.text ?? "")), ); -const xmlOf = (json: ReturnType): string => js2xml(json); +const xmlOf = (json: ReturnType): string => stringifyElement(json); const ITEMS: TableRowsPatch = { type: PatchType.TABLE_ROWS, @@ -224,7 +224,7 @@ describe("patchTableRows", () => { const [first, second] = json .elements![0].elements![0].elements!.filter((e) => e.name === "w:tr") - .map((r) => js2xml({ elements: [r] })); + .map((r) => stringifyElement({ elements: [r] })); expect(first).to.contain('w14:paraId="00000001"').and.contain('w14:paraId="00000003"').and.contain(''); expect(first).to.contain('').and.contain(''); expect(second).not.to.match(/paraId|textId|w:id|bookmark/); diff --git a/src/patcher/table-rows.ts b/src/patcher/table-rows.ts index fc9e11824f..186d7bf158 100644 --- a/src/patcher/table-rows.ts +++ b/src/patcher/table-rows.ts @@ -3,7 +3,8 @@ * * @module */ -import type { Element } from "xml-js"; + +import type { XmlElement as Element } from "@util/xml"; import type { RenumberDrawings } from "./drawing-ids"; import type { IPatch, TableRowsPatch } from "./from-docx"; diff --git a/src/patcher/theme-colors.ts b/src/patcher/theme-colors.ts index a904796474..9e8dd7fb67 100644 --- a/src/patcher/theme-colors.ts +++ b/src/patcher/theme-colors.ts @@ -6,10 +6,10 @@ */ // cspell:ignore hlink Hlink import type JSZip from "jszip"; -import type { Element } from "xml-js"; import { type ThemeColorValues, themeColorValues } from "@file/theme/color-scheme"; import type { ThemeColorName } from "@file/theme/theme-color"; +import type { XmlElement as Element } from "@util/xml"; import { resolveTarget } from "./drawing-patch"; import { toJson } from "./util"; diff --git a/src/patcher/traverser.ts b/src/patcher/traverser.ts index 02d94dee24..1ae29aa270 100644 --- a/src/patcher/traverser.ts +++ b/src/patcher/traverser.ts @@ -3,7 +3,8 @@ * * @module */ -import type { Element } from "xml-js"; + +import type { XmlElement as Element } from "@util/xml"; import { type IRenderedParagraphNode, renderParagraphNode } from "./run-renderer"; diff --git a/src/patcher/util.ts b/src/patcher/util.ts index 43b93d09ee..4c6f4edff5 100644 --- a/src/patcher/util.ts +++ b/src/patcher/util.ts @@ -3,11 +3,10 @@ * * @module */ -import xml from "xml"; -import { type Element, xml2js } from "xml-js"; import { Formatter } from "@export/formatter"; import { Text } from "@file/paragraph/run/run-components/text"; +import { type XmlElement as Element, parseXml, stringifyXmlable } from "@util/xml"; const formatter = new Formatter(); @@ -27,7 +26,7 @@ const formatter = new Formatter(); * ``` */ export const toJson = (xmlData: string): Element => { - const xmlObj = xml2js(xmlData, { compact: false, captureSpacesBetweenElements: true }) as Element; + const xmlObj = parseXml(xmlData, { keepWhitespaceText: true }); return xmlObj; }; @@ -49,7 +48,7 @@ export const toJson = (xmlData: string): Element => { */ // eslint-disable-next-line functional/prefer-readonly-type export const createTextElementContents = (text: string): Element[] => { - const textJson = toJson(xml(formatter.format(new Text({ text })))); + const textJson = toJson(stringifyXmlable(formatter.format(new Text({ text })))); return textJson.elements![0].elements ?? []; }; diff --git a/src/tests/html.ts b/src/tests/html.ts index 1fa49f7de3..93019832cc 100644 --- a/src/tests/html.ts +++ b/src/tests/html.ts @@ -8,7 +8,6 @@ // cspell:ignore IHDR IDAT IEND import JSZip from "jszip"; import { deflateSync } from "node:zlib"; -import xml from "xml"; import { Formatter } from "@export/formatter"; import { Packer } from "@export/packer/packer"; @@ -16,6 +15,7 @@ import { File } from "@file/file"; import type { Paragraph } from "@file/paragraph"; import type { Table } from "@file/table"; import type { IContext } from "@file/xml-components"; +import { stringifyXmlable } from "@util/xml"; /** * Written content with its ids made the same each time: relationships', bookmarks', tracked changes' and drawings' @@ -37,7 +37,7 @@ const contextOf = (): IContext => { /** Paragraphs and tables written as WordprocessingML, in one document */ export const written = (children: readonly (Paragraph | Table)[]): string => { const context = contextOf(); - return children.map((child) => xml(new Formatter().format(child, context))).join(""); + return children.map((child) => stringifyXmlable(new Formatter().format(child, context))).join(""); }; /** @@ -53,10 +53,10 @@ export const formattedWithNotes = ( children: readonly (Paragraph | Table)[], ): { readonly body: string; readonly footnotes: string; readonly endnotes: string } => { const context = contextOf(); - const body = children.map((child) => xml(new Formatter().format(child, context))).join(""); + const body = children.map((child) => stringifyXmlable(new Formatter().format(child, context))).join(""); const notesOf = (wrapper: typeof context.file.FootNotes | typeof context.file.Endnotes, kind: string): string => [ - ...xml(new Formatter().format(wrapper.View, { ...context, viewWrapper: wrapper })).matchAll( + ...stringifyXmlable(new Formatter().format(wrapper.View, { ...context, viewWrapper: wrapper })).matchAll( new RegExp(`.*?`, "g"), ), ] diff --git a/src/util/index.ts b/src/util/index.ts index b5675ded35..73c27fe117 100644 --- a/src/util/index.ts +++ b/src/util/index.ts @@ -9,3 +9,4 @@ export * from "./convenience-functions"; export * from "./values"; export type * from "./output-type"; +export type * from "./xml/types"; diff --git a/src/util/xml/corpus.spec.ts b/src/util/xml/corpus.spec.ts new file mode 100644 index 0000000000..ddff37dc35 --- /dev/null +++ b/src/util/xml/corpus.spec.ts @@ -0,0 +1,142 @@ +import JSZip from "jszip"; +import type { ImportGlobFunction } from "vite"; +import { describe, expect, it } from "vitest"; + +import { parseXml } from "./parse"; +import { stringifyElement } from "./stringify"; +import type { XmlElement } from "./types"; + +/** + * Checks parseXml and stringifyElement against every XML part in the repository: the parts of each Word document, such + * as those Word saved for the layout probes, and the OOXML schemas. jsdom's DOMParser, a separate XML parser, says what + * each part holds, so a mistake parseXml and stringifyElement make alike still shows. + */ + +declare global { + // Vite's own types for import.meta, vite/client, would type every "?raw" import, which other specs expect not to be + // typed + // eslint-disable-next-line @typescript-eslint/consistent-type-definitions + interface ImportMeta { + readonly glob: ImportGlobFunction; + } +} + +// Vite gives each document as a data URL, and each schema as text +const documents = import.meta.glob(["/demo/assets/*.{docx,dotx}", "/scripts/layout-probes/**/*.docx"], { + query: "?inline", + import: "default", +}); +const texts = import.meta.glob(["/ooxml-schemas/**/*.xsd", "/demo/assets/*.xml"], { + query: "?raw", + import: "default", + eager: true, +}); + +/** + * The largest part read. The parts over it, a dozen of the layout probes' documents, each repeat one run thousands of + * times to measure Word's character widths. They hold nothing the smaller parts don't, and jsdom takes seconds over each. + */ +const MAX_PART_LENGTH = 1_000_000; + +const partsOf = async (dataUrl: string): Promise> => { + const zip = await JSZip.loadAsync(dataUrl.slice(dataUrl.indexOf(",") + 1), { base64: true }); + const names = Object.keys(zip.files).filter((name) => name.endsWith(".xml") || name.endsWith(".rels")); + const parts = await Promise.all(names.map(async (name) => [name, await zip.file(name)!.async("string")] as const)); + return new Map(parts.filter(([, xml]) => xml.length <= MAX_PART_LENGTH)); +}; + +/** A node of the DOM as parseXml reads it */ +const fromDom = (node: Node): XmlElement | undefined => { + switch (node.nodeType) { + case Node.ELEMENT_NODE: { + const element = node as Element; + const attributes = Object.fromEntries([...element.attributes].map(({ name, value }) => [name, value])); + const elements = [...element.childNodes].map(fromDom).filter((child) => child !== undefined); + return { + type: "element", + name: element.tagName, + ...(Object.keys(attributes).length > 0 ? { attributes } : {}), + ...(elements.length > 0 ? { elements } : {}), + }; + } + case Node.TEXT_NODE: + return { type: "text", text: (node as Text).data }; + case Node.CDATA_SECTION_NODE: + return (node as CDATASection).data === "" ? undefined : { type: "cdata", cdata: (node as CDATASection).data }; + case Node.COMMENT_NODE: + return (node as Comment).data === "" ? undefined : { type: "comment", comment: (node as Comment).data }; + case Node.PROCESSING_INSTRUCTION_NODE: + return { type: "instruction", name: (node as ProcessingInstruction).target, instruction: (node as ProcessingInstruction).data }; + default: + return { type: "doctype" }; + } +}; + +/** + * A node with each line break as "\n". XML parsers such as jsdom's read "\r\n" as "\n", but parseXml keeps it, as + * xml-js did, so that patchDocument writes a template's text back as it was. + */ +const withLineFeeds = (node: XmlElement): XmlElement => { + const lineFeeds = (value: string): string => value.replace(/\r\n?/g, "\n"); + switch (node.type) { + case "element": + return { + ...node, + ...(node.attributes + ? { + attributes: Object.fromEntries( + Object.entries(node.attributes).map(([key, value]) => [key, lineFeeds(String(value))]), + ), + } + : {}), + ...(node.elements ? { elements: node.elements.map(withLineFeeds) } : {}), + }; + case "text": + return { ...node, text: lineFeeds(String(node.text)) }; + case "cdata": + return { ...node, cdata: lineFeeds(node.cdata!) }; + case "comment": + return { ...node, comment: lineFeeds(node.comment!) }; + case "instruction": + return { ...node, instruction: lineFeeds(node.instruction!) }; + default: + // The DOM keeps a DOCTYPE's name and identifiers, not its text + return { type: node.type }; + } +}; + +/** + * The nodes of a document as the DOM has them: without the declaration, which the DOM has no node for, or the whitespace + * between the top-level nodes + */ +const comparable = (document: XmlElement): readonly XmlElement[] => + (document.elements ?? []).filter(({ type }) => type !== "text").map(withLineFeeds); + +const check = (xml: string, part: string): void => { + const dom = new DOMParser().parseFromString(xml, "application/xml"); + expect(dom.getElementsByTagName("parsererror"), `jsdom can't read ${part}`).to.have.length(0); + + const parsed = parseXml(xml, { keepWhitespaceText: true }); + expect(comparable(parsed), part).to.deep.equal([...dom.childNodes].map(fromDom)); + expect(parseXml(stringifyElement(parsed), { keepWhitespaceText: true }), `${part}, written and read again`).to.deep.equal(parsed); +}; + +describe("parseXml and stringifyElement with the repository's XML", () => { + describe("documents", () => { + for (const [path, load] of Object.entries(documents)) { + it(`should read and write each part of ${path} as jsdom reads it`, async () => { + for (const [name, xml] of await partsOf(await load())) { + check(xml, name); + } + }); + } + }); + + describe("schemas", () => { + for (const [path, xml] of Object.entries(texts)) { + it(`should read and write ${path} as jsdom reads it`, () => { + check(xml, path); + }); + } + }); +}); diff --git a/src/util/xml/index.ts b/src/util/xml/index.ts new file mode 100644 index 0000000000..2155ace2f9 --- /dev/null +++ b/src/util/xml/index.ts @@ -0,0 +1,8 @@ +/** + * Reading and writing XML. + * + * @module + */ +export * from "./parse"; +export * from "./stringify"; +export type * from "./types"; diff --git a/src/util/xml/parse.spec.ts b/src/util/xml/parse.spec.ts new file mode 100644 index 0000000000..67461865de --- /dev/null +++ b/src/util/xml/parse.spec.ts @@ -0,0 +1,177 @@ +import { describe, expect, it } from "vitest"; + +import { parseXml } from "./parse"; + +describe("parseXml", () => { + describe("the document", () => { + it("should read the declaration's attributes, in either quotes, before the nodes", () => { + const document = parseXml(``); + expect(document).to.deep.equal({ + declaration: { attributes: { version: "1.0", encoding: "UTF-8", standalone: "yes" } }, + elements: [{ type: "element", name: "a" }], + }); + expect(Object.keys(document)).to.deep.equal(["declaration", "elements"]); + }); + + it("should read a declaration without attributes", () => { + expect(parseXml("")).to.deep.equal({ declaration: {}, elements: [{ type: "element", name: "a" }] }); + }); + + it("should read nothing from an empty string", () => { + expect(parseXml("")).to.deep.equal({}); + }); + + it("should skip a byte order mark and the whitespace before the first tag", () => { + expect(parseXml("\uFEFF \r\n", { keepWhitespaceText: true })).to.deep.equal({ elements: [{ type: "element", name: "a" }] }); + }); + + it("should read elements one after another at the top level", () => { + expect(parseXml("")).to.deep.equal({ + elements: [ + { type: "element", name: "a" }, + { type: "element", name: "b" }, + ], + }); + }); + }); + + describe("elements", () => { + it("should read nested elements and their attributes", () => { + expect(parseXml(`Hi`)).to.deep.equal({ + elements: [ + { + type: "element", + name: "w:p", + attributes: { "w14:paraId": "1A" }, + elements: [ + { + type: "element", + name: "w:r", + elements: [ + { + type: "element", + name: "w:t", + attributes: { "xml:space": "preserve" }, + elements: [{ type: "text", text: "Hi" }], + }, + ], + }, + { type: "element", name: "w:r" }, + ], + }, + ], + }); + }); + + it("should allow whitespace between attributes, around their equals signs and in tags", () => { + expect(parseXml(``).elements).to.deep.equal([ + { type: "element", name: "a", attributes: { b: "1", c: "2" } }, + { type: "element", name: "d" }, + ]); + }); + + it("should keep the first of attributes with the same name", () => { + expect(parseXml(``).elements![0].attributes).to.deep.equal({ b: "1" }); + }); + + it("should decode entities in attributes, and keep their whitespace", () => { + expect(parseXml(``).elements![0].attributes).to.deep.equal({ b: '&"<\n\tA' }); + }); + + it("should read an attribute named __proto__ as an attribute, not the prototype", () => { + const { attributes } = parseXml(``).elements![0]; + expect(Object.keys(attributes!)).to.deep.equal(["__proto__", "constructor"]); + expect(Object.getPrototypeOf(attributes)).to.equal(Object.prototype); + }); + + it("should throw for elements that aren't well formed", () => { + expect(() => parseXml("")).to.throw(" isn't closed"); + expect(() => parseXml(" that isn't closed"); + expect(() => parseXml(` that isn't closed"); + expect(() => parseXml("<>")).to.throw("tag without a name"); + expect(() => parseXml("")).to.throw("closing tag doesn't match "); + expect(() => parseXml("")).to.throw("closing tag doesn't match <>"); + expect(() => parseXml(" { + expect(() => parseXml("")).to.throw("attribute of without a value"); + expect(() => parseXml(``)).to.throw("attribute of without a value"); + expect(() => parseXml(``)).to.throw("attribute of without a value"); + expect(() => parseXml("")).to.throw("value of b on isn't quoted"); + expect(() => parseXml(` isn't closed"); + }); + }); + + describe("text", () => { + it("should decode the entities XML predefines and character references", () => { + expect(parseXml("&<>"'ABC😀").elements![0].elements).to.deep.equal([ + { type: "text", text: `&<>"'ABC\u{1F600}` }, + ]); + }); + + it("should throw for an entity XML doesn't predefine, or a character reference to no character", () => { + expect(() => parseXml(" ")).to.throw('unknown entity " "'); + expect(() => parseXml("�")).to.throw('unknown entity "�"'); + expect(() => parseXml("�")).to.throw('unknown entity "�"'); + expect(() => parseXml("&#xZ;")).to.throw('unknown entity "&#xZ;"'); + }); + + it("should throw for an & that starts no entity", () => { + expect(() => parseXml("Fish & chips")).to.throw('"&" that starts no entity'); + }); + + it("should leave out text that is only whitespace, unless told to keep it", () => { + const xml = `\r\n \n\n`; + expect(parseXml(xml).elements).to.deep.equal([{ type: "element", name: "a", elements: [{ type: "element", name: "b" }] }]); + expect(parseXml(xml, { keepWhitespaceText: true }).elements).to.deep.equal([ + { type: "text", text: "\r\n" }, + { + type: "element", + name: "a", + elements: [ + { type: "text", text: " " }, + { type: "element", name: "b" }, + { type: "text", text: "\n" }, + ], + }, + { type: "text", text: "\n" }, + ]); + }); + + it("should throw for text outside of the root element", () => { + expect(() => parseXml("text")).to.throw('text outside of the root element, "text"'); + expect(() => parseXml("text")).to.throw('text outside of the root element, "text"'); + }); + }); + + describe("other nodes", () => { + it("should read processing instructions, with and without a body", () => { + expect(parseXml(``).elements).to.deep.equal([ + { type: "instruction", name: "mso-application", instruction: 'progid="Word.Document"' }, + { type: "element", name: "a", elements: [{ type: "instruction", name: "pi", instruction: "" }] }, + ]); + }); + + it("should read comments and CDATA sections, leaving out empty ones", () => { + expect(parseXml("").elements![0].elements).to.deep.equal([ + { type: "comment", comment: " c " }, + { type: "cdata", cdata: "x and ] in its internal subset and quotes", () => { + expect(parseXml(`"> ]>`).elements).to.deep.equal([ + { type: "doctype", doctype: `a [ "> ]` }, + { type: "element", name: "a" }, + ]); + }); + + it("should throw for nodes that aren't closed", () => { + expect(() => parseXml(" parseXml("", tagStart + 4, "comment"); + const comment = text.slice(tagStart + 4, end); + if (comment !== "") { + append({ type: "comment", comment }); + } + position = end + 3; + } else if (text.startsWith("", tagStart + 9, "CDATA section"); + const cdata = text.slice(tagStart + 9, end); + if (cdata !== "") { + append({ type: "cdata", cdata }); + } + position = end + 3; + } else if (text.startsWith("" that isn't in its internal subset, between "[" and "]", or quoted + let end = tagStart + 9; + let quote: string | undefined; + let inSubset = false; + for (; end < text.length; end++) { + const char = text[end]; + if (quote !== undefined) { + quote = char === quote ? undefined : quote; + } else if (char === '"' || char === "'") { + quote = char; + } else if (char === "[") { + inSubset = true; + } else if (char === "]") { + inSubset = false; + } else if (char === ">" && !inSubset) { + break; + } + } + if (end === text.length) { + throw new Error("Invalid XML: DOCTYPE that isn't closed"); + } + append({ type: "doctype", doctype: text.slice(tagStart + 9, end).replace(/^ /, "") }); + position = end + 1; + } else if (text.startsWith("", tagStart + 2, "closing tag"); + const name = text.slice(tagStart + 2, end).trimEnd(); + // eslint-disable-next-line functional/immutable-data + const element = open.pop(); + if (element?.name !== name) { + throw new Error(`Invalid XML: closing tag doesn't match <${element?.name ?? ""}>`); + } + position = end + 1; + } else { + position = parseStartTag(text, tagStart + 1, (element, selfClosing) => { + append(element); + if (!selfClosing) { + // eslint-disable-next-line functional/immutable-data + open.push(element); + } + }); + } + } + + if (open.length > 0) { + throw new Error(`Invalid XML: <${open[open.length - 1].name}> isn't closed`); + } + + // xml-js gave the declaration before the nodes + const { elements, ...rest } = document; + return elements === undefined ? rest : { ...rest, elements }; +}; + +/** + * Reads a start tag from just after its "<", such as `w:p w14:paraId="1A2B3C4D">` or `w:br/>`. + * + * @returns The position just after the tag's ">" + */ +const parseStartTag = (text: string, from: number, onElement: (element: XmlElement, selfClosing: boolean) => void): number => { + let nameEnd = from; + while (nameEnd < text.length && !isWhitespace(text[nameEnd]) && text[nameEnd] !== "/" && text[nameEnd] !== ">") { + nameEnd++; + } + const name = text.slice(from, nameEnd); + if (name === "") { + throw new Error("Invalid XML: tag without a name"); + } + + // Entries, not an object, so that an attribute such as __proto__ is one of them rather than the object's prototype + // eslint-disable-next-line functional/prefer-readonly-type + const attributes: (readonly [string, string])[] = []; + let position = nameEnd; + for (;;) { + while (position < text.length && isWhitespace(text[position])) { + position++; + } + if (position >= text.length) { + throw new Error(`Invalid XML: <${name}> that isn't closed`); + } + if (text[position] === ">" || text.startsWith("/>", position)) { + const selfClosing = text[position] === "/"; + onElement( + { + type: "element", + name, + ...(attributes.length > 0 ? { attributes: Object.fromEntries(attributes) as XmlAttributes } : {}), + }, + selfClosing, + ); + return position + (selfClosing ? 2 : 1); + } + + const equals = text.indexOf("=", position); + const attributeName = text.slice(position, equals === -1 ? text.length : equals).trimEnd(); + if (equals === -1 || attributeName === "" || /[\s/>]/.test(attributeName)) { + throw new Error(`Invalid XML: attribute of <${name}> without a value`); + } + let valueStart = equals + 1; + while (valueStart < text.length && isWhitespace(text[valueStart])) { + valueStart++; + } + const quote = text[valueStart]; + if (quote !== '"' && quote !== "'") { + throw new Error(`Invalid XML: value of ${attributeName} on <${name}> isn't quoted`); + } + const valueEnd = text.indexOf(quote, valueStart + 1); + if (valueEnd === -1) { + throw new Error(`Invalid XML: value of ${attributeName} on <${name}> isn't closed`); + } + // Like xml-js, the first of attributes with the same name is kept + if (!attributes.some(([existing]) => existing === attributeName)) { + // eslint-disable-next-line functional/immutable-data + attributes.push([attributeName, decodeEntities(text.slice(valueStart + 1, valueEnd))]); + } + position = valueEnd + 1; + } +}; diff --git a/src/util/xml/stringify.spec.ts b/src/util/xml/stringify.spec.ts new file mode 100644 index 0000000000..e4f575c49e --- /dev/null +++ b/src/util/xml/stringify.spec.ts @@ -0,0 +1,136 @@ +// cspell:words apos +import { describe, expect, it } from "vitest"; + +import { stringifyElement, stringifyXmlable } from "./stringify"; +import type { XmlElement } from "./types"; + +describe("stringifyXmlable", () => { + it("should write elements with attributes, children and text", () => { + expect( + stringifyXmlable({ + "w:p": [ + { _attr: { "w14:paraId": "1A" } }, + { "w:r": [{ "w:t": [{ _attr: { "xml:space": "preserve" } }, "Hi"] }] }, + { "w:r": {} }, + ], + }), + ).to.equal('Hi'); + }); + + it("should write an element's value, whatever its type", () => { + expect(stringifyXmlable({ a: "text" })).to.equal("text"); + expect(stringifyXmlable({ a: 5 })).to.equal("5"); + expect(stringifyXmlable({ a: true })).to.equal("true"); + expect(stringifyXmlable({ a: "" })).to.equal(""); + expect(stringifyXmlable({ a: undefined })).to.equal(""); + expect(stringifyXmlable({ a: null })).to.equal(""); + expect(stringifyXmlable({ a: [] })).to.equal(""); + expect(stringifyXmlable({ a: [5] })).to.equal("5"); + expect(stringifyXmlable({ a: { _attr: { b: 1, c: false, d: "x" } } })).to.equal(''); + expect(stringifyXmlable({})).to.equal(""); + }); + + it("should escape text and attributes", () => { + expect(stringifyXmlable({ a: [{ _attr: { b: `&"'<>` } }, `&"'<>`] })).to.equal( + '&"'<>', + ); + }); + + it("should write CDATA, splitting it at each ]]>", () => { + expect(stringifyXmlable({ a: { _cdata: "x]]>y" } })).to.equal("y]]>"); + }); + + it("should let text take the place of what came before it, as the xml package did", () => { + expect(stringifyXmlable({ a: [{ b: {} }, "text"] })).to.equal("text"); + expect(stringifyXmlable({ a: ["one", "two"] })).to.equal("two"); + }); + + it("should write a declaration first", () => { + expect(stringifyXmlable({ a: {} }, { declaration: { standalone: "yes", encoding: "UTF-8" } })).to.equal( + '', + ); + expect(stringifyXmlable({ a: {} }, { declaration: {} })).to.equal(''); + }); + + it("should write several objects one after another", () => { + expect(stringifyXmlable([{ a: {} }, { b: "x" }])).to.equal("x"); + }); + + it("should indent each level, as the xml package did", () => { + expect( + stringifyXmlable( + { a: [{ _attr: { x: 1 } }, { b: [{ c: "text" }, { d: {} }] }, { e: [] }] }, + { indent: " ", declaration: { standalone: "yes" } }, + ), + ).to.equal( + [ + '', + '', + " ", + " text", + " ", + " ", + " ", + " ", + "", + ].join("\n"), + ); + expect(stringifyXmlable([{ a: {} }, { b: "x" }], { indent: " " })).to.equal("\nx"); + }); +}); + +describe("stringifyElement", () => { + it("should write a document's declaration and nodes", () => { + const document: XmlElement = { + declaration: { attributes: { version: "1.0", standalone: "yes" } }, + elements: [ + { type: "instruction", name: "mso-application", instruction: 'progid="Word.Document"' }, + { type: "doctype", doctype: "a" }, + { + type: "element", + name: "a", + attributes: { b: "1", c: 2, d: undefined }, + elements: [ + { type: "element", name: "empty" }, + { type: "element", name: "w:t", attributes: { "xml:space": "preserve" } }, + { type: "text", text: 5 }, + { type: "comment", comment: " c " }, + { type: "cdata", cdata: "x]]>y" }, + { type: "instruction", name: "pi" }, + { type: "element", name: "children", elements: [{ type: "text", text: "t" }] }, + { type: "unknown" }, + ], + }, + ], + }; + expect(stringifyElement(document)).to.equal( + '' + + '5y]]>t', + ); + }); + + it("should escape text and attributes, so that what is read is written back as it was", () => { + expect( + stringifyElement({ + elements: [ + { + type: "element", + name: "a", + attributes: { b: `& &"'<>` }, + elements: [{ type: "text", text: `& &"'<>` }], + }, + ], + }), + ).to.equal(`&amp; &"'<>`); + }); + + it("should leave out attributes without a value", () => { + expect(stringifyElement({ elements: [{ type: "element", name: "a", attributes: { b: null as unknown as string } }] })).to.equal( + "", + ); + }); + + it("should write nothing for an empty document", () => { + expect(stringifyElement({})).to.equal(""); + }); +}); diff --git a/src/util/xml/stringify.ts b/src/util/xml/stringify.ts new file mode 100644 index 0000000000..afc4d0209a --- /dev/null +++ b/src/util/xml/stringify.ts @@ -0,0 +1,191 @@ +/** + * Writes XML, from the objects docx's `Formatter` makes or from an {@link XmlElement} tree. + * + * @module + */ +import type { IXmlableObject } from "@file/xml-components/xmlable-object"; + +import type { XmlElement } from "./types"; + +const ESCAPES: ReadonlyMap = new Map([ + ["&", "&"], + ['"', """], + ["'", "'"], // cspell:words apos + ["<", "<"], + [">", ">"], +]); + +const escapeAll = (value: string): string => value.replace(/[&"'<>]/g, (char) => ESCAPES.get(char)!); + +const escapeText = (value: string): string => value.replace(/[&<>]/g, (char) => ESCAPES.get(char)!); + +/** + * Escapes a value the way the xml package did, leaving values that aren't strings, such as numbers, as they are. + */ +const escapeValue = (value: T): T | string => (typeof value === "string" ? escapeAll(value) : value); + +/** + * Options for {@link stringifyXmlable}. + */ +export type StringifyXmlableOptions = { + /** What to indent each level with, such as two spaces. Without it, the XML is written on one line. */ + readonly indent?: string; + /** Write an XML declaration first, with these attributes. */ + readonly declaration?: { readonly encoding?: string; readonly standalone?: string }; +}; + +type ResolvedContent = ResolvedElement | string | number | boolean | undefined; + +type ResolvedElement = { + readonly name: string | undefined; + readonly attributes: readonly string[]; + readonly content: readonly ResolvedContent[]; + readonly indents: string; +}; + +/** + * Works out an element's tag, attributes and content, as the xml package did, quirks and all, so that docx writes the + * same XML byte for byte. + */ +const resolve = (data: object, indent: string, depth: number): ResolvedElement => { + // An empty object has no name, and writes nothing + const name = Object.keys(data)[0] as string | undefined; + const values: unknown = name === undefined ? undefined : (data as Record)[name]; + + // Built in place, as an element of a document's body can have thousands of children + // eslint-disable-next-line functional/prefer-readonly-type + const attributes: string[] = []; + // eslint-disable-next-line functional/prefer-readonly-type + const content: ResolvedContent[] = []; + const addAttributes = (attr: Readonly>): void => { + for (const [key, value] of Object.entries(attr)) { + // eslint-disable-next-line functional/immutable-data + attributes.push(`${key}="${String(escapeValue(value))}"`); + } + }; + + if (typeof values === "object") { + if (values !== null) { + const { _attr: attr, _cdata: cdata } = values as { readonly _attr?: Record; readonly _cdata?: string }; + if (attr) { + addAttributes(attr); + } + if (cdata) { + // eslint-disable-next-line functional/immutable-data + content.push(`/g, "]]]]>")}]]>`); + } + if (Array.isArray(values)) { + let isStringContent = false; + // eslint-disable-next-line functional/immutable-data + content.push(""); + for (const value of values) { + if (typeof value === "object") { + if (Object.keys(value)[0] === "_attr") { + addAttributes((value as { readonly _attr: Record })._attr); + } else { + // eslint-disable-next-line functional/immutable-data + content.push(resolve(value as object, indent, depth + 1)); + } + } else { + // Text takes the place of whatever came before it, as it did in the xml package + // eslint-disable-next-line functional/immutable-data + content.pop(); + isStringContent = true; + // eslint-disable-next-line functional/immutable-data + content.push(escapeValue(value as string)); + } + } + if (!isStringContent) { + // eslint-disable-next-line functional/immutable-data + content.push(""); + } + } + } + } else { + // eslint-disable-next-line functional/immutable-data + content.push(escapeValue(values as string | number | boolean | undefined)); + } + + return { name, attributes, content, indents: depth > 1 ? indent.repeat(depth - 1) : "" }; +}; + +const format = (element: ResolvedElement | string | number | boolean, indent: string, isLast: boolean): string => { + if (typeof element !== "object") { + return String(element); + } + const { name, attributes, content, indents } = element; + const { length } = content; + const open = + indents + + (name ? `<${name}` : "") + + (attributes.length > 0 ? ` ${attributes.join(" ")}` : "") + + (length > 0 ? (name ? ">" : "") : "/>") + + (indent && length > 1 ? "\n" : ""); + if (length === 0) { + return open + (indent ? "\n" : ""); + } + const children = content.map((child) => (child === undefined ? "" : format(child, indent, false))).join(""); + return open + children + (length > 1 ? indents : "") + (name ? `` : "") + (indent && !isLast ? "\n" : ""); +}; + +/** + * Writes the XML of an object from docx's `Formatter`, such as `{ "w:b": { _attr: { "w:val": false } } }`, + * as the xml package did. + * + * @param input - The object, or several to write one after another + * @param options - How to indent, and the XML declaration to write first + * @returns The XML + */ +export const stringifyXmlable = ( + input: IXmlableObject | readonly IXmlableObject[], + { indent = "", declaration }: StringifyXmlableOptions = {}, +): string => { + const items = Array.isArray(input) ? input : [input]; + const startDepth = indent ? 1 : 0; + const standalone = declaration?.standalone ? ` standalone="${escapeAll(declaration.standalone)}"` : ""; + const declarationXml = + declaration === undefined + ? "" + : `${indent ? "\n" : ""}`; + return declarationXml + items.map((item, i) => format(resolve(item, indent, startDepth), indent, i === items.length - 1)).join(""); +}; + +const stringifyAttributes = (attributes: XmlElement["attributes"]): string => + Object.entries(attributes ?? {}) + .flatMap(([key, value]) => (value === undefined || value === null ? [] : [` ${key}="${escapeAll(String(value))}"`])) + .join(""); + +const stringifyNode = (node: XmlElement): string => { + switch (node.type) { + case "element": { + const elements = node.elements ?? []; + const open = `<${node.name}${stringifyAttributes(node.attributes)}`; + // An empty element that preserves its whitespace is written with both tags, as xml-js did + return elements.length > 0 || node.attributes?.["xml:space"] === "preserve" + ? `${open}>${elements.map(stringifyNode).join("")}` + : `${open}/>`; + } + case "text": + return escapeText(String(node.text)); + case "cdata": + return `/g, "]]]]>")}]]>`; + case "comment": + return ``; + case "doctype": + return ``; + case "instruction": + return ``; + default: + return ""; + } +}; + +/** + * Writes the XML of an {@link XmlElement} tree, such as one from {@link parseXml}. + * + * @param document - The document, with its declaration and the nodes at its top level + * @returns The XML + */ +export const stringifyElement = (document: XmlElement): string => + (document.declaration ? `` : "") + + (document.elements ?? []).map(stringifyNode).join(""); diff --git a/src/util/xml/types.ts b/src/util/xml/types.ts new file mode 100644 index 0000000000..076f04df43 --- /dev/null +++ b/src/util/xml/types.ts @@ -0,0 +1,47 @@ +/** + * The tree that docx reads XML into, such as the parts of a document it patches or the XML given to + * `convertToXmlComponent`. + * + * @module + */ +/* eslint-disable functional/prefer-readonly-type -- Changes to a document, such as patches, are made to its tree in place */ + +/** + * The attributes of an element, by name. + */ +export type XmlAttributes = Record; + +/** + * The attributes of an XML declaration, such as ``. + */ +export type XmlDeclarationAttributes = { + version?: string | number; + encoding?: string; + standalone?: "yes" | "no"; +}; + +/** + * A node of an XML document, or the document itself. + * + * It has the shape of xml-js's non-compact `Element`, which docx used before it read XML itself, so a tree from + * xml-js can still be given wherever docx takes one. `type` says which of the other fields the node has: + * + * - The document has no `type`. It has its `declaration`, if it has one, and the nodes at its top level in `elements`. + * - `"element"` has its `name`, and its `attributes` and `elements` if it has any. + * - `"text"` has its `text`, with entities such as `&` decoded. + * - `"cdata"`, `"comment"` and `"doctype"` have their content in the field of their name. + * - `"instruction"`, a processing instruction such as ``, has its `name` + * and the rest in `instruction`. + */ +export type XmlElement = { + declaration?: { attributes?: XmlDeclarationAttributes }; + instruction?: string; + attributes?: XmlAttributes; + cdata?: string; + doctype?: string; + comment?: string; + text?: string | number | boolean; + type?: string; + name?: string; + elements?: XmlElement[]; +}; diff --git a/vite.config.ts b/vite.config.ts index 7f8c71ef4c..74eb92c699 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -34,6 +34,8 @@ export default defineConfig({ protocolImports: true, }), ], + // Lets specs import Word documents with ?inline, such as the corpus src/util/xml reads + assetsInclude: ["**/*.docx", "**/*.dotx"], resolve: { tsconfigPaths: true, alias: {