Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions .changeset/max-columns.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
---
"javascript-excel": minor
---

A wide sheet can no longer make an import run out of memory. A new read limit, `maxColumns`, bounds the highest column any kept cell uses on each sheet read, checked as each cell is kept (not from `<dimension>`), and refuses a wider sheet with `LimitError` (`details: { limit: 'maxColumns', value, max, part, ref }`) at its first cell past the limit. Its default is Excel's own width, 16,384 (`XFD`), so no valid sheet is refused; servers and browsers reading untrusted files should set it low, for example 256. It applies to `read`, `importDataset` (`limits.maxColumns`, for xlsx and CSV) and the worker client, and `parseCsv`/`readCsv` take `maxColumns` as a CSV option for the fields of one record (default 1,048,576, wider than any spreadsheet).

`importDataset` now counts the empty fields its dataset pads short rows with (a `null` for every column a row has no cell in) against `limits.maxCells`, for xlsx and CSV, before any row is built, and rejects past it with `LimitError` (`details: { limit: 'maxCells', value, max, rows, columns }`). Before, a 614 KB file with a title in each of 16,384 columns over 10,000 three-cell rows held only about 46,000 cells, so `maxCells` never tripped, and `importDataset` built 164 million fields and exhausted a 4 GB heap; under the default limits it is now refused in about 0.6 s. Cells with a value or formula are not counted, so dense data within the limits imports exactly as before; a cell that only carries a hyperlink or a style counts as an empty field.

Other differences from 2.3: the dataset count is checked while the dataset is built, so it can win over errors 2.3 raised later for the same input (a `types` key naming no column, `maxRows`). CSV imports are counted too: more than 500,000 rows of 10 fields under a 30-column header pad more than 10 M empty fields (20 per row) and are refused under the defaults (raise `maxCells`). CSV imports now validate `limits.maxCells` (a bad value throws `TypeError`, where 2.3 ignored it), and spreading `DEFAULT_READ_LIMITS` into a CSV import passes `maxColumns: 16384`, so a wider record is a `LimitError` instead of 2.3's `ValidationError`. The public `toDataset` is not bounded by the dataset count; when calling it on untrusted sheets, set `maxColumns` on the `read`.
20 changes: 16 additions & 4 deletions docs/api.md

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion packages/javascript-excel/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@ const bytes = await excel.write(workbook, { signal: controller.signal, onProgres
- **Reader:** `.xlsx`, `.xlsm`, `.xltx` and `.xltm`, including ISO 29500 Strict files.
- Reads values, shared, inline and rich strings, and formula text with cached values (shared formulas expanded).
- Styles come back as shared frozen objects. Merges, column widths and row heights, views and panes, print setup, hyperlinks, defined names and document properties are read too.
- **Untrusted files:** bounded by limits on size, zip entries, compression ratio, XML depth and token length, sheets, cells, shared strings and the length of one cell's text; a shared formula is expanded only from a master within Excel's 8,192-character formula limit. A `DOCTYPE` is rejected, nothing is ever fetched or executed, and file content never becomes an object key.
- **Untrusted files:** bounded by limits on size, zip entries, compression ratio, XML depth and token length, sheets, cells, sheet width (`maxColumns`; set it low, for example 256, for untrusted files), shared strings and the length of one cell's text; a shared formula is expanded only from a master within Excel's 8,192-character formula limit. A `DOCTYPE` is rejected, nothing is ever fetched or executed, and file content never becomes an object key.
- **Rejected formats:** `.xls`, `.xlsb`, `.ods` and encrypted files throw `UNSUPPORTED_FORMAT`.
- **CSV:** RFC 4180 parsing with delimiter detection, BOM and CRLF/LF/CR handling, lenient or strict modes, and optional type inference. `readCsv` decodes bytes in any `TextDecoder` encoding. Serializing gives you quoting, a BOM for Excel, ISO dates and a formula-injection guard, which is on by default.
- **Datasets:** `fromDataset` and `fromDatasets` support `key`, `path` and function accessors, grouped headers, number formats, widths and a totals row. `toDataset` reads a sheet back into `{ columns, data }`.
Expand Down
7 changes: 7 additions & 0 deletions packages/javascript-excel/scripts/consumer.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,11 @@ const full22: ReadLimits = { maxInputBytes: 1, maxEntries: 1, maxEntryBytes: 1,
const cellTextMax: number = DEFAULT_READ_LIMITS.maxCellTextLength;
const cellTextLimited: ReadOptions = { limits: { maxCellTextLength: 32_767 } };
void full22; void cellTextMax; void cellTextLimited;
// A complete ReadLimits object written for 2.3 (before maxColumns) still compiles.
const full23: ReadLimits = { maxInputBytes: 1, maxEntries: 1, maxEntryBytes: 1, maxTotalBytes: 1, maxRatio: 1, maxXmlDepth: 1, maxXmlTokenLength: 1, maxSheets: 1, maxCells: 1, maxItems: 1, maxSharedStrings: 1, maxCellTextLength: 1, maxWarnings: 1 };
const columnsMax: number = DEFAULT_READ_LIMITS.maxColumns;
const columnsLimited: ReadOptions = { limits: { maxColumns: 256 } };
void full23; void columnsMax; void columnsLimited;
import { importDataset, type DroppedIssues, type ImportDatasetResult } from ${JSON.stringify(`${pkg.name}/import`)};
const imp: Promise<ImportDatasetResult> = importDataset("a", { maxIssues: 10, limits: { maxCellTextLength: 100 } });
imp.then((r) => { const d: DroppedIssues | undefined = r.meta.droppedIssues; void d; }, () => {});
Expand Down Expand Up @@ -251,6 +256,8 @@ import { parseCsv, readCsv, toCsv, toCsvBlob, type CsvParseResult, type CsvWrite
const parsed: CsvParseResult = parseCsv("a,b\\r\\n1,2\\r\\n", { delimiter: "auto", inferTypes: true, mode: undefined });
const parsedLimited: CsvParseResult = parseCsv("a", { maxCellTextLength: 10, maxFieldBytes: 30 });
void parsedLimited;
const parsedNarrow: CsvParseResult = parseCsv("a", { maxColumns: 256 });
void parsedNarrow;
const first: string | number | boolean | Date | object | undefined = parsed.rows[0]?.[0];
const opts: CsvWriteOptions = { delimiter: ";", bom: undefined, escapeFormulas: true, dates: (d: Date) => d.toISOString() };
const text: string = toCsv([["x", 1, true, null, undefined, { value: 2, formula: "A1*2" }]], opts);
Expand Down
11 changes: 10 additions & 1 deletion packages/javascript-excel/src/csv.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import type { BinaryInput, BlobType } from "./binary";
import { CsvError, EnvironmentError } from "./errors";
import { decodeBytes } from "./internal/csv/decode";
import { toBytes } from "./internal/input";
import { CsvParser, DEFAULT_MAX_CELL_TEXT_LENGTH, DEFAULT_MAX_FIELD_BYTES, MAX_WARNINGS, type ParseConfig } from "./internal/csv/parse";
import { CsvParser, DEFAULT_MAX_CELL_TEXT_LENGTH, DEFAULT_MAX_COLUMNS, DEFAULT_MAX_FIELD_BYTES, MAX_WARNINGS, type ParseConfig } from "./internal/csv/parse";
import { serialize, type WriteConfig } from "./internal/csv/write";
import type { CellInput, CellValue, Sheet } from "./model";
import type { AbortSignalLike } from "./signal";
Expand Down Expand Up @@ -77,6 +77,14 @@ export interface CsvParseOptions {
* as `maxFieldBytes`, as before. A positive number; default 1,048,576 (1 Mi).
*/
maxCellTextLength?: number | undefined;
/**
* Fields in one record; a record with more throws `LimitError` (`LIMIT_EXCEEDED`, `details.limit`
* `'maxColumns'`, `details.value` the field's 1-based position, `details.ref` its cell) while it
* is read. The same name as `ReadLimits.maxColumns` for xlsx (added in 2.4). A positive number;
* default 1,048,576, wider than any spreadsheet (Excel: 16,384 columns), so no existing file is
* refused; set it to the widest file you accept (for example 256) for untrusted input.
*/
maxColumns?: number | undefined;
/**
* Warnings kept before the cap applies (as `ReadLimits.maxWarnings` for `read`). Past it,
* informational warnings are dropped and counted in one `WARNINGS_TRUNCATED` at the end;
Expand Down Expand Up @@ -149,6 +157,7 @@ function parseConfig(options: CsvParseOptions | undefined): ParseConfig {
maxRows: o.maxRows ?? Number.POSITIVE_INFINITY,
maxFieldBytes: o.maxFieldBytes ?? DEFAULT_MAX_FIELD_BYTES,
maxCellTextLength: o.maxCellTextLength === undefined ? DEFAULT_MAX_CELL_TEXT_LENGTH : o.maxCellTextLength,
maxColumns: o.maxColumns === undefined ? DEFAULT_MAX_COLUMNS : o.maxColumns,
dateZone: o.dateZone ?? "local",
maxWarnings: o.maxWarnings === undefined ? MAX_WARNINGS : o.maxWarnings, // null is rejected, as read does
};
Expand Down
57 changes: 55 additions & 2 deletions packages/javascript-excel/src/dataset.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { decodeCell, decodeRange, encodeCell, encodeCol, encodeRange, MAX_COLS,
import { type AutoWidthOptions } from "./auto-width";
import { cellText } from "./cells";
import { dateToSerial } from "./dates";
import { ValidationError } from "./errors";
import { LimitError, ValidationError } from "./errors";
import { isoDate, parseIsoDate } from "./internal/iso-date";
import { AUTO_WIDTH, textWidth } from "./internal/write/sheet-features";
import type { Cell, CellInput, CellValue, ColumnProps, ColumnWidth, NumFmt, RichText, Sheet, Style } from "./model";
Expand Down Expand Up @@ -664,8 +664,60 @@ export interface DetailedDataset {
range: string | undefined;
}

/** @internal What javascript-excel/import bounds while it builds the dataset (JSE-68). */
export interface DatasetBudget {
/** Empty fields the rows may be padded with: a column where a data row has no cell, or a cell with neither value nor formula. */
maxCells: number;
}

/**
* Every data row gets a key for every column, null where the row has no cell
* (the contract of toDataset). A wide header over short rows therefore costs
* rows × columns, far beyond the cells the sheet holds: 16,384 titles over
* 10,000 three-cell rows are 164 million fields. This counts those empty
* fields, row by row in the order they would be built, and refuses at the
* first row that passes `max`, before any row is built (JSE-68). A cell with
* neither value nor formula (only a hyperlink, which the reader charges to
* maxItems, or a style) is an empty field too. Work is
* bounded by the cells visited plus `max`: a row costs at most its stored
* cells plus its empty fields.
*/
function checkPadding(s: Sheet<CellInput>, rng: { start: { col: number }; end: { row: number; col: number } }, firstData: number, max: number): void {
const width = rng.end.col - rng.start.col + 1;
const height = rng.end.row - firstData + 1;
if (height <= 0 || width * height <= max) return; // cannot pass it
let padding = 0;
let rows = 0;
for (let r = firstData; r <= rng.end.row; r++) {
const row = s.rows[r];
if (!row) continue;
const end = Math.min(rng.end.col, row.length - 1);
let any = false;
let present = 0;
for (let c = rng.start.col; c <= end; c++) {
const v = row[c];
if (v === undefined || v === null) continue;
// A cell with neither value nor formula (one that only carries a hyperlink or a style)
// still becomes a null field: it is counted as empty, as the empty-row test treats it.
if (isCellObject(v) && (v.value === undefined || v.value === null) && !v.formula) continue;
present++;
any = true;
}
if (!any) continue; // an empty row is skipped, not built
rows++;
padding += width - present;
if (padding > max) {
throw new LimitError(
"LIMIT_EXCEEDED",
`The dataset needs more than maxCells (${max}) empty fields: ${rows} data rows × ${width} columns hold few cells. Read a narrower range or set maxColumns.`,
{ details: { limit: "maxCells", value: padding, max, rows, columns: width } },
);
}
}
}

/** @internal */
export function toDatasetDetailed(sheet: Sheet<Cell> | Sheet, options: ToDatasetOptions = {}): DetailedDataset {
export function toDatasetDetailed(sheet: Sheet<Cell> | Sheet, options: ToDatasetOptions = {}, budget?: DatasetBudget): DetailedDataset {
const s = sheet as Sheet<CellInput>;
const rng = options.range ? decodeRange(options.range) : s.dimension ? decodeRange(s.dimension) : usedRange(s);
if (!rng) return { columns: [], data: [], rowNumbers: [], totalsSkipped: false, range: undefined };
Expand Down Expand Up @@ -693,6 +745,7 @@ export function toDatasetDetailed(sheet: Sheet<Cell> | Sheet, options: ToDataset
const rowNumbers: number[] = [];
let lastRaw: ReadonlyArray<CellInput> | undefined;
const firstData = headerRow === false ? rng.start.row : Math.max(rng.start.row, headerRow + headerRows);
if (budget) checkPadding(s, rng, firstData, budget.maxCells);
for (let r = firstData; r <= rng.end.row; r++) {
const row = s.rows[r];
if (!row) continue;
Expand Down
22 changes: 22 additions & 0 deletions packages/javascript-excel/src/internal/csv/parse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ export interface ParseConfig {
maxRows: number;
maxFieldBytes: number;
maxCellTextLength: number;
maxColumns: number;
dateZone: "local" | "utc";
maxWarnings: number;
}
Expand All @@ -40,6 +41,12 @@ export interface ParseOutput {
export const DEFAULT_MAX_FIELD_BYTES = 1_048_576;
/** Default `maxCellTextLength`: 1 Mi UTF-16 code units per field, as `DEFAULT_READ_LIMITS` for xlsx (JSE-58). */
export const DEFAULT_MAX_CELL_TEXT_LENGTH = 1_048_576;
/**
* Default `maxColumns`: fields in one record (JSE-68). 1 Mi, 64 times Excel's 16,384 columns and
* beyond any spreadsheet's width, so it refuses no CSV file that 2.3 read; a record that wide is
* at least 1 MiB of text, so the rows parseCsv returns stay linear in the input.
*/
export const DEFAULT_MAX_COLUMNS = 1_048_576;
/** Default `maxWarnings`: warnings kept per parse before the cap (internal/warning-cap.ts) applies. */
export const MAX_WARNINGS = 1000;

Expand Down Expand Up @@ -158,13 +165,15 @@ export class CsvParser {
value = this.plainField(row, col);
}
this.checkSize(value, row, col);
this.checkWidth(col, row);
fields.push({ text: value, quoted });
if (this.pos >= len) return fields;
const c = text.charCodeAt(this.pos);
if (c === this.delimCode) {
this.pos++;
if (this.pos >= len) {
// Trailing delimiter at end of input: one more empty field.
this.checkWidth(fields.length, row);
fields.push({ text: "", quoted: false });
return fields;
}
Expand Down Expand Up @@ -296,6 +305,18 @@ export class CsvParser {
}
}

/**
* Field `col` (zero-based) of a record, before it is kept: refused past maxColumns (JSE-68). The
* record read only to find that maxRows was reached is dropped, so it is not checked.
*/
private checkWidth(col: number, row: number): void {
const max = this.cfg.maxColumns;
if (col < max || row >= this.cfg.maxRows) return;
throw new LimitError("LIMIT_EXCEEDED", `Row ${row + 1} has more than maxColumns (${max}) fields.`, {
details: { limit: "maxColumns", value: col + 1, max, ref: cellRef(row, col) },
});
}

private warn(code: ExcelWarningCode, message: string, ref: string | undefined, malformed = true): void {
if (this.cfg.strict && malformed) {
throw new CsvError("CSV_MALFORMED", message, { details: { warning: code, ...(ref === undefined ? {} : { ref }), line: this.line } });
Expand Down Expand Up @@ -327,6 +348,7 @@ function validateConfig(cfg: ParseConfig): void {
if (!(cfg.maxRows >= 0)) throw new TypeError("maxRows must be a non-negative number");
if (!(cfg.maxFieldBytes > 0)) throw new TypeError("maxFieldBytes must be a positive number");
if (!(cfg.maxCellTextLength > 0)) throw new TypeError("maxCellTextLength must be a positive number");
if (!(cfg.maxColumns > 0)) throw new TypeError("maxColumns must be a positive number");
checkMaxWarnings("maxWarnings", cfg.maxWarnings);
}

Expand Down
18 changes: 15 additions & 3 deletions packages/javascript-excel/src/internal/import/pipeline.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import type { AbortSignalLike } from "../../signal";
import type { ExcelWarning } from "../../warnings";
import { DEFAULT_MAX_FIELD_BYTES } from "../csv/parse";
import { excerpt } from "../excerpt";
import { DEFAULT_LIMITS } from "../read/limits";
import { toBytes } from "../input";
import { checkMaxWarnings } from "../warning-cap";
import { DEFAULT_MAX_SCAN, detectHeader, type ImportLocale } from "./header";
Expand Down Expand Up @@ -55,8 +56,10 @@ export interface ImportDatasetOptions {
*/
maxIssues?: number | undefined;
/**
* Reader limits for xlsx. For a CSV file, `maxWarnings` caps its warnings and
* `maxCellTextLength` limits its fields (raising CSV's 1 MiB `maxFieldBytes` to match).
* Reader limits for xlsx. For a CSV file, `maxWarnings` caps its warnings,
* `maxCellTextLength` limits its fields (raising CSV's 1 MiB `maxFieldBytes` to match)
* and `maxColumns` the fields of one record. For both formats, `maxCells` also bounds
* the empty fields the dataset pads short rows with (since 2.4; docs/api.md §5.6).
*/
limits?: Partial<ReadLimits> | undefined;
signal?: AbortSignalLike | undefined;
Expand Down Expand Up @@ -204,6 +207,9 @@ export async function importDataset(input: string | BinaryInput, options: Import
if (o.maxIssues !== Number.POSITIVE_INFINITY) checkCount("maxIssues", o.maxIssues, 1);
const maxText = o.limits?.maxCellTextLength;
if (maxText !== undefined && (typeof maxText !== "number" || !(maxText > 0))) throw new TypeError("limits.maxCellTextLength must be a positive number");
// JSE-68: maxColumns also limits CSV records (read checks it for xlsx).
const maxColumns = o.limits?.maxColumns;
if (maxColumns !== undefined && (typeof maxColumns !== "number" || !(maxColumns > 0))) throw new TypeError("limits.maxColumns must be a positive number");
if (typeof o.header === "object" && o.header !== null) {
checkCount("header.rows", o.header.rows, 1);
checkCount("header.row", o.header.row, 0);
Expand Down Expand Up @@ -258,6 +264,8 @@ export async function importDataset(input: string | BinaryInput, options: Import
maxRows: cap,
maxWarnings: o.limits?.maxWarnings,
maxCellTextLength: maxText,
// Only when given: otherwise CSV's own default (1,048,576 fields), not the xlsx one.
maxColumns,
// The CSV byte limit stays at its 1 MiB default unless maxCellTextLength asks for more
// characters than 1 MiB can ever hold; then it follows (at most 3 UTF-8 bytes per code
// unit), so a field the caller allowed is not refused for its bytes. A byte cap is never
Expand Down Expand Up @@ -334,13 +342,17 @@ export async function importDataset(input: string | BinaryInput, options: Import
headerRows = Array.from({ length: header.rows }, (_, i) => start! + i);
join = header.join;
}
// JSE-68: maxCells also bounds the empty fields the dataset pads rows with, for both formats.
// Checked here, after read has checked it for xlsx, so the order of errors is as in 2.3.
const maxCells = o.limits?.maxCells;
if (maxCells !== undefined && (typeof maxCells !== "number" || !(maxCells > 0))) throw new TypeError("limits.maxCells must be a positive number");
const ds: DetailedDataset = toDatasetDetailed(sheet, {
headerRow: headerRows.length ? headerRows[0]! : false,
headerRows: Math.max(1, headerRows.length),
join,
range: o.range,
skipTotals: o.skipTotals ?? "auto",
});
}, { maxCells: maxCells ?? DEFAULT_LIMITS.maxCells });
const issueCap = new IssueCap(o.maxIssues ?? DEFAULT_MAX_ISSUES);
const issues = issueCap.issues;
const base = { header: { rows: headerRows, detected, ...(confidence ? { confidence } : {}) }, range: ds.range ?? "", totalsRowSkipped: ds.totalsSkipped };
Expand Down
1 change: 1 addition & 0 deletions packages/javascript-excel/src/internal/read/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ export interface ReaderLimits {
maxCells: number;
maxSharedStrings: number;
maxCellTextLength: number;
maxColumns: number;
maxWarnings: number;
}

Expand Down
1 change: 1 addition & 0 deletions packages/javascript-excel/src/internal/read/limits.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ export const DEFAULT_LIMITS: Readonly<Required<ReadLimits>> = Object.freeze({
maxItems: 10_000_000,
maxSharedStrings: 5_000_000,
maxCellTextLength: 1_048_576,
maxColumns: 16_384,
maxWarnings: 1000,
});

Loading