Open History to see the last commit
1import { pipe } from "effect/Function";
2import {
3 IMAGE_DIMENSIONS_HEADER_BYTES,
4 readImageDimensions,
5} from "@t3tools/shared/imageDimensions";
6import { XMLParser, XMLValidator } from "fast-xml-parser";
7import { decodeHTMLAttribute, decodeHTMLStrict as decodeEntities } from "entities";
8import type JSZip from "jszip";
9import { terminalOutputPlainText } from "@t3tools/shared/terminalOutput";
10
11import { type OfficeWorkerResult, type NotebookCell } from "./officePreviewProtocol";
12import { PreviewError } from "./previewFailure";
13
14const TABLE_PREVIEW_MAX_ROWS = 500;
15const TABLE_PREVIEW_MAX_COLUMNS = 50;
16
17// `text` and `attrs` hold decoded values: escaped text is decoded once, CDATA stays literal.
18type XmlNode = { name: string; attrs: Record<string, string>; children: XmlNode[]; text: string };
19type OrderedXml = { [key: string]: OrderedXml[] | Record<string, string> | string };
20const escape = (value: string) =>
21 value
22 .replaceAll("&", "&")
23 .replaceAll("<", "<")
24 .replaceAll(">", ">")
25 .replaceAll('"', """);
26
27const namespacePrefixes: Record<string, string> = {
28 "urn:oasis:names:tc:opendocument:xmlns:office:1.0": "office",
29 "urn:oasis:names:tc:opendocument:xmlns:table:1.0": "table",
30 "urn:oasis:names:tc:opendocument:xmlns:text:1.0": "text",
31 "urn:oasis:names:tc:opendocument:xmlns:drawing:1.0": "draw",
32 "urn:oasis:names:tc:opendocument:xmlns:presentation:1.0": "presentation",
33 "http://www.w3.org/1999/xlink": "xlink",
34 "http://www.w3.org/1999/xhtml": "",
35 "http://www.idpf.org/2007/opf": "",
36 "urn:oasis:names:tc:opendocument:xmlns:container": "",
37};
38function parseXml(source: string): XmlNode {
39 // EPUB XHTML commonly declares an external DTD: discard it without resolving it. Any other
40 // declaration is rejected; CDATA, comments and processing instructions pass through untouched.
41 let declares = false;
42 source = source.replaceAll(
43 /<\?[\s\S]*?(?:\?>|$)|<!\[CDATA\[[\s\S]*?(?:]]>|$)|<!--[\s\S]*?(?:-->|$)|(<!DOCTYPE\s+[^<>[\]]*>)|(<!\s*(?:DOCTYPE|ENTITY))/gi,
44 (markup, externalDoctype?: string, declaration?: string) => {
45 if (declaration) declares = true;
46 return externalDoctype ? " " : markup;
47 },
48 );
49 if (source.length > 8 * 1024 * 1024 || declares || XMLValidator.validate(source) !== true)
50 throw new PreviewError({ code: "xml-invalid" });
51 const parser = new XMLParser({
52 preserveOrder: true,
53 ignoreAttributes: false,
54 attributeNamePrefix: "",
55 processEntities: false,
56 trimValues: false,
57 parseTagValue: false,
58 cdataPropName: "#cdata",
59 });
60 const ordered = parser.parse(source) as OrderedXml[];
61 let count = 0;
62 function convert(
63 items: OrderedXml[],
64 depth: number,
65 inherited: Record<string, string>,
66 ): XmlNode[] {
67 if (depth > 100) throw new PreviewError({ code: "xml-too-deep" });
68 return items.map((item) => {
69 if (++count > 100_000) throw new PreviewError({ code: "xml-too-much-content" });
70 const name = Object.keys(item).find((key) => key !== ":@") ?? "#text";
71 const value = item[name];
72 if (name === "#cdata") {
73 const literal = Array.isArray(value)
74 ? value.map((part) => part["#text"] ?? "").join("")
75 : "";
76 return { name: "#text", attrs: {}, children: [], text: literal };
77 }
78 const attrs = Object.fromEntries(
79 Object.entries((item[":@"] ?? {}) as Record<string, string>).map(([key, value]) => {
80 // fast-xml-parser accepts raw '<' in element attributes, which can mask declarations
81 // above. Processing instructions end at their first '?>', so their data may hold '<'.
82 if (!name.startsWith("?") && value.includes("<"))
83 throw new PreviewError({ code: "xml-invalid" });
84 return [key, decodeEntities(value)];
85 }),
86 );
87 const namespaces = Object.create(inherited) as Record<string, string>;
88 for (const [key, value] of Object.entries(attrs)) {
89 if (key === "xmlns") namespaces[""] = value;
90 else if (key.startsWith("xmlns:")) namespaces[key.slice(6)] = value;
91 }
92 const expanded = (name: string, attribute = false) => {
93 if (name.startsWith("#")) return name;
94 const colon = name.indexOf(":");
95 if (colon < 0 && attribute) return name;
96 const uri = namespaces[colon < 0 ? "" : name.slice(0, colon)];
97 if (!uri) return name;
98 const prefix = Object.hasOwn(namespacePrefixes, uri) ? namespacePrefixes[uri] : undefined;
99 const local = name.slice(colon + 1);
100 return prefix === undefined
101 ? "{" + uri + "}" + local
102 : prefix
103 ? prefix + ":" + local
104 : local;
105 };
106 return {
107 name: expanded(name),
108 attrs: Object.fromEntries(
109 Object.entries(attrs).map(([key, value]) => [expanded(key, true), value]),
110 ),
111 children: Array.isArray(value) ? convert(value, depth + 1, namespaces) : [],
112 text: typeof value === "string" ? decodeEntities(value) : "",
113 };
114 });
115 }
116 return {
117 name: "root",
118 attrs: {},
119 children: convert(ordered, 0, Object.create(null) as Record<string, string>),
120 text: "",
121 };
122}
123function find(node: XmlNode, name: string, skip?: string): XmlNode[] {
124 return node.children.flatMap((child) =>
125 child.name === skip
126 ? []
127 : child.name === name || (!name.includes(":") && child.name.endsWith(`:${name}`))
128 ? [child]
129 : find(child, name, skip),
130 );
131}
132function text(node: XmlNode): string {
133 if (node.name === "office:annotation") return "";
134 if (node.name === "text:s") return " ".repeat(repeat(node.attrs["text:c"], 100));
135 if (node.name === "text:tab") return "\t";
136 if (node.name === "text:line-break") return "\n";
137 return node.name === "#text" ? node.text : node.children.map(text).join("");
138}
139function archivePath(base: string, href: string): string | null {
140 if (/^(?:[a-z][a-z\d+.-]*:|\/|\\)/i.test(href)) return null;
141 const parts = base.split("/").slice(0, -1);
142 let decoded: string;
143 try {
144 decoded = decodeURIComponent(href.split(/[?#]/, 1)[0] ?? "");
145 } catch {
146 return null;
147 }
148 for (const part of decoded.split("/")) {
149 if (part === "..") {
150 if (!parts.length) return null;
151 parts.pop();
152 } else if (part && part !== ".") parts.push(part);
153 }
154 return parts.join("/");
155}
156function imageFits(bytes: Uint8Array) {
157 const size = readImageDimensions(bytes.subarray(0, IMAGE_DIMENSIONS_HEADER_BYTES));
158 return size !== null && size.width <= 16_777_216 / size.height;
159}
160function base64ImageFits(base64: string) {
161 return (
162 /^[a-z\d+/]*={0,2}$/i.test(base64) &&
163 base64.length % 4 !== 1 &&
164 (!base64.endsWith("=") || base64.length % 4 === 0) &&
165 imageFits(
166 Uint8Array.from(
167 atob(base64.slice(0, 4 * Math.ceil(IMAGE_DIMENSIONS_HEADER_BYTES / 3))),
168 (char) => char.charCodeAt(0),
169 ),
170 )
171 );
172}
173function htmlImagesFit(html: string) {
174 // HTML attribute entities can obscure a data URL until the client parses it.
175 for (const match of decodeHTMLAttribute(html).matchAll(
176 /data:image\/(?:png|jpeg|gif|webp);base64,([a-z\d+/]*={0,2})/gi,
177 ))
178 if (!base64ImageFits(match[1]!)) return false;
179 return true;
180}
181async function imageData(archive: JSZip, path: string | null): Promise<string> {
182 if (!path) return "";
183 const mime = (
184 { png: "png", jpg: "jpeg", jpeg: "jpeg", gif: "gif", webp: "webp" } as Record<string, string>
185 )[path.split(".").at(-1)?.toLowerCase() ?? ""];
186 const entry = archive.file(path);
187 if (!mime || !entry) return "";
188 const bytes = await entry.async("uint8array");
189 if (bytes.length > 4 * 1024 * 1024 || !imageFits(bytes)) return "";
190 reserveMarkup(4 * Math.ceil(bytes.length / 3) + 100);
191 return `data:image/${mime};base64,${await entry.async("base64")}`;
192}
193let markupBytes = 0;
194function reserveMarkup(size: number) {
195 markupBytes += size;
196 if (markupBytes > 16 * 1024 * 1024) throw new PreviewError({ code: "rendered-too-large" });
197}
198function boundedMarkup(value: string): string {
199 reserveMarkup(value.length);
200 return value;
201}
202const HTML_TAGS = new Set([
203 "p",
204 "h1",
205 "h2",
206 "h3",
207 "h4",
208 "h5",
209 "h6",
210 "div",
211 "span",
212 "strong",
213 "b",
214 "em",
215 "i",
216 "u",
217 "s",
218 "ul",
219 "ol",
220 "li",
221 "blockquote",
222 "pre",
223 "code",
224 "table",
225 "thead",
226 "tbody",
227 "tr",
228 "th",
229 "td",
230 "caption",
231 "figure",
232 "figcaption",
233 "br",
234 "hr",
235 "sub",
236 "sup",
237 "dl",
238 "dt",
239 "dd",
240]);
241async function epubHtml(node: XmlNode, archive: JSZip, base: string): Promise<string> {
242 if (node.name === "#text") return pipe(text(node), escape, boundedMarkup);
243 const tag =
244 node.name
245 .replace(/^\{[^}]*\}/, "")
246 .split(":")
247 .at(-1) ?? "";
248 if (["head", "script", "style", "iframe", "object", "embed", "svg", "math", "form"].includes(tag))
249 return "";
250 if (tag === "br" || tag === "hr") return boundedMarkup(`<${tag}>`);
251 if (tag === "img") {
252 const src = await imageData(archive, archivePath(base, node.attrs.src ?? ""));
253 return src ? `<img src="${src}" alt="${boundedMarkup(escape(node.attrs.alt ?? ""))}">` : "";
254 }
255 let children = "";
256 for (const child of node.children) children += await epubHtml(child, archive, base);
257 if (!HTML_TAGS.has(tag)) return children;
258 const spans =
259 tag === "td" || tag === "th"
260 ? ["colspan", "rowspan"]
261 .map((name) =>
262 /^\d{1,4}$/.test(node.attrs[name] ?? "") ? ` ${name}="${node.attrs[name]}"` : "",
263 )
264 .join("")
265 : "";
266 reserveMarkup(tag.length * 2 + spans.length + 5);
267 return `<${tag}${spans}>${children}</${tag}>`;
268}
269async function odfHtml(node: XmlNode, archive: JSZip): Promise<string> {
270 if (node.name === "#text") return pipe(text(node), escape, boundedMarkup);
271 if (node.name === "text:s" || node.name === "text:tab")
272 return boundedMarkup(
273 `<span data-odf-whitespace>${node.name === "text:tab" ? "	" : " ".repeat(repeat(node.attrs["text:c"], 100))}</span>`,
274 );
275 if (node.name === "text:line-break") return boundedMarkup("<br>");
276 if (node.name === "draw:image") {
277 const src = await imageData(
278 archive,
279 archivePath("content.xml", node.attrs["xlink:href"] ?? ""),
280 );
281 return src ? `<img src="${src}" alt="">` : "";
282 }
283 if (
284 [
285 "office:annotation",
286 "presentation:notes",
287 "text:tracked-changes",
288 "office:scripts",
289 "draw:object",
290 "draw:object-ole",
291 "text:table-of-content-source",
292 "text:illustration-index-source",
293 "text:table-index-source",
294 "text:object-index-source",
295 "text:user-index-source",
296 "text:alphabetical-index-source",
297 "text:bibliography-source",
298 ].includes(node.name)
299 )
300 return "";
301 let children = "";
302 for (const child of node.children) children += await odfHtml(child, archive);
303 const tags: Record<string, string> = {
304 "text:p": "p",
305 "text:h": "h2",
306 "text:span": "span",
307 "text:list": "ul",
308 "text:list-item": "li",
309 "table:table": "table",
310 "table:table-row": "tr",
311 "table:table-cell": "td",
312 };
313 const tag = tags[node.name];
314 if (!tag) return children;
315 const count =
316 tag === "tr"
317 ? repeat(node.attrs["table:number-rows-repeated"], TABLE_PREVIEW_MAX_ROWS)
318 : tag === "td"
319 ? repeat(node.attrs["table:number-columns-repeated"], TABLE_PREVIEW_MAX_COLUMNS)
320 : 1;
321 const markup = `<${tag}>${children}</${tag}>`;
322 reserveMarkup(count * markup.length - children.length);
323 return markup.repeat(count);
324}
325function repeat(value: string | undefined, max: number) {
326 const count = Number(value ?? 1);
327 if (!Number.isSafeInteger(count) || count < 1)
328 throw new PreviewError({ code: "repeated-content-invalid" });
329 return Math.min(count, max);
330}
331export async function openDocument(
332 archive: JSZip,
333 kind: "odt" | "ods" | "odp",
334): Promise<OfficeWorkerResult> {
335 markupBytes = 0;
336 const source = await archive.file("content.xml")?.async("string");
337 if (!source) throw new PreviewError({ code: "odf-no-content" });
338 const root = parseXml(source);
339 if (kind === "ods") {
340 const tables = find(root, "table:table");
341 if (!tables.length || tables.length > 100) throw new PreviewError({ code: "ods-sheet-count" });
342 let cellBytes = 0;
343 return {
344 type: "ods",
345 sheets: tables.map((table) => {
346 const rows: string[][] = [];
347 let truncated = false;
348 let pendingEmptyRows = 0;
349 for (const row of find(table, "table:table-row")) {
350 const cells: string[] = [];
351 for (const cell of row.children.filter((child) =>
352 ["table:table-cell", "table:covered-table-cell"].includes(child.name),
353 )) {
354 const value =
355 find(cell, "text:p", "office:annotation").map(text).join("\n") ||
356 cell.attrs["office:value"] ||
357 cell.attrs["office:date-value"] ||
358 cell.attrs["office:time-value"] ||
359 cell.attrs["office:boolean-value"] ||
360 cell.attrs["office:string-value"] ||
361 "";
362 const count = repeat(
363 cell.attrs["table:number-columns-repeated"],
364 TABLE_PREVIEW_MAX_COLUMNS + 1,
365 );
366 if (value && cells.length + count > TABLE_PREVIEW_MAX_COLUMNS) truncated = true;
367 for (let i = 0; i < count && cells.length < TABLE_PREVIEW_MAX_COLUMNS; i++) {
368 if (value.length > 10_000) throw new PreviewError({ code: "ods-cell-too-large" });
369 cells.push(value);
370 }
371 }
372 while (cells.at(-1) === "") cells.pop();
373 const count = repeat(row.attrs["table:number-rows-repeated"], TABLE_PREVIEW_MAX_ROWS + 1);
374 if (!cells.length) {
375 pendingEmptyRows = Math.min(TABLE_PREVIEW_MAX_ROWS + 1, pendingEmptyRows + count);
376 continue;
377 }
378 while (pendingEmptyRows > 0 && rows.length < TABLE_PREVIEW_MAX_ROWS) {
379 rows.push([]);
380 pendingEmptyRows--;
381 }
382 pendingEmptyRows = 0;
383 if (rows.length + count > TABLE_PREVIEW_MAX_ROWS) truncated = true;
384 if (rows.length >= TABLE_PREVIEW_MAX_ROWS) break;
385 for (let i = 0; i < count && rows.length < TABLE_PREVIEW_MAX_ROWS; i++) {
386 cellBytes += cells.reduce((size, cell) => size + cell.length, 0);
387 if (cellBytes > 8 * 1024 * 1024) throw new PreviewError({ code: "ods-too-much-text" });
388 rows.push(cells);
389 }
390 }
391 return {
392 name: table.attrs["table:name"] || undefined,
393 rows,
394 rowCount: rows.length,
395 columns: rows.reduce((columns, row) => Math.max(columns, row.length), 1),
396 truncated,
397 };
398 }),
399 };
400 }
401 const pages = kind === "odp" ? find(root, "draw:page") : find(root, "office:text");
402 if (!pages.length || pages.length > 500) throw new PreviewError({ code: "odf-page-count" });
403 const rendered = [];
404 for (const page of pages) {
405 rendered.push({
406 title: page.attrs["draw:name"] || undefined,
407 html: await odfHtml(page, archive),
408 });
409 }
410 return { type: "document", navigation: kind === "odp" ? "slide" : "page", pages: rendered };
411}
412export async function openEpub(archive: JSZip): Promise<OfficeWorkerResult> {
413 markupBytes = 0;
414 const container = parseXml((await archive.file("META-INF/container.xml")?.async("string")) ?? "");
415 const rootfile = find(container, "rootfile")[0]?.attrs["full-path"];
416 if (!rootfile || !archive.file(rootfile)) throw new PreviewError({ code: "epub-no-package" });
417 const packageRoot = parseXml(await archive.file(rootfile)!.async("string"));
418 const manifest = new Map(find(packageRoot, "item").map((item) => [item.attrs.id, item]));
419 const spine = find(packageRoot, "itemref");
420 if (!spine.length || spine.length > 500) throw new PreviewError({ code: "epub-chapter-count" });
421 const pages = [];
422 for (const itemref of spine) {
423 const item = manifest.get(itemref.attrs.idref);
424 if (!item || item.attrs["media-type"] !== "application/xhtml+xml") continue;
425 const path = archivePath(rootfile, item.attrs.href ?? "");
426 const entry = path ? archive.file(path) : null;
427 if (!entry || !path) continue;
428 const chapter = parseXml(await entry.async("string"));
429 pages.push({
430 title:
431 text(find(chapter, "title")[0] ?? find(chapter, "h1")[0] ?? chapter)
432 .trim()
433 .slice(0, 120) || undefined,
434 html: await epubHtml(chapter, archive, path),
435 });
436 }
437 if (!pages.length) throw new PreviewError({ code: "epub-no-chapters" });
438 return { type: "document", navigation: "chapter", pages };
439}
440function record(value: unknown): Record<string, unknown> {
441 return value !== null && typeof value === "object" && !Array.isArray(value)
442 ? (value as Record<string, unknown>)
443 : {};
444}
445function notebookText(value: unknown, limit = 256_000): string {
446 const result =
447 typeof value === "string"
448 ? value
449 : Array.isArray(value)
450 ? value.filter((part) => typeof part === "string").join("")
451 : "";
452 if (result.length > limit) throw new PreviewError({ code: "notebook-cell-too-large" });
453 return result;
454}
455// IPython traceback frames carry ANSI SGR colors and may omit a final newline.
456function tracebackLines(value: unknown): unknown {
457 if (!Array.isArray(value)) return value;
458 const frames = value
459 .filter((frame): frame is string => typeof frame === "string")
460 .map(terminalOutputPlainText);
461 return frames.map((frame, index) =>
462 index && !frames[index - 1]!.endsWith("\n") ? `\n${frame}` : frame,
463 );
464}
465export function openNotebook(bytes: ArrayBuffer): OfficeWorkerResult {
466 if (bytes.byteLength > 8 * 1024 * 1024) throw new PreviewError({ code: "notebook-too-large" });
467 const notebook = record(JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes)));
468 if (notebook.nbformat !== 4 || !Array.isArray(notebook.cells) || notebook.cells.length > 500)
469 throw new PreviewError({ code: "notebook-unsupported" });
470 const language = String(record(record(notebook.metadata).language_info).name ?? "text")
471 .replaceAll(/[^a-z\d+#-]/gi, "")
472 .slice(0, 40);
473 const cells: NotebookCell[] = notebook.cells.map((value) => {
474 const cell = record(value);
475 const outputs = Array.isArray(cell.outputs) ? cell.outputs : [];
476 if (outputs.length > 100) throw new PreviewError({ code: "notebook-too-many-outputs" });
477 return {
478 kind: cell.cell_type === "markdown" ? "markdown" : cell.cell_type === "code" ? "code" : "raw",
479 source: notebookText(cell.source),
480 outputs: outputs
481 .map((value) => {
482 const output = record(value);
483 const data = record(output.data);
484 for (const mime of ["image/png", "image/jpeg", "image/gif", "image/webp"]) {
485 if (data[mime]) {
486 const base64 = notebookText(data[mime], 4 * 1024 * 1024).replaceAll(/\s/g, "");
487 if (base64ImageFits(base64))
488 return { kind: "image" as const, text: `data:${mime};base64,${base64}` };
489 }
490 }
491 const html = notebookText(data["text/html"]);
492 if (html.trim() && htmlImagesFit(html)) return { kind: "html" as const, text: html };
493 return {
494 kind: "text" as const,
495 text: terminalOutputPlainText(
496 notebookText(output.text ?? data["text/plain"] ?? tracebackLines(output.traceback)),
497 ),
498 };
499 })
500 .filter((output) => output.text.trim().length > 0),
501 };
502 });
503 return { type: "notebook", language, cells };
504}
505
506// Characters RTF writes as control symbols (`\~`) and control words (`\emspace`).
507const RTF_CHARACTERS = new Map([
508 ["~", "\u00a0"],
509 ["_", "\u2011"],
510 ["-", "\u00ad"],
511 ["tab", "\t"],
512 ["endash", "–"],
513 // oxlint-disable-next-line t3code/no-em-dash-copy -- Preserve the RTF document's punctuation.
514 ["emdash", "—"],
515 ["bullet", "•"],
516 ["lquote", "‘"],
517 ["rquote", "’"],
518 ["ldblquote", "“"],
519 ["rdblquote", "”"],
520 ["enspace", "\u2002"],
521 ["emspace", "\u2003"],
522 ["qmspace", "\u2005"],
523 ["zwbo", "\u200b"],
524 ["zwnj", "\u200c"],
525 ["zwj", "\u200d"],
526 ["ltrmark", "\u200e"],
527 ["rtlmark", "\u200f"],
528]);
529
530export function openRtf(bytes: ArrayBuffer): OfficeWorkerResult {
531 if (bytes.byteLength > 8 * 1024 * 1024) throw new PreviewError({ code: "rtf-too-large" });
532 // Keep byte offsets intact for binary destinations and multibyte code pages.
533 const input = new Uint8Array(bytes);
534 let source = "";
535 for (let offset = 0; offset < input.length; offset += 8192)
536 source += String.fromCharCode(...input.subarray(offset, offset + 8192));
537 if (!source.startsWith("{\\rtf")) throw new PreviewError({ code: "rtf-invalid" });
538 let state = {
539 skip: false,
540 deleted: false,
541 bold: false,
542 italic: false,
543 underline: false,
544 uc: 1,
545 font: 0,
546 fontTable: false,
547 decoder: new TextDecoder("windows-1252"),
548 };
549 const fonts = new Map<number, TextDecoder>();
550 let defaultFont = 0;
551 const stack: (typeof state)[] = [];
552 let html = "";
553 const pages: { title: undefined; html: string }[] = [];
554 let completedLength = 0;
555 const finishPage = () => {
556 if (pages.length >= 500) throw new PreviewError({ code: "rtf-too-many-pages" });
557 pages.push({ title: undefined, html: `<p>${html}</p>` });
558 completedLength += html.length;
559 html = "";
560 };
561 let run = "";
562 let fallback = 0;
563 const hidden = () => state.skip || state.deleted;
564 const encoded = new Uint8Array(bytes.byteLength);
565 let encodedLength = 0;
566 const flush = () => {
567 if (encodedLength) {
568 run += escape(
569 (fonts.get(state.font) ?? state.decoder).decode(encoded.subarray(0, encodedLength)),
570 );
571 encodedLength = 0;
572 }
573 if (completedLength + html.length + run.length > 8 * 1024 * 1024)
574 throw new PreviewError({ code: "rtf-too-much-content" });
575 if (!run) return;
576 let span = run;
577 if (state.bold) span = `<strong>${span}</strong>`;
578 if (state.italic) span = `<em>${span}</em>`;
579 if (state.underline) span = `<u>${span}</u>`;
580 html += span;
581 run = "";
582 };
583 const emit = (value: string, skip = hidden()) => {
584 if (fallback > 0) {
585 fallback--;
586 return;
587 }
588 if (skip) return;
589 run += escape(value);
590 if (completedLength + html.length + run.length > 8 * 1024 * 1024)
591 throw new PreviewError({ code: "rtf-too-much-content" });
592 };
593 const emitByte = (value: number) => {
594 if (fallback > 0) fallback--;
595 else if (!hidden()) encoded[encodedLength++] = value;
596 };
597 for (let i = 0; i < source.length;) {
598 const char = source[i++];
599 if (char === "{") {
600 flush();
601 fallback = 0;
602 if (stack.length > 100) throw new PreviewError({ code: "rtf-too-deep" });
603 stack.push({ ...state });
604 } else if (char === "}") {
605 flush();
606 fallback = 0;
607 const parent = stack.pop();
608 if (!parent) throw new PreviewError({ code: "rtf-damaged" });
609 state = parent;
610 } else if (char === "\\") {
611 const next = source[i];
612 if (next === "'") {
613 const hex = source.slice(i + 1, i + 3);
614 if (!/^[\da-f]{2}$/i.test(hex)) throw new PreviewError({ code: "rtf-byte-escape" });
615 i += 3;
616 emitByte(Number.parseInt(hex, 16));
617 continue;
618 }
619 flush();
620 if (next === "\\" || next === "{" || next === "}") {
621 i++;
622 emit(next);
623 continue;
624 }
625 if (next === "*") {
626 state.skip = true;
627 i++;
628 continue;
629 }
630 const match = /^([a-z]+)(-?\d+)? ?/i.exec(source.slice(i));
631 if (!match) {
632 const character = RTF_CHARACTERS.get(next!);
633 if (character) emit(character);
634 // A backslash before a line break is \par; TextEdit ends paragraphs this way.
635 else if ((next === "\n" || next === "\r") && !hidden()) html += "<br>";
636 i++;
637 continue;
638 }
639 i += match[0].length;
640 const word = match[1];
641 const arg = match[2] === undefined ? 1 : Number(match[2]);
642 if (word === "bin") {
643 if (!Number.isSafeInteger(arg) || arg < 0 || arg > source.length - i)
644 throw new PreviewError({ code: "rtf-binary-data" });
645 i += arg;
646 }
647 if (fallback > 0) {
648 fallback--;
649 continue;
650 }
651 if (word === "fonttbl") {
652 state.fontTable = true;
653 state.skip = true;
654 } else if (word === "deff") state.font = defaultFont = arg;
655 else if (word === "f") state.font = arg;
656 else if (word === "fcharset" && state.fontTable) {
657 const label = (
658 {
659 0: state.decoder.encoding,
660 1: state.decoder.encoding,
661 77: "macintosh",
662 128: "shift_jis",
663 129: "euc-kr",
664 134: "gbk",
665 136: "big5",
666 161: "windows-1253",
667 162: "windows-1254",
668 163: "windows-1258",
669 177: "windows-1255",
670 178: "windows-1256",
671 186: "windows-1257",
672 204: "windows-1251",
673 222: "windows-874",
674 238: "windows-1250",
675 255: "ibm866",
676 } as Record<number, string>
677 )[arg];
678 if (label) fonts.set(state.font, new TextDecoder(label));
679 } else if (
680 [
681 "colortbl",
682 "stylesheet",
683 "info",
684 "pict",
685 "object",
686 "fldinst",
687 "header",
688 "headerl",
689 "headerr",
690 "headerf",
691 "footer",
692 "footerl",
693 "footerr",
694 "footerf",
695 "filetbl",
696 "datastore",
697 "themedata",
698 ].includes(word!)
699 )
700 state.skip = true;
701 else if (word === "mac") state.decoder = new TextDecoder("macintosh");
702 else if (word === "ansicpg") {
703 const label =
704 (
705 {
706 65001: "utf-8",
707 932: "shift_jis",
708 936: "gbk",
709 949: "euc-kr",
710 950: "big5",
711 874: "windows-874",
712 10000: "macintosh",
713 } as Record<number, string>
714 )[arg] ?? `windows-${arg}`;
715 try {
716 state.decoder = new TextDecoder(label);
717 } catch {
718 throw new PreviewError({ code: "rtf-code-page" });
719 }
720 } else if (word === "b") state.bold = arg !== 0;
721 else if (word === "i") state.italic = arg !== 0;
722 else if (word === "ul") state.underline = arg !== 0;
723 else if (word === "ulnone") state.underline = false;
724 else if (word === "deleted") state.deleted = arg !== 0;
725 else if (word === "plain")
726 state = {
727 ...state,
728 deleted: false,
729 bold: false,
730 italic: false,
731 underline: false,
732 font: defaultFont,
733 };
734 else if (word === "uc") state.uc = Math.max(0, Math.min(10, arg));
735 else if (word === "u") {
736 fallback = 0;
737 // TextEdit writes a soft line break as U+2028, where Chromium does not break the line.
738 if (arg !== 0x2028) emit(String.fromCharCode(arg < 0 ? arg + 65536 : arg));
739 else if (!hidden()) html += "<br>";
740 fallback = state.uc;
741 } else if (!hidden() && word === "page") finishPage();
742 else if (word === "cell") emit("\t", state.skip);
743 else if (
744 (!state.skip && word === "row") ||
745 (!hidden() && (word === "par" || word === "line"))
746 )
747 html += "<br>";
748 // Writers usually end the paragraph before these breaks; a second break would add a blank line.
749 else if (!hidden() && (word === "sect" || word === "column")) {
750 if (html && !html.endsWith("<br>")) html += "<br>";
751 } else {
752 const character = RTF_CHARACTERS.get(word!);
753 if (character) emit(character);
754 }
755 } else if (char !== "\r" && char !== "\n" && char) emitByte(char.charCodeAt(0));
756 }
757 if (stack.length) throw new PreviewError({ code: "rtf-damaged" });
758 flush();
759 if (html || !pages.length) finishPage();
760 return { type: "document", navigation: "page", pages };
761}