Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
chore(spreadsheet): address requested changes
Elian Doran33a20d2449dd
diff --git a/packages/commons/src/lib/spreadsheet/parse_from_xlsx.spec.ts b/packages/commons/src/lib/spreadsheet/parse_from_xlsx.spec.tsindex 607f997118..26cef25d1b 100644--- a/packages/commons/src/lib/spreadsheet/parse_from_xlsx.spec.ts+++ b/packages/commons/src/lib/spreadsheet/parse_from_xlsx.spec.ts@@ -1,7 +1,7 @@import ExcelJS from "exceljs";import { describe, expect, it } from "vitest";-import { parseXlsxToWorkbook } from "./parse_from_xlsx.js";+import { parseXlsxToWorkbook, toArrayBuffer } from "./parse_from_xlsx.js";import {BorderStyle,CellValueType,@@ -218,4 +218,60 @@ describe("parseXlsxToWorkbook", () => {it("throws on a non-xlsx buffer", async () => {await expect(parseXlsxToWorkbook(new Uint8Array([1, 2, 3]))).rejects.toThrow(/parse/i);});++ it("parses an xlsx delivered as an offset view into a larger buffer (Node Buffer import path)", async () => {+ // Reproduces the real server-import shape: a Node Buffer that views part of a larger+ // backing buffer at a non-zero offset (single.ts / zip.ts both pass Buffers). With the+ // buggy `slice().buffer`, exceljs receives the WHOLE backing; the stray end-of-central-+ // directory marker placed in the trailing bytes then makes JSZip read an empty archive,+ // silently dropping every sheet.+ const wb = new ExcelJS.Workbook();+ wb.addWorksheet("Data").getCell("A1").value = "survived";+ const xlsx = Buffer.from((await wb.xlsx.writeBuffer()) as ArrayBuffer);++ const PREFIX = 8;+ const TRAILER = 32;+ const backing = Buffer.alloc(PREFIX + xlsx.length + TRAILER); // standalone, zero-filled+ xlsx.copy(backing, PREFIX);+ // A fake EOCD signature ("PK\x05\x06") at the very end; the 18 zero bytes after it read as+ // a valid record describing zero entries, so the whole backing parses as an empty zip.+ backing.set([0x50, 0x4b, 0x05, 0x06], backing.length - 22);+ const view = backing.subarray(PREFIX, PREFIX + xlsx.length);++ const { workbook } = await parseXlsxToWorkbook(view);+ const sheet = workbook.sheets[workbook.sheetOrder[0]];+ expect(sheet?.cellData[0]?.[0]).toMatchObject({ v: "survived" });+ });+});++describe("toArrayBuffer", () => {+ it("copies a Node Buffer view into a tightly-sized ArrayBuffer, not the whole backing", () => {+ // Buffer.prototype.slice returns a VIEW over the same backing (unlike+ // Uint8Array.prototype.slice, which copies), so `input.slice().buffer` would expose the+ // entire backing — foreign bytes and all — to exceljs.+ const backing = Buffer.alloc(64);+ for (let i = 0; i < backing.length; i++) backing[i] = i;+ const view = backing.subarray(8, 24); // 16 bytes at a non-zero offset++ const result = toArrayBuffer(view);++ expect(result.byteLength).toBe(view.byteLength);+ expect([...new Uint8Array(result)]).toEqual([...view]);+ });++ it("copies a Uint8Array subarray tightly (browser/standalone import path)", () => {+ const backing = new Uint8Array(64);+ for (let i = 0; i < backing.length; i++) backing[i] = i;+ const view = backing.subarray(8, 24);++ const result = toArrayBuffer(view);++ expect(result.byteLength).toBe(view.byteLength);+ expect([...new Uint8Array(result)]).toEqual([...view]);+ });++ it("returns a standalone ArrayBuffer unchanged", () => {+ const ab = new ArrayBuffer(8);+ expect(toArrayBuffer(ab)).toBe(ab);+ });});diff --git a/packages/commons/src/lib/spreadsheet/parse_from_xlsx.ts b/packages/commons/src/lib/spreadsheet/parse_from_xlsx.tsindex 3c26585693..8ee74ceb86 100644--- a/packages/commons/src/lib/spreadsheet/parse_from_xlsx.ts+++ b/packages/commons/src/lib/spreadsheet/parse_from_xlsx.ts@@ -538,10 +538,13 @@ function isFiniteNumber(v: unknown): v is number {/*** Normalizes input to a tight `ArrayBuffer` for exceljs. A `Uint8Array`/Node `Buffer` can be a* view into a larger pooled buffer, so reading `.buffer` directly would include foreign bytes —- * slice by its offset/length when it isn't already a full-buffer view.+ * slice by its offset/length to copy out exactly the viewed region.*/-function toArrayBuffer(input: ArrayBuffer | Uint8Array): ArrayBuffer {+export function toArrayBuffer(input: ArrayBuffer | Uint8Array): ArrayBuffer {if (!(input instanceof Uint8Array)) return input;- // `slice()` copies into a fresh, tightly-sized ArrayBuffer — independent of any pool.- return input.slice().buffer as ArrayBuffer;+ // NB: `input.slice()` can't be used here — Node's `Buffer.prototype.slice` returns a VIEW over+ // the same (often pooled) backing, so `.buffer` would expose the entire backing. Slicing the+ // backing ArrayBuffer by offset/length copies out exactly the viewed bytes in both Node and+ // the browser.+ return input.buffer.slice(input.byteOffset, input.byteOffset + input.byteLength) as ArrayBuffer;}diff --git a/packages/commons/src/lib/spreadsheet/render_to_xlsx.spec.ts b/packages/commons/src/lib/spreadsheet/render_to_xlsx.spec.tsindex 5ea9f97e28..b6c4bc1905 100644--- a/packages/commons/src/lib/spreadsheet/render_to_xlsx.spec.ts+++ b/packages/commons/src/lib/spreadsheet/render_to_xlsx.spec.ts@@ -1,7 +1,7 @@import ExcelJS from "exceljs";import { beforeAll, describe, expect, it } from "vitest";-import { renderSpreadsheetToXlsx } from "./render_to_xlsx.js";+import { renderSpreadsheetToXlsx, uniqueSheetName } from "./render_to_xlsx.js";/** Wrap a single styled cell (at A1 / row 0, col 0) into a complete workbook payload. */function singleCellWorkbook(cell: unknown, sheetExtra: Record<string, unknown> = {}, styles: Record<string, unknown> = {}): string {@@ -225,3 +225,68 @@ describe("renderSpreadsheetToXlsx", () => {});});});++describe("uniqueSheetName", () => {+ it("sanitises illegal characters, apostrophes, over-long and empty/reserved names", () => {+ // Excel/exceljs reject \ / ? * : [ ] -> replace with underscore.+ expect(uniqueSheetName("Sheet/1", new Set())).toBe("Sheet_1");+ expect(uniqueSheetName("a:b*c?", new Set())).toBe("a_b_c_");+ expect(uniqueSheetName("[ledger]\\", new Set())).toBe("_ledger__");+ // A leading/trailing single quote is rejected.+ expect(uniqueSheetName("'quoted'", new Set())).toBe("_quoted_");+ // 31-char cap.+ expect(uniqueSheetName("A".repeat(40), new Set())).toBe("A".repeat(31));+ // Empty/whitespace falls back to a default; "History" is reserved (case-insensitive).+ expect(uniqueSheetName("", new Set())).toBe("Sheet");+ expect(uniqueSheetName(" ", new Set())).toBe("Sheet");+ expect(uniqueSheetName("History", new Set())).toBe("History_");+ expect(uniqueSheetName("history", new Set())).toBe("history_");+ });++ it("de-duplicates case-insensitively, keeping names within the 31-char limit", () => {+ const used = new Set<string>();+ expect(uniqueSheetName("Data", used)).toBe("Data");+ expect(uniqueSheetName("data", used)).toBe("data (2)");+ expect(uniqueSheetName("DATA", used)).toBe("DATA (3)");++ const long = new Set<string>();+ expect(uniqueSheetName("A".repeat(40), long)).toBe("A".repeat(31));+ const second = uniqueSheetName("A".repeat(40), long);+ expect(second).toHaveLength(31);+ expect(second.endsWith(" (2)")).toBe(true);+ });+});++describe("renderSpreadsheetToXlsx sheet-name safety", () => {+ it("writes hostile sheet names as legal, unique, readable sheets without throwing", async () => {+ const json = workbookWithSheetNames(["Sheet/1", "History", "'Sales'", "A".repeat(40)]);+ const wb = await roundTrip(json);+ expect(wb.worksheets.map((ws) => ws.name)).toEqual(["Sheet_1", "History_", "_Sales_", "A".repeat(31)]);+ });++ it("de-duplicates colliding sheet names case-insensitively", async () => {+ const json = workbookWithSheetNames(["Data", "data", "DATA"]);+ const wb = await roundTrip(json);+ expect(wb.worksheets.map((ws) => ws.name)).toEqual(["Data", "data (2)", "DATA (3)"]);+ });+});++/** Build a workbook payload whose visible sheets carry the given (possibly hostile) names. */+function workbookWithSheetNames(names: string[]): string {+ const sheets: Record<string, unknown> = {};+ const sheetOrder: string[] = [];+ names.forEach((name, i) => {+ const id = `s${i}`;+ sheetOrder.push(id);+ sheets[id] = {+ id,+ name,+ hidden: 0,+ mergeData: [],+ cellData: { "0": { "0": { v: `cell-${i}`, t: 1 } } },+ rowData: {},+ columnData: {}+ };+ });+ return JSON.stringify({ version: 1, workbook: { sheetOrder, styles: {}, sheets } });+}diff --git a/packages/commons/src/lib/spreadsheet/render_to_xlsx.ts b/packages/commons/src/lib/spreadsheet/render_to_xlsx.tsindex 775fc2d667..9769979177 100644--- a/packages/commons/src/lib/spreadsheet/render_to_xlsx.ts+++ b/packages/commons/src/lib/spreadsheet/render_to_xlsx.ts@@ -54,15 +54,50 @@ export async function renderSpreadsheetToXlsx(jsonContent: string): Promise<Excereturn out.xlsx.writeBuffer();}+ // Sheet names come from arbitrary user/imported data; exceljs throws (aborting the whole+ // export) on names that are illegal or collide, so resolve each to an Excel-legal unique name.+ const usedNames = new Set<string>();for (const sheet of visibleSheets) {- writeSheet(out, sheet, styles);+ writeSheet(out, sheet, uniqueSheetName(sheet.name, usedNames), styles);}return out.xlsx.writeBuffer();}-function writeSheet(out: ExcelJS.Workbook, sheet: IWorksheetData, styles: Record<string, IStyleData | null>): void {- const ws = out.addWorksheet(sheet.name || "Sheet", {+const MAX_SHEET_NAME_LENGTH = 31;+// Excel/exceljs reject these characters anywhere in a worksheet name.+const ILLEGAL_SHEET_NAME_CHARS = /[\\/?*:[\]]/g;++/**+ * Returns an Excel-legal, workbook-unique worksheet name derived from `name`, recording the result+ * in `usedNames`. exceljs throws when a name is empty, equals the reserved "History", contains+ * \ / ? * : [ ], begins/ends with a single quote, or collides case-insensitively with an existing+ * sheet — so sanitise, truncate, then de-duplicate.+ */+export function uniqueSheetName(name: string | undefined, usedNames: Set<string>): string {+ const base = sanitizeSheetName(name);+ let candidate = base;+ for (let n = 2; usedNames.has(candidate.toLowerCase()); n++) {+ const suffix = ` (${n})`;+ candidate = `${base.slice(0, MAX_SHEET_NAME_LENGTH - suffix.length)}${suffix}`;+ }+ usedNames.add(candidate.toLowerCase());+ return candidate;+}++function sanitizeSheetName(name: string | undefined): string {+ const cleaned = (name ?? "")+ .replace(ILLEGAL_SHEET_NAME_CHARS, "_")+ .trim()+ .slice(0, MAX_SHEET_NAME_LENGTH)+ .replace(/^'+|'+$/g, "_"); // a leading/trailing single quote is illegal — check after the cut+ if (cleaned === "") return "Sheet";+ if (/^history$/i.test(cleaned)) return `${cleaned}_`;+ return cleaned;+}++function writeSheet(out: ExcelJS.Workbook, sheet: IWorksheetData, name: string, styles: Record<string, IStyleData | null>): void {+ const ws = out.addWorksheet(name, {views: [{ showGridLines: sheet.showGridlines !== 0 }],// Carry Univer's sheet-wide defaults so rows/columns without an explicit size keep it on// round-trip; otherwise Excel falls back to its own defaults (15pt rows / 8.43-char cols).