Open History to see the last commit
1import JSZip from "jszip";
2import { describe, expect, it } from "vite-plus/test";
3
4import { prepareOffice } from "./officeArchive";
5
6const W = 'xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"';
7const V = 'xmlns:v="urn:schemas-microsoft-com:vml"';
8const R = 'xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"';
9const relationship = (type: string, target: string) =>
10 `<Relationship Id="${type}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/${type}" Target="${target}"/>`;
11const paragraph = (text: string, properties = "") =>
12 `<w:p>${properties}<w:r><w:t xml:space="preserve">${text}</w:t></w:r></w:p>`;
13
14async function wordFile(
15 body: string,
16 parts: Partial<Record<"styles" | "numbering" | "header" | "footer" | "footnotes", string>> = {},
17 section = "",
18 extraRels = "",
19) {
20 const zip = new JSZip();
21 zip.file(
22 "[Content_Types].xml",
23 `<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/></Types>`,
24 );
25 zip.file(
26 "_rels/.rels",
27 `<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">${relationship("officeDocument", "word/document.xml")}</Relationships>`,
28 );
29 zip.file(
30 "word/_rels/document.xml.rels",
31 `<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">${Object.keys(
32 parts,
33 )
34 .map((part) => relationship(part, `${part}.xml`))
35 .join("")}${extraRels}</Relationships>`,
36 );
37 for (const [part, xml] of Object.entries(parts)) zip.file(`word/${part}.xml`, xml);
38 zip.file(
39 "word/document.xml",
40 `<w:document ${W} ${V} ${R}><w:body>${body}<w:sectPr>${section}<w:pgSz w:w="12240" w:h="15840"/></w:sectPr></w:body></w:document>`,
41 );
42 return zip.generateAsync({ type: "arraybuffer" });
43}
44
45async function prepared(bytes: ArrayBuffer) {
46 const result = await prepareOffice(bytes, "docx");
47 const zip = await JSZip.loadAsync(result.bytes);
48 return { truncated: result.truncated, part: (path: string) => zip.file(path)?.async("string") };
49}
50
51// regression: the budgets sized for a main-thread renderer cut ordinary documents short.
52describe("Word preview limits", () => {
53 it("keeps a document whose table follows a long one", async () => {
54 const rows = Array.from(
55 { length: 500 },
56 (_, row) =>
57 `<w:tr>${Array.from({ length: 5 }, (_, cell) => `<w:tc>${paragraph(`r${row}c${cell}`)}</w:tc>`).join("")}</w:tr>`,
58 ).join("");
59 const result = await prepared(
60 await wordFile(`<w:tbl>${rows}</w:tbl>${paragraph("After the table")}`),
61 );
62 expect(result.truncated).toBe(false);
63 expect(await result.part("word/document.xml")).toContain("After the table");
64 });
65
66 it("keeps the list and style definitions of a long document", async () => {
67 const levels = Array.from(
68 { length: 9 },
69 (_, level) =>
70 `<w:lvl w:ilvl="${level}"><w:numFmt w:val="decimal"/><w:lvlText w:val="%${level + 1}."/></w:lvl>`,
71 ).join("");
72 const numbering = `<w:numbering ${W}>${Array.from({ length: 60 }, (_, list) => `<w:abstractNum w:abstractNumId="${list}">${levels}</w:abstractNum>`).join("")}${Array.from({ length: 60 }, (_, list) => `<w:num w:numId="${list + 1}"><w:abstractNumId w:val="${list}"/></w:num>`).join("")}</w:numbering>`;
73 const styles = `<w:styles ${W}>${Array.from(
74 { length: 1_500 },
75 (_, style) =>
76 `<w:style w:type="paragraph" w:styleId="S${style}">${style % 10 ? `<w:basedOn w:val="S${style - 1}"/>` : ""}<w:pPr><w:spacing w:after="${style}"/></w:pPr><w:rPr><w:sz w:val="22"/></w:rPr></w:style>`,
77 ).join("")}</w:styles>`;
78 const result = await prepared(
79 await wordFile(
80 Array.from({ length: 6_000 }, (_, index) =>
81 paragraph(
82 `Item ${index}`,
83 `<w:pPr><w:pStyle w:val="S${index % 1_500}"/><w:numPr><w:ilvl w:val="0"/><w:numId w:val="${(index % 60) + 1}"/></w:numPr></w:pPr>`,
84 ),
85 ).join(""),
86 { styles, numbering },
87 ),
88 );
89 expect(result.truncated).toBe(false);
90 expect(await result.part("word/numbering.xml")).toBe(numbering);
91 expect(await result.part("word/styles.xml")).toBe(styles);
92 expect(await result.part("word/document.xml")).toContain("Item 5999");
93 });
94
95 it("keeps the lists of a document with picture bullets, with their text bullets", async () => {
96 const picture = `<w:numPicBullet w:numPicBulletId="0"><w:pict><v:shape style="width:9pt;height:9pt"><v:imagedata r:id="rId1"/></v:shape></w:pict></w:numPicBullet>`;
97 const pictured = `<w:abstractNum w:abstractNumId="0"><w:lvl w:ilvl="0"><w:numFmt w:val="bullet"/><w:lvlText w:val="\uf0b7"/><w:lvlPicBulletId w:val="0"/></w:lvl></w:abstractNum>`;
98 const numbered = `<w:abstractNum w:abstractNumId="1"><w:lvl w:ilvl="0"><w:numFmt w:val="decimal"/><w:lvlText w:val="%1."/></w:lvl></w:abstractNum>`;
99 const lists = `<w:num w:numId="1"><w:abstractNumId w:val="0"/></w:num><w:num w:numId="2"><w:abstractNumId w:val="1"/></w:num>`;
100 const result = await prepared(
101 await wordFile(paragraph("Item", `<w:pPr><w:numPr><w:numId w:val="2"/></w:numPr></w:pPr>`), {
102 numbering: `<w:numbering ${W} ${V} ${R}>${picture}${pictured}${numbered}${lists}</w:numbering>`,
103 }),
104 );
105 expect(await result.part("word/numbering.xml")).toBe(
106 `<w:numbering ${W} ${V} ${R}>${pictured.replace('<w:lvlPicBulletId w:val="0"/>', "")}${numbered}${lists}</w:numbering>`,
107 );
108 });
109
110 const text = "x".repeat(140_000);
111 it.each([
112 ["on its own", `<w:p><w:r><w:t>${text}</w:t></w:r></w:p>`],
113 [
114 "after an empty paragraph in a text box",
115 `<w:p><w:r><w:pict><v:shape><v:textbox><w:txbxContent><w:p/></w:txbxContent></v:textbox></v:shape></w:pict></w:r><w:r><w:t>${text}</w:t></w:r></w:p>`,
116 ],
117 ["written as CDATA", `<w:p><w:r><w:t><![CDATA[${text}]]></w:t></w:r></w:p>`],
118 ])("stops before a paragraph too long to lay out %s", async (_, long) => {
119 const result = await prepared(
120 await wordFile(paragraph("Kept") + long + paragraph("Not reached")),
121 );
122 expect(result.truncated).toBe(true);
123 const document = await result.part("word/document.xml");
124 expect(document).toContain("Kept");
125 expect(document).not.toContain("Not reached");
126 });
127
128 it("counts only the text a paragraph lays out", async () => {
129 const formatted = `<w:p>${" ".repeat(140_000)}<w:r><w:instrText>${"x".repeat(140_000)}</w:instrText></w:r><w:r><w:t>${"x".repeat(40_000)}</w:t></w:r></w:p>`;
130 const result = await prepared(await wordFile(formatted + paragraph("After")));
131 expect(result.truncated).toBe(false);
132 expect(await result.part("word/document.xml")).toContain("After");
133 });
134
135 it("keeps a long header", async () => {
136 const header = `<w:hdr ${W}>${Array.from({ length: 3_000 }, (_, line) => paragraph(`Header line ${line}`)).join("")}</w:hdr>`;
137 const footer = `<w:ftr ${W}>${paragraph("Footer")}</w:ftr>`;
138 const footnotes = `<w:footnotes ${W}><w:footnote w:id="1">${paragraph("Note")}</w:footnote></w:footnotes>`;
139 const result = await prepared(
140 await wordFile(
141 `<w:p><w:r><w:t>Body</w:t></w:r><w:r><w:footnoteReference w:id="1"/></w:r></w:p>`,
142 { header, footer, footnotes },
143 `<w:headerReference w:type="default" r:id="header"/><w:footerReference w:type="default" r:id="footer"/>`,
144 ),
145 );
146 expect(result.truncated).toBe(false);
147 expect(await result.part("word/header.xml")).toBe(header);
148 expect(await result.part("word/footer.xml")).toBe(footer);
149 expect(await result.part("word/footnotes.xml")).toBe(footnotes);
150 expect(await result.part("word/document.xml")).toContain("Body");
151 });
152
153 it("drops a malformed external hyperlink relationship while keeping body text", async () => {
154 const result = await prepared(
155 await wordFile(
156 paragraph("Body text"),
157 {},
158 "",
159 `<Relationship Id="badLink" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink" Target="http://[placeholder]/" TargetMode="External"/>`,
160 ),
161 );
162 expect(result.truncated).toBe(false);
163 expect(await result.part("word/document.xml")).toContain("Body text");
164 expect(await result.part("word/_rels/document.xml.rels")).not.toContain("badLink");
165 });
166});
167
168async function workbookFile(
169 target: string,
170 sheetPath: string,
171 extraRels = "",
172 targetMode = "Internal",
173) {
174 const zip = new JSZip();
175 zip.file(
176 "[Content_Types].xml",
177 `<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/></Types>`,
178 );
179 zip.file(
180 "_rels/.rels",
181 `<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">${relationship("officeDocument", "xl/workbook.xml")}</Relationships>`,
182 );
183 zip.file(
184 "xl/workbook.xml",
185 `<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" ${R}><sheets><sheet name="Sample" sheetId="1" r:id="sheet"/></sheets></workbook>`,
186 );
187 zip.file(
188 "xl/_rels/workbook.xml.rels",
189 `<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="sheet" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="${target}" TargetMode="${targetMode}"/>${extraRels}</Relationships>`,
190 );
191 zip.file(
192 sheetPath,
193 `<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><sheetData><row r="1"><c r="A1"><v>42</v></c></row></sheetData></worksheet>`,
194 );
195 return zip.generateAsync({ type: "arraybuffer" });
196}
197
198describe("Workbook relationship targets", () => {
199 it.each(["sheet 1.xml", "sheet%201.xml", "sheet#1.xml"])(
200 "prepares a worksheet whose ZIP name matches its target literally (%s)",
201 async (name) => {
202 const result = await prepareOffice(
203 await workbookFile(`worksheets/${name}`, `xl/worksheets/${name}`),
204 "xlsx",
205 );
206 const zip = await JSZip.loadAsync(result.bytes);
207 expect(result.truncated).toBe(false);
208 expect(await zip.file(`xl/worksheets/${name}`)?.async("string")).toContain("42");
209 },
210 );
211
212 it("refuses a worksheet whose relationship is external", async () => {
213 await expect(
214 prepareOffice(
215 await workbookFile("worksheets/sheet2.xml", "xl/worksheets/sheet2.xml", "", "External"),
216 "xlsx",
217 ),
218 ).rejects.toMatchObject({ code: "workbook-sheet-count" });
219 });
220
221 it("handles a malformed external relationship in workbook relationships", async () => {
222 const result = await prepareOffice(
223 await workbookFile(
224 "worksheets/sheet1.xml",
225 "xl/worksheets/sheet1.xml",
226 `<Relationship Id="ext" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/externalLinkPath" Target="http://[placeholder]/" TargetMode="External"/>`,
227 ),
228 "xlsx",
229 );
230 const zip = await JSZip.loadAsync(result.bytes);
231 expect(result.truncated).toBe(false);
232 expect(await zip.file("xl/worksheets/sheet1.xml")?.async("string")).toContain("42");
233 });
234});