Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

documentPreviewXml.ts

186 lines7.3 KB

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