Open History to see the last commit
1import { pipe } from "effect/Function";
2import { IMAGE_DIMENSIONS_HEADER_BYTES } from "@t3tools/shared/imageDimensions";
3import { notebookOutputGroups, notebookStreamText } from "@t3tools/shared/notebookOutput";
4import { decodeHTMLAttribute } from "entities";
5import type JSZip from "jszip";
6import { terminalOutputPlainText } from "@t3tools/shared/terminalOutput";
7
8import { type OfficeWorkerResult, type NotebookCell } from "./officePreviewProtocol";
9import { isPreviewError, PreviewError } from "./previewFailure";
10import { officeXmlDecoder } from "./officeArchive";
11import { isSignedNumberDisplay } from "./office/sheet-cells";
12import {
13 archivePath,
14 escape,
15 find,
16 imageFits,
17 parseXml,
18 repeat,
19 text,
20 type XmlNode,
21} from "./documentPreviewXml";
22
23const TABLE_PREVIEW_MAX_ROWS = 500;
24const TABLE_PREVIEW_MAX_COLUMNS = 50;
25// Window-title (OSC) controls; terminalOutputPlainText strips only CSI.
26const NOTEBOOK_OSC_PATTERN = /\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\)/gu;
27
28function base64ImageFits(base64: string) {
29 return (
30 /^[a-z\d+/]*={0,2}$/i.test(base64) &&
31 base64.length % 4 !== 1 &&
32 (!base64.endsWith("=") || base64.length % 4 === 0) &&
33 imageFits(
34 Uint8Array.from(
35 atob(base64.slice(0, 4 * Math.ceil(IMAGE_DIMENSIONS_HEADER_BYTES / 3))),
36 (char) => char.charCodeAt(0),
37 ),
38 )
39 );
40}
41function htmlImagesFit(html: string) {
42 // HTML attribute entities can obscure a data URL until the client parses it.
43 for (const match of decodeHTMLAttribute(html).matchAll(
44 /(?<=[\t\n\f\r "'/])src[\t\n\f\r ]*=[\t\n\f\r ]*(["'])[\t\n\f\r ]*data:image\/(?:png|jpeg|gif|webp);base64,([a-z\d+/\t\n\f\r ]*(?:=[\t\n\f\r ]*){0,2})\1|data:image\/(?:png|jpeg|gif|webp);base64,([a-z\d+/]*={0,2})/gi,
45 ))
46 if (!base64ImageFits(match[2]?.replaceAll(/[\t\n\f\r ]/g, "") ?? match[3]!)) return false;
47 return true;
48}
49async function imageData(archive: JSZip, path: string | null): Promise<string> {
50 if (!path) return "";
51 const mime = (
52 { png: "png", jpg: "jpeg", jpeg: "jpeg", gif: "gif", webp: "webp" } as Record<string, string>
53 )[path.split(".").at(-1)?.toLowerCase() ?? ""];
54 const entry = archive.file(path);
55 if (!mime || !entry) return "";
56 const bytes = await entry.async("uint8array");
57 if (bytes.length > 4 * 1024 * 1024 || !imageFits(bytes)) return "";
58 reserveMarkup(4 * Math.ceil(bytes.length / 3) + 100);
59 return `data:image/${mime};base64,${await entry.async("base64")}`;
60}
61let markupBytes = 0;
62const odfNotes: string[] = [];
63// Impress saves a slide number field in a slide shape as the placeholder "<number>".
64let odfSlide = 0;
65function reserveMarkup(size: number) {
66 markupBytes += size;
67 if (markupBytes > 16 * 1024 * 1024) throw new PreviewError({ code: "rendered-too-large" });
68}
69function boundedMarkup(value: string): string {
70 reserveMarkup(value.length);
71 return value;
72}
73function odfListStart(node: XmlNode | undefined): number | undefined {
74 const start = node?.attrs["text:start-value"]?.trim();
75 if (!start || !/^[+-]?\d+$/.test(start)) return undefined;
76 const value = Number(start);
77 return value >= 0 && value <= 2_147_483_647 ? value : undefined;
78}
79// Writer hides text whose character style sets text:display="none"; a style without it inherits from its
80// parent style, and a span whose styles set nothing inherits from the enclosing span.
81// ODF 1.3 Part 3 §19.510: parent-style-name names a common style, never an automatic one.
82// Paragraph styles hide their paragraph's text the same way, within the paragraph family.
83function odfStyleHidden(
84 styles: Map<string, XmlNode>,
85 family: "text" | "paragraph",
86 name = "",
87): boolean | undefined {
88 let style = styles.get(`auto\n${family}\n${name}`) ?? styles.get(`common\n${family}\n${name}`);
89 for (const seen = new Set<XmlNode>(); style && !seen.has(style);) {
90 seen.add(style);
91 const display = find(style, "style:text-properties")[0]?.attrs["text:display"]?.trim();
92 if (display) return display === "none";
93 style = styles.get(`common\n${family}\n${style.attrs["style:parent-style-name"] ?? ""}`);
94 }
95 return undefined;
96}
97// Writer saves bold, italic, underline and strikethrough as character or paragraph style properties, like RTF's \b, \i, \ul and \strike.
98function odfStyleMarks(styles: Map<string, XmlNode>, family: "text" | "paragraph", name = "") {
99 const found: Partial<Record<string, string>> = {};
100 let style = styles.get(`auto\n${family}\n${name}`) ?? styles.get(`common\n${family}\n${name}`);
101 for (const seen = new Set<XmlNode>(); style && !seen.has(style);) {
102 seen.add(style);
103 const properties = find(style, "style:text-properties")[0]?.attrs ?? {};
104 for (const key of [
105 "fo:font-weight",
106 "fo:font-style",
107 "style:text-underline-style",
108 "style:text-line-through-style",
109 "style:text-position",
110 ])
111 found[key] ??= properties[key]?.trim();
112 style = styles.get(`common\n${family}\n${style.attrs["style:parent-style-name"] ?? ""}`);
113 }
114 // Writer saves raised and lowered text as "super", "sub" or a signed percentage; "0%" is baseline.
115 const position = found["style:text-position"];
116 const raised = position?.startsWith("super")
117 ? 1
118 : position?.startsWith("sub")
119 ? -1
120 : Math.sign(parseFloat(position ?? "") || 0);
121 const script: "sup" | "sub" | null | undefined =
122 position === undefined ? undefined : raised > 0 ? "sup" : raised < 0 ? "sub" : null;
123 const on = (key: string) => !!found[key] && found[key] !== "none" && found[key] !== "normal";
124 const marks = [
125 ...(/^(?:bold|[6-9]00)$/.test(found["fo:font-weight"] ?? "") ? ["strong"] : []),
126 ...(on("fo:font-style") ? ["em"] : []),
127 ...(on("style:text-underline-style") ? ["u"] : []),
128 ...(on("style:text-line-through-style") ? ["s"] : []),
129 ];
130 return {
131 marks,
132 script,
133 normalWeight: /^(?:normal|400)$/.test(found["fo:font-weight"] ?? ""),
134 normalStyle: found["fo:font-style"] === "normal",
135 };
136}
137// Writer recomputes hidden-text and hidden-paragraph fields from text:condition on load and ignores
138// the saved text:is-hidden, so only a literal condition can be decided here; others stay undecided.
139function odfFieldHidden(field: XmlNode): boolean | undefined {
140 const condition = (field.attrs["text:condition"] ?? "")
141 .trim()
142 .replace(/^ooow:/, "")
143 .trim();
144 if (!condition || /^false$/i.test(condition)) return false;
145 if (/^true$/i.test(condition)) return true;
146 return /^[+-]?(?:\d+\.?\d*|\.\d+)$/.test(condition) ? Number(condition) !== 0 : undefined;
147}
148async function odfHtml(
149 node: XmlNode,
150 archive: JSZip,
151 listStyles: Map<string, XmlNode>,
152 imageAlt = "",
153 inRepeatedRow = false,
154 list: [string, number] = ["", 0],
155 inOrderedList = false,
156 listEnds = new Map<string, number>(),
157 hidden = false,
158 // Wraps text rather than the span, so an explicit baseline inside raised text can reset it.
159 script: "sup" | "sub" | null = null,
160): Promise<string> {
161 const slideNumber = node.name === "text:page-number" && odfSlide && text(node) === "<number>";
162 if (
163 hidden &&
164 (slideNumber ||
165 ["#text", "text:s", "text:tab", "text:line-break", "text:note", "draw:image"].includes(
166 node.name,
167 ))
168 )
169 return "";
170 if (node.name === "#text" || slideNumber)
171 return pipe(
172 slideNumber ? String(odfSlide) : text(node),
173 escape,
174 (value) => (script && value ? `<${script}>${value}</${script}>` : value),
175 boundedMarkup,
176 );
177 if (node.name === "text:s" || node.name === "text:tab")
178 return boundedMarkup(
179 `<span data-odf-whitespace>${node.name === "text:tab" ? "	" : " ".repeat(repeat(node.attrs["text:c"], 100))}</span>`,
180 );
181 if (node.name === "text:line-break") return boundedMarkup("<br>");
182 if (node.name === "text:hidden-text") {
183 const value = node.attrs["text:string-value"];
184 const fieldHidden = odfFieldHidden(node);
185 if (fieldHidden) return "";
186 if (fieldHidden === false && value !== undefined)
187 return hidden ? "" : pipe(value, escape, boundedMarkup);
188 }
189 if (node.name === "text:p" || node.name === "text:h") {
190 // A frame or note anchored here holds its own paragraphs, whose fields do not hide this one.
191 const ownFields = (parent: XmlNode): XmlNode[] =>
192 parent.children.flatMap((child) =>
193 child.name === "text:hidden-paragraph"
194 ? [child]
195 : child.name === "text:p" || child.name === "text:h"
196 ? []
197 : ownFields(child),
198 );
199 const fields = ownFields(node);
200 if (fields.length && fields.every((field) => odfFieldHidden(field))) return "";
201 }
202 if (node.name === "text:note") {
203 const mark = `<sup>${escape(find(node, "text:note-citation", "text:note-body").map(text).join(""))}</sup>`;
204 const [body] = find(node, "text:note-body");
205 const html = body ? (await odfHtml(body, archive, listStyles)).trimStart() : "";
206 odfNotes.push(
207 html.startsWith("<p>")
208 ? `<p>${boundedMarkup(mark)}${html.slice(3)}`
209 : `${boundedMarkup(`<p>${mark}</p>`)}${html}`,
210 );
211 return boundedMarkup(mark);
212 }
213 if (node.name === "draw:image") {
214 const src = await imageData(
215 archive,
216 archivePath("content.xml", node.attrs["xlink:href"] ?? ""),
217 );
218 return src ? `<img src="${src}" alt="${boundedMarkup(escape(imageAlt))}">` : "";
219 }
220 if (
221 [
222 "office:annotation",
223 "presentation:notes",
224 "svg:title",
225 "svg:desc",
226 "text:tracked-changes",
227 "office:scripts",
228 "draw:object",
229 "draw:object-ole",
230 "text:table-of-content-source",
231 "text:illustration-index-source",
232 "text:table-index-source",
233 "text:object-index-source",
234 "text:user-index-source",
235 "text:alphabetical-index-source",
236 "text:bibliography-source",
237 "table:covered-table-cell",
238 ].includes(node.name) ||
239 (node.name === "text:section" && node.attrs["text:display"]?.trim() === "none") ||
240 // LibreOffice marks objects hidden on screen "none", or "printer" when they still print.
241 ["none", "printer"].includes(node.attrs["drawooo:display"]?.trim() ?? "")
242 )
243 return "";
244 const childImageAlt =
245 node.name === "draw:frame"
246 ? ["svg:title", "svg:desc"]
247 .map((name) => node.children.find((child) => child.name === name))
248 .map((child) => (child ? text(child).trim() : ""))
249 .filter(Boolean)
250 .join(" ")
251 : "";
252 let children = "";
253 const paragraph = node.name === "text:p" || node.name === "text:h";
254 const childHidden =
255 node.name === "text:span" || paragraph
256 ? (odfStyleHidden(
257 listStyles,
258 paragraph ? "paragraph" : "text",
259 node.attrs["text:style-name"],
260 ) ?? hidden)
261 : hidden;
262 const repeatedRow =
263 node.name === "table:table-row"
264 ? Number(node.attrs["table:number-rows-repeated"]) > 1
265 : inRepeatedRow;
266 // Sub-lists nest directly in list items; a list in a table cell, frame or note restarts at level 1.
267 const nextList: [string, number] =
268 node.name === "text:list"
269 ? [node.attrs["text:style-name"] || list[0], list[1] + 1]
270 : node.name === "text:list-item" || node.name === "text:list-header"
271 ? list
272 : ["", 0];
273 const numberingLevel =
274 node.name === "text:list"
275 ? listStyles
276 .get(nextList[0])
277 ?.children.find(
278 (level) =>
279 level.name === "text:list-level-style-number" &&
280 level.attrs["text:level"] === String(nextList[1]) &&
281 !!level.attrs["style:num-format"],
282 )
283 : undefined;
284 const style =
285 node.name === "text:span" || paragraph
286 ? odfStyleMarks(listStyles, paragraph ? "paragraph" : "text", node.attrs["text:style-name"])
287 : undefined;
288 // A paragraph in a frame inside raised text sits at its own style's position.
289 const childScript = style?.script !== undefined ? style.script : paragraph ? null : script;
290 for (const child of node.children)
291 children += await odfHtml(
292 child,
293 archive,
294 listStyles,
295 childImageAlt,
296 repeatedRow,
297 nextList,
298 numberingLevel !== undefined,
299 listEnds,
300 childHidden,
301 childScript,
302 );
303 if (paragraph && childHidden && !children) return "";
304 const tags: Record<string, string> = {
305 "text:p": "p",
306 "text:h": "h2",
307 "text:span": "span",
308 "text:list": numberingLevel ? "ol" : "ul",
309 "text:list-item": "li",
310 "table:table": "table",
311 "table:table-row": "tr",
312 "table:table-cell": "td",
313 "text:ruby": "ruby",
314 "text:ruby-text": "rt",
315 };
316 const level = node.name === "text:h" ? Number(node.attrs["text:outline-level"]) : NaN;
317 const tag =
318 Number.isSafeInteger(level) && level >= 1 ? `h${Math.min(level, 6)}` : tags[node.name];
319 if (!tag || (tag === "span" && childHidden)) return children;
320 const { marks, normalWeight, normalStyle } = style ?? {
321 marks: [],
322 normalWeight: false,
323 normalStyle: false,
324 };
325 // Writer's heading styles are bold; a <strong> inside an already bold heading would render heavier.
326 const content = marks
327 .filter((mark) => mark !== "strong" || node.name !== "text:h")
328 .reduceRight((html, mark) => `<${mark}>${html}</${mark}>`, children);
329 const count =
330 tag === "tr"
331 ? repeat(node.attrs["table:number-rows-repeated"], TABLE_PREVIEW_MAX_ROWS)
332 : tag === "td"
333 ? repeat(node.attrs["table:number-columns-repeated"], TABLE_PREVIEW_MAX_COLUMNS)
334 : 1;
335 // A list split by a paragraph continues the one it names, or the last one in its style and level.
336 const styleKey = `${nextList[0]}\n${nextList[1]}`;
337 const continueKey =
338 node.attrs["text:continue-list"] ??
339 (node.attrs["text:continue-numbering"] === "true" ? styleKey : undefined);
340 const continuedFrom = numberingLevel && continueKey ? listEnds.get(continueKey) : undefined;
341 const start =
342 continuedFrom === undefined
343 ? odfListStart(tag === "li" && inOrderedList ? node : numberingLevel)
344 : continuedFrom + 1;
345 if (numberingLevel) {
346 let last = (start ?? 1) - 1;
347 for (const item of node.children)
348 if (item.name === "text:list-item") last = odfListStart(item) ?? last + 1;
349 listEnds.set(styleKey, last);
350 if (node.attrs["xml:id"]) listEnds.set(node.attrs["xml:id"], last);
351 }
352 let attributes = start === undefined ? "" : ` ${tag === "ol" ? "start" : "value"}="${start}"`;
353 if (normalWeight) attributes += " data-odf-normal-weight";
354 if (normalStyle) attributes += " data-odf-normal-style";
355 const format = numberingLevel?.attrs["style:num-format"] ?? "";
356 if (/^[aAiI]$/.test(format)) attributes += ` type="${format}"`;
357 // Spans on repeated cells or rows would multiply past the preview's table limits.
358 if (tag === "td" && count === 1)
359 for (const [name, attr, max] of [
360 ["colspan", "table:number-columns-spanned", TABLE_PREVIEW_MAX_COLUMNS],
361 ["rowspan", "table:number-rows-spanned", repeatedRow ? 1 : TABLE_PREVIEW_MAX_ROWS],
362 ] as const) {
363 const span = Number(node.attrs[attr]);
364 if (max > 1 && Number.isSafeInteger(span) && span > 1)
365 attributes += ` ${name}="${Math.min(span, max)}"`;
366 }
367 const markup = `<${tag}${attributes}>${content}</${tag}>`;
368 reserveMarkup(count * markup.length - children.length);
369 return markup.repeat(count);
370}
371// A drawing can contain paragraphs of its own, even when anchored inside cell text.
372function withoutOdsDrawings(node: XmlNode): XmlNode | undefined {
373 if (node.name.startsWith("draw:")) return undefined;
374 let children: XmlNode[] | undefined;
375 for (const [index, child] of node.children.entries()) {
376 const content = withoutOdsDrawings(child);
377 if (content !== child) children ??= node.children.slice(0, index);
378 if (content) children?.push(content);
379 }
380 return children ? { ...node, children } : node;
381}
382function odsCellText(cell: XmlNode): string {
383 const paragraphs = cell.children
384 .filter((child) => child.name !== "office:annotation")
385 .map(withoutOdsDrawings)
386 .flatMap((child) => (!child ? [] : child.name === "text:p" ? [child] : find(child, "text:p")))
387 .map(text);
388 return paragraphs.some(Boolean) ? paragraphs.join("\n") : "";
389}
390function odsColumnRunEnd(node: XmlNode, start: number): number {
391 const end = start + repeat(node.attrs["table:number-columns-repeated"], Number.MAX_SAFE_INTEGER);
392 if (!Number.isSafeInteger(end)) throw new PreviewError({ code: "repeated-content-invalid" });
393 return end;
394}
395
396export type ParsedOdsWorkbook = {
397 readonly type: "ods";
398 readonly sheets: (Extract<OfficeWorkerResult, { type: "ods" }>["sheets"][number] & {
399 /** Visible row and column offsets of signed numeric values. */
400 readonly signedNumberColumns: Partial<Record<number, number[]>>;
401 })[];
402};
403
404export async function openDocument(
405 archive: JSZip,
406 kind: "odt" | "ods" | "odp",
407): Promise<Extract<OfficeWorkerResult, { type: "document" }> | ParsedOdsWorkbook> {
408 markupBytes = 0;
409 odfNotes.length = 0;
410 const content = await archive.file("content.xml")?.async("uint8array");
411 if (!content?.length) throw new PreviewError({ code: "odf-no-content" });
412 const root = parseXml(officeXmlDecoder(content).decode(content));
413 if (kind === "ods") {
414 const tables = find(root, "table:table");
415 if (!tables.length || tables.length > 100) throw new PreviewError({ code: "ods-sheet-count" });
416 const hidden = new Set<string>();
417 for (const style of find(root, "style:style", "office:body"))
418 if (style.attrs["style:family"] === "table" && style.attrs["style:name"])
419 if (find(style, "style:table-properties")[0]?.attrs["table:display"]?.trim() === "false")
420 hidden.add(style.attrs["style:name"]);
421 const visible = tables.filter((table) => !hidden.has(table.attrs["table:style-name"] ?? ""));
422 if (!visible.length) throw new PreviewError({ code: "ods-sheet-count" });
423 let cellBytes = 0;
424 return {
425 type: "ods",
426 sheets: visible.map((table) => {
427 const rows: string[][] = [];
428 const signedNumberColumns: Record<number, number[]> = {};
429 const rowIndexes: number[] = [];
430 let truncated = false;
431 const pendingEmptyRows: number[] = [];
432 // Calc hides rows and columns whose table:visibility is collapse or filter. The preview drops
433 // them and labels the rest with their real positions, so addresses still match Calc.
434 const shown = (node: XmlNode) =>
435 !["collapse", "filter"].includes(node.attrs["table:visibility"]?.trim() ?? "");
436 const columnIndexes: number[] = [];
437 const omittedColumns: { start: number; end: number }[] = [];
438 const addVisibleColumns = (start: number, end: number) => {
439 while (start < end && columnIndexes.length < TABLE_PREVIEW_MAX_COLUMNS)
440 columnIndexes.push(start++);
441 if (start < end) omittedColumns.push({ start, end });
442 };
443 // Skip hidden runs without expanding them into individual columns.
444 let sourceColumn = 0;
445 let hidesColumns = false;
446 for (const column of find(table, "table:table-column")) {
447 const end = odsColumnRunEnd(column, sourceColumn);
448 if (shown(column)) addVisibleColumns(sourceColumn, end);
449 else hidesColumns = true;
450 sourceColumn = end;
451 }
452 addVisibleColumns(sourceColumn, Number.MAX_SAFE_INTEGER);
453 let sourceRow = 0;
454 let hidesRows = false;
455 for (const row of find(table, "table:table-row")) {
456 const firstRow = sourceRow;
457 sourceRow += repeat(row.attrs["table:number-rows-repeated"], Number.MAX_SAFE_INTEGER);
458 if (!shown(row)) {
459 hidesRows = true;
460 continue;
461 }
462 const cells: string[] = [];
463 const signedColumns: number[] = [];
464 let column = 0;
465 for (const cell of row.children.filter((child) =>
466 ["table:table-cell", "table:covered-table-cell"].includes(child.name),
467 )) {
468 const display = odsCellText(cell);
469 const value =
470 cell.name === "table:covered-table-cell" ||
471 // An empty display paragraph is how Calc stores a value its number format hides.
472 (!display &&
473 cell.children.some((child) => child.name === "text:p" && !child.children.length))
474 ? ""
475 : display ||
476 cell.attrs["office:value"] ||
477 cell.attrs["office:date-value"] ||
478 cell.attrs["office:time-value"] ||
479 cell.attrs["office:boolean-value"] ||
480 cell.attrs["office:string-value"] ||
481 "";
482 const end = odsColumnRunEnd(cell, column);
483 if ((columnIndexes[cells.length] ?? Infinity) < end && value.length > 10_000)
484 throw new PreviewError({ code: "ods-cell-too-large" });
485 const type = cell.attrs["office:value-type"];
486 const signedNumber =
487 (type === "float" || type === "percentage" || type === "currency") &&
488 isSignedNumberDisplay(value);
489 while ((columnIndexes[cells.length] ?? Infinity) < end) {
490 if (signedNumber) signedColumns.push(cells.length);
491 cells.push(value);
492 }
493 if (value && !truncated) {
494 // Find the first omitted range whose exclusive end is after this run starts.
495 let lower = 0;
496 let upper = omittedColumns.length;
497 while (lower < upper) {
498 const middle = Math.floor((lower + upper) / 2);
499 if (omittedColumns[middle]!.end <= column) lower = middle + 1;
500 else upper = middle;
501 }
502 truncated = (omittedColumns[lower]?.start ?? Infinity) < end;
503 }
504 column = end;
505 }
506 while (cells.at(-1) === "") cells.pop();
507 const count = Math.min(sourceRow - firstRow, TABLE_PREVIEW_MAX_ROWS + 1);
508 if (!cells.length) {
509 for (let i = 0; i < count && pendingEmptyRows.length <= TABLE_PREVIEW_MAX_ROWS; i++)
510 pendingEmptyRows.push(firstRow + i);
511 continue;
512 }
513 for (const index of pendingEmptyRows) {
514 if (rows.length >= TABLE_PREVIEW_MAX_ROWS) break;
515 rows.push([]);
516 rowIndexes.push(index);
517 }
518 pendingEmptyRows.length = 0;
519 if (rows.length + count > TABLE_PREVIEW_MAX_ROWS) truncated = true;
520 if (rows.length >= TABLE_PREVIEW_MAX_ROWS) break;
521 for (let i = 0; i < count && rows.length < TABLE_PREVIEW_MAX_ROWS; i++) {
522 cellBytes += cells.reduce((size, cell) => size + cell.length, 0);
523 if (cellBytes > 8 * 1024 * 1024) throw new PreviewError({ code: "ods-too-much-text" });
524 if (signedColumns.length) signedNumberColumns[rows.length] = signedColumns;
525 rows.push(cells);
526 rowIndexes.push(firstRow + i);
527 }
528 }
529 return {
530 name: table.attrs["table:name"]?.trim() ? table.attrs["table:name"] : undefined,
531 rows,
532 signedNumberColumns,
533 rowCount: rows.length,
534 columns: rows.length && rows.reduce((columns, row) => Math.max(columns, row.length), 1),
535 truncated,
536 rowIndexes: hidesRows ? rowIndexes : undefined,
537 columnIndexes: hidesColumns ? columnIndexes : undefined,
538 };
539 }),
540 };
541 }
542 const pages = kind === "odp" ? find(root, "draw:page") : find(root, "office:text");
543 if (!pages.length || pages.length > 500) throw new PreviewError({ code: "odf-page-count" });
544 const listStyles = new Map<string, XmlNode>();
545 // Named styles live in styles.xml; it only decides numbering, marks and hidden text, so a bad part loses them.
546 let named: XmlNode[] = [];
547 const styles = await archive.file("styles.xml")?.async("uint8array");
548 try {
549 if (styles?.length)
550 named = find(parseXml(officeXmlDecoder(styles).decode(styles)), "office:styles");
551 } catch (cause) {
552 if (!isPreviewError(cause) && !(cause instanceof RangeError)) throw cause;
553 }
554 for (const style of [...named, root].flatMap((part) =>
555 find(part, "text:list-style", "office:body"),
556 ))
557 if (style.attrs["style:name"]) listStyles.set(style.attrs["style:name"], style);
558 for (const [prefix, part] of [
559 ...named.map((part) => ["common", part] as const),
560 ["auto", root] as const,
561 ])
562 for (const style of find(part, "style:style", "office:body")) {
563 const family = style.attrs["style:family"];
564 if ((family === "text" || family === "paragraph") && style.attrs["style:name"])
565 listStyles.set(`${prefix}\n${family}\n${style.attrs["style:name"]}`, style);
566 }
567 const rendered = [];
568 for (const page of pages) {
569 odfSlide = kind === "odp" ? rendered.length + 1 : 0;
570 const html = await odfHtml(page, archive, listStyles);
571 rendered.push({
572 title: page.attrs["draw:name"]?.trim() ? page.attrs["draw:name"] : undefined,
573 html: odfNotes.length
574 ? `${html}${boundedMarkup("<hr>")}${odfNotes.splice(0).join("")}`
575 : html,
576 });
577 }
578 return { type: "document", navigation: kind === "odp" ? "slide" : "page", pages: rendered };
579}
580function record(value: unknown): Record<string, unknown> {
581 return value !== null && typeof value === "object" && !Array.isArray(value)
582 ? (value as Record<string, unknown>)
583 : {};
584}
585function notebookText(value: unknown, limit = 256_000): string {
586 const result =
587 typeof value === "string"
588 ? value
589 : Array.isArray(value)
590 ? value.filter((part) => typeof part === "string").join("")
591 : "";
592 if (result.length > limit) throw new PreviewError({ code: "notebook-cell-too-large" });
593 return result;
594}
595// IPython traceback frames carry ANSI SGR colors and may omit a final newline.
596function tracebackLines(value: unknown): unknown {
597 if (!Array.isArray(value)) return value;
598 const frames = value
599 .filter((frame): frame is string => typeof frame === "string")
600 .map(terminalOutputPlainText);
601 return frames.map((frame, index) =>
602 index && !frames[index - 1]!.endsWith("\n") ? `\n${frame}` : frame,
603 );
604}
605export function openNotebook(bytes: ArrayBuffer): OfficeWorkerResult {
606 if (bytes.byteLength > 8 * 1024 * 1024) throw new PreviewError({ code: "notebook-too-large" });
607 const notebook = record(JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes)));
608 if (notebook.nbformat !== 4 || !Array.isArray(notebook.cells) || notebook.cells.length > 500)
609 throw new PreviewError({ code: "notebook-unsupported" });
610 const metadata = record(notebook.metadata);
611 const kernelspec = record(metadata.kernelspec);
612 const explicitLanguage = [record(metadata.language_info).name, kernelspec.language].find(
613 (value): value is string => typeof value === "string" && value !== "",
614 );
615 const language =
616 (
617 explicitLanguage ??
618 (typeof kernelspec.name === "string" && kernelspec.name.toLowerCase() === "python3"
619 ? "python"
620 : "")
621 )
622 .replaceAll(/[^a-z\d+#-]/gi, "")
623 .slice(0, 40) || "text";
624 const cells: NotebookCell[] = notebook.cells.map((value) => {
625 const cell = record(value);
626 // Count outputs as shown: consecutive stream records of one name join into one block.
627 const groups = Array.from(
628 notebookOutputGroups(Array.isArray(cell.outputs) ? cell.outputs : [], notebookText),
629 );
630 if (groups.length > 100) throw new PreviewError({ code: "notebook-too-many-outputs" });
631 return {
632 kind: cell.cell_type === "markdown" ? "markdown" : cell.cell_type === "code" ? "code" : "raw",
633 source: notebookText(cell.source),
634 outputs: Array.from(groups, (group) => {
635 if (group.kind === "stream") {
636 return {
637 kind: "text" as const,
638 text: notebookStreamText(group.text),
639 };
640 }
641 const output = record(group.output);
642 const data = record(output.data);
643 for (const mime of ["image/png", "image/jpeg", "image/gif", "image/webp"]) {
644 if (data[mime]) {
645 const base64 = notebookText(data[mime], 4 * 1024 * 1024).replaceAll(/\s/g, "");
646 if (base64ImageFits(base64))
647 return { kind: "image" as const, text: `data:${mime};base64,${base64}` };
648 }
649 }
650 const html = notebookText(data["text/html"]);
651 if (html.trim() && htmlImagesFit(html)) return { kind: "html" as const, text: html };
652 // Jupyter writes an empty or control-only text/plain beside the Markdown it renders.
653 const plainIsBlank = !terminalOutputPlainText(notebookText(data["text/plain"]))
654 .replaceAll(NOTEBOOK_OSC_PATTERN, "")
655 .trim();
656 const raw = notebookText(
657 output.text ??
658 (plainIsBlank ? undefined : data["text/plain"]) ??
659 data["text/markdown"] ??
660 tracebackLines(output.traceback),
661 );
662 const text =
663 output.output_type === "stream" ? notebookStreamText(raw) : terminalOutputPlainText(raw);
664 if (text.trim() || output.output_type !== "error") return { kind: "text" as const, text };
665 const summary = [output.ename, output.evalue]
666 .filter((part) => typeof part === "string")
667 .map((part) => terminalOutputPlainText(notebookText(part)))
668 .filter((part) => part.trim().length > 0)
669 .join(": ");
670 return { kind: "text" as const, text: summary };
671 }).filter((output) => output.text.trim().length > 0),
672 };
673 });
674 return { type: "notebook", language, cells };
675}
676
677// Characters RTF writes as control symbols (`\~`) and control words (`\emspace`).
678const RTF_CHARACTERS = new Map([
679 ["~", "\u00a0"],
680 ["_", "\u2011"],
681 ["-", "\u00ad"],
682 ["tab", "\t"],
683 ["endash", "–"],
684 // oxlint-disable-next-line t3code/no-em-dash-copy -- Preserve the RTF document's punctuation.
685 ["emdash", "—"],
686 ["bullet", "•"],
687 ["lquote", "‘"],
688 ["rquote", "’"],
689 ["ldblquote", "“"],
690 ["rdblquote", "”"],
691 ["enspace", "\u2002"],
692 ["emspace", "\u2003"],
693 ["qmspace", "\u2005"],
694 ["zwbo", "\u200b"],
695 ["zwnj", "\u200c"],
696 ["zwj", "\u200d"],
697 ["ltrmark", "\u200e"],
698 ["rtlmark", "\u200f"],
699]);
700
701const RTF_UNDERLINE_WORD =
702 /^(?:ul|uld|uldash|uldashd|uldashdd|uldb|ulhair|ulhwave|ulldash|ulth|ulthd|ulthdash|ulthdashd|ulthdashdd|ulthldash|ululdbwave|ulw|ulwave)$/;
703
704const rtfCodePageLabel = (codePage: number) =>
705 (
706 {
707 0: "windows-1252",
708 866: "ibm866",
709 65001: "utf-8",
710 932: "shift_jis",
711 936: "gbk",
712 949: "euc-kr",
713 950: "big5",
714 874: "windows-874",
715 10000: "macintosh",
716 54936: "gb18030",
717 } as Record<number, string>
718 )[codePage] ?? `windows-${codePage}`;
719
720export function openRtf(bytes: ArrayBuffer): OfficeWorkerResult {
721 if (bytes.byteLength > 8 * 1024 * 1024) throw new PreviewError({ code: "rtf-too-large" });
722 // Keep byte offsets intact for binary destinations and multibyte code pages.
723 const input = new Uint8Array(bytes);
724 let source = "";
725 for (let offset = 0; offset < input.length; offset += 8192)
726 source += String.fromCharCode(...input.subarray(offset, offset + 8192));
727 if (!source.startsWith("{\\rtf")) throw new PreviewError({ code: "rtf-invalid" });
728 let state = {
729 skip: false,
730 nestedTableProperties: false,
731 deleted: false,
732 hiddenText: false,
733 inTable: false,
734 bold: false,
735 italic: false,
736 underline: false,
737 strike: false,
738 script: null as "sup" | "sub" | null,
739 uc: 1,
740 font: 0,
741 fontTable: false,
742 fontFile: false,
743 decoder: new TextDecoder("windows-1252"),
744 };
745 // A font's \cpg, else its \fcharset, encodes the bytes written in that font. A \cpg inside
746 // \fontfile encodes the font's file name instead.
747 const fonts = new Map<number, TextDecoder>();
748 let defaultFont = 0;
749 const stack: (typeof state)[] = [];
750 let html = "";
751 const pages: { title: undefined; html: string }[] = [];
752 let completedLength = 0;
753 // Footnotes follow the page text, as in ODT previews; noteDepth marks the open footnote group.
754 let notes = "";
755 let noteCount = 0;
756 let noteDepth: number | undefined;
757 let noteParent = "";
758 const finishPage = () => {
759 if (pages.length >= 500) throw new PreviewError({ code: "rtf-too-many-pages" });
760 pages.push({
761 title: undefined,
762 html: `<p data-rtf-whitespace>${html}</p>${notes && `<hr>${notes}`}`,
763 });
764 completedLength += html.length;
765 html = notes = "";
766 nestedRowEnd = -1;
767 };
768 let nestedRowEnd = -1;
769 let run = "";
770 let fallback = 0;
771 const hidden = () => state.skip || state.deleted || state.hiddenText;
772 // A table cell's lines share its column, so the row stays on one line.
773 const lineBreak = () => (state.inTable ? " " : "<br>");
774 const encoded = new Uint8Array(bytes.byteLength);
775 let encodedLength = 0;
776 const decodeBytes = () => {
777 if (!encodedLength) return;
778 run += escape(
779 (fonts.get(state.font) ?? state.decoder).decode(encoded.subarray(0, encodedLength)),
780 );
781 encodedLength = 0;
782 };
783 const flush = () => {
784 decodeBytes();
785 if (completedLength + html.length + run.length > 8 * 1024 * 1024)
786 throw new PreviewError({ code: "rtf-too-much-content" });
787 if (!run) return;
788 let span = run;
789 if (state.bold) span = `<strong>${span}</strong>`;
790 if (state.italic) span = `<em>${span}</em>`;
791 if (state.underline) span = `<u>${span}</u>`;
792 if (state.strike) span = `<s>${span}</s>`;
793 if (state.script) span = `<${state.script}>${span}</${state.script}>`;
794 html += span;
795 run = "";
796 };
797 const emit = (value: string, skip = hidden()) => {
798 if (fallback > 0) {
799 fallback--;
800 return;
801 }
802 if (skip) return;
803 decodeBytes();
804 run += escape(value);
805 if (completedLength + html.length + run.length > 8 * 1024 * 1024)
806 throw new PreviewError({ code: "rtf-too-much-content" });
807 };
808 const emitByte = (value: number) => {
809 if (fallback > 0) fallback--;
810 else if (!hidden()) encoded[encodedLength++] = value;
811 };
812 const nestedTablePropertiesHeader = /[\r\n]*\\\*[\r\n]*\\nesttableprops(?![A-Za-z])/y;
813 const keptOptionalDestination = /\*[\r\n]*\\(?:shpinst|footnote)(?![A-Za-z])/y;
814 // \upr pairs an ANSI group with a {\*\ud} Unicode group; find where the Unicode text starts.
815 const rtfToken = /[{}]|\\(?:bin(\d+) ?|[^])/g;
816 const unicodeHeader = /[\r\n]*\{[\r\n]*\\\*[\r\n]*\\ud(?![A-Za-z]|-?\d) ?/y;
817 const unicodeBody = (start: number) => {
818 let depth = 0;
819 rtfToken.lastIndex = start;
820 for (let token; (token = rtfToken.exec(source)) && (depth || token[0] === "{");) {
821 if (token[0] === "{") depth++;
822 else if (token[1]) rtfToken.lastIndex += Number(token[1]);
823 else if (token[0] === "}" && !--depth) {
824 unicodeHeader.lastIndex = rtfToken.lastIndex;
825 return unicodeHeader.test(source) ? unicodeHeader.lastIndex : undefined;
826 }
827 }
828 };
829 const enterGroup = () => {
830 if (stack.length > 100) throw new PreviewError({ code: "rtf-too-deep" });
831 stack.push({ ...state });
832 };
833 for (let i = 0; i < source.length;) {
834 const char = source[i++];
835 if (char === "{") {
836 flush();
837 fallback = 0;
838 enterGroup();
839 // Only this destination's own row marker can render while its contents are skipped.
840 nestedTablePropertiesHeader.lastIndex = i;
841 state.nestedTableProperties = !state.skip && nestedTablePropertiesHeader.test(source);
842 } else if (char === "}") {
843 flush();
844 fallback = 0;
845 if (noteDepth === stack.length) {
846 notes += `<p data-rtf-whitespace>${html}</p>`;
847 completedLength += html.length;
848 html = noteParent;
849 noteDepth = undefined;
850 }
851 const parent = stack.pop();
852 if (!parent) throw new PreviewError({ code: "rtf-damaged" });
853 state = parent;
854 } else if (char === "\\") {
855 const next = source[i];
856 if (next === "'") {
857 const hex = source.slice(i + 1, i + 3);
858 if (!/^[\da-f]{2}$/i.test(hex)) throw new PreviewError({ code: "rtf-byte-escape" });
859 i += 3;
860 emitByte(Number.parseInt(hex, 16));
861 continue;
862 }
863 // \u, \uc and skipped fallbacks change no formatting, so a character written as two \u
864 // words stays in one run.
865 if (fallback === 0 && !/^uc?-?\d/.test(source.slice(i, i + 4))) flush();
866 if (next === "\\" || next === "{" || next === "}") {
867 i++;
868 emit(next);
869 continue;
870 }
871 if (next === "*") {
872 // Shape instructions are an optional destination, but a text box keeps its text there.
873 keptOptionalDestination.lastIndex = i;
874 if (!keptOptionalDestination.test(source)) state.skip = true;
875 i++;
876 continue;
877 }
878 const match = /^([a-z]+)(-?\d+)? ?/i.exec(source.slice(i));
879 if (!match) {
880 const character = RTF_CHARACTERS.get(next!);
881 if (character) emit(character);
882 // A backslash before a line break is \par; TextEdit ends paragraphs this way.
883 else if (next === "\n" || next === "\r") {
884 if (fallback > 0) fallback--;
885 else if (!hidden()) html += lineBreak();
886 }
887 i++;
888 continue;
889 }
890 i += match[0].length;
891 const word = match[1];
892 const arg = match[2] === undefined ? 1 : Number(match[2]);
893 if (word === "bin") {
894 if (!Number.isSafeInteger(arg) || arg < 0 || arg > source.length - i)
895 throw new PreviewError({ code: "rtf-binary-data" });
896 i += arg;
897 }
898 if (fallback > 0) {
899 fallback--;
900 continue;
901 }
902 if (word === "fonttbl") {
903 state.fontTable = true;
904 state.skip = true;
905 } else if (word === "deff") state.font = defaultFont = arg;
906 else if (word === "f") state.font = arg;
907 else if (word === "fcharset" && state.fontTable) {
908 const label = (
909 {
910 0: "windows-1252",
911 1: state.decoder.encoding,
912 77: "macintosh",
913 128: "shift_jis",
914 129: "euc-kr",
915 134: "gbk",
916 136: "big5",
917 161: "windows-1253",
918 162: "windows-1254",
919 163: "windows-1258",
920 177: "windows-1255",
921 178: "windows-1256",
922 186: "windows-1257",
923 204: "windows-1251",
924 222: "windows-874",
925 238: "windows-1250",
926 255: "ibm866",
927 } as Record<number, string>
928 )[arg];
929 if (label) fonts.set(state.font, new TextDecoder(label));
930 } else if (word === "fontfile") state.fontFile = true;
931 else if (word === "upr") {
932 const body = unicodeBody(i);
933 // Skip the ANSI group and enter the Unicode group as if its header were read.
934 if (body !== undefined) {
935 enterGroup();
936 i = body;
937 }
938 } else if (word === "cpg" && state.fontTable && !state.fontFile) {
939 try {
940 fonts.set(state.font, new TextDecoder(rtfCodePageLabel(arg)));
941 } catch {
942 // An unknown font code page leaves the font on its \fcharset.
943 }
944 } else if (
945 [
946 "colortbl",
947 "stylesheet",
948 "info",
949 "pict",
950 "object",
951 "fldinst",
952 // Shape properties, and the drawing that repeats a shape for older readers.
953 "sp",
954 "shprslt",
955 "nonesttables",
956 "header",
957 "headerl",
958 "headerr",
959 "headerf",
960 "footer",
961 "footerl",
962 "footerr",
963 "footerf",
964 "filetbl",
965 "datastore",
966 "themedata",
967 ].includes(word!)
968 )
969 state.skip = true;
970 else if (word === "mac") state.decoder = new TextDecoder("macintosh");
971 else if (word === "ansicpg") {
972 try {
973 state.decoder = new TextDecoder(rtfCodePageLabel(arg));
974 } catch {
975 throw new PreviewError({ code: "rtf-code-page" });
976 }
977 } else if (word === "b") state.bold = arg !== 0;
978 else if (word === "i") state.italic = arg !== 0;
979 else if (RTF_UNDERLINE_WORD.test(word!)) state.underline = arg !== 0;
980 else if (word === "ulnone") state.underline = false;
981 else if (word === "strike" || word === "striked") state.strike = arg !== 0;
982 else if (word === "super") state.script = "sup";
983 else if (word === "sub") state.script = "sub";
984 else if (word === "nosupersub") state.script = null;
985 // \up and \dn raise or lower by half-points; LibreOffice writes them for x² and H₂O.
986 else if (word === "up" || word === "dn")
987 state.script = arg === 0 ? null : word === "up" ? "sup" : "sub";
988 else if (word === "deleted") state.deleted = arg !== 0;
989 else if (word === "v") state.hiddenText = arg !== 0;
990 // \intbl is a paragraph property, so it lasts until \pard resets the paragraph.
991 else if (word === "intbl" || word === "pard") state.inTable = word === "intbl";
992 else if (word === "plain")
993 state = {
994 ...state,
995 deleted: false,
996 hiddenText: false,
997 bold: false,
998 italic: false,
999 underline: false,
1000 strike: false,
1001 script: null,
1002 font: defaultFont,
1003 };
1004 else if (word === "uc") state.uc = Math.max(0, arg);
1005 else if (word === "u") {
1006 fallback = 0;
1007 // TextEdit writes a soft line break as U+2028, where Chromium does not break the line.
1008 if (arg !== 0x2028) emit(String.fromCharCode(arg < 0 ? arg + 65536 : arg));
1009 else if (!hidden()) {
1010 flush();
1011 html += lineBreak();
1012 }
1013 fallback = state.uc;
1014 } else if (word === "footnote") {
1015 if (hidden() || noteDepth !== undefined) state.skip = true;
1016 else {
1017 [noteDepth, noteParent, html] = [stack.length, html, ""];
1018 state.inTable = false;
1019 }
1020 } else if (word === "chftn" && !hidden())
1021 html += `<sup>${noteDepth === undefined ? ++noteCount : noteCount}</sup>`;
1022 else if (!hidden() && word === "page" && noteDepth === undefined) finishPage();
1023 // \pagebb starts the paragraph on a new page; the first paragraph has no page to leave,
1024 // and inside a footnote html holds the note, not the page.
1025 else if (!hidden() && word === "pagebb" && arg !== 0 && html && noteDepth === undefined)
1026 finishPage();
1027 else if (word === "cell" || word === "nestcell") emit("\t", state.skip);
1028 else if (word === "nestrow" && (!state.skip || state.nestedTableProperties)) {
1029 html += "<br>";
1030 nestedRowEnd = html.length;
1031 } else if (!state.skip && word === "row") {
1032 // A cell holding only a nested table ends after the nested row's break; skip its empty line.
1033 if (nestedRowEnd >= 0 && /^\t*$/.test(html.slice(nestedRowEnd)))
1034 html = html.slice(0, nestedRowEnd);
1035 else html += "<br>";
1036 nestedRowEnd = -1;
1037 } else if (!hidden() && (word === "par" || word === "line")) html += lineBreak();
1038 // Writers usually end the paragraph before these breaks; a second break would add a blank line.
1039 // A footnote has no page of its own, so its \page is one of these breaks.
1040 else if (!hidden() && (word === "sect" || word === "column" || word === "page")) {
1041 if (html && !html.endsWith("<br>")) html += "<br>";
1042 } else {
1043 const character = RTF_CHARACTERS.get(word!);
1044 if (character) emit(character);
1045 }
1046 } else if (char !== "\r" && char !== "\n" && char) emitByte(char.charCodeAt(0));
1047 }
1048 if (stack.length) throw new PreviewError({ code: "rtf-damaged" });
1049 flush();
1050 if (html || notes || !pages.length) finishPage();
1051 return { type: "document", navigation: "page", pages };
1052}