Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 19 additions & 6 deletions src/file/xml-components/default-attributes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
* @module
*/
import { BaseXmlComponent, type IContext } from "./base";
import type { IXmlAttribute, IXmlableObject } from "./xmlable-object";
import type { IXmlableObject } from "./xmlable-object";

/**
* Maps TypeScript property names to their XML attribute names.
Expand Down Expand Up @@ -72,13 +72,14 @@ export abstract class XmlAttributeComponent<T extends Record<string, any>> exten
*/
public prepForXml(_: IContext): IXmlableObject {
const attrs: Record<string, string> = {};
Object.entries(this.root).forEach(([key, value]) => {
for (const key of Object.keys(this.root)) {
const value = this.root[key];
if (value !== undefined) {
const newKey = (this.xmlKeys && this.xmlKeys[key]) || key;
// eslint-disable-next-line functional/immutable-data
attrs[newKey] = value;
}
});
}
return { _attr: attrs };
}
}
Expand Down Expand Up @@ -119,9 +120,21 @@ export class NextAttributeComponent<T extends AttributeData> extends BaseXmlComp
* @returns Object with _attr key containing the attributes
*/
public prepForXml(_: IContext): IXmlableObject {
const attrs = Object.values<{ readonly key: string; readonly value: string | boolean | number }>(this.root)
.filter(({ value }) => value !== undefined)
.reduce((acc, { key, value }) => ({ ...acc, [key]: value }), {} as IXmlAttribute);
// Built in place, rather than copied for each attribute
const attrs: Record<string, string | boolean | number> = {};
for (const { key, value } of Object.values<{ readonly key: string; readonly value: string | boolean | number }>(this.root)) {
if (value === undefined) {
continue;
}
if (key === "__proto__") {
// Assigning would call the inherited setter and drop the attribute
// eslint-disable-next-line functional/immutable-data
Object.defineProperty(attrs, key, { value, enumerable: true, writable: true, configurable: true });
} else {
// eslint-disable-next-line functional/immutable-data
attrs[key] = value;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
}
return { _attr: attrs };
}
}
15 changes: 15 additions & 0 deletions src/file/xml-components/simple-elements.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,21 @@ describe("BuilderElement", () => {
},
});
});

it("should keep an attribute with the key __proto__", () => {
const element = new BuilderElement<{ readonly testAttr: string }>({
name: "test",
attributes: {
testAttr: {
key: "__proto__",
value: "test",
},
},
});

const tree = new Formatter().format(element) as { readonly test: { readonly _attr: object } };
expect(Object.entries(tree.test._attr)).to.deep.equal([["__proto__", "test"]]);
});
});
});

Expand Down
48 changes: 35 additions & 13 deletions src/file/xml-components/xml-component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,17 @@ import type { IXmlableObject } from "./xmlable-object";
*/
export const EMPTY_OBJECT = Object.seal({});

/**
* Adds what a child wrote to an element's children, leaving it out when it is undefined.
*/
// eslint-disable-next-line functional/prefer-readonly-type
const addChild = (children: IXmlableObject[], written: unknown): void => {
if (written !== undefined) {
// eslint-disable-next-line functional/immutable-data
children.push(written as IXmlableObject);
}
};

/**
* Base class for all XML components in WordprocessingML documents.
*
Expand Down Expand Up @@ -92,20 +103,31 @@ export abstract class XmlComponent extends BaseXmlComponent {
context.stack.push(this);

// Recursively prepare all children for serialization. A child written as several components, such as a run with
// a run in its children, is written as each of them in turn
const children = this.root
.flatMap((comp) => {
// A component from another copy of docx, such as one a plugin was bundled with, isn't an instance of
// this copy's classes. Taken for an object to write as XML, its fields, such as `rootKey`, are written
// as elements, and Word can't open the document. So components are known by the method that writes
// them, and that method is given this document's context, so it adds its relationships and media here
if (isXmlComponent(comp)) {
const parts = comp.writtenAs;
return parts ? parts.map((part) => part.prepForXml(context)) : comp.prepForXml(context);
// a run in its children, is written as each of them in turn. 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 children: IXmlableObject[] = [];
for (const comp of this.root) {
// A component from another copy of docx, such as one a plugin was bundled with, isn't an instance of
// this copy's classes. Taken for an object to write as XML, its fields, such as `rootKey`, are written
// as elements, and Word can't open the document. So components are known by the method that writes
// them, and that method is given this document's context, so it adds its relationships and media here
const parts = isXmlComponent(comp) ? comp.writtenAs : undefined;
// What a child writes as an array, such as the parts it is written as, is written as each of its items, as
// with flatMap
const written: unknown = parts
? parts.map((part) => part.prepForXml(context))
: isXmlComponent(comp)
? comp.prepForXml(context)
: comp;
if (Array.isArray(written)) {
for (const item of written) {
addChild(children, item);
}
return comp;
})
.filter((comp) => comp !== undefined); // Exclude undefined
} else {
addChild(children, written);
}
}

// Pop this component from the stack
// eslint-disable-next-line functional/immutable-data
Expand Down
99 changes: 50 additions & 49 deletions src/util/xml/stringify.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,11 @@ const escapeText = (value: string): string =>
*/
const escapeValue = <T>(value: T): T | string => (typeof value === "string" ? escapeAll(value) : value);

/**
* Writes text content, escaped, as the xml package did, writing nothing for undefined.
*/
const writeText = (value: unknown): string => (value === undefined ? "" : String(escapeValue(value)));

/**
* Options for {@link stringifyXmlable}.
*/
Expand All @@ -42,33 +47,32 @@ export type StringifyXmlableOptions = {
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.
* Writes an element as the xml package did, quirks and all, so that docx writes the same XML byte for byte. Its XML
* is pushed onto `out` in pieces, which are joined once at the end, rather than built as a string for each element.
*
* @param data - The object to write, such as `{ "w:b": {} }`
* @param indent - What to indent each level with, or an empty string to write one line
* @param indents - The indentation of this element
* @param isLast - Whether this is the last object written, which isn't followed by a line break
* @param out - The pieces of XML written so far
*/
const resolve = (data: object, indent: string, depth: number): ResolvedElement => {
// eslint-disable-next-line functional/prefer-readonly-type
const write = (data: object, indent: string, indents: string, isLast: boolean, out: string[]): void => {
// 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<string, unknown>)[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[] = [];
// The open tag is written once the attributes and the content are known, as an attribute can come after content
const start = out.length;
// eslint-disable-next-line functional/immutable-data
out.push("");
let attributes = "";
// How many items of content the element has, which decides how it is indented
let length = 0;
const addAttributes = (attr: Readonly<Record<string, unknown>>): void => {
for (const [key, value] of Object.entries(attr)) {
// eslint-disable-next-line functional/immutable-data
attributes.push(`${key}="${String(escapeValue(value))}"`);
for (const key of Object.keys(attr)) {
attributes += ` ${key}="${String(escapeValue(attr[key]))}"`;
}
};

Expand All @@ -80,60 +84,55 @@ const resolve = (data: object, indent: string, depth: number): ResolvedElement =
}
if (cdata) {
// eslint-disable-next-line functional/immutable-data
content.push(`<![CDATA[${cdata.replace(/\]\]>/g, "]]]]><![CDATA[>")}]]>`);
out.push(`<![CDATA[${cdata.replace(/\]\]>/g, "]]]]><![CDATA[>")}]]>`);
length++;
}
if (Array.isArray(values)) {
let isStringContent = false;
// eslint-disable-next-line functional/immutable-data
content.push("");
const childIndents = indents + indent;
// Where the last item of content starts, so that text can take its place
let lastStart = out.length;
length++;
for (const value of values) {
if (typeof value === "object") {
if (Object.keys(value)[0] === "_attr") {
addAttributes((value as { readonly _attr: Record<string, unknown> })._attr);
} else {
// eslint-disable-next-line functional/immutable-data
content.push(resolve(value as object, indent, depth + 1));
lastStart = out.length;
length++;
write(value as object, indent, childIndents, false, out);
}
} 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();
out.length = lastStart;
isStringContent = true;
// eslint-disable-next-line functional/immutable-data
content.push(escapeValue(value as string));
out.push(writeText(value));
}
}
if (!isStringContent) {
// eslint-disable-next-line functional/immutable-data
content.push("");
length++;
}
}
}
} else {
// eslint-disable-next-line functional/immutable-data
content.push(escapeValue(values as string | number | boolean | undefined));
out.push(writeText(values));
length++;
}

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" : "");
indents + (name ? `<${name}` : "") + attributes + (length > 0 ? (name ? ">" : "") : "/>") + (indent && length > 1 ? "\n" : "");
if (length === 0) {
return open + (indent ? "\n" : "");
// eslint-disable-next-line functional/immutable-data
out[start] = open + (indent ? "\n" : "");
return;
}
const children = content.map((child) => (child === undefined ? "" : format(child, indent, false))).join("");
return open + children + (length > 1 ? indents : "") + (name ? `</${name}>` : "") + (indent && !isLast ? "\n" : "");
// eslint-disable-next-line functional/immutable-data
out[start] = open;
// eslint-disable-next-line functional/immutable-data
out.push((length > 1 ? indents : "") + (name ? `</${name}>` : "") + (indent && !isLast ? "\n" : ""));
};

/**
Expand All @@ -149,13 +148,15 @@ export const stringifyXmlable = (
{ 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
? ""
: `<?xml version="1.0" encoding="${escapeAll(declaration.encoding || "UTF-8")}"${standalone}?>${indent ? "\n" : ""}`;
return declarationXml + items.map((item, i) => format(resolve(item, indent, startDepth), indent, i === items.length - 1)).join("");
// eslint-disable-next-line functional/prefer-readonly-type
const out: string[] = [declarationXml];
items.forEach((item, i) => write(item, indent, "", i === items.length - 1, out));
return out.join("");
};

const stringifyAttributes = (attributes: XmlElement["attributes"]): string =>
Expand Down
Loading