import { afterEach, expect, it } from "bun:test"; import { promises as fs } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { randomBytes } from "node:crypto"; import { zipSync, unzipSync, strToU8, strFromU8 } from "fflate"; import { SaxesParser } from "saxes"; import { restoreXlsxFile } from "../src/lib/xlsx-restoration"; const S = "http://schemas.openxmlformats.org/spreadsheetml/2006/main"; const roots: string[] = []; afterEach(async () => { for (const root of roots.splice(0)) await fs.rm(root, { recursive: true, force: true }); }); async function fixture(parts: Record = {}) { const root = await fs.mkdtemp(join(tmpdir(), "velum-xlsx-restore-")); roots.push(root); const source = join(root, "source.xlsx"), target = join(root, "restored.xlsx"); await fs.writeFile(source, zipSync({ "[Content_Types].xml": strToU8(''), "xl/workbook.xml": strToU8(``), ...parts, }, { level: 0 })); return { source, target }; } function xmlTexts(xml: string): string[] { const values: string[] = []; const parser = new SaxesParser(); parser.on("text", (text) => values.push(text)); parser.write(xml).close(); return values; } it("restores placeholders across rich-text runs while preserving XML escaping and boundaries", async () => { const { source, target } = await fixture({ "xl/sharedStrings.xml": strToU8(`PERSON_01PERSON_010 PERSON_01 xPERSON_01 ÄPERSON_01 UNKNOWN_99`), "xl/media/image1.png": Uint8Array.from([0, 42, 255]), }); const before = await fs.readFile(source); const result = await restoreXlsxFile(source, target, { PERSON_01: { original: 'A & B "😀"', type: "PERSON" }, PERSON_010: { original: "Anna", type: "PERSON" }, }); const parts = unzipSync(await fs.readFile(target)); expect(xmlTexts(strFromU8(parts["xl/sharedStrings.xml"]))).toEqual([ 'A & B "😀"', 'Anna A & B "😀" xPERSON_01 ÄPERSON_01 UNKNOWN_99', ]); expect(strFromU8(parts["xl/sharedStrings.xml"])).toContain(""); expect(parts["xl/media/image1.png"]).toEqual(Uint8Array.from([0, 42, 255])); expect(strFromU8(parts["xl/workbook.xml"])).toContain('name="A & B <Müller> "😀""'); expect(result.replacements).toBe(4); expect(await fs.readFile(source)).toEqual(before); expect((await fs.stat(target)).mode & 0o777).toBe(0o600); }); it("restores inline strings, formulas, comments, links and UTF-16 XML without changing numbers", async () => { const xml = `PERSON_01"PERSON_01"42`; const { source, target } = await fixture({ "xl/worksheets/sheet1.xml": Buffer.concat([Buffer.from([0xff, 0xfe]), Buffer.from(xml, "utf16le")]), "xl/comments/comment1.xml": strToU8(`PERSON_01`), "xl/_rels/workbook.xml.rels": strToU8(''), }); await restoreXlsxFile(source, target, { PERSON_01: { original: "Anna Berger", type: "PERSON" } }); const parts = unzipSync(await fs.readFile(target)); expect(xmlTexts(strFromU8(parts["xl/worksheets/sheet1.xml"]))).toEqual(["Anna Berger", '"Anna Berger"', "42"]); expect(xmlTexts(strFromU8(parts["xl/comments/comment1.xml"]))).toEqual(["Anna Berger"]); expect(strFromU8(parts["xl/_rels/workbook.xml.rels"])).toContain('Target="https://example.test/Anna Berger"'); }); it("supports compressed workbooks above the API's 20 MiB upload limit", async () => { const binary = randomBytes(21 * 1024 * 1024); const { source, target } = await fixture({ "xl/media/opaque.bin": binary, "xl/sharedStrings.xml": strToU8(`` + 'PERSON_6001'.repeat(170_000) + ''), }); const mapping = Object.fromEntries(Array.from({ length: 6001 }, (_, i) => [`PERSON_${String(i + 1).padStart(2, "0")}`, { original: `Name ${i + 1}`, type: "PERSON" }])); const result = await restoreXlsxFile(source, target, mapping); expect((await fs.stat(source)).size).toBeGreaterThan(20 * 1024 * 1024); expect(result.replacements).toBe(170_001); const parts = unzipSync(await fs.readFile(target)); expect(parts["xl/media/opaque.bin"]).toEqual(new Uint8Array(binary)); const restored = strFromU8(parts["xl/sharedStrings.xml"]); expect(restored.match(/Name 6001/g)).toHaveLength(170_000); expect(restored).not.toContain("PERSON_6001"); }, 60_000); it("removes incomplete outputs on malformed XML, DTDs and damaged ZIP payloads", async () => { for (const xml of ['', ']>&x;']) { const { source, target } = await fixture({ "xl/sharedStrings.xml": strToU8(xml) }); await expect(restoreXlsxFile(source, target, {})).rejects.toThrow(); expect(await fs.stat(target).catch(() => undefined)).toBeUndefined(); } const { source, target } = await fixture({ "xl/data.bin": strToU8("UNIQUE_PAYLOAD") }); const data = await fs.readFile(source); data[data.indexOf("UNIQUE_PAYLOAD")] ^= 1; await fs.writeFile(source, data); await expect(restoreXlsxFile(source, target, {})).rejects.toThrow("CRC"); expect(await fs.stat(target).catch(() => undefined)).toBeUndefined(); }); it("does not overwrite an existing target or accept a truncated archive", async () => { const { source, target } = await fixture(); await fs.writeFile(target, "keep this file"); await expect(restoreXlsxFile(source, target, {})).rejects.toThrow(); expect(await fs.readFile(target, "utf8")).toBe("keep this file"); await fs.rm(target); const data = await fs.readFile(source); await fs.writeFile(source, data.subarray(0, data.length - 30)); await expect(restoreXlsxFile(source, target, {})).rejects.toThrow("ZIP"); expect(await fs.stat(target).catch(() => undefined)).toBeUndefined(); }); it("restores split placeholders in DrawingML text boxes and keeps run formatting", async () => { const { source, target } = await fixture({ "xl/drawings/drawing1.xml": strToU8('PERSON_01'), }); await restoreXlsxFile(source, target, { PERSON_01: { original: "Anna Berger", type: "PERSON" } }); const drawing = strFromU8(unzipSync(await fs.readFile(target))["xl/drawings/drawing1.xml"]); expect(xmlTexts(drawing)).toEqual(["Anna Berger"]); expect(drawing).toContain('b="1"'); });