Open History to see the last commit
1import { readImageDimensions } from "@t3tools/shared/imageDimensions";
2import { XMLParser, XMLValidator } from "fast-xml-parser";
3import { decodeHTMLStrict as decodeEntities } from "entities";
4import { PreviewError } from "./previewFailure";
5
6// `text` and `attrs` hold decoded values: escaped text is decoded once, CDATA stays literal.
7export type XmlNode = {
8 name: string;
9 attrs: Record<string, string>;
10 children: XmlNode[];
11 text: string;
12};
13type OrderedXml = { [key: string]: OrderedXml[] | Record<string, string> | string };
14export const escape = (value: string) =>
15 value
16 .replaceAll("&", "&")
17 .replaceAll("<", "<")
18 .replaceAll(">", ">")
19 .replaceAll('"', """);
20
21const namespacePrefixes: Record<string, string> = {
22 "urn:oasis:names:tc:opendocument:xmlns:office:1.0": "office",
23 "urn:oasis:names:tc:opendocument:xmlns:style:1.0": "style",
24 "urn:oasis:names:tc:opendocument:xmlns:table:1.0": "table",
25 "urn:oasis:names:tc:opendocument:xmlns:text:1.0": "text",
26 "urn:oasis:names:tc:opendocument:xmlns:drawing:1.0": "draw",
27 "urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0": "fo",
28 "urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0": "svg",
29 "urn:oasis:names:tc:opendocument:xmlns:presentation:1.0": "presentation",
30 "http://openoffice.org/2010/draw": "drawooo",
31 "http://www.w3.org/1999/xlink": "xlink",
32 "http://www.w3.org/1999/xhtml": "",
33 "http://www.idpf.org/2007/opf": "",
34 "http://www.daisy.org/z3986/2005/ncx/": "",
35 "http://www.w3.org/2000/svg": "svg",
36 "http://www.w3.org/1998/Math/MathML": "math",
37 "http://www.w3.org/ns/SMIL": "smil",
38 "http://www.w3.org/ns/ttml": "ttml",
39 "http://www.w3.org/2006/04/ttaf1": "ttml",
40 "http://www.idpf.org/2007/ops": "epub",
41 "http://www.w3.org/XML/1998/namespace": "xml",
42 "urn:oasis:names:tc:opendocument:xmlns:container": "",
43};
44export function parseXml(source: string): XmlNode {
45 // EPUB XHTML commonly declares an external DTD: discard it without resolving it. Any other
46 // declaration is rejected; CDATA, comments and processing instructions pass through untouched.
47 let declares = false;
48 source = source.replaceAll(
49 /<\?[\s\S]*?(?:\?>|$)|<!\[CDATA\[[\s\S]*?(?:]]>|$)|<!--[\s\S]*?(?:-->|$)|(<!DOCTYPE\s+[^<>[\]]*(?:\[\s*\]\s*)?>)|(<!\s*(?:DOCTYPE|ENTITY))/gi,
50 (markup, externalDoctype?: string, declaration?: string) => {
51 if (declaration) declares = true;
52 return externalDoctype ? " " : markup;
53 },
54 );
55 if (source.length > 8 * 1024 * 1024 || declares || XMLValidator.validate(source) !== true)
56 throw new PreviewError({ code: "xml-invalid" });
57 const parser = new XMLParser({
58 preserveOrder: true,
59 ignoreAttributes: false,
60 attributeNamePrefix: "",
61 processEntities: false,
62 trimValues: false,
63 parseTagValue: false,
64 cdataPropName: "#cdata",
65 });
66 let ordered: OrderedXml[];
67 try {
68 ordered = parser.parse(source) as OrderedXml[];
69 } catch (cause) {
70 if (cause instanceof Error && cause.message === "Maximum nested tags exceeded")
71 throw new PreviewError({ code: "xml-too-deep" });
72 throw cause;
73 }
74 let count = 0;
75 function convert(
76 items: OrderedXml[],
77 depth: number,
78 inherited: Record<string, string>,
79 ): XmlNode[] {
80 if (depth > 100) throw new PreviewError({ code: "xml-too-deep" });
81 return items.map((item) => {
82 if (++count > 100_000) throw new PreviewError({ code: "xml-too-much-content" });
83 const name = Object.keys(item).find((key) => key !== ":@") ?? "#text";
84 const value = item[name];
85 if (name === "#cdata") {
86 const literal = Array.isArray(value)
87 ? value.map((part) => part["#text"] ?? "").join("")
88 : "";
89 return { name: "#text", attrs: {}, children: [], text: literal };
90 }
91 const attrs = Object.fromEntries(
92 Object.entries((item[":@"] ?? {}) as Record<string, string>).map(([key, value]) => {
93 // fast-xml-parser accepts raw '<' in element attributes, which can mask declarations
94 // above. Processing instructions end at their first '?>', so their data may hold '<'.
95 if (!name.startsWith("?") && value.includes("<"))
96 throw new PreviewError({ code: "xml-invalid" });
97 return [key, decodeEntities(value)];
98 }),
99 );
100 const namespaces = Object.create(inherited) as Record<string, string>;
101 for (const [key, value] of Object.entries(attrs)) {
102 if (key === "xmlns") namespaces[""] = value;
103 else if (key.startsWith("xmlns:")) namespaces[key.slice(6)] = value;
104 }
105 const expanded = (name: string, attribute = false) => {
106 if (name.startsWith("#")) return name;
107 const colon = name.indexOf(":");
108 if (colon < 0 && attribute) return name;
109 const uri = namespaces[colon < 0 ? "" : name.slice(0, colon)];
110 if (!uri) return name;
111 const prefix = Object.hasOwn(namespacePrefixes, uri) ? namespacePrefixes[uri] : undefined;
112 const local = name.slice(colon + 1);
113 return prefix === undefined
114 ? "{" + uri + "}" + local
115 : prefix
116 ? prefix + ":" + local
117 : local;
118 };
119 return {
120 name: expanded(name),
121 attrs: Object.fromEntries(
122 Object.entries(attrs).map(([key, value]) => [expanded(key, true), value]),
123 ),
124 children: Array.isArray(value) ? convert(value, depth + 1, namespaces) : [],
125 text: typeof value === "string" ? decodeEntities(value) : "",
126 };
127 });
128 }
129 return {
130 name: "root",
131 attrs: {},
132 children: convert(ordered, 0, Object.create(null) as Record<string, string>),
133 text: "",
134 };
135}
136export function find(node: XmlNode, name: string, skip?: string): XmlNode[] {
137 return node.children.flatMap((child) =>
138 child.name === skip
139 ? []
140 : child.name === name || (!name.includes(":") && child.name.endsWith(`:${name}`))
141 ? [child]
142 : find(child, name, skip),
143 );
144}
145export function text(node: XmlNode): string {
146 if (node.name === "office:annotation") return "";
147 if (node.name === "text:s") return " ".repeat(repeat(node.attrs["text:c"], 100));
148 if (node.name === "text:tab") return "\t";
149 if (node.name === "text:line-break") return "\n";
150 return node.name === "#text" ? node.text : node.children.map(text).join("");
151}
152export function archivePath(base: string, href: string): string | null {
153 if (/^(?:[a-z][a-z\d+.-]*:|\/|\\)/i.test(href)) return null;
154 const parts = base.split("/").slice(0, -1);
155 let decoded: string;
156 try {
157 decoded = decodeURIComponent(href.split(/[?#]/, 1)[0] ?? "");
158 } catch {
159 return null;
160 }
161 for (const part of decoded.split("/")) {
162 if (part === "..") {
163 if (!parts.length) return null;
164 parts.pop();
165 } else if (part && part !== ".") parts.push(part);
166 }
167 return parts.join("/");
168}
169export function previewImageSize(bytes: Uint8Array) {
170 const size = readImageDimensions(bytes);
171 return size && size.width <= 16_777_216 / size.height ? size : null;
172}
173
174export function imageFits(bytes: Uint8Array) {
175 return previewImageSize(bytes) !== null;
176}
177
178export function repeat(value: string | undefined, max: number) {
179 const count = Number(value ?? 1);
180 if (!Number.isSafeInteger(count) || count < 1)
181 throw new PreviewError({ code: "repeated-content-invalid" });
182 return Math.min(count, max);
183}