Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
94aa856
JSE-71: tests for inspect()
securedeveloper Dec 2, 2026
1363a2f
JSE-71: inspect() checks a workbook without building cells
securedeveloper Dec 2, 2026
39e324a
JSE-71: document inspect() and add a changeset
securedeveloper Dec 2, 2026
2d0ccea
JSE-71: measured memory of inspect on a 20 MiB file
securedeveloper Dec 2, 2026
974fb6a
JSE-71: heap test bounds relative to the young generation's size
securedeveloper Dec 2, 2026
0e9f5d2
JSE-71 review: tests for shared-formula memory, encodings and the DOC…
securedeveloper Dec 2, 2026
4db9ecc
JSE-71 review: lean shared-formula masters; DOCTYPE search over every…
securedeveloper Dec 2, 2026
8b24cdb
JSE-71 review: document the DOCTYPE search, the encoding check, false…
securedeveloper Dec 2, 2026
798b938
JSE-71 review 2: tests for chunked and long declarations, straddling …
securedeveloper Dec 2, 2026
9d11dc7
JSE-71 review 2: encoding from the whole declaration; reference recor…
securedeveloper Dec 2, 2026
828b855
JSE-71 review 2: document how the encoding is decided, what the guara…
securedeveloper Dec 2, 2026
8a56a91
Merge origin/main (JSE-72 package scan, CSV binary encoding) into jse-71
securedeveloper Dec 2, 2026
2ee9060
JSE-71: inspect uses the package scan's relationships; differential c…
securedeveloper Dec 2, 2026
bab1285
JSE-71 review 3: tests for the master budget, lazy shaping, strict de…
securedeveloper Dec 2, 2026
64d4f73
JSE-71 review 3: lean masters counted and shaped lazily; strict XML d…
securedeveloper Dec 2, 2026
f0ccbc8
JSE-71 review 3: document the master budget, off-heap records, waitin…
securedeveloper Dec 2, 2026
ec530f3
JSE-71 review 4: tests that a redefined si keeps nothing
securedeveloper Dec 2, 2026
b9e4bfd
JSE-71 review 4: drop a replaced master; move test-only length helper…
securedeveloper Dec 2, 2026
a5f4e14
JSE-71 review 4: docs for <?xml in CDATA, cap-forced shaping, release…
securedeveloper Dec 2, 2026
e7eef56
JSE-71 review 4: measure reachable memory in the redefinition test
securedeveloper Dec 2, 2026
dcc888a
JSE-71: time ratio test takes the best of five runs
securedeveloper Dec 2, 2026
89c96c6
JSE-71: reference records as plain arrays on the heap; retention test…
securedeveloper Dec 2, 2026
b756805
name-cost test: best of three aborted reads, like its baselines
securedeveloper Dec 2, 2026
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
5 changes: 5 additions & 0 deletions .changeset/inspect.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"javascript-excel": minor
---

New `inspect(input, { limits, signal })` in `javascript-excel/read` checks an `.xlsx`, `.xlsm`, `.xltx` or `.xltm` file part by part without building its cells, for servers and browsers that must accept or refuse an upload without reading it into the model. Under the same limits it refuses every file `read` refuses, with the same error class, code and details (zip and reader limits, encryption, CFB and other formats, `NOT_XLSX`, `XML_DTD_FORBIDDEN`, malformed XML in the parts `read` parses, every sheet to its last row), and it returns `read`'s `UNSUPPORTED_PART` warnings with their `partKinds` (VBA, macro sheets, external links, connections, OLE objects, query tables, …), the format, the worksheets with their cell counts (as `maxCells` counts them) and used ranges, and the counts of parts, inflated bytes, cells and shared strings. It also inflates every part `read` never opens (zip limits and CRC-32 apply) and searches its bytes for `<!DOCTYPE` (ASCII-compatible, UTF-16 and UTF-32 forms, whatever the part's name or content type, so a declaration inside an XML comment or an embedded file is refused too), and it refuses an XML part, including the parts `read` parses, whose byte order mark, first bytes or complete XML declaration show any encoding but UTF-8 or UTF-16, whose declaration does not follow the XMLDecl grammar, or that has a `<?xml` declaration anywhere but at its very start (`XML_MALFORMED`); so it can refuse files `read` accepts. Set `maxItems` with it: the styles table and the defined names are held, bounded by that limit. It keeps no cells, no shared strings and no more than 8 MiB of shared-formula text per sheet under any `maxCellTextLength` (a master's text waits only until a copy needs it; then a few numbers per master, and with a small limit per relative reference, all counted against `maxItems`): on a 19.8 MiB file of 3,420,000 cells its peak heap was about 30 MB, against about 410 MB for `read`, and it checks that file with the old generation limited to 32 MB. `read` is unchanged.
77 changes: 75 additions & 2 deletions docs/api.md

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions packages/javascript-excel/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,8 @@ console.log(cell?.type, cell?.value, cell?.rawText); // "number" 50.3 "50.30"

Damage the reader can recover from comes back as `warnings`. `isDataLossWarning(w)` tells the ones where data was lost (a cell skipped, rows cut, a part missing, comments or charts not read; `partKind` names the part, including ActiveX controls, embedded files, customUI, web add-ins and parts no relationship reaches, wherever they sit in the package) from informational ones; the warning cap (`limits.maxWarnings`, default 1,000) drops only informational warnings, so filtering `warnings` with it is enough to refuse a damaged file.

To accept or refuse an upload without reading it into the model, `inspect(file, { limits, signal })` checks it part by part without building cells: it refuses every file `read` refuses under the same limits, with the same error, and returns the format, the worksheets with their cell counts, and the part kinds `read` reports (`partKinds`: VBA, external links, OLE objects, …). It also inflates the parts `read` never opens, searches the bytes of every one of them for `<!DOCTYPE` (ASCII-compatible, UTF-16 and UTF-32 forms, whatever the part's name; a declaration inside an XML comment or in an embedded file is refused too), and refuses XML parts whose byte order mark, first bytes or complete declaration show an encoding other than UTF-8 or UTF-16, or whose declaration is malformed or not at the very start. Set `limits.maxItems` (for example 100,000): it bounds the styles and defined names `inspect` still holds, and the shared-formula masters and reference records it keeps. See [docs/api.md §5.2.1](https://github.com/securedeveloper/javascript-excel/blob/main/docs/api.md#521-inspect-inspect-added-in-25).

## CSV

<!-- example: examples/snippets/src/csv.ts -->
Expand Down
6 changes: 5 additions & 1 deletion packages/javascript-excel/scripts/consumer.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ const specifier = (sub) => (sub === "." ? pkg.name : `${pkg.name}/${sub.slice(2)
export const FUNCTION = Symbol("function");
const expected = {
".": { VERSION: pkg.version },
"./read": { read: FUNCTION, readSheetNames: FUNCTION, detectFormat: FUNCTION },
"./read": { read: FUNCTION, readSheetNames: FUNCTION, detectFormat: FUNCTION, inspect: FUNCTION },
"./csv": { CSV_MIME: "text/csv;charset=utf-8", parseCsv: FUNCTION, readCsv: FUNCTION, toCsv: FUNCTION, toCsvBlob: FUNCTION },
"./dom": { fromTable: FUNCTION, download: FUNCTION, DOWNLOAD_REVOKE_DELAY_MS: 40000 },
"./worker": { exposeWorker: FUNCTION, createWorkerClient: FUNCTION },
Expand Down Expand Up @@ -199,6 +199,10 @@ const full23: ReadLimits = { maxInputBytes: 1, maxEntries: 1, maxEntryBytes: 1,
const columnsMax: number = DEFAULT_READ_LIMITS.maxColumns;
const columnsLimited: ReadOptions = { limits: { maxColumns: 256 } };
void full23; void columnsMax; void columnsLimited;
import { inspect, type InspectOptions, type InspectResult, type InspectedSheet, type InspectFormat } from ${JSON.stringify(`${pkg.name}/read`)};
const iopts: InspectOptions = { limits: { maxColumns: 256, maxCells: 1_000_000 }, signal: undefined };
const checked: Promise<InspectResult> = inspect(new Uint8Array(0), iopts);
checked.then((r) => { const f: InspectFormat = r.format; const s: InspectedSheet | undefined = r.sheets[0]; const kinds: string[] = r.partKinds; const n: number = r.cells + r.parts + r.inflatedBytes + r.sharedStrings + (s?.cells ?? 0); const code: string | undefined = r.warnings[0]?.code; void f; void kinds; void n; void code; }, () => {});
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
27 changes: 24 additions & 3 deletions packages/javascript-excel/src/internal/read/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export interface ProgressInfo {
ratio: number;
}

interface TextDecoderLike {
export interface TextDecoderLike {
decode(input?: Uint8Array, options?: { stream?: boolean }): string;
}
type TextDecoderCtor = new (label?: string, options?: { fatal?: boolean }) => TextDecoderLike;
Expand Down Expand Up @@ -61,6 +61,16 @@ export class ReadContext {
}

private readonly onProgress: ((p: ProgressInfo) => void) | undefined;
/** Sees every warning before the cap applies (inspect collects UNSUPPORTED_PART with it, JSE-71). */
tap: ((w: ExcelWarning) => void) | undefined;
/**
* inspect (JSE-71): for every part parsed as XML, a sniffer that sees its
* inflated bytes (however the inflater splits them) and, from the tokenizer,
* every processing instruction whose target is `xml` in any case.
*/
sniff: ((part: string) => PartSniffer | undefined) | undefined;
/** inspect (JSE-71): sees every relationship part the package parses, with its relationships. */
relsParsed: ((part: string, rels: ReadonlyArray<{ kind: string; target: string; external: boolean; altTarget?: string | undefined; tooLong?: boolean | undefined }>) => void) | undefined;
/** Returns to the event loop about every 16 ms between chunks, so a big read does not freeze the page (JSE-24). */
private readonly pause = createYielder();

Expand All @@ -76,6 +86,7 @@ export class ReadContext {
if (where?.ref !== undefined) w.ref = where.ref;
if (where?.partKind !== undefined) w.partKind = where.partKind;
if (where?.parts !== undefined) w.parts = where.parts;
this.tap?.(w);
const kept = this.cap.add(w, (dropped) => {
const t: ExcelWarning = { code: "WARNINGS_TRUNCATED", message: `More than maxWarnings (${this.limits.maxWarnings}) warnings; later ones were dropped.`, dropped };
this.cap.warnings.push(t);
Expand Down Expand Up @@ -146,10 +157,12 @@ export class ReadContext {
*/
async parse(entry: ZipEntryInfo, handler: XmlHandler, onChunk?: (bytes: number) => void): Promise<void> {
this.consumed.add(entry.name);
const tok = new XmlTokenizer(handler, this.limits.maxXmlDepth, this.limits.maxXmlTokenLength);
const sniffer = this.sniff?.(entry.name);
const tok = new XmlTokenizer(handler, this.limits.maxXmlDepth, this.limits.maxXmlTokenLength, sniffer && ((pi) => sniffer.pi(pi)));
let decoder: TextDecoderLike | undefined;
try {
for await (const chunk of this.zip.stream(entry, this.signal)) {
sniffer?.feed(chunk);
let bytes = chunk;
if (!decoder) {
decoder = newDecoder(chunk);
Expand Down Expand Up @@ -181,12 +194,20 @@ export class ReadContext {
}
if (decoder) tok.feed(decoder.decode());
tok.end();
sniffer?.end();
} catch (err) {
throw withPart(err, entry.name);
}
}
}

/** What inspect (JSE-71) sees of a part read parses: every inflated chunk in order, every `<?xml` processing instruction, and the end. */
export interface PartSniffer {
feed(chunk: Uint8Array): void;
pi(text: string): void;
end(): void;
}

export function withPart(err: unknown, part: string): unknown {
if (err instanceof FormatError && (err.code === "XML_MALFORMED" || err.code === "XML_DTD_FORBIDDEN") && !err.details?.["part"]) {
return new FormatError(err.code, `${excerpt(part)}: ${err.message}`, { details: { ...err.details, part }, cause: err });
Expand All @@ -198,7 +219,7 @@ export function withPart(err: unknown, part: string): unknown {
return err;
}

function newDecoder(first: Uint8Array): TextDecoderLike {
export function newDecoder(first: Uint8Array): TextDecoderLike {
const Ctor = (globalThis as unknown as { TextDecoder: TextDecoderCtor }).TextDecoder;
// OOXML parts are UTF-8 or UTF-16 (with a BOM).
if (first[0] === 0xff && first[1] === 0xfe) return new Ctor("utf-16le");
Expand Down
223 changes: 222 additions & 1 deletion packages/javascript-excel/src/internal/read/formula.ts
Original file line number Diff line number Diff line change
Expand Up @@ -221,7 +221,7 @@ function refText(r: Ref, dRow: number, dCol: number): string {
}

/** Whether every relative reference of `c` stays on the sheet when shifted by (dRow, dCol). Constant time. */
export function canShift(c: CompiledFormula, dRow: number, dCol: number): boolean {
export function canShift(c: Pick<CompiledFormula, "rowMin" | "rowMax" | "colMin" | "colMax">, dRow: number, dCol: number): boolean {
if (dRow === 0 && dCol === 0) return true;
if (c.rowMin !== Infinity && (c.rowMin + dRow < 1 || c.rowMax + dRow > MAX_ROW)) return false;
if (c.colMin !== Infinity && (c.colMin + dCol < 1 || c.colMax + dCol > MAX_COL)) return false;
Expand Down Expand Up @@ -250,6 +250,213 @@ export function shiftCompiled(c: CompiledFormula, dRow: number, dCol: number, ma
return out;
}

/** The length of a copy shifted by (dRow, dCol), from formulaShape's `fixed` and partsOf's records; the offset must pass `canShift`. */
export function shiftedLength(fixed: number, parts: ArrayLike<number>, dRow: number, dCol: number): number {
let n = fixed;
for (let i = 0; i < parts.length; i += 3) {
const v = parts[i + 1]! + (parts[i] ? dRow : dCol);
n += parts[i + 2]! * (parts[i] ? digitCount(v) : v <= 26 ? 1 : v <= 702 ? 2 : 3);
}
return n;
}

function digitCount(v: number): number {
let d = 1;
while (v >= 10) {
v = Math.floor(v / 10);
d++;
}
return d;
}

/** What a lean shared-formula master keeps (JSE-71): see formulaShape. */
export interface FormulaShape {
rowMin: number;
rowMax: number;
colMin: number;
colMax: number;
/** The shortest and longest text a shifted copy can have: a relative column takes 1 to 3 letters, a relative row 1 to 7 digits. */
min: number;
max: number;
/** The copy's characters that never change; with partsOf(keys), its exact length per offset (shiftedLength). */
fixed: number;
/** Relative parts as keys (value * 2 + isRow), with collectParts; else empty. */
keys: number[];
}

/**
* One pass over a master's text (JSE-71), allocating nothing per reference:
* the relative bounds as compileFormula gives them, the range of a copy's
* length and the characters that never change (the tests compute both from
* the compiled formula too); with `collectParts`, the relative parts. It walks the text as
* compileFormula does and recognises references as parseRef does (the tests
* compare the two on seeded formulas), so a copy's text is the original's
* with each reference re-printed as refText prints it.
*/
export function formulaShape(formula: string, collectParts: boolean): FormulaShape {
let rowMin = Infinity;
let rowMax = -Infinity;
let colMin = Infinity;
let colMax = -Infinity;
let fixed = formula.length;
let relCols = 0;
let relRows = 0;
const keys: number[] = [];
const col = (anchored: boolean, v: number): void => {
if (anchored) fixed += 1 + (v <= 26 ? 1 : v <= 702 ? 2 : 3);
else {
relCols++;
if (v < colMin) colMin = v;
if (v > colMax) colMax = v;
if (collectParts) keys.push(v * 2);
}
};
const row = (anchored: boolean, v: number): void => {
if (anchored) fixed += 1 + digitCount(v);
else {
relRows++;
if (v < rowMin) rowMin = v;
if (v > rowMax) rowMax = v;
if (collectParts) keys.push(v * 2 + 1);
}
};
const n = formula.length;
let i = 0;
while (i < n) {
const code = formula.charCodeAt(i);
if (code === 34 || code === 39) {
let j = i + 1;
for (; j < n; j++) {
if (formula.charCodeAt(j) === code) {
if (formula.charCodeAt(j + 1) === code) j++;
else break;
}
}
i = j + 1;
continue;
}
if (code === 91) {
let depth = 0;
let j = i;
for (; j < n; j++) {
const c = formula.charCodeAt(j);
if (c === 91) depth++;
else if (c === 93 && --depth === 0) break;
}
i = j + 1;
continue;
}
const prev = i > 0 ? formula.charCodeAt(i - 1) : -1;
if ((code === 36 || isAlnumCode(code)) && !isWordCode(prev) && prev !== 36) {
const end = refAt(formula, i);
if (end >= 0) {
fixed -= end - i;
const r = REF;
if (r.kind === COLS_REF) {
col(r.aAnchored, r.a);
col(r.bAnchored, r.b);
fixed += 1;
} else if (r.kind === ROWS_REF) {
row(r.aAnchored, r.a);
row(r.bAnchored, r.b);
fixed += 1;
} else {
col(r.aAnchored, r.a);
row(r.bAnchored, r.b);
}
i = end;
continue;
}
let j = i + 1;
while (j < n && isWordCode(formula.charCodeAt(j))) j++;
i = j;
continue;
}
i++;
}
return { rowMin, rowMax, colMin, colMax, min: fixed + relCols + relRows, max: fixed + 3 * relCols + 7 * relRows, fixed, keys };
}

/** refAt's result, reused (formulaShape reads it before the next call). */
const REF = { kind: CELL_REF as number, aAnchored: false, a: 0, bAnchored: false, b: 0 };

/** parseRef without allocating: the reference at `i` into REF and the index after it, or -1. */
function refAt(f: string, i: number): number {
const n = f.length;
const aAnchored = f.charCodeAt(i) === 36;
const p = i + (aAnchored ? 1 : 0);
let la = 0;
while (la < 3 && p + la < n && isLetterCode(f.charCodeAt(p + la))) la++;
let da = 0;
if (la === 0) while (da < 7 && p + da < n && isDigitCode(f.charCodeAt(p + da))) da++;
const first = la || da;
if (first > 0 && f.charCodeAt(p + first) === 58) {
const q = p + first + 1;
const bAnchored = q < n && f.charCodeAt(q) === 36;
const r = q + (bAnchored ? 1 : 0);
let second = 0;
if (la) while (second < 3 && r + second < n && isLetterCode(f.charCodeAt(r + second))) second++;
else while (second < 7 && r + second < n && isDigitCode(f.charCodeAt(r + second))) second++;
if (second > 0 && isEnd(f, r + second)) {
if (la) {
const a = colAt(f, p, la);
const b = colAt(f, r, second);
if (a > MAX_COL || b > MAX_COL) return -1;
return setRef(COLS_REF, aAnchored, a, bAnchored, b, r + second);
}
return setRef(ROWS_REF, aAnchored, digitsAt(f, p, da), bAnchored, digitsAt(f, r, second), r + second);
}
}
if (la > 0) {
const q = p + la;
const bAnchored = f.charCodeAt(q) === 36;
const r = q + (bAnchored ? 1 : 0);
let digits = 0;
while (digits < 7 && r + digits < n && isDigitCode(f.charCodeAt(r + digits))) digits++;
if (digits > 0 && isEnd(f, r + digits)) {
const c = colAt(f, p, la);
if (c > MAX_COL) return -1;
return setRef(CELL_REF, aAnchored, c, bAnchored, digitsAt(f, r, digits), r + digits);
}
}
return -1;
}

function setRef(kind: number, aAnchored: boolean, a: number, bAnchored: boolean, b: number, end: number): number {
REF.kind = kind;
REF.aAnchored = aAnchored;
REF.a = a;
REF.bAnchored = bAnchored;
REF.b = b;
return end;
}

/** formulaShape's keys as records: triples (isRow, value, count), one per distinct relative part. */
/** partsOf's sort buffer, reused so that sorting allocates nothing. */
let sortScratch = new Int32Array(256);

export function partsOf(list: number[]): number[] {
if (sortScratch.length < list.length) sortScratch = new Int32Array(Math.max(list.length, 2 * sortScratch.length));
const keys = sortScratch.subarray(0, list.length);
keys.set(list);
keys.sort();
let distinct = 0;
for (let i = 0; i < keys.length; i++) if (i === 0 || keys[i] !== keys[i - 1]) distinct++;
// A plain array: on the JavaScript heap (a worker's heap cap counts it), and smaller than a typed array for a few records.
const out: number[] = new Array<number>(distinct * 3).fill(0);
let o = -3;
for (let i = 0; i < keys.length; i++) {
const k = keys[i]!;
if (i === 0 || k !== keys[i - 1]) {
o += 3;
out[o] = k & 1;
out[o + 1] = Math.floor(k / 2);
}
out[o + 2] = out[o + 2]! + 1;
}
return out;
}

/** `formula` shifted by (dRow, dCol), or undefined when a reference would leave the sheet. */
export function shiftFormula(formula: string, dRow: number, dCol: number): string | undefined {
if (dRow === 0 && dCol === 0) return formula;
Expand All @@ -258,6 +465,20 @@ export function shiftFormula(formula: string, dRow: number, dCol: number): strin
}

/** Whether a reference may end before `end`: no word character, `(`, `!` or `$` follows. */
/** colNumber(f.slice(at, at + n)) without the slice; `n` ASCII letters. */
function colAt(f: string, at: number, n: number): number {
let v = 0;
for (let k = 0; k < n; k++) v = v * 26 + ((f.charCodeAt(at + k) & ~32) - 64);
return v;
}

/** Number(f.slice(at, at + n)) without the slice; `n` (at most 7) ASCII digits. */
function digitsAt(f: string, at: number, n: number): number {
let v = 0;
for (let k = 0; k < n; k++) v = v * 10 + (f.charCodeAt(at + k) - 48);
return v;
}

function isEnd(f: string, end: number): boolean {
if (end >= f.length) return true;
const c = f.charCodeAt(end);
Expand Down
Loading