From ba3ad49bd31fc964b9e0d55f2855b95cd3bb5401 Mon Sep 17 00:00:00 2001 From: Markus Date: Wed, 25 Nov 2026 15:10:58 +0100 Subject: [PATCH 1/3] feat: e-mail messages (.eml, .msg) open read-only, attachments saved from the File menu Internet messages (.eml, Apple Mail's .emlx) and Outlook items (.msg, .oft templates) open as a read-only document, like Visio drawings and iWork files: the worker reads the message and builds a DOCX of it. - src/core/mail: a MIME reader (encoded words, RFC 2231 parameters, nested multiparts, charsets, format=flowed, forwarded messages), an Outlook item reader on the existing compound file reader (MAPI properties, recipients, attachments, attached items), compressed RTF (LZFu / MELA) and the HTML or text Outlook wraps in RTF; native RTF bodies go through the RTF converter with the header around them - the document: subject, item kind and importance, a From / Sent / To / Cc / Bcc / Attachments table, the body (HTML with tables, cell colors and the pictures the message carries; plain text with links), attached messages - pictures an HTML body loads from the web are never fetched, and the document says so - parasToDocx writes tables, raster pictures, list levels and rules - File menu: an Attachments section saves each attachment; core API: `info.mail` and `mail.attachment`; the header's words follow the viewer's strings (`strings.mail`, German included) and locale Co-Authored-By: Claude Opus 5.5 --- README.md | 5 +- docs/api.md | 10 +- docs/development.md | 2 + docs/features.md | 21 +- e2e/mail.spec.ts | 60 ++++ package.json | 2 +- playground/main.tsx | 4 +- playground/public/samples/sample.eml | 61 ++++ playground/public/samples/sample.msg | Bin 0 -> 12800 bytes scripts/mail-samples.ts | 7 + src/core/convert.ts | 244 +++++++++++---- src/core/filetype.ts | 2 +- src/core/html.ts | 10 +- src/core/legacy/rtf/docx.ts | 4 +- src/core/legacy/rtf/index.ts | 9 +- src/core/mail/docx.ts | 250 ++++++++++++++++ src/core/mail/index.ts | 71 +++++ src/core/mail/mime.ts | 433 +++++++++++++++++++++++++++ src/core/mail/msg.ts | 279 +++++++++++++++++ src/core/mail/picture.ts | 57 ++++ src/core/mail/rtf.ts | 233 ++++++++++++++ src/core/mail/types.ts | 102 +++++++ src/core/worker/engine.ts | 35 ++- src/core/worker/protocol.ts | 17 +- src/react/DocViewer.tsx | 15 +- src/react/file/FileMenu.tsx | 6 + src/react/file/importFile.ts | 8 +- src/react/strings/de.ts | 38 ++- src/react/strings/en.ts | 40 ++- src/react/useDocument.ts | 4 +- test/mail-builder.ts | 312 +++++++++++++++++++ test/mail.test.ts | 317 ++++++++++++++++++++ 32 files changed, 2566 insertions(+), 92 deletions(-) create mode 100644 e2e/mail.spec.ts create mode 100644 playground/public/samples/sample.eml create mode 100644 playground/public/samples/sample.msg create mode 100644 scripts/mail-samples.ts create mode 100644 src/core/mail/docx.ts create mode 100644 src/core/mail/index.ts create mode 100644 src/core/mail/mime.ts create mode 100644 src/core/mail/msg.ts create mode 100644 src/core/mail/picture.ts create mode 100644 src/core/mail/rtf.ts create mode 100644 src/core/mail/types.ts create mode 100644 test/mail-builder.ts create mode 100644 test/mail.test.ts diff --git a/README.md b/README.md index d27c4eaf..76a44e14 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ [![CI](https://github.com/p10node/office-engine/actions/workflows/ci.yml/badge.svg)](https://github.com/p10node/office-engine/actions/workflows/ci.yml) [![License: MIT](https://img.shields.io/npm/l/@p10node/office-engine)](LICENSE) -View + edit **DOCX / XLSX / PPTX** directly in the browser, open and edit **DOC / XLS / PPT** (Office 97-2003), **RTF** and **OpenDocument** (ODT / ODS / ODP), view Apple **Pages**, **Keynote** and **Numbers** files, Microsoft **Visio** drawings and **PDF** files (with your pdf.js), open **CSV**, text, Markdown, HTML and SVG as editable sheets / documents and source code with syntax colors, and draw **Mermaid**, **PlantUML** and **Graphviz** diagrams (no server, no extra library). Loads progressively like Google Docs, handles heavy files, one-line React embed, saves back to the original format. +View + edit **DOCX / XLSX / PPTX** directly in the browser, open and edit **DOC / XLS / PPT** (Office 97-2003), **RTF** and **OpenDocument** (ODT / ODS / ODP), view Apple **Pages**, **Keynote** and **Numbers** files, Microsoft **Visio** drawings, **e-mail** messages (`.eml`, Outlook `.msg`) and **PDF** files (with your pdf.js), open **CSV**, text, Markdown, HTML and SVG as editable sheets / documents and source code with syntax colors, and draw **Mermaid**, **PlantUML** and **Graphviz** diagrams (no server, no extra library). Loads progressively like Google Docs, handles heavy files, one-line React embed, saves back to the original format. **Zero runtime dependencies, zero servers.** Parsing, layout, formulas, diagrams and ZIP are all in the library, running in a Web Worker: nothing leaves the browser. @@ -73,12 +73,13 @@ Also online at [p10node.github.io/office-engine](https://p10node.github.io/offic - **Apple Pages, Keynote and Numbers (view only)**: `.pages` / `.key` / `.numbers` files open read-only, converted to Word / PowerPoint / Excel in the worker (styles, lists, tables, images, shapes, header/footer, footnotes, master slides, typed and formatted cells); *Download as* Word / PowerPoint / Excel saves the converted file - **Microsoft Visio (view only)**: `.vsdx` drawings (also `.vsdm`, templates and stencils) open read-only, a slide per page: shapes with their geometry (lines, arcs, ellipses, Béziers, NURBS), masters, groups, connectors with line ends, fills, gradients, themes, text, pictures, background pages and layers; *Download as* PowerPoint saves the converted file - **PDF (view only)**: `.pdf` files are shown as they are, drawn by [pdf.js](https://mozilla.github.io/pdf.js/) that the host passes in (`pdfjs`: optional, the library still ships no dependency): the text over each page is selected with the mouse, copied and found; links are followed, bookmarks are the outline, pages zoom and only those near the view are drawn; the bytes are read as pdf.js asks, so a large file served with ranges is not downloaded whole first. *Download as* gives the file itself and its text; Print prints the file ([API](docs/api.md#pdf-files)) +- **E-mail messages (view only)**: `.eml` (also Apple Mail's `.emlx`) and Outlook `.msg` / `.oft` files open read-only as a document: subject, sender, recipients, date, the HTML (tables, the pictures the message carries), rich-text (Outlook's compressed RTF) or plain-text body, attached messages; attachments are listed and saved from the File menu. Pictures from the web are never fetched - **CSV, text, Markdown, HTML, SVG**: `.csv` / `.tsv` open as a workbook (streamed: a million rows in about 2 s; past 12 million cells the rows are read from the file as they are shown, so there is no row limit), `.txt` / `.md` / `.html` as a document, `.svg` / `.svgz` as a picture (`.gz` files are unpacked first), from any `src` (file, Blob, URL); format from the extension, MIME type or content; UTF-8 / UTF-16 / Windows-1252; editable. Markdown, HTML and SVG are saved back in their own format (CSV and text as `.xlsx` / `.docx`) - **Diagrams as code**: `.mmd` (Mermaid), `.puml` (PlantUML), `.dot` / `.gv` (Graphviz) open as a document with the drawing; ` ```mermaid ` / ` ```plantuml ` / ` ```dot ` blocks in Markdown and `
` in HTML are drawn too. Drawn by a built-in layout engine in the worker: no server, no network, no dependency
 - **Math in Markdown**: `$…$` and `$$…$$` TeX formulas are drawn as equations (the browser's own MathML: selectable, read by screen readers, printed); the document stays editable around them and saves each formula back exactly as it was written. Currency (`$5 and $10`), `\$` and code are left alone; a formula that cannot be read shows its source. *Download as* Word gives real Word equations
 - **Code side by side**: Markdown, HTML, SVG and diagram files show their source next to the document (**Code** button); edit it and the document is rebuilt as you type; edit the document and the Markdown / HTML is built again from it
 - **Syntax highlighting**: Markdown code blocks are colored by their fence's language (JavaScript / TypeScript / JSX, JSON, Python, CSS, HTML / XML, YAML, shell, SQL, Go, Rust, Java, C / C++ / C#, and more), stay editable, and are saved back with their language and exact code; the colors are only drawn, never stored. Source files (`main.ts`, `script.py`, `config.json`…, or any text with the `language` prop) open in a **code view** with line numbers, in light and dark, editable and saved as plain text. One built-in tokenizer, no dependency ([Features](docs/features.md#syntax-highlighting))
-- **File menu**: new, open (also DOC / XLS / PPT / RTF / OpenDocument / Pages / Keynote / Numbers / Visio / PDF / CSV / text / Markdown / HTML / SVG / diagrams / source code), import CSV, rename, download as PDF / HTML / text / CSV, document details, print
+- **File menu**: new, open (also DOC / XLS / PPT / RTF / OpenDocument / Pages / Keynote / Numbers / Visio / e-mail / PDF / CSV / text / Markdown / HTML / SVG / diagrams / source code), import CSV, rename, download as PDF / HTML / text / CSV, document details, print
 - **Comments**: threads with replies, resolve, edit / delete, @mentions; on DOCX text, XLSX cells and PPTX slides, stored in the file the way Word, Excel and PowerPoint store them
 - **Real-time collaboration**: live edits, avatars, collaborators' cursors, offline edits sync on reconnect
 - **Fonts**: hand the viewer font files (the OFL fallbacks Carlito, Caladea, Liberation, or the originals) and documents are laid out once they are loaded, so lines and pages break as with the fonts the document names ([API](docs/api.md#fonts))
diff --git a/docs/api.md b/docs/api.md
index a0d90ec4..f37e2984 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -56,7 +56,7 @@ CSS is auto-injected, no import needed (or import `@p10node/office-engine/styles
 
 | Prop               | Type                                                         | Default   | Notes                                                                                                                                                        |
 |--------------------|--------------------------------------------------------------|-----------|--------------------------------------------------------------------------------------------------------------------------------------------------------------|
-| `src`              | `File \| Blob \| ArrayBuffer \| Uint8Array \| string \| URL` | –         | Office (also 97-2003); OpenDocument; RTF; Pages/Keynote/Numbers; Visio; CSV/TSV, text, code, Markdown, HTML, diagrams; PDF (with `pdfjs`)                    |
+| `src`              | `File \| Blob \| ArrayBuffer \| Uint8Array \| string \| URL` | –         | Office (also 97-2003); OpenDocument; RTF; Pages/Keynote/Numbers; Visio; e-mail; CSV/TSV, text, code, Markdown, HTML, diagrams; PDF (with `pdfjs`)            |
 | `name`             | `string`                                                     | auto      | Display name; its extension also tells the format of a `Blob` / `ArrayBuffer`                                                                                |
 | `language`         | `string`                                                     | –         | Source code in this language (`'typescript'`, `'ts'`, `'python'`, `'c++'`…): the code view, whatever the name says                                           |
 | `toolbar`          | `boolean`                                                    | `true`    | Top bar (name, status, progress)                                                                                                                             |
@@ -71,7 +71,7 @@ CSS is auto-injected, no import needed (or import `@p10node/office-engine/styles
 | `theme`            | `'light' \| 'dark' \| 'auto' \| ThemeOptions`                | `'light'` | Color scheme of the chrome; `'auto'` follows `prefers-color-scheme`; an object adds token overrides ([Theming](theming.md)). Documents keep their own colors |
 | `locale`           | `string`                                                     | inherited | BCP 47 tag for number/date display and numeric input. See [UI texts](#ui-texts) and [input](#numbers-typed-in-a-locale)                                      |
 | `strings`          | `StringsOverride`                                            | –         | Texts merged over the enclosing provider or English, key by key; may include a formatting `locale`                                                           |
-| `editable`         | `boolean`                                                    | `false`   | Open in edit mode (Pages, Keynote, Numbers and Visio files stay view only)                                                                                   |
+| `editable`         | `boolean`                                                    | `false`   | Open in edit mode (Pages, Keynote, Numbers, Visio files and e-mail stay view only)                                                                            |
 | `allowEdit`        | `boolean`                                                    | `true`    | Show Edit/View button                                                                                                                                        |
 | `allowSave`        | `boolean`                                                    | `true`    | Show Save/Download button, enable Ctrl+S                                                                                                                     |
 | `allowDownload`    | `boolean`                                                    | `true`    | Allow downloads to device (save without `onSave`, images)                                                                                                    |
@@ -563,7 +563,11 @@ import { DocumentClient } from '@p10node/office-engine/core'
 
 const doc = await DocumentClient.open(fileOrUrl, { onProgress: console.log })
 doc.kind                                   // 'docx' | 'xlsx' | 'pptx'
-doc.info.from                              // 'pages' / 'keynote' / 'numbers' / 'visio': an Apple or Visio file, converted to docx / pptx / xlsx / pptx (view only)
+doc.info.from                              // 'pages' / 'keynote' / 'numbers' / 'visio' / 'eml' / 'msg': an Apple or Visio file, converted to docx / pptx / xlsx / pptx,
+                                           // or a mail message (.eml / .emlx, .msg / .oft) as docx (view only)
+doc.info.mail                              // a mail message: { subject, attachments: [{ name, type, size }] }
+await doc.call('mail.attachment', 0)       // an attachment's file (a Blob of its type)
+// open(src, { mail: { texts: { from: 'Von', … }, locale: 'de-DE' } }): the words of a message's header and the locale of its dates
 doc.info.imported                          // 'csv' / 'tsv' / 'text' / 'markdown' / 'html' / 'svg' / 'mermaid' / 'plantuml' / 'graphviz' / 'code': a plain file, built as xlsx / docx (editable)
 doc.info.language                          // 'code' (a source file): its language, 'typescript' / 'python' / 'json'… (the hint's own word when it is not one the highlighter knows)
 doc.info.converted                         // 'doc' / 'xls' / 'ppt' / 'rtf' / 'odt' / 'ods' / 'odp': converted to docx / xlsx / pptx (editable, saved as such)
diff --git a/docs/development.md b/docs/development.md
index b462f44a..b9df4dc5 100644
--- a/docs/development.md
+++ b/docs/development.md
@@ -13,6 +13,7 @@ python3 -m venv .venv && .venv/bin/pip install python-docx openpyxl python-pptx
 bun scripts/iwork-samples.ts                   # sample.pages / .key / .numbers (built by test/iwork-builder.ts)
 bun scripts/visio-samples.ts                   # sample.vsdx (built by test/visio-builder.ts)
 bun scripts/pdf-sample.ts                      # sample.pdf (built by test/pdf-builder.ts)
+bun scripts/mail-samples.ts                    # sample.eml / sample.msg (built by test/mail-builder.ts)
 bun scripts/legacy-samples/doc.ts              # .doc / .ppt / .rtf test fixtures and samples (also ppt.ts, rtf.ts; .xls / .odt / .ods / .odp from the *.py scripts: see scripts/legacy-samples/*.md)
 bun run screenshots  # README screenshots -> docs/screenshots/ (headless Chromium)
 bun run gifs         # README GIFs (300k-row sheet opening, collaboration) -> docs/screenshots/*.gif (headless Chromium + ffmpeg)
@@ -35,6 +36,7 @@ src/core     parsers, DOM-free (runs in worker / Bun)
   legacy     .doc / .xls / .ppt (compound file reader + converters), .rtf, OpenDocument → DOCX / XLSX / PPTX
   iwork      Pages / Keynote / Numbers → DOCX / PPTX / XLSX
   visio      Visio drawings (.vsdx) → PPTX
+  mail       e-mail messages (.eml, .emlx, .msg, .oft) → DOCX (MIME, Outlook's MAPI properties, compressed RTF)
   math       TeX math: `$…$` / `$$…$$` in Markdown, TeX → MathML (views, web pages) and → OMML (Word file)
   font       font files read for layout: glyph widths, kerning, ligatures, line metrics, subsets (no DOM)
 src/react    view components
diff --git a/docs/features.md b/docs/features.md
index d90fefff..08ed7468 100644
--- a/docs/features.md
+++ b/docs/features.md
@@ -142,6 +142,24 @@ A PDF file is shown as it is, drawn by [pdf.js](https://mozilla.github.io/pdf.js
 - **File menu**: *Download as* the file itself and its text; *Document details*: title, author, subject, pages, page size, PDF version, application, producer; Print (`Ctrl/⌘+P`) prints the file itself
 - **Not yet**: a find bar over the whole file, page thumbnails, filling forms, annotations other than links (drawn on the page), rotating pages; `@p10node/convert` refuses a PDF file
 
+### E-mail messages (view only)
+
+Mail messages open read-only as a document: the worker reads the message and builds a DOCX file of it in memory, and the document view shows it (pages, zoom, find, print, *Download as* **Word** / PDF / web page / text). The bar shows an `EML` or `MSG` badge and no Edit button, even with `editable`. The format is told by the file's bytes: an Outlook item is a compound file, an Internet message starts with mail headers (a file with no name, or served as `message/rfc822`, is recognised by them too).
+
+| Format                       | Read                                                                                                                                                                                                         |
+|------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
+| `.eml` (RFC 5322 / MIME)     | headers (encoded words, RFC 2231 parameters, 8-bit UTF-8), nested multiparts (`alternative`: the HTML, `related`: its pictures, `mixed`, `signed`, `report`), base64 / quoted-printable, any charset the browser decodes, `format=flowed`, forwarded messages (`message/rfc822`) |
+| `.emlx` (Apple Mail)         | the message inside it (the length line and the property list after it are left out)                                                                                                                         |
+| `.msg` / `.oft` (Outlook)    | MAPI properties (MS-OXMSG): sender, recipients (To / Cc / Bcc), sent time, importance, message class; the HTML body, else the HTML or text Outlook wraps in compressed RTF (MS-OXRTFCP, MS-OXRTFEX), else the RTF itself (converted as `.rtf` files are), else the plain text; attachments and attached Outlook items |
+
+The document holds, in order: the subject, the item's kind when it is not a plain message (meeting request, appointment, contact, task, delivery report) and its importance, a table of *From*, *Sent*, *To*, *Cc*, *Bcc* and *Attachments* (names and sizes), then the body, then each attached message the same way. An HTML body keeps its headings, lists, links, text formatting, tables (spans, borders, cell colors) and the pictures the message carries (`cid:` pictures and `data:` URLs, PNG / JPEG / GIF / BMP / WebP); a plain-text body has a paragraph per line, its web addresses as links and quoted lines (`>`) in grey. Addresses are `mailto:` links.
+
+- **Attachments**: listed in the header and in the File menu under **Attachments**, each saved as it is from there (`mail.attachment` in the core API). Pictures the body shows and Outlook's hidden attachments are not listed
+- **Privacy**: nothing is downloaded. Pictures an HTML body loads from the web (tracking pixels included) are left out, and the document says so; scripts, styles and forms of the HTML are not read, and links that would run script are not links
+- **Language**: the header's words are the viewer's (`strings.mail`, German in the optional `de` table); dates are written in the viewer's locale and the browser's time zone
+- **Not yet**: Outlook archives (`.pst`, `.ost`, `.olm`) and mailboxes (`.mbox`), the calendar details of meeting items (time, place: shown as a message), contact and task fields, `winmail.dat` (TNEF) unpacked, attachments opened in the viewer, CSS of the HTML body (layout from `',
+    '

Logo

', + '

Quarterly review: agenda

', + '

Hi team,

here is the agenda for Thursday. The figures are in the attached sheet; the dashboard is at example.org/q3.

', + '', + '
TimeTopicOwner
10:00Revenue and marginsAna
10:30Hiring planJonas
11:00RoadmapMei
', + '
  • Bring the updated forecast
  • Read the notes from last time
', + '

Thanks,
Ana

', + '', + ].join('\r\n') + const sheet = utf8('Quarter,Revenue,Margin\r\nQ1,1200,0.31\r\nQ2,1350,0.33\r\nQ3,1420,0.35\r\n') + return latin1( + [ + 'Return-Path: ', + 'Received: from mail.example.org by mx.example.com; Thu, 19 Nov 2026 09:14:02 +0100', + 'From: =?UTF-8?Q?Ana_Mart=C3=ADnez?= ', + 'To: Jonas Weber , "Lee, Mei" ', + 'Cc: team@example.com', + 'Subject: =?UTF-8?B?UXVhcnRlcmx5IHJldmlldyDigJMgYWdlbmRh?=', + 'Date: Thu, 19 Nov 2026 09:14:00 +0100', + 'Message-ID: ', + 'MIME-Version: 1.0', + 'Content-Type: multipart/mixed; boundary="mixed"', + '', + '--mixed', + 'Content-Type: multipart/related; boundary="related"', + '', + '--related', + 'Content-Type: multipart/alternative; boundary="alt"', + '', + '--alt', + 'Content-Type: text/plain; charset=utf-8', + 'Content-Transfer-Encoding: quoted-printable', + '', + 'Hi team, here is the agenda for Thursday.', + '--alt', + 'Content-Type: text/html; charset=utf-8', + 'Content-Transfer-Encoding: base64', + '', + b64(utf8(html)), + '--alt--', + '--related', + 'Content-Type: image/png', + 'Content-Transfer-Encoding: base64', + 'Content-ID: ', + 'Content-Disposition: inline; filename="logo.png"', + '', + b64(logo), + '--related--', + '--mixed', + 'Content-Type: text/csv; name="q3-figures.csv"', + 'Content-Transfer-Encoding: base64', + 'Content-Disposition: attachment; filename="q3-figures.csv"', + '', + b64(sheet), + '--mixed--', + '', + ].join('\r\n'), + ) +} + +/** the playground's sample .msg: an Outlook item with an HTML body, recipients, a hidden picture and an attached message */ +export function sampleMsg(): Uint8Array { + return msgFile({ + subject: 'Contract renewal – signed copy', + fromName: 'Jonas Weber', + fromSmtp: 'jonas@example.com', + sent: new Date(Date.UTC(2026, 10, 20, 15, 42)), + importance: 2, + recipients: [ + { name: 'Ana Martínez', smtp: 'ana@example.org' }, + { name: 'Legal', smtp: 'legal@example.org', type: 2 }, + ], + body: 'Hello Ana,\r\n\r\nattached is the signed contract. Please file it.\r\n\r\nJonas', + html: '

Hello Ana,

attached is the signed contract. Please file it.

Jonas

', + attachments: [ + { name: 'contract-signed.pdf', mime: 'application/pdf', data: latin1('%PDF-1.4\n% sample\n') }, + { name: 'signature.png', mime: 'image/png', cid: 'sig', hidden: true, data: png(160, 24, [0x1f, 0x29, 0x37]) }, + { + name: 'Original request.msg', + message: { + subject: 'Contract renewal', + fromName: 'Ana Martínez', + fromSmtp: 'ana@example.org', + sent: new Date(Date.UTC(2026, 10, 18, 8, 5)), + recipients: [{ name: 'Jonas Weber', smtp: 'jonas@example.com' }], + body: 'Jonas,\r\n\r\ncould you send the signed renewal by Friday?\r\n\r\nThanks, Ana', + }, + }, + ], + }) +} diff --git a/test/mail.test.ts b/test/mail.test.ts new file mode 100644 index 00000000..7e13d908 --- /dev/null +++ b/test/mail.test.ts @@ -0,0 +1,317 @@ +import { describe, expect, test } from 'bun:test' +import type { Block, Paragraph, Table } from '../src/core/docx/types' +import { isMsg, mailTextFormat, openMail, readEml, readEmlx, readMsg } from '../src/core/mail' +import { decodeWords, parseAddresses, parseParams, unflow } from '../src/core/mail/mime' +import { pictureSize } from '../src/core/mail/picture' +import { decompressRtf, unwrapRtf } from '../src/core/mail/rtf' +import { BlobSource } from '../src/core/source' +import { Engine } from '../src/core/worker/engine' +import { ZipArchive } from '../src/core/zip' +import { writeCfb } from './cfb-writer' +import { b64, compressRtf, latin1, msgFile, png, sampleEml, sampleMsg, utf8 } from './mail-builder' + +async function open(bytes: Uint8Array, name: string, params: Record = {}) { + const events: { event: string; data: any }[] = [] + const engine = new Engine((event, data) => events.push({ event, data })) + const info = await engine.open(new Blob([bytes as Uint8Array]), { name, ...params }) + await engine.call('docx.start', []) + const done = events.find((e) => e.event === 'docx:done')?.data + if (done?.error) throw new Error(done.error) + const blocks: Block[] = events.filter((e) => e.event === 'docx:blocks').flatMap((e) => e.data) + return { engine, info, blocks } +} + +const textOf = (b: Block): string => + b.t === 'p' ? b.runs.map((r) => (r.t === 'text' ? r.text : r.t === 'img' ? '' : '')).join('') : b.t === 'tbl' ? b.rows.map((r) => r.cells.map((c) => c.blocks.map(textOf).join('/')).join(' | ')).join('\n') : '' +const allText = (blocks: Block[]) => blocks.map(textOf).join('\n') +const tables = (blocks: Block[]) => blocks.filter((b): b is Table => b.t === 'tbl') +const paras = (blocks: Block[]) => blocks.filter((b): b is Paragraph => b.t === 'p') + +/** an Internet message of header lines and a body */ +const eml = (headers: string[], body: string) => latin1([...headers, '', body].join('\r\n')) + +describe('mail: Internet message headers', () => { + test('encoded words: B and Q, charsets, a character split between two words, spaces between words dropped', () => { + expect(decodeWords('=?UTF-8?B?w6l0w6k=?= report')).toBe('été report') + expect(decodeWords('=?iso-8859-1?Q?Caf=E9_cr=E8me?=')).toBe('Café crème') + // "€" (E2 82 AC) split over two words + expect(decodeWords('=?utf-8?Q?Price_=E2=82?= =?utf-8?Q?=AC5?=')).toBe('Price €5') + expect(decodeWords('=?utf-8?q?a?= b =?utf-8?q?c?=')).toBe('a b c') + // 8-bit UTF-8 in a header (RFC 6532) + expect(decodeWords(String.fromCharCode(...utf8('Grüße')))).toBe('Grüße') + // an unknown charset: read as UTF-8 + expect(decodeWords('=?x-unknown?Q?plain?=')).toBe('plain') + }) + + test('addresses: names quoted, with commas, encoded, in comments; groups; mailto', () => { + expect(parseAddresses('"Lee, Mei" , Bob , ann@z.org (Ann Z), plain@w.net')).toEqual([ + { name: 'Lee, Mei', addr: 'mei@x.org' }, + { name: 'Bob', addr: 'bob@y.com' }, + { name: 'Ann Z', addr: 'ann@z.org' }, + { name: '', addr: 'plain@w.net' }, + ]) + expect(parseAddresses('=?utf-8?Q?Doe=2C_J=C3=BCrgen?= ')).toEqual([{ name: 'Doe, Jürgen', addr: 'j@x.de' }]) + expect(parseAddresses('Team: a@x.org, b@x.org;, undisclosed-recipients:;')).toEqual([ + { name: '', addr: 'a@x.org' }, + { name: '', addr: 'b@x.org' }, + ]) + expect(parseAddresses('')).toEqual([{ name: '', addr: 'm@x.org' }]) + }) + + test('parameters: quoted, RFC 2231 encoded and continued, encoded words in a quoted name', () => { + expect(parseParams('text/HTML; charset="utf-8"; format=flowed')).toEqual({ value: 'text/html', params: { charset: 'utf-8', format: 'flowed' } } as any) + expect(parseParams("attachment; filename*=UTF-8''r%C3%A9sum%C3%A9.pdf").params.filename).toBe('résumé.pdf') + expect(parseParams("attachment; filename*0*=UTF-8''long%20na; filename*1=me.txt").params.filename).toBe('long name.txt') + expect(parseParams('attachment; filename="=?UTF-8?B?w7xiZXIucGRm?="').params.filename).toBe('über.pdf') + }) + + test('format=flowed: soft breaks joined, quotes kept apart, space-stuffing undone', () => { + expect(unflow('A line that \r\ngoes on.\r\n> quoted \r\n> more\r\n plain', false)).toBe('A line that goes on.\n> quoted more\nplain') + expect(unflow('one \r\ntwo', true)).toBe('onetwo') + }) +}) + +describe('mail: Internet message structure', () => { + test('the sample: subject, people, date, the HTML of the alternatives, the related picture shown, the CSV attached', () => { + const m = readEml(sampleEml()) + expect(m.subject).toBe('Quarterly review – agenda') + expect(m.from).toEqual([{ name: 'Ana Martínez', addr: 'ana@example.org' }]) + expect(m.to.map((a) => a.name)).toEqual(['Jonas Weber', 'Lee, Mei']) + expect(m.cc).toEqual([{ name: '', addr: 'team@example.com' }]) + expect(m.date?.toISOString()).toBe('2026-11-19T08:14:00.000Z') + expect(m.body.length).toBe(1) + expect('html' in m.body[0] && m.body[0].html).toContain('

Quarterly review: agenda

') + expect(m.attachments.map((a) => [a.name, a.type, a.cid])).toEqual([ + ['logo.png', 'image/png', 'logo@example.org'], + ['q3-figures.csv', 'text/csv', undefined], + ]) + }) + + test('a plain message: no MIME headers, LF line ends, quoted-printable in another charset', () => { + const m = readEml(latin1('From: a@x.org\nTo: b@y.org\nSubject: Hi\nContent-Type: text/plain; charset=iso-8859-1\nContent-Transfer-Encoding: quoted-printable\n\nCaf=E9 =\nat noon')) + expect(m.body).toEqual([{ text: 'Café at noon' }]) + }) + + test('mixed parts: text after an attachment goes on in the body; signatures dropped; a forwarded message read', () => { + const inner = ['From: Old ', 'Subject: Original', 'Date: Mon, 2 Nov 2026 10:00:00 +0000', '', 'The first message.'].join('\r\n') + const m = readEml( + eml( + ['From: a@x.org', 'Subject: Fwd', 'Content-Type: multipart/signed; boundary=s; protocol="application/pkcs7-signature"'], + [ + '--s', + 'Content-Type: multipart/mixed; boundary=m', + '', + '--m', + 'Content-Type: text/plain', + '', + 'Before.', + '--m', + 'Content-Type: application/octet-stream; name=data.bin', + 'Content-Transfer-Encoding: base64', + '', + b64(Uint8Array.of(1, 2, 3)), + '--m', + 'Content-Type: text/plain', + 'Content-Disposition: inline', + '', + 'After.', + '--m', + 'Content-Type: message/rfc822', + '', + inner, + '--m--', + '--s', + 'Content-Type: application/pkcs7-signature; name=smime.p7s', + '', + 'MIAG', + '--s--', + ].join('\r\n'), + ), + ) + expect(m.body).toEqual([{ text: 'Before.' }, { text: 'After.' }]) + expect(m.attachments.map((a) => a.name)).toEqual(['data.bin', 'Original.eml']) + expect([...m.attachments[0].data!]).toEqual([1, 2, 3]) + expect(m.attachments[1].message).toMatchObject({ subject: 'Original', from: [{ name: 'Old', addr: 'old@x.org' }], body: [{ text: 'The first message.' }] }) + }) + + test('a message cut short still shows what is there; an encrypted one says so; no date is no date', () => { + const cut = readEml(eml(['Subject: Cut', 'Content-Type: multipart/alternative; boundary=b'], '--b\r\nContent-Type: text/plain\r\n\r\nPartial te')) + expect(cut.body).toEqual([{ text: 'Partial te' }]) + const enc = readEml(eml(['Subject: Secret', 'Content-Type: application/pkcs7-mime; smime-type=enveloped-data; name=smime.p7m', 'Content-Transfer-Encoding: base64'], 'MIAGCSqG')) + expect(enc.encrypted).toBe(true) + const odd = readEml(eml(['Subject: x', 'Date: sometime soon'], 'x')) + expect(odd.date).toBeUndefined() + expect(odd.dateText).toBe('sometime soon') + }) + + test('emlx: the length line and the property list after the message are left out', () => { + const msg = 'From: a@x.org\nSubject: Apple\n\nBody.\n' + const m = readEmlx(latin1(`${msg.length}\n${msg}`)) + expect(m.subject).toBe('Apple') + expect(m.body).toEqual([{ text: 'Body.\n' }]) + }) +}) + +describe('mail: Outlook items', () => { + test('the sample: sender, recipients by type, sent time, importance, HTML body, attachments in order, the attached item', () => { + const m = readMsg(sampleMsg()) + expect(m.subject).toBe('Contract renewal – signed copy') + expect(m.from).toEqual([{ name: 'Jonas Weber', addr: 'jonas@example.com' }]) + expect(m.to).toEqual([{ name: 'Ana Martínez', addr: 'ana@example.org' }]) + expect(m.cc).toEqual([{ name: 'Legal', addr: 'legal@example.org' }]) + expect(m.date?.toISOString()).toBe('2026-11-20T15:42:00.000Z') + expect(m.importance).toBe('high') + expect('html' in m.body[0]).toBe(true) + expect(m.attachments.map((a) => [a.name, a.hidden ?? false, !!a.message])).toEqual([ + ['contract-signed.pdf', false, false], + ['signature.png', true, false], + ['Original request.msg', false, true], + ]) + expect(m.attachments[2].message).toMatchObject({ subject: 'Contract renewal', body: [{ text: expect.stringContaining('signed renewal') }] }) + }) + + test('an Exchange sender has no address to show; recipients from the display strings when there are no recipient storages', () => { + const m = readMsg(msgFile({ subject: 'x', fromName: 'Pat', fromExchange: '/O=EXCHANGELABS/OU=GROUP/CN=RECIPIENTS/CN=PAT', extra: { 0x0e04: { str: 'Ann Lee; Bob' } } })) + expect(m.from).toEqual([{ name: 'Pat', addr: '' }]) + expect(m.to).toEqual([ + { name: 'Ann Lee', addr: '' }, + { name: 'Bob', addr: '' }, + ]) + }) + + test('message classes other than a note are said; a compound file that is no Outlook item is not one', () => { + expect(readMsg(msgFile({ subject: 'Sync', messageClass: 'IPM.Schedule.Meeting.Request' })).itemClass).toBe('IPM.Schedule.Meeting.Request') + expect(readMsg(msgFile({ subject: 'x' })).itemClass).toBeUndefined() + expect(isMsg(sampleMsg())).toBe(true) + expect(isMsg(writeCfb({ WordDocument: new Uint8Array(512) }))).toBe(false) + expect(isMsg(latin1('not a compound file'))).toBe(false) + }) +}) + +describe('mail: Outlook RTF bodies', () => { + const htmlRtf = String.raw`{\rtf1\ansi\ansicpg1252\fromhtml1 \deff0{\fonttbl{\f0\fswiss\fcharset0 Arial;}}` + + String.raw`{\*\htmltag19 }{\*\htmltag34 }{\*\htmltag41 }{\*\htmltag50 }` + + String.raw`\htmlrtf {\htmlrtf0{\*\htmltag64

}Caf\'e9 荤?5 {\*\htmltag84 }bold{\*\htmltag92 }` + + String.raw`\htmlrtf\par\htmlrtf0{\*\htmltag72

}\htmlrtf }\htmlrtf0{\*\htmltag58 }{\*\htmltag27 }}` + + test('compressed RTF: LZFu (literal runs, the end reference) and uncompressed (MELA)', () => { + const rtf = latin1(htmlRtf) + expect(new TextDecoder().decode(decompressRtf(compressRtf(rtf)))).toBe(htmlRtf) + expect(new TextDecoder().decode(decompressRtf(compressRtf(rtf, 'MELA')))).toBe(htmlRtf) + // references into the initial dictionary: "{\rtf1\ansi\mac" is its first 15 bytes (offset 0, length 15) + const head = new Uint8Array(16) + new DataView(head.buffer).setUint32(4, 15, true) + new DataView(head.buffer).setUint32(8, 0x75465a4c, true) + const ref = Uint8Array.from([0x03, 0x00, 0x0d, 0x0c, 0xf0]) + new DataView(head.buffer).setUint32(0, ref.length + 12, true) + const out = decompressRtf(new Uint8Array([...head, ...ref])) + expect(new TextDecoder().decode(out)).toBe('{\\rtf1\\ansi\\mac') + expect(() => decompressRtf(new Uint8Array(4))).toThrow() + }) + + test('the HTML an RTF body wraps: its tags, its text in the code page and \\u, the RTF-only text left out', () => { + const r = unwrapRtf(latin1(htmlRtf)) + expect('html' in r && r.html.replace(/\s+/g, ' ')).toBe('

Café €5 bold

') + }) + + test('plain text wrapped (\\fromtext) and RTF of its own', () => { + expect(unwrapRtf(latin1(String.raw`{\rtf1\ansi\fromtext{\fonttbl{\f0 Courier;}}Line one\par Line two}`))).toEqual({ text: 'Line one\nLine two' }) + expect('rtf' in unwrapRtf(latin1(String.raw`{\rtf1\ansi Plain {\b rich} text}`))).toBe(true) + }) + + test('an item whose body is only compressed RTF: the wrapped HTML is shown; RTF of its own is converted with the header around it', async () => { + const wrapped = await open(msgFile({ subject: 'From RTF', rtf: compressRtf(latin1(htmlRtf)) }), 'r.msg') + expect(allText(wrapped.blocks)).toContain('Café €5 bold') + const own = await open(msgFile({ subject: 'Rich', fromName: 'Ann', body: 'fallback', rtf: compressRtf(latin1(String.raw`{\rtf1\ansi\deff0{\fonttbl{\f0 Arial;}}Some {\b bold} words\par}`)) }), 'own.msg') + const ps = paras(own.blocks) + expect(textOf(ps[0])).toBe('Rich') + expect(tables(own.blocks)[0].rows[0].cells.map((c) => c.blocks.map(textOf).join(''))).toEqual(['From', 'Ann']) + const body = ps.find((p) => textOf(p) === 'Some bold words')! + expect(body.runs.find((r) => r.t === 'text' && r.text === 'bold')).toMatchObject({ s: { b: true } }) + }) +}) + +describe('mail: the document', () => { + test('opened by the engine: read-only, the attachments listed and saved; the pictures the body shows are not', async () => { + const { engine, info, blocks } = await open(sampleEml(), 'sample.eml') + expect(info).toMatchObject({ kind: 'docx', from: 'eml', mail: { subject: 'Quarterly review – agenda', attachments: [{ name: 'q3-figures.csv', type: 'text/csv', size: 66 }] } }) + const header = tables(blocks)[0] + expect(header.rows.map((r) => textOf(r.cells[0].blocks[0] as Paragraph))).toEqual(['From', 'Sent', 'To', 'Cc', 'Attachments']) + // the logo is a picture of the body, at the size the HTML gives + const img = paras(blocks).flatMap((p) => p.runs).find((r) => r.t === 'img') + expect(img).toMatchObject({ t: 'img', w: 90, h: 30 }) + // a mailto: link on each address + expect(paras(header.rows[0].cells[1].blocks).flatMap((p) => p.runs).some((r) => r.t === 'text' && r.href === 'mailto:ana@example.org')).toBe(true) + // the agenda table keeps its lines and the shading of its header row + const agenda = tables(blocks)[1] + expect(agenda.rows[0].cells.map((c) => c.shd)).toEqual(['#e8eef9', '#e8eef9', '#e8eef9']) + const csv = (await engine.call('mail.attachment', [0])) as Blob + expect(await csv.text()).toStartWith('Quarter,Revenue') + expect(csv.type).toBe('text/csv') + await expect(engine.call('mail.attachment', [5])).rejects.toThrow('No such attachment') + }) + + test('the header in the host’s words and locale', async () => { + const { blocks } = await open(sampleMsg(), 'sample.msg', { mail: { texts: { from: 'Von', sent: 'Gesendet', item: { report: 'Bericht' } }, locale: 'de-DE' } }) + const text = allText(blocks) + expect(text).toContain('Von | Jonas Weber') + expect(text).toContain('Gesendet | Freitag, 20. November 2026') + // the words not given stay English + expect(text).toContain('To | Ana Martínez') + }) + + test('remote pictures are left out and said; links that run script are not links', async () => { + const m = eml(['From: a@x.org', 'Subject: Web', 'Content-Type: text/html'], '

Hi there

') + const { blocks } = await open(m, 'web.eml') + const text = allText(blocks) + expect(text).toContain('Pictures from the web are not shown') + expect(paras(blocks).flatMap((p) => p.runs).some((r) => r.t === 'img')).toBe(false) + expect(paras(blocks).flatMap((p) => p.runs).some((r) => r.t === 'text' && r.href)).toBe(false) + }) + + test('a plain-text body: a paragraph per line, web addresses linked, quoted lines grey', async () => { + const { blocks } = await open(eml(['From: a@x.org', 'Subject: Text'], 'See https://example.org/a.\r\n> earlier\r\nEnd'), 'text.eml') + const body = paras(blocks).slice(-3) + expect(body.map(textOf)).toEqual(['See https://example.org/a.', '> earlier', 'End']) + expect(body[0].runs.find((r) => r.t === 'text' && r.href)).toMatchObject({ text: 'https://example.org/a' }) + expect(body[1].runs[0]).toMatchObject({ s: { color: '#595959' } }) + }) + + test('found by its content (no name, a MIME type), not mistaken: web pages saved as MHTML, other text', () => { + const head = latin1('Received: from x\r\nFrom: a@x.org\r\nTo: b@y.org\r\nSubject: s\r\n\r\nbody') + expect(mailTextFormat(undefined, '', head)).toBe('eml') + expect(mailTextFormat('download', 'message/rfc822', latin1('junk'))).toBe('eml') + expect(mailTextFormat('page.mht', '', head)).toBe(null) + expect(mailTextFormat(undefined, '', latin1('From: \r\nSnapshot-Content-Location: https://x\r\nSubject: p\r\nMIME-Version: 1.0\r\n\r\n'))).toBe(null) + expect(mailTextFormat(undefined, '', latin1('Name: value\r\nOther: thing\r\n'))).toBe(null) + }) + + test('damaged or odd files: no crash, a message that says so', async () => { + await expect(open(latin1('garbage'), 'x.msg')).rejects.toThrow('not an Outlook message') + // (some programs save Internet messages as .msg) + const mime = await open(eml(['From: a@x.org', 'To: b@y.org', 'Subject: Saved as msg'], 'Body'), 'saved.msg') + expect(mime.info.from).toBe('eml') + // a damaged compound file + const msg = sampleMsg() + await expect(open(msg.subarray(0, 600), 'cut.msg')).rejects.toThrow() + // an empty .eml is an empty message + const empty = await open(new Uint8Array(0), 'empty.eml') + expect(allText(empty.blocks)).toContain('(no subject)') + }) + + test('pictures: the size of PNG, GIF, JPEG and BMP read from their bytes', async () => { + expect(pictureSize(png(7, 3))).toEqual({ w: 7, h: 3 }) + expect(pictureSize(latin1('GIF89a\x05\x00\x04\x00' + '\0'.repeat(30)))).toEqual({ w: 5, h: 4 }) + const jpeg = Uint8Array.from([0xff, 0xd8, 0xff, 0xe0, 0, 4, 0, 0, 0xff, 0xc0, 0, 11, 8, 0, 20, 0, 30, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) + expect(pictureSize(jpeg)).toEqual({ w: 30, h: 20 }) + const bmp = new Uint8Array(40) + bmp.set([0x42, 0x4d]) + new DataView(bmp.buffer).setInt32(18, 9, true) + new DataView(bmp.buffer).setInt32(22, -6, true) + expect(pictureSize(bmp)).toEqual({ w: 9, h: 6 }) + // the built document has the PNG as a part of its own + const { docx } = await openMail(sampleEml(), 'eml') + const zip = await ZipArchive.open(new BlobSource(docx)) + expect(zip.list().map((e) => e.name)).toContain('word/media/image1.png') + }) +}) From 76d10f3b83dd3c4eb59e00376430cb68393f17d1 Mon Sep 17 00:00:00 2001 From: Markus Date: Sun, 6 Dec 2026 20:53:41 +0100 Subject: [PATCH 2/3] fix(mail): review after rebase: a language change keeps edits, engines reopened clean, no live session for a message - The mail texts and locale reopen a mail message only (in the new words); another document is not opened again, so its edits stay. - An engine opened again keeps nothing of the PDF or the message it had before (`pdf.read`, `save`, `dirty`, `mail.attachment`). - A mail message, view only, is not shared live: a peer's edits in the same room no longer change it. - API docs: `doc.kind` may be 'pdf'. Co-Authored-By: Claude Opus 5.5 --- docs/api.md | 2 +- e2e/mail.spec.ts | 17 +++++++++++++++++ src/core/worker/engine.ts | 3 +++ src/react/DocViewer.tsx | 3 ++- src/react/useDocument.ts | 8 +++++++- test/mail.test.ts | 16 ++++++++++++++++ 6 files changed, 46 insertions(+), 3 deletions(-) diff --git a/docs/api.md b/docs/api.md index f37e2984..135a1f5d 100644 --- a/docs/api.md +++ b/docs/api.md @@ -562,7 +562,7 @@ const pdfjs = async () => { import { DocumentClient } from '@p10node/office-engine/core' const doc = await DocumentClient.open(fileOrUrl, { onProgress: console.log }) -doc.kind // 'docx' | 'xlsx' | 'pptx' +doc.kind // 'docx' | 'xlsx' | 'pptx' | 'pdf' (a PDF file, read with 'pdf.read') doc.info.from // 'pages' / 'keynote' / 'numbers' / 'visio' / 'eml' / 'msg': an Apple or Visio file, converted to docx / pptx / xlsx / pptx, // or a mail message (.eml / .emlx, .msg / .oft) as docx (view only) doc.info.mail // a mail message: { subject, attachments: [{ name, type, size }] } diff --git a/e2e/mail.spec.ts b/e2e/mail.spec.ts index cf7d7bde..09573951 100644 --- a/e2e/mail.spec.ts +++ b/e2e/mail.spec.ts @@ -57,4 +57,21 @@ describe('mail messages', () => { expect(text).toContain('November 2026') expect(v.errors).toEqual([]) }) + test("a change of language writes a mail message's header again in its words; another document keeps its edits", async () => { + const mail = await viewer({ src: 'samples/sample.eml' }) + expect(await mail.page.locator('.de-page-inner').first().innerText()).toContain('From') + await mail.page.evaluate(() => window.__setLanguage('de-DE')) + await mail.page.waitForFunction(() => /\bVon\b/.test((document.querySelector('.de-page-inner') as HTMLElement | null)?.innerText ?? ''), null, { timeout: 20_000 }) + expect(mail.errors).toEqual([]) + + const doc = await viewer({ src: 'samples/sample.docx', editable: true }) + await doc.selectText('document', 'end') + await doc.page.keyboard.type('XY') + await doc.page.waitForFunction(() => document.querySelector('.de-pages')?.textContent?.includes('documentXY')) + await doc.page.evaluate(() => window.__setLanguage('de-DE')) + // (what would open the document again, the language, has had its time) + await doc.page.waitForTimeout(1500) + expect(await doc.pagesText()).toContain('documentXY') + expect(doc.errors).toEqual([]) + }) }) diff --git a/src/core/worker/engine.ts b/src/core/worker/engine.ts index ba777b5c..39958fd0 100644 --- a/src/core/worker/engine.ts +++ b/src/core/worker/engine.ts @@ -73,6 +73,9 @@ export class Engine { const size = source.size // the first bytes say the format, whatever the name says (a real .doc named .docx, a web page named .xls): a ZIP is a package const first = source.size ? await source.read(0, Math.min(source.size, 4096)) : new Uint8Array(0) + // (an engine opened again keeps nothing of the file before: its PDF or its message) + this.pdfFile = undefined + this.mail = null // a PDF file: shown as it is, nothing converted or read here (its pages are read where they are drawn) if (isPdf(first, namedPdf(name, source.type))) { this.kind = 'pdf' diff --git a/src/react/DocViewer.tsx b/src/react/DocViewer.tsx index 93d547a7..ca5e2ed9 100644 --- a/src/react/DocViewer.tsx +++ b/src/react/DocViewer.tsx @@ -257,7 +257,8 @@ function Viewer(props: DocViewerProps) { const docName = renamed ?? loadName // a PDF file: shown as it is, view only (nothing in it is edited, commented on or shared live) const isPdf = client?.kind === 'pdf' - const collab = useCollab(client, isPdf ? undefined : props.collab) + // a mail message, view only as well: the document it is shown as is not shared live (a peer's edits would change it) + const collab = useCollab(client, isPdf || client?.info?.mail ? undefined : props.collab) const srcFormat = client?.info?.imported // an SVG file: the picture alone, read only (its text is edited in the source pane) const isPicture = srcFormat === 'svg' diff --git a/src/react/useDocument.ts b/src/react/useDocument.ts index e1324d0e..ac20c0b6 100644 --- a/src/react/useDocument.ts +++ b/src/react/useDocument.ts @@ -21,6 +21,10 @@ export function useDocument(src: DocSource | null | undefined, options: OpenOpti const headersKey = options.headers ? JSON.stringify(options.headers) : '' const mailKey = options.mail ? JSON.stringify(options.mail) : '' const shown = useRef(null) + // the mail texts and locale a document was opened with: a change opens a mail message again (in the new words; it + // holds no edits), never another document, whose edits would be lost + const openedMail = useRef(mailKey) + const mailDep = shown.current?.info?.mail ? mailKey : openedMail.current const keepRef = useRef(keep) keepRef.current = keep /** the client shown from now on; the one before it is closed */ @@ -36,6 +40,7 @@ export function useDocument(src: DocSource | null | undefined, options: OpenOpti return } let live = true + openedMail.current = mailKey if (keepRef.current && shown.current) setState((s) => ({ ...s, error: null, loading: true })) else { show(null) @@ -69,6 +74,7 @@ export function useDocument(src: DocSource | null | undefined, options: OpenOpti live = false giveUp.abort() } - }, [src, name, worker, credentials, headersKey, language, mailKey]) + // (mailKey counts through mailDep: for a mail message only) + }, [src, name, worker, credentials, headersKey, language, mailDep]) // eslint-disable-line react-hooks/exhaustive-deps return state } diff --git a/test/mail.test.ts b/test/mail.test.ts index 7e13d908..a17d8a8b 100644 --- a/test/mail.test.ts +++ b/test/mail.test.ts @@ -315,3 +315,19 @@ describe('mail: the document', () => { expect(zip.list().map((e) => e.name)).toContain('word/media/image1.png') }) }) + +describe('an engine opened again', () => { + test('keeps nothing of the PDF or the message before', async () => { + const { samplePdf } = await import('./pdf-builder') + const { readFileSync } = await import('node:fs') + const eml = new Uint8Array(readFileSync(`${import.meta.dir}/../playground/public/samples/sample.eml`)) + const e = new Engine(() => {}) + expect((await e.open(new Blob([(await samplePdf()) as BlobPart]), { name: 'a.pdf' })).kind).toBe('pdf') + expect((await e.open(new Blob([eml as BlobPart]), { name: 'a.eml' })).kind).toBe('docx') + // (the PDF before is gone: nothing reads or saves it any more) + expect(e.call('pdf.read', [0, 4])).rejects.toThrow() + expect(await e.call('mail.attachment', [0])).toBeInstanceOf(Blob) + expect((await e.open(new Blob([(await samplePdf()) as BlobPart]), { name: 'b.pdf' })).kind).toBe('pdf') + expect(e.call('mail.attachment', [0])).rejects.toThrow('No such attachment') + }) +}) From b29c121f7169a64a8bc79c92a373659d23b2d4e0 Mon Sep 17 00:00:00 2001 From: Markus Date: Sun, 6 Dec 2026 20:58:55 +0100 Subject: [PATCH 3/3] fix(mail): re-check: an engine opened again forgets everything, the mail words reload a message only - Engine.open forgets the document before it (package, document, sheet editor, slides, live-session workers, PDF, message, source text) before it reads the new one, so a failed open leaves nothing stale and a message's document is never saved for the workbook opened after it. - useDocument: the mail texts and locale are no longer an input of the open effect (a change of language just before another file could open it twice); a mail message shown in other words than the viewer's is reloaded by its own effect. Co-Authored-By: Claude Opus 5.5 --- e2e/mail.spec.ts | 12 ++++++++++++ src/core/worker/engine.ts | 11 ++++++++--- src/react/useDocument.ts | 19 ++++++++++++------- test/mail.test.ts | 11 +++++++++++ 4 files changed, 43 insertions(+), 10 deletions(-) diff --git a/e2e/mail.spec.ts b/e2e/mail.spec.ts index 09573951..0d3752fe 100644 --- a/e2e/mail.spec.ts +++ b/e2e/mail.spec.ts @@ -73,5 +73,17 @@ describe('mail messages', () => { await doc.page.waitForTimeout(1500) expect(await doc.pagesText()).toContain('documentXY') expect(doc.errors).toEqual([]) + + // a change of language, then another file: it is opened once, in the new words + const next = await viewer({ src: 'samples/sample.docx' }) + const fetched: string[] = [] + // (an open asks for the file's first byte, then reads it: the first requests count the opens) + next.page.context().on('request', (r) => r.url().includes('sample.eml') && r.headers().range === 'bytes=0-0' && fetched.push(r.url())) + await next.page.evaluate(() => window.__setLanguage('de-DE')) + await next.page.evaluate(() => window.__setProps({ src: 'samples/sample.eml' })) + await next.page.waitForFunction(() => /\bVon\b/.test((document.querySelector('.de-page-inner') as HTMLElement | null)?.innerText ?? ''), null, { timeout: 20_000 }) + await next.page.waitForTimeout(1000) + expect(fetched.length).toBe(1) + expect(next.errors).toEqual([]) }) }) diff --git a/src/core/worker/engine.ts b/src/core/worker/engine.ts index 39958fd0..59dcf7f5 100644 --- a/src/core/worker/engine.ts +++ b/src/core/worker/engine.ts @@ -63,6 +63,8 @@ export class Engine { constructor(private emit: Emit) {} async open(src: DocSource, params: OpenParams = {}): Promise { + // an engine opened again keeps nothing of the file before, also when this one fails to open + this.forget() if (params.encoding && !knownEncoding(params.encoding)) throw new Error(`Unknown text encoding “${params.encoding}”`) let source = await openSource(src, { ...params, @@ -73,9 +75,6 @@ export class Engine { const size = source.size // the first bytes say the format, whatever the name says (a real .doc named .docx, a web page named .xls): a ZIP is a package const first = source.size ? await source.read(0, Math.min(source.size, 4096)) : new Uint8Array(0) - // (an engine opened again keeps nothing of the file before: its PDF or its message) - this.pdfFile = undefined - this.mail = null // a PDF file: shown as it is, nothing converted or read here (its pages are read where they are drawn) if (isPdf(first, namedPdf(name, source.type))) { this.kind = 'pdf' @@ -405,6 +404,12 @@ export class Engine { this.abort.abort() } + /** the document opened, gone: what is read, edited, shared live, saved */ + private forget() { + this.pkg = this.kind = this.docx = this.xlsx = this.xlsxEd = this.pptx = this.pdfFile = this.xcollab = this.pcollab = undefined + this.plainText = this.original = this.mail = null + } + private need(v: T | undefined): T { if (!v) throw new Error(this.kind ? `Operation not available for ${this.kind}` : 'Document not opened') return v diff --git a/src/react/useDocument.ts b/src/react/useDocument.ts index ac20c0b6..5dcdf863 100644 --- a/src/react/useDocument.ts +++ b/src/react/useDocument.ts @@ -21,10 +21,12 @@ export function useDocument(src: DocSource | null | undefined, options: OpenOpti const headersKey = options.headers ? JSON.stringify(options.headers) : '' const mailKey = options.mail ? JSON.stringify(options.mail) : '' const shown = useRef(null) - // the mail texts and locale a document was opened with: a change opens a mail message again (in the new words; it - // holds no edits), never another document, whose edits would be lost + // the mail texts and locale: the latest are what a document is opened with; a change opens a mail message shown + // again (in the new words; it holds no edits), never another document, whose edits would be lost + const mailRef = useRef(mailKey) + mailRef.current = mailKey const openedMail = useRef(mailKey) - const mailDep = shown.current?.info?.mail ? mailKey : openedMail.current + const [mailReload, setMailReload] = useState(0) const keepRef = useRef(keep) keepRef.current = keep /** the client shown from now on; the one before it is closed */ @@ -40,7 +42,7 @@ export function useDocument(src: DocSource | null | undefined, options: OpenOpti return } let live = true - openedMail.current = mailKey + const mail = (openedMail.current = mailRef.current) if (keepRef.current && shown.current) setState((s) => ({ ...s, error: null, loading: true })) else { show(null) @@ -54,7 +56,7 @@ export function useDocument(src: DocSource | null | undefined, options: OpenOpti credentials, language, headers: headersKey ? JSON.parse(headersKey) : undefined, - mail: mailKey ? JSON.parse(mailKey) : undefined, + mail: mail ? JSON.parse(mail) : undefined, onProgress: (p) => live && setState((s) => ({ ...s, progress: p })), signal: giveUp.signal, }).then( @@ -74,7 +76,10 @@ export function useDocument(src: DocSource | null | undefined, options: OpenOpti live = false giveUp.abort() } - // (mailKey counts through mailDep: for a mail message only) - }, [src, name, worker, credentials, headersKey, language, mailDep]) // eslint-disable-line react-hooks/exhaustive-deps + }, [src, name, worker, credentials, headersKey, language, mailReload]) + // a mail message shown, opened in other words than the viewer's now (changed since, or while it was loading) + useEffect(() => { + if (state.client?.info?.mail && state.client === shown.current && openedMail.current !== mailKey) setMailReload((n) => n + 1) + }, [mailKey, state.client]) return state } diff --git a/test/mail.test.ts b/test/mail.test.ts index a17d8a8b..29651dd8 100644 --- a/test/mail.test.ts +++ b/test/mail.test.ts @@ -329,5 +329,16 @@ describe('an engine opened again', () => { expect(await e.call('mail.attachment', [0])).toBeInstanceOf(Blob) expect((await e.open(new Blob([(await samplePdf()) as BlobPart]), { name: 'b.pdf' })).kind).toBe('pdf') expect(e.call('mail.attachment', [0])).rejects.toThrow('No such attachment') + // a message, then a workbook: nothing of the message's document is left to save or read + const xlsx = new Uint8Array(readFileSync(`${import.meta.dir}/../playground/public/samples/sample.xlsx`)) + await e.open(new Blob([eml as BlobPart]), { name: 'c.eml' }) + expect((await e.open(new Blob([xlsx as BlobPart]), { name: 'd.xlsx' })).kind).toBe('xlsx') + expect(e.call('docx.start', [])).rejects.toThrow() + // an open that fails leaves nothing of the file before + await e.open(new Blob([eml as BlobPart]), { name: 'e.eml' }) + expect(e.open(new Blob([new TextEncoder().encode('PK\x03\x04 broken')]), { name: 'f.docx' })).rejects.toThrow() + await Bun.sleep(0) + expect(e.call('mail.attachment', [0])).rejects.toThrow() + expect(e.call('pdf.read', [0, 4])).rejects.toThrow() }) })