javascript-excel 2.1.0 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -13,10 +13,27 @@ const DEFAULT_LIMITS = Object.freeze({
13
13
  maxRatio: 1e3,
14
14
  maxXmlDepth: 64,
15
15
  maxXmlTokenLength: 16777216,
16
+ maxSheets: 1e4,
16
17
  maxCells: 1e7,
18
+ maxItems: 1e7,
17
19
  maxSharedStrings: 5e6,
20
+ maxCellTextLength: 1048576,
18
21
  maxWarnings: 1e3
19
22
  });
23
+ function head(s) {
24
+ let end = 64;
25
+ const c = s.charCodeAt(end - 1);
26
+ if (c >= 55296 && c <= 56319) end--;
27
+ return s.slice(0, end);
28
+ }
29
+ /** `s` itself when short; else its start, `…` and its length: `abc… (16000000 characters)`. */
30
+ function excerpt(s) {
31
+ return s.length <= 128 ? s : `${head(s)}… (${s.length} characters)`;
32
+ }
33
+ /** `JSON.stringify(s)` when short; else the quoted start, `…` and its length: `"abc"… (16000000 characters)`. */
34
+ function quoted(s) {
35
+ return s.length <= 128 ? JSON.stringify(s) : `${JSON.stringify(head(s))}… (${s.length} characters)`;
36
+ }
20
37
  // src/internal/zip/read.ts
21
38
  /**
22
39
  * Zip container reader (docs/api.md §6, §8). Internal.
@@ -137,6 +154,8 @@ function findEocd(bytes) {
137
154
  }
138
155
  throw invalid("Not a zip file: no end-of-central-directory record.");
139
156
  }
157
+ /** Bytes of a stored entry checksummed between two abort checks. */
158
+ const STORED_CRC_STEP = 1048576;
140
159
  /** Parses and validates the archive layout. Does not inflate anything. */
141
160
  function openZip(bytes, options = {}) {
142
161
  const limits = {
@@ -217,15 +236,15 @@ function openZip(bytes, options = {}) {
217
236
  }
218
237
  if (diskStart !== 0) throw invalid("Multi-disk zip archives are not supported.");
219
238
  const name = decodeName(rawName, flags, extra);
220
- if (flags & 65 || method === METHOD_AES) throw new require_errors.FormatError("ZIP_ENCRYPTED", `Entry ${name} is encrypted.`, { details: { entry: name } });
221
- if (method !== 0 && method !== 8) throw new require_errors.FormatError("ZIP_UNSUPPORTED_METHOD", `Entry ${name} uses compression method ${method}.`, { details: {
239
+ if (flags & 65 || method === METHOD_AES) throw new require_errors.FormatError("ZIP_ENCRYPTED", `Entry ${excerpt(name)} is encrypted.`, { details: { entry: name } });
240
+ if (method !== 0 && method !== 8) throw new require_errors.FormatError("ZIP_UNSUPPORTED_METHOD", `Entry ${excerpt(name)} uses compression method ${method}.`, { details: {
222
241
  entry: name,
223
242
  method
224
243
  } });
225
- if (method === 0 && compressedSize !== size) throw invalid(`Stored entry ${name} has mismatched sizes.`);
226
- if (byName.has(name)) throw invalid(`Duplicate entry name: ${name}`, { entry: name });
244
+ if (method === 0 && compressedSize !== size) throw invalid(`Stored entry ${excerpt(name)} has mismatched sizes.`);
245
+ if (byName.has(name)) throw invalid(`Duplicate entry name: ${excerpt(name)}`, { entry: name });
227
246
  const l = new Cursor(bytes, localOffset);
228
- if (localOffset + 30 > cdOffset || l.u32() !== SIG_LOCAL) throw invalid(`Bad local header for ${name}.`, { entry: name });
247
+ if (localOffset + 30 > cdOffset || l.u32() !== SIG_LOCAL) throw invalid(`Bad local header for ${excerpt(name)}.`, { entry: name });
229
248
  l.u16();
230
249
  const lFlags = l.u16();
231
250
  const lMethod = l.u16();
@@ -240,10 +259,10 @@ function openZip(bytes, options = {}) {
240
259
  l.take(lExtraLength);
241
260
  let agrees = lNameLength === nameLength && lName.every((b, k) => b === rawName[k]) && lMethod === method && (lFlags & FLAG_ENCRYPTED) === 0;
242
261
  if (agrees && !(lFlags & FLAG_DATA_DESCRIPTOR)) agrees = lCrc === crc && (lCompressed === compressedSize || lCompressed === 4294967295) && (lSize === size || lSize === 4294967295);
243
- if (!agrees) throw invalid(`Local header disagrees with the central directory for ${name}.`, { entry: name });
262
+ if (!agrees) throw invalid(`Local header disagrees with the central directory for ${excerpt(name)}.`, { entry: name });
244
263
  const dataOffset = l.pos;
245
264
  const dataEnd = dataOffset + compressedSize;
246
- if (dataEnd > cdOffset) throw invalid(`Data of ${name} runs into the central directory.`, { entry: name });
265
+ if (dataEnd > cdOffset) throw invalid(`Data of ${excerpt(name)} runs into the central directory.`, { entry: name });
247
266
  spans.push({
248
267
  start: localOffset,
249
268
  end: dataEnd,
@@ -263,7 +282,7 @@ function openZip(bytes, options = {}) {
263
282
  byName.set(name, info);
264
283
  }
265
284
  spans.sort((a, b) => a.start - b.start);
266
- for (let i = 1; i < spans.length; i++) if (spans[i].start < spans[i - 1].end) throw invalid(`Entries ${spans[i - 1].name} and ${spans[i].name} overlap.`);
285
+ for (let i = 1; i < spans.length; i++) if (spans[i].start < spans[i - 1].end) throw invalid(`Entries ${excerpt(spans[i - 1].name)} and ${excerpt(spans[i].name)} overlap.`);
267
286
  let totalBytesRead = 0;
268
287
  const resolve = (entry) => {
269
288
  const info = typeof entry === "string" ? byName.get(entry) : entry;
@@ -277,13 +296,16 @@ function openZip(bytes, options = {}) {
277
296
  async function* stream(entry, signal) {
278
297
  const info = resolve(entry);
279
298
  require_dos_time.throwIfAborted(signal);
280
- if (info.size > limits.maxEntryBytes) throw limitError("maxEntryBytes", info.size, limits.maxEntryBytes, `Entry ${info.name}`);
299
+ if (info.size > limits.maxEntryBytes) throw limitError("maxEntryBytes", info.size, limits.maxEntryBytes, `Entry ${excerpt(info.name)}`);
281
300
  const data = bytes.subarray(info.dataOffset, info.dataOffset + info.compressedSize);
282
301
  let crc = 0;
283
302
  let produced = 0;
284
303
  if (info.method === 0) {
285
304
  countTotal(data.length);
286
- crc = require_dos_time.crc32(data);
305
+ for (let at = 0; at < data.length; at += STORED_CRC_STEP) {
306
+ if (at > 0) require_dos_time.throwIfAborted(signal);
307
+ crc = require_dos_time.crc32(data.subarray(at, at + STORED_CRC_STEP), crc);
308
+ }
287
309
  produced = data.length;
288
310
  if (crc !== info.crc32) throw crcMismatch(info);
289
311
  yield data;
@@ -295,12 +317,12 @@ function openZip(bytes, options = {}) {
295
317
  }, signal);
296
318
  for await (const chunk of chunks) {
297
319
  produced += chunk.length;
298
- if (produced > info.size) throw invalid(`Entry ${info.name} is larger than declared.`, { entry: info.name });
320
+ if (produced > info.size) throw invalid(`Entry ${excerpt(info.name)} is larger than declared.`, { entry: info.name });
299
321
  countTotal(chunk.length);
300
322
  crc = require_dos_time.crc32(chunk, crc);
301
323
  yield chunk;
302
324
  }
303
- if (produced !== info.size) throw invalid(`Entry ${info.name} is smaller than declared.`, { entry: info.name });
325
+ if (produced !== info.size) throw invalid(`Entry ${excerpt(info.name)} is smaller than declared.`, { entry: info.name });
304
326
  if (crc !== info.crc32) throw crcMismatch(info);
305
327
  }
306
328
  return {
@@ -318,7 +340,7 @@ function openZip(bytes, options = {}) {
318
340
  };
319
341
  }
320
342
  function crcMismatch(info) {
321
- return new require_errors.FormatError("ZIP_CRC_MISMATCH", `CRC-32 mismatch in ${info.name}.`, { details: { entry: info.name } });
343
+ return new require_errors.FormatError("ZIP_CRC_MISMATCH", `CRC-32 mismatch in ${excerpt(info.name)}.`, { details: { entry: info.name } });
322
344
  }
323
345
  // src/internal/read/xml-reader.ts
324
346
  /**
@@ -459,9 +481,9 @@ var XmlTokenizer = class {
459
481
  end() {
460
482
  if (this.wait !== Wait.None) this.unsuspend();
461
483
  this.pump(true);
462
- if (this.skipTag !== void 0) throw malformed(`Element <${this.skipTag.slice(2)}> is not closed.`);
484
+ if (this.skipTag !== void 0) throw malformed(`Element <${excerpt(this.skipTag.slice(2))}> is not closed.`);
463
485
  if (this.buf.trim() !== "") throw malformed("Unexpected end of XML data.");
464
- if (this.stack.length > 0) throw malformed(`Element <${this.stack.at(-1)}> is not closed.`);
486
+ if (this.stack.length > 0) throw malformed(`Element <${excerpt(this.stack.at(-1))}> is not closed.`);
465
487
  if (!this.rootSeen) throw malformed("XML part has no root element.");
466
488
  }
467
489
  /**
@@ -533,7 +555,7 @@ var XmlTokenizer = class {
533
555
  const tag = this.skipTag;
534
556
  const end = this.skipTo(buf, i);
535
557
  if (end === -1) {
536
- if (final) throw malformed(`Element <${tag.slice(2)}> is not closed.`);
558
+ if (final) throw malformed(`Element <${excerpt(tag.slice(2))}> is not closed.`);
537
559
  i = len;
538
560
  break;
539
561
  }
@@ -600,7 +622,7 @@ var XmlTokenizer = class {
600
622
  this.checkToken(e + 1 - i);
601
623
  const qname = buf.slice(i + 2, e).trim();
602
624
  const open = this.stack.pop();
603
- if (open === void 0 || open !== qname) throw malformed(open === void 0 ? `Unexpected end tag </${qname}>.` : `End tag </${qname}> does not match <${open}>.`);
625
+ if (open === void 0 || open !== qname) throw malformed(open === void 0 ? `Unexpected end tag </${excerpt(qname)}>.` : `End tag </${excerpt(qname)}> does not match <${excerpt(open)}>.`);
604
626
  if (this.stack.length === 0) this.rootClosed = true;
605
627
  this.handler.close(localName(qname));
606
628
  i = e + 1;
@@ -684,15 +706,15 @@ var XmlTokenizer = class {
684
706
  while (p < stop && buf.charCodeAt(p) !== 61 && !isSpace(buf.charCodeAt(p))) p++;
685
707
  const aname = buf.slice(nameStart, p);
686
708
  while (p < stop && isSpace(buf.charCodeAt(p))) p++;
687
- if (buf.charCodeAt(p) !== 61 || aname.length === 0) throw malformed(`Malformed attribute in <${qname}>.`);
709
+ if (buf.charCodeAt(p) !== 61 || aname.length === 0) throw malformed(`Malformed attribute in <${excerpt(qname)}>.`);
688
710
  p++;
689
711
  while (p < stop && isSpace(buf.charCodeAt(p))) p++;
690
712
  const q = buf.charCodeAt(p);
691
- if (q !== 34 && q !== 39) throw malformed(`Unquoted attribute value in <${qname}>.`);
713
+ if (q !== 34 && q !== 39) throw malformed(`Unquoted attribute value in <${excerpt(qname)}>.`);
692
714
  const close = buf.indexOf(q === 34 ? "\"" : "'", p + 1);
693
- if (close === -1 || close >= stop) throw malformed(`Unterminated attribute value in <${qname}>.`);
715
+ if (close === -1 || close >= stop) throw malformed(`Unterminated attribute value in <${excerpt(qname)}>.`);
694
716
  const raw = buf.slice(p + 1, close);
695
- if (raw.indexOf("<") !== -1) throw malformed(`'<' in an attribute value of <${qname}>.`);
717
+ if (raw.indexOf("<") !== -1) throw malformed(`'<' in an attribute value of <${excerpt(qname)}>.`);
696
718
  items.push(aname, normaliseAttr(raw));
697
719
  p = close + 1;
698
720
  }
@@ -791,6 +813,8 @@ function isXmlChar(cp) {
791
813
  * Per-read state shared by the part parsers: the zip, the limits, the
792
814
  * warning collector, the abort signal and progress reporting. Internal.
793
815
  */
816
+ /** Bytes of one part tokenized between two abort checks (stored entries arrive whole). */
817
+ const PARSE_SLICE = 262144;
794
818
  var ReadContext = class {
795
819
  zip;
796
820
  limits;
@@ -801,6 +825,8 @@ var ReadContext = class {
801
825
  /** Names of the parts read so far (for keeping the others, see InternalReadOptions). */
802
826
  consumed = /* @__PURE__ */ new Set();
803
827
  cells = 0;
828
+ /** Items other than cells built so far (maxItems). */
829
+ items = 0;
804
830
  constructor(zip, limits, signal, onWarning, onProgress) {
805
831
  this.zip = zip;
806
832
  this.limits = limits;
@@ -845,9 +871,41 @@ var ReadContext = class {
845
871
  max: this.limits.maxCells
846
872
  } });
847
873
  }
874
+ /**
875
+ * Counts `n` items the reader builds besides cells (column and row property
876
+ * objects, merges, hyperlinks, selections, defined names, style records,
877
+ * custom properties, rich-text runs after the first of a string) against
878
+ * maxItems, before they are built (JSE-52). A workbook can list one small
879
+ * part under many sheet entries, or one `<col>` can stand for 16,384 column
880
+ * objects, so these need a budget; maxCells keeps counting cells only, as in
881
+ * 2.1. `details.value` is `max + 1` ("more than max"), also when a batch
882
+ * (a sheet's column objects) jumps past the limit.
883
+ */
884
+ charge(n) {
885
+ this.items += n;
886
+ if (this.items > this.limits.maxItems) {
887
+ const max = this.limits.maxItems;
888
+ throw new require_errors.LimitError("LIMIT_EXCEEDED", `The workbook builds more than maxItems (${max}) items besides cells (column and row properties, merges, hyperlinks, defined names, styles, rich-text runs).`, { details: {
889
+ limit: "maxItems",
890
+ value: max + 1,
891
+ max
892
+ } });
893
+ }
894
+ }
848
895
  checkAbort() {
849
896
  require_dos_time.throwIfAborted(this.signal);
850
897
  }
898
+ /**
899
+ * For loops over workbook-level lists (sheet entries, defined names): consults
900
+ * the signal and, once the yield budget has passed, returns a promise to await
901
+ * before the next item (JSE-52). Returns undefined otherwise, so a loop pays
902
+ * no microtask per item.
903
+ */
904
+ step() {
905
+ this.checkAbort();
906
+ const pause = this.pause();
907
+ return pause ? pause.then(() => this.checkAbort()) : void 0;
908
+ }
851
909
  progress(p) {
852
910
  this.onProgress?.(p);
853
911
  }
@@ -867,10 +925,24 @@ var ReadContext = class {
867
925
  let decoder;
868
926
  try {
869
927
  for await (const chunk of this.zip.stream(entry, this.signal)) {
928
+ let bytes = chunk;
870
929
  if (!decoder) {
871
930
  decoder = newDecoder(chunk);
872
- tok.feed(decoder.decode(stripBom(chunk), { stream: true }));
873
- } else tok.feed(decoder.decode(chunk, { stream: true }));
931
+ bytes = stripBom(chunk);
932
+ }
933
+ let at = 0;
934
+ for (;;) {
935
+ const piece = bytes.length - at > 262144 ? bytes.subarray(at, at + PARSE_SLICE) : at === 0 ? bytes : bytes.subarray(at);
936
+ at += piece.length;
937
+ tok.feed(decoder.decode(piece, { stream: true }));
938
+ if (at >= bytes.length) break;
939
+ this.checkAbort();
940
+ const pause = this.pause();
941
+ if (pause) {
942
+ await pause;
943
+ this.checkAbort();
944
+ }
945
+ }
874
946
  onChunk?.(chunk.length);
875
947
  this.checkAbort();
876
948
  const pause = this.pause();
@@ -887,7 +959,7 @@ var ReadContext = class {
887
959
  }
888
960
  };
889
961
  function withPart(err, part) {
890
- if (err instanceof require_errors.FormatError && (err.code === "XML_MALFORMED" || err.code === "XML_DTD_FORBIDDEN") && !err.details?.["part"]) return new require_errors.FormatError(err.code, `${part}: ${err.message}`, {
962
+ if (err instanceof require_errors.FormatError && (err.code === "XML_MALFORMED" || err.code === "XML_DTD_FORBIDDEN") && !err.details?.["part"]) return new require_errors.FormatError(err.code, `${excerpt(part)}: ${err.message}`, {
891
963
  details: {
892
964
  ...err.details,
893
965
  part
@@ -895,7 +967,7 @@ function withPart(err, part) {
895
967
  cause: err
896
968
  });
897
969
  const limit = err instanceof require_errors.LimitError ? err.details?.["limit"] : void 0;
898
- if (err instanceof require_errors.LimitError && (limit === "maxXmlDepth" || limit === "maxXmlTokenLength") && !err.details?.["part"]) return new require_errors.LimitError(err.code, `${part}: ${err.message}`, {
970
+ if (err instanceof require_errors.LimitError && (limit === "maxXmlDepth" || limit === "maxXmlTokenLength" || limit === "maxCellTextLength") && !err.details?.["part"]) return new require_errors.LimitError(err.code, `${excerpt(part)}: ${err.message}`, {
899
971
  details: {
900
972
  ...err.details,
901
973
  part
@@ -1024,7 +1096,7 @@ var Package = class {
1024
1096
  for (const e of ctx.zip.entries) {
1025
1097
  if (e.name.endsWith("/")) continue;
1026
1098
  const key = e.name.toLowerCase();
1027
- if (this.parts.has(key)) throw new require_errors.FormatError("ZIP_INVALID", `Part names ${this.parts.get(key).name} and ${e.name} differ only in case.`, { details: { entry: e.name } });
1099
+ if (this.parts.has(key)) throw new require_errors.FormatError("ZIP_INVALID", `Part names ${excerpt(this.parts.get(key).name)} and ${excerpt(e.name)} differ only in case.`, { details: { entry: e.name } });
1028
1100
  this.parts.set(key, e);
1029
1101
  }
1030
1102
  }
@@ -1419,6 +1491,7 @@ var FontBuilder = class {
1419
1491
  /** Streaming handler state for styles.xml. */
1420
1492
  var StylesParser = class {
1421
1493
  full;
1494
+ charge;
1422
1495
  numFmts = /* @__PURE__ */ new Map();
1423
1496
  fonts = [];
1424
1497
  fills = [];
@@ -1431,8 +1504,14 @@ var StylesParser = class {
1431
1504
  fillColorTarget;
1432
1505
  border;
1433
1506
  xf;
1434
- constructor(full) {
1507
+ /**
1508
+ * @param charge Counts each record kept (number format, xf, font, fill, border,
1509
+ * gradient stop, indexed colour) against the read's maxItems budget (JSE-52). With `styles: false`
1510
+ * fonts, fills, gradient stops and borders are not kept and not counted.
1511
+ */
1512
+ constructor(full, charge = () => {}) {
1435
1513
  this.full = full;
1514
+ this.charge = charge;
1436
1515
  }
1437
1516
  open(name, a, empty) {
1438
1517
  switch (name) {
@@ -1455,7 +1534,10 @@ var StylesParser = class {
1455
1534
  if (sec === "numFmts" && name === "numFmt") {
1456
1535
  const id = int(a.get("numFmtId"));
1457
1536
  const code = a.get("formatCode");
1458
- if (id !== void 0 && code !== void 0) this.numFmts.set(id, code);
1537
+ if (id !== void 0 && code !== void 0) {
1538
+ this.charge(1);
1539
+ this.numFmts.set(id, code);
1540
+ }
1459
1541
  return;
1460
1542
  }
1461
1543
  if (sec === "cellXfs" && name === "xf") {
@@ -1465,13 +1547,17 @@ var StylesParser = class {
1465
1547
  fillId: int(a.get("fillId")) ?? 0,
1466
1548
  borderId: int(a.get("borderId")) ?? 0
1467
1549
  };
1550
+ this.charge(1);
1468
1551
  this.xfs.push(this.xf);
1469
1552
  if (empty) this.xf = void 0;
1470
1553
  return;
1471
1554
  }
1472
1555
  if (sec === "indexedColors" && name === "rgbColor") {
1473
1556
  const rgb = a.get("rgb");
1474
- if (rgb && /^[0-9A-Fa-f]{8}$/.test(rgb)) (this.indexed ??= []).push(rgb.toUpperCase());
1557
+ if (rgb && /^[0-9A-Fa-f]{8}$/.test(rgb)) {
1558
+ this.charge(1);
1559
+ (this.indexed ??= []).push(rgb.toUpperCase());
1560
+ }
1475
1561
  return;
1476
1562
  }
1477
1563
  if (!this.full) return;
@@ -1527,6 +1613,7 @@ var StylesParser = class {
1527
1613
  if (c) this.fill.pattern[name] = c;
1528
1614
  } else if (name === "color" && this.fillColorTarget === "stop" && this.fill?.gradient) {
1529
1615
  const c = color(a);
1616
+ if (c) this.charge(1);
1530
1617
  if (c) this.fill.gradient.stops.push({
1531
1618
  position: this.fill.stop ?? 0,
1532
1619
  color: c
@@ -1600,7 +1687,10 @@ var StylesParser = class {
1600
1687
  }
1601
1688
  text() {}
1602
1689
  endFont() {
1603
- if (this.font) this.fonts.push(this.font.font);
1690
+ if (this.font) {
1691
+ this.charge(1);
1692
+ this.fonts.push(this.font.font);
1693
+ }
1604
1694
  this.font = void 0;
1605
1695
  }
1606
1696
  endFill() {
@@ -1608,12 +1698,14 @@ var StylesParser = class {
1608
1698
  let out;
1609
1699
  if (f?.gradient) out = f.gradient;
1610
1700
  else if (f?.pattern && f.pattern.pattern !== "none") out = f.pattern;
1701
+ if (this.full) this.charge(1);
1611
1702
  this.fills.push(out);
1612
1703
  this.fill = void 0;
1613
1704
  }
1614
1705
  endBorder() {
1615
1706
  if (this.border) {
1616
1707
  const b = this.border.b;
1708
+ this.charge(1);
1617
1709
  this.borders.push(Object.keys(b).length ? b : void 0);
1618
1710
  }
1619
1711
  this.border = void 0;
@@ -1709,10 +1801,105 @@ function decodeXstring(s) {
1709
1801
  return s.replace(/_x([0-9A-Fa-f]{4})_/g, (_, hex) => String.fromCharCode(parseInt(hex, 16)));
1710
1802
  }
1711
1803
  /**
1804
+ * The length a text will have once `decodeXstring` has run on it, counted
1805
+ * chunk by chunk as the text streams in (JSE-58), so a cell's text can be
1806
+ * refused before it is held whole. `committed` never exceeds the final
1807
+ * length: up to six trailing characters that may start an escape are held
1808
+ * back until the next chunk or `end()`. With `decode` false the text is
1809
+ * counted as it is (`<v>` of number, date, error and boolean cells).
1810
+ */
1811
+ var XstringLength = class {
1812
+ decode;
1813
+ /** Characters known so far. */
1814
+ committed = 0;
1815
+ tail = "";
1816
+ constructor(decode = true) {
1817
+ this.decode = decode;
1818
+ }
1819
+ add(chunk) {
1820
+ if (!this.decode) {
1821
+ this.committed += chunk.length;
1822
+ return;
1823
+ }
1824
+ const s = this.tail.length ? this.tail + chunk : chunk;
1825
+ const n = s.length;
1826
+ let i = 0;
1827
+ let escapes = 0;
1828
+ for (let j = s.indexOf("_x"); j !== -1 && j + 7 <= n; j = s.indexOf("_x", i)) if (isHex(s.charCodeAt(j + 2)) && isHex(s.charCodeAt(j + 3)) && isHex(s.charCodeAt(j + 4)) && isHex(s.charCodeAt(j + 5)) && s.charCodeAt(j + 6) === 95) {
1829
+ escapes++;
1830
+ i = j + 7;
1831
+ } else i = j + 1;
1832
+ const cut = Math.max(i, n - 6);
1833
+ this.committed += cut - 6 * escapes;
1834
+ this.tail = cut < n ? s.slice(cut) : "";
1835
+ }
1836
+ /** Settles the held-back characters and returns the final length. */
1837
+ end() {
1838
+ this.committed += this.tail.length;
1839
+ this.tail = "";
1840
+ return this.committed;
1841
+ }
1842
+ };
1843
+ function isHex(c) {
1844
+ return c >= 48 && c <= 57 || c >= 65 && c <= 70 || c >= 97 && c <= 102;
1845
+ }
1846
+ /** The LimitError for a cell's text over maxCellTextLength; `value` is max + 1, "more than max" (JSE-58). */
1847
+ function cellTextTooLong(max, details = {}) {
1848
+ const where = typeof details["ref"] === "string" && details["ref"] !== "" ? `Cell ${details["ref"]}: its` : "A cell's";
1849
+ return new require_errors.LimitError("LIMIT_EXCEEDED", `${where} text is longer than maxCellTextLength (${max}) characters.`, { details: {
1850
+ limit: "maxCellTextLength",
1851
+ value: max + 1,
1852
+ max,
1853
+ ...details
1854
+ } });
1855
+ }
1856
+ /**
1857
+ * Counts text the reader keeps outside cells (header and footer text, a
1858
+ * defined name's formula, a document property's value) against
1859
+ * maxCellTextLength as it streams in, so it is refused before it is held
1860
+ * whole (JSE-58 review). This text is kept as written, so it is counted as
1861
+ * written. `what` names it in the error message.
1862
+ */
1863
+ var TextBudget = class {
1864
+ max;
1865
+ what;
1866
+ n = 0;
1867
+ constructor(max, what) {
1868
+ this.max = max;
1869
+ this.what = what;
1870
+ }
1871
+ add(s) {
1872
+ this.n += s.length;
1873
+ if (this.n > this.max) throw new require_errors.LimitError("LIMIT_EXCEEDED", `${this.what} is longer than maxCellTextLength (${this.max}) characters.`, { details: {
1874
+ limit: "maxCellTextLength",
1875
+ value: this.max + 1,
1876
+ max: this.max
1877
+ } });
1878
+ }
1879
+ };
1880
+ /**
1712
1881
  * Collects one string item (<si> or <is>). Feed it the events between the
1713
1882
  * item's open and close; `value()` gives the string or rich text.
1714
1883
  */
1715
1884
  var StringItem = class {
1885
+ charge;
1886
+ max;
1887
+ details;
1888
+ /**
1889
+ * @param charge Counts each run after the first against the read's maxItems budget (JSE-52).
1890
+ * @param max maxCellTextLength: the item's text (all runs together, after decoding) may not be
1891
+ * longer; checked as the text arrives, so a longer item is refused before it is held whole (JSE-58).
1892
+ * @param details Extra `details` for the LimitError (a sheet cell's `ref`).
1893
+ */
1894
+ constructor(charge = () => {}, max = 1e400, details = {}) {
1895
+ this.charge = charge;
1896
+ this.max = max;
1897
+ this.details = details;
1898
+ }
1899
+ /** Decoded length of the plain text and of the current run; finished runs are in `runsLength`. */
1900
+ plainLength = new XstringLength();
1901
+ runLength = new XstringLength();
1902
+ runsLength = 0;
1716
1903
  runs = [];
1717
1904
  plain = "";
1718
1905
  hasRuns = false;
@@ -1735,6 +1922,7 @@ var StringItem = class {
1735
1922
  this.inRun = true;
1736
1923
  this.hasRuns = true;
1737
1924
  this.runText = "";
1925
+ this.runLength = new XstringLength();
1738
1926
  this.font = void 0;
1739
1927
  return;
1740
1928
  case "rPr":
@@ -1760,6 +1948,9 @@ var StringItem = class {
1760
1948
  this.inRPr = false;
1761
1949
  return;
1762
1950
  case "r": {
1951
+ this.runsLength += this.runLength.end();
1952
+ this.check(0);
1953
+ if (this.runs.length > 0) this.charge(1);
1763
1954
  const run = { text: decodeXstring(this.runText) };
1764
1955
  if (this.font && Object.keys(this.font.font).length) run.font = this.font.font;
1765
1956
  this.runs.push(run);
@@ -1771,10 +1962,23 @@ var StringItem = class {
1771
1962
  }
1772
1963
  text(s) {
1773
1964
  if (!this.inT || this.inRPh > 0) return;
1774
- if (this.inRun) this.runText += s;
1775
- else this.plain += s;
1965
+ if (this.inRun) {
1966
+ this.runLength.add(s);
1967
+ this.check(this.runLength.committed);
1968
+ this.runText += s;
1969
+ } else {
1970
+ this.plainLength.add(s);
1971
+ this.check(0);
1972
+ this.plain += s;
1973
+ }
1974
+ }
1975
+ /** Throws once the text known so far (`current`: the open run's) is longer than max. */
1976
+ check(current) {
1977
+ if (this.plainLength.committed + this.runsLength + current > this.max) throw cellTextTooLong(this.max, this.details);
1776
1978
  }
1777
1979
  value(mode) {
1980
+ this.plainLength.end();
1981
+ this.check(0);
1778
1982
  if (!this.hasRuns) return decodeXstring(this.plain);
1779
1983
  if (mode === "plain") return this.runs.map((r) => r.text).join("");
1780
1984
  return { richText: this.runs };
@@ -1785,6 +1989,8 @@ var SharedStringsParser = class {
1785
1989
  mode;
1786
1990
  max;
1787
1991
  stopAfter;
1992
+ charge;
1993
+ maxText;
1788
1994
  strings = [];
1789
1995
  item;
1790
1996
  depth = 0;
@@ -1793,10 +1999,12 @@ var SharedStringsParser = class {
1793
1999
  * `stopAfter`: decode only the first `stopAfter` items, then jump to the
1794
2000
  * end of the part without tokenizing the rest (previews, ReadOptions.maxRows).
1795
2001
  */
1796
- constructor(mode, max, stopAfter = 1e400) {
2002
+ constructor(mode, max, stopAfter = 1e400, charge = () => {}, maxText = 1e400) {
1797
2003
  this.mode = mode;
1798
2004
  this.max = max;
1799
2005
  this.stopAfter = stopAfter;
2006
+ this.charge = charge;
2007
+ this.maxText = maxText;
1800
2008
  }
1801
2009
  attach(control) {
1802
2010
  this.control = control;
@@ -1831,7 +2039,7 @@ var SharedStringsParser = class {
1831
2039
  this.strings.push("");
1832
2040
  this.pushed();
1833
2041
  } else {
1834
- this.item = new StringItem();
2042
+ this.item = new StringItem(this.charge, this.maxText);
1835
2043
  this.depth = 0;
1836
2044
  }
1837
2045
  }
@@ -1854,6 +2062,8 @@ var SharedStringsParser = class {
1854
2062
  // src/internal/read/sheet.ts
1855
2063
  const MAX_ROWS = 1048576;
1856
2064
  const MAX_COLS = 16384;
2065
+ /** `<col>` ranges kept before they are applied together (see SheetParser.flushCols). */
2066
+ const COL_BATCH = 16384;
1857
2067
  const ERROR_CODES = /* @__PURE__ */ new Set([
1858
2068
  "#NULL!",
1859
2069
  "#DIV/0!",
@@ -1889,8 +2099,9 @@ var DeferredStrings = class {
1889
2099
  parts = [];
1890
2100
  maxIndex = -1;
1891
2101
  /** Fills each cell from `sst`; a missing entry is reported and the cell dropped unless it has a formula or style, as on the full path. */
1892
- resolve(sst, warn) {
2102
+ resolve(sst, warn, checkAbort) {
1893
2103
  for (let i = 0; i < this.cells.length; i++) {
2104
+ if (checkAbort && (i & 4095) === 4095) checkAbort();
1894
2105
  const cell = this.cells[i];
1895
2106
  const str = sst[this.indexes[i]];
1896
2107
  if (str === void 0) {
@@ -1976,6 +2187,17 @@ var SheetParser = class {
1976
2187
  rows = [];
1977
2188
  rowProps = [];
1978
2189
  colProps = [];
2190
+ /** `<col>` ranges not applied yet, in document order: [first, end) columns, zero-based. */
2191
+ colRanges = [];
2192
+ /** Per column, the properties of the last `<col>` element that covers it, as far as applied. */
2193
+ colOwner = [];
2194
+ /** Columns that `colOwner` holds. */
2195
+ colCount = 0;
2196
+ /** The columns [colLo, colHi) that `colOwner` can hold. */
2197
+ colLo = MAX_COLS;
2198
+ colHi = 0;
2199
+ /** Steps spent on `<col>` ranges, from the first batch to the column objects in finish() (for the linear-work tests, JSE-52). */
2200
+ colWork = 0;
1979
2201
  merges = [];
1980
2202
  hyperlinks = [];
1981
2203
  shared = /* @__PURE__ */ new Map();
@@ -2042,7 +2264,7 @@ var SheetParser = class {
2042
2264
  return;
2043
2265
  case "is":
2044
2266
  if (this.cell && !empty) {
2045
- this.inline = new StringItem();
2267
+ this.inline = new StringItem((n) => this.ctx.charge(n), this.ctx.limits.maxCellTextLength, this.cell.ref ? { ref: this.cell.ref } : {});
2046
2268
  this.inlineDepth = 0;
2047
2269
  }
2048
2270
  return;
@@ -2054,12 +2276,16 @@ var SheetParser = class {
2054
2276
  return;
2055
2277
  case "mergeCell": {
2056
2278
  const ref = a.get("ref");
2057
- if (ref) this.merges.push(cleanRange(ref));
2279
+ if (ref) {
2280
+ this.ctx.charge(1);
2281
+ this.merges.push(cleanRange(ref));
2282
+ }
2058
2283
  return;
2059
2284
  }
2060
2285
  case "hyperlink":
2061
2286
  if (parent === "hyperlinks") {
2062
2287
  const ref = a.get("ref");
2288
+ if (ref) this.ctx.charge(1);
2063
2289
  if (ref) this.hyperlinks.push({
2064
2290
  ref: cleanRange(ref),
2065
2291
  relId: a.getPrefixed("id"),
@@ -2075,11 +2301,14 @@ var SheetParser = class {
2075
2301
  if (parent === "sheetView" && this.viewCount === 1) this.openPane(a);
2076
2302
  return;
2077
2303
  case "selection":
2078
- if (parent === "sheetView" && this.viewCount === 1) this.selections.push({
2079
- pane: a.get("pane"),
2080
- activeCell: a.get("activeCell"),
2081
- sqref: a.get("sqref")
2082
- });
2304
+ if (parent === "sheetView" && this.viewCount === 1) {
2305
+ this.ctx.charge(1);
2306
+ this.selections.push({
2307
+ pane: a.get("pane"),
2308
+ activeCell: a.get("activeCell"),
2309
+ sqref: a.get("sqref")
2310
+ });
2311
+ }
2083
2312
  return;
2084
2313
  case "sheetFormatPr": {
2085
2314
  const w = num(a.get("defaultColWidth"));
@@ -2141,10 +2370,12 @@ var SheetParser = class {
2141
2370
  this.path.pop();
2142
2371
  switch (name) {
2143
2372
  case "v":
2373
+ this.endText();
2144
2374
  if (this.cell && this.textTarget === "v") this.cell.v = this.buf;
2145
2375
  this.textTarget = void 0;
2146
2376
  return;
2147
2377
  case "f":
2378
+ this.endText();
2148
2379
  if (this.cell && this.textTarget === "f") this.cell.f = decodeXstring(this.buf);
2149
2380
  this.textTarget = void 0;
2150
2381
  return;
@@ -2170,11 +2401,38 @@ var SheetParser = class {
2170
2401
  this.inline.text(s);
2171
2402
  return;
2172
2403
  }
2173
- if (this.textTarget) this.buf += s;
2404
+ if (!this.textTarget) return;
2405
+ if (this.textTarget === "hf") this.hfBudget?.add(s);
2406
+ const len = this.textLength;
2407
+ if (len) {
2408
+ len.add(s);
2409
+ if (len.committed > this.ctx.limits.maxCellTextLength) this.textTooLong();
2410
+ }
2411
+ this.buf += s;
2412
+ }
2413
+ /**
2414
+ * Counts the text of a cell's `<v>` or `<f>` against maxCellTextLength as it
2415
+ * arrives (JSE-58), decoded as the cell's value will be: `_xHHHH_` escapes
2416
+ * count once in strings and formulas; other `<v>` text is kept as written.
2417
+ * Header and footer text is not cell text.
2418
+ */
2419
+ textLength;
2420
+ hfBudget;
2421
+ endText() {
2422
+ const len = this.textLength;
2423
+ this.textLength = void 0;
2424
+ if (len && len.end() > this.ctx.limits.maxCellTextLength) this.textTooLong();
2425
+ }
2426
+ textTooLong() {
2427
+ const ref = this.cell?.ref;
2428
+ throw cellTextTooLong(this.ctx.limits.maxCellTextLength, ref ? { ref } : {});
2174
2429
  }
2175
2430
  startText(target) {
2176
2431
  this.textTarget = target;
2177
2432
  this.buf = "";
2433
+ const t = this.cell?.t;
2434
+ this.textLength = target === "hf" ? void 0 : new XstringLength(target === "f" || t === "str" || t === "inlineStr");
2435
+ this.hfBudget = target === "hf" ? new TextBudget(this.ctx.limits.maxCellTextLength, "Header or footer text") : void 0;
2178
2436
  }
2179
2437
  openRow(a) {
2180
2438
  const r = int(a.get("r"));
@@ -2205,7 +2463,10 @@ var SheetParser = class {
2205
2463
  const st = this.styles.style(s);
2206
2464
  if (st) p.style = st;
2207
2465
  }
2208
- if (Object.keys(p).length) this.rowProps[this.curRow] = p;
2466
+ if (Object.keys(p).length) {
2467
+ if (this.rowProps[this.curRow] === void 0) this.ctx.charge(1);
2468
+ this.rowProps[this.curRow] = p;
2469
+ }
2209
2470
  }
2210
2471
  openCol(a) {
2211
2472
  const min = int(a.get("min"));
@@ -2224,8 +2485,61 @@ var SheetParser = class {
2224
2485
  if (st) p.style = st;
2225
2486
  }
2226
2487
  if (!Object.keys(p).length) return;
2227
- const last = Math.min(max, MAX_COLS);
2228
- for (let c = min - 1; c < last; c++) this.colProps[c] = { ...p };
2488
+ const end = Math.min(max, MAX_COLS);
2489
+ if (min - 1 >= end) return;
2490
+ this.colRanges.push({
2491
+ first: min - 1,
2492
+ end,
2493
+ p
2494
+ });
2495
+ if (this.colRanges.length >= COL_BATCH) this.flushCols();
2496
+ }
2497
+ /**
2498
+ * Applies the pending `<col>` ranges: where they overlap, the later element
2499
+ * wins, as when each range was written out in document order. Writing every
2500
+ * column of every range cost up to 16,384 steps per element, so a tiny
2501
+ * compressed part of repeated `<col min="1" max="16384">` took minutes
2502
+ * (JSE-52). The batch is applied from last to first instead, and a column
2503
+ * already taken by a later range is jumped over (`next`, with path halving),
2504
+ * so a batch costs about its size plus the columns it covers. Batches are
2505
+ * applied in order, so a later batch still wins over an earlier one.
2506
+ */
2507
+ flushCols() {
2508
+ const ranges = this.colRanges;
2509
+ if (!ranges.length) return;
2510
+ this.colRanges = [];
2511
+ let lo = MAX_COLS;
2512
+ let top = 0;
2513
+ for (const r of ranges) {
2514
+ if (r.end > top) top = r.end;
2515
+ if (r.first < lo) lo = r.first;
2516
+ }
2517
+ this.colWork += ranges.length;
2518
+ if (lo < this.colLo) this.colLo = lo;
2519
+ if (top > this.colHi) this.colHi = top;
2520
+ const owner = this.colOwner;
2521
+ const next = new Int32Array(top - lo + 1);
2522
+ for (let i = 0; i < next.length; i++) next[i] = i;
2523
+ this.colWork += next.length;
2524
+ const find = (col) => {
2525
+ let x = col - lo;
2526
+ while (next[x] !== x) {
2527
+ next[x] = next[next[x]];
2528
+ x = next[x];
2529
+ this.colWork++;
2530
+ }
2531
+ return x + lo;
2532
+ };
2533
+ for (let i = ranges.length - 1; i >= 0; i--) {
2534
+ const { first, end, p } = ranges[i];
2535
+ this.colWork++;
2536
+ for (let c = find(first); c < end; c = find(c + 1)) {
2537
+ if (owner[c] === void 0) this.colCount++;
2538
+ owner[c] = p;
2539
+ next[c - lo] = c + 1 - lo;
2540
+ this.colWork++;
2541
+ }
2542
+ }
2229
2543
  }
2230
2544
  openCell(a, empty) {
2231
2545
  let row = this.curRow;
@@ -2234,7 +2548,7 @@ var SheetParser = class {
2234
2548
  if (r !== void 0) {
2235
2549
  const pos = parseRef(r);
2236
2550
  if (!pos) {
2237
- this.ctx.warn("INVALID_CELL_REF", `Cell reference "${r}" is not valid; the cell was skipped.`, {
2551
+ this.ctx.warn("INVALID_CELL_REF", `Cell reference "${excerpt(r)}" is not valid; the cell was skipped.`, {
2238
2552
  part: this.part,
2239
2553
  sheet: this.sheet.name
2240
2554
  });
@@ -2251,7 +2565,7 @@ var SheetParser = class {
2251
2565
  return;
2252
2566
  }
2253
2567
  if (row >= 1048576 || col >= 16384) {
2254
- this.ctx.warn("CELL_OUT_OF_BOUNDS", `Cell ${r ?? `${colLetters(col + 1)}${row + 1}`} is beyond the format limits; it was skipped.`, {
2568
+ this.ctx.warn("CELL_OUT_OF_BOUNDS", `Cell ${excerpt(r ?? `${colLetters(col + 1)}${row + 1}`)} is beyond the format limits; it was skipped.`, {
2255
2569
  part: this.part,
2256
2570
  sheet: this.sheet.name
2257
2571
  });
@@ -2277,7 +2591,7 @@ var SheetParser = class {
2277
2591
  truncate() {
2278
2592
  if (this.truncated) return;
2279
2593
  this.truncated = true;
2280
- this.ctx.warn("ROWS_TRUNCATED", `Sheet "${this.sheet.name}" has rows beyond maxRows (${this.opts.maxRows}); they were not read.`, {
2594
+ this.ctx.warn("ROWS_TRUNCATED", `Sheet "${excerpt(this.sheet.name)}" has rows beyond maxRows (${this.opts.maxRows}); they were not read.`, {
2281
2595
  part: this.part,
2282
2596
  sheet: this.sheet.name
2283
2597
  });
@@ -2359,7 +2673,7 @@ var SheetParser = class {
2359
2673
  const sst = this.sharedStrings;
2360
2674
  const str = Number.isInteger(idx) && idx >= 0 ? sst[idx] : void 0;
2361
2675
  if (str === void 0) {
2362
- this.ctx.warn("INVALID_SHARED_STRING", `Cell ${p.ref} refers to shared string ${v}, which does not exist; the cell was left empty.`, {
2676
+ this.ctx.warn("INVALID_SHARED_STRING", `Cell ${p.ref} refers to shared string ${excerpt(v)}, which does not exist; the cell was left empty.`, {
2363
2677
  part: this.part,
2364
2678
  sheet: this.sheet.name,
2365
2679
  ref: p.ref
@@ -2571,6 +2885,16 @@ var SheetParser = class {
2571
2885
  /** Applies hyperlinks, merges and layout once the part is parsed. */
2572
2886
  finish(rels) {
2573
2887
  const sheet = this.sheet;
2888
+ this.flushCols();
2889
+ const owner = this.colOwner;
2890
+ if (this.colCount) {
2891
+ this.ctx.charge(this.colCount);
2892
+ for (let c = this.colLo; c < this.colHi; c++) {
2893
+ this.colWork++;
2894
+ const p = owner[c];
2895
+ if (p) this.colProps[c] = { ...p };
2896
+ }
2897
+ }
2574
2898
  if (this.rowProps.length) sheet.rowProps = this.rowProps;
2575
2899
  if (this.colProps.length) sheet.colProps = this.colProps;
2576
2900
  if (this.merges.length) sheet.merges = this.merges;
@@ -2582,7 +2906,18 @@ var SheetParser = class {
2582
2906
  }
2583
2907
  if (this.fitToPage && this.fitTo) this.printSetup().fitTo = this.fitTo;
2584
2908
  if (this.print && Object.keys(this.print).length) sheet.print = this.print;
2585
- for (const h of this.hyperlinks) this.attachHyperlink(h, rels);
2909
+ if (this.hyperlinks.length) {
2910
+ const byId = /* @__PURE__ */ new Map();
2911
+ for (let i = 0; i < rels.length; i++) {
2912
+ if ((i & 4095) === 4095) this.ctx.checkAbort();
2913
+ const r = rels[i];
2914
+ if (!byId.has(r.id)) byId.set(r.id, r);
2915
+ }
2916
+ for (let i = 0; i < this.hyperlinks.length; i++) {
2917
+ if ((i & 4095) === 4095) this.ctx.checkAbort();
2918
+ this.attachHyperlink(this.hyperlinks[i], byId);
2919
+ }
2920
+ }
2586
2921
  if (this.maxRow >= 0) {
2587
2922
  const tl = `${colLetters(this.minCol + 1)}${this.minRow + 1}`;
2588
2923
  const br = `${colLetters(this.maxCol + 1)}${this.maxRow + 1}`;
@@ -2594,14 +2929,14 @@ var SheetParser = class {
2594
2929
  const first = h.ref.split(":")[0];
2595
2930
  const pos = parseRef(first);
2596
2931
  if (!pos) return;
2597
- if (h.ref.includes(":") && h.ref.split(":")[1] !== first) this.ctx.warn("HYPERLINK_RANGE_REDUCED", `The hyperlink on ${h.ref} was attached to its top-left cell ${first}.`, {
2932
+ if (h.ref.includes(":") && h.ref.split(":")[1] !== first) this.ctx.warn("HYPERLINK_RANGE_REDUCED", `The hyperlink on ${excerpt(h.ref)} was attached to its top-left cell ${excerpt(first)}.`, {
2598
2933
  part: this.part,
2599
2934
  sheet: this.sheet.name,
2600
2935
  ref: h.ref
2601
2936
  });
2602
2937
  let link;
2603
2938
  if (h.relId) {
2604
- const rel = rels.find((r) => r.id === h.relId);
2939
+ const rel = rels.get(h.relId);
2605
2940
  if (rel) {
2606
2941
  const target = h.location ? `${rel.target}#${h.location}` : rel.target;
2607
2942
  link = h.tooltip !== void 0 ? {
@@ -2622,8 +2957,12 @@ var SheetParser = class {
2622
2957
  cell.hyperlink = link;
2623
2958
  }
2624
2959
  };
2625
- // src/internal/read/workbook.ts
2626
2960
  var WorkbookParser = class {
2961
+ maxSheets;
2962
+ part;
2963
+ checkAbort;
2964
+ charge;
2965
+ maxText;
2627
2966
  sheets = [];
2628
2967
  definedNames = [];
2629
2968
  date1904 = false;
@@ -2634,6 +2973,19 @@ var WorkbookParser = class {
2634
2973
  name;
2635
2974
  nameText = "";
2636
2975
  seenView = false;
2976
+ /**
2977
+ * @param maxSheets Sheet entries allowed (ReadLimits.maxSheets); one more throws LimitError while the part is parsed.
2978
+ * @param part The workbook part's name, for the error.
2979
+ * @param checkAbort Called every SHEET_ABORT_INTERVAL sheet entries, so a long sheet list cannot outrun the signal.
2980
+ */
2981
+ constructor(maxSheets = 1e400, part = "", checkAbort, charge = () => {}, maxText = 1e400) {
2982
+ this.maxSheets = maxSheets;
2983
+ this.part = part;
2984
+ this.checkAbort = checkAbort;
2985
+ this.charge = charge;
2986
+ this.maxText = maxText;
2987
+ }
2988
+ nameBudget;
2637
2989
  open(name, a, empty) {
2638
2990
  switch (name) {
2639
2991
  case "workbook":
@@ -2651,6 +3003,13 @@ var WorkbookParser = class {
2651
3003
  case "sheet": {
2652
3004
  const n = a.get("name");
2653
3005
  if (n === void 0) return;
3006
+ if (this.sheets.length >= this.maxSheets) throw new require_errors.LimitError("LIMIT_EXCEEDED", `The workbook declares more than maxSheets (${this.maxSheets}) sheets.`, { details: {
3007
+ limit: "maxSheets",
3008
+ value: this.sheets.length + 1,
3009
+ max: this.maxSheets,
3010
+ part: this.part
3011
+ } });
3012
+ if (this.checkAbort && this.sheets.length % 256 === 0) this.checkAbort();
2654
3013
  const st = a.get("state");
2655
3014
  this.sheets.push({
2656
3015
  name: n,
@@ -2662,6 +3021,7 @@ var WorkbookParser = class {
2662
3021
  case "definedName": {
2663
3022
  const n = a.get("name");
2664
3023
  if (n === void 0) return;
3024
+ this.charge(1);
2665
3025
  const d = {
2666
3026
  name: n,
2667
3027
  ref: ""
@@ -2684,13 +3044,16 @@ var WorkbookParser = class {
2684
3044
  }
2685
3045
  close(name) {
2686
3046
  if (name === "definedName" && this.name) {
3047
+ this.nameBudget = void 0;
2687
3048
  this.name.ref = this.nameText;
2688
3049
  this.definedNames.push(this.name);
2689
3050
  this.name = void 0;
2690
3051
  }
2691
3052
  }
2692
3053
  text(s) {
2693
- if (this.name) this.nameText += s;
3054
+ if (!this.name) return;
3055
+ (this.nameBudget ??= new TextBudget(this.maxText, `The formula of defined name "${excerpt(this.name.name)}"`)).add(s);
3056
+ this.nameText += s;
2694
3057
  }
2695
3058
  };
2696
3059
  const SCHEME_ORDER = [
@@ -2758,18 +3121,23 @@ const CORE_FIELDS = {
2758
3121
  /** docProps/core.xml and docProps/app.xml: simple elements with text. */
2759
3122
  var PropsParser = class {
2760
3123
  props;
3124
+ maxText;
2761
3125
  field;
2762
3126
  value = "";
2763
3127
  depth = 0;
2764
- constructor(props) {
3128
+ /** @param maxText maxCellTextLength, for each property's value (JSE-58 review). */
3129
+ constructor(props, maxText = 1e400) {
2765
3130
  this.props = props;
3131
+ this.maxText = maxText;
2766
3132
  }
3133
+ budget;
2767
3134
  open(name, _a, empty) {
2768
3135
  if (empty) return;
2769
3136
  this.depth++;
2770
3137
  if (this.depth === 2 && Object.prototype.hasOwnProperty.call(CORE_FIELDS, name)) {
2771
3138
  this.field = CORE_FIELDS[name];
2772
3139
  this.value = "";
3140
+ this.budget = new TextBudget(this.maxText, `Document property ${name}`);
2773
3141
  }
2774
3142
  }
2775
3143
  close() {
@@ -2785,12 +3153,23 @@ var PropsParser = class {
2785
3153
  this.depth--;
2786
3154
  }
2787
3155
  text(s) {
2788
- if (this.field) this.value += s;
3156
+ if (!this.field) return;
3157
+ this.budget?.add(s);
3158
+ this.value += s;
2789
3159
  }
2790
3160
  };
2791
3161
  /** docProps/custom.xml. */
2792
3162
  var CustomPropsParser = class {
3163
+ charge;
3164
+ maxText;
2793
3165
  items = [];
3166
+ /** @param charge Counts each property kept against the read's maxItems budget (JSE-52). */
3167
+ /** @param maxText maxCellTextLength, for each property's value (JSE-58 review). */
3168
+ constructor(charge = () => {}, maxText = 1e400) {
3169
+ this.charge = charge;
3170
+ this.maxText = maxText;
3171
+ }
3172
+ budget;
2794
3173
  name;
2795
3174
  kind;
2796
3175
  value = "";
@@ -2801,6 +3180,7 @@ var CustomPropsParser = class {
2801
3180
  } else if (this.name !== void 0 && this.kind === void 0) {
2802
3181
  this.kind = name;
2803
3182
  this.value = "";
3183
+ this.budget = new TextBudget(this.maxText, `Custom document property "${excerpt(this.name)}"`);
2804
3184
  }
2805
3185
  }
2806
3186
  close(name) {
@@ -2829,6 +3209,7 @@ var CustomPropsParser = class {
2829
3209
  if (Number.isFinite(n)) out = n;
2830
3210
  }
2831
3211
  }
3212
+ if (out !== void 0) this.charge(1);
2832
3213
  if (out !== void 0) this.items.push({
2833
3214
  name: this.name,
2834
3215
  value: out
@@ -2836,7 +3217,9 @@ var CustomPropsParser = class {
2836
3217
  this.kind = "";
2837
3218
  }
2838
3219
  text(s) {
2839
- if (this.kind) this.value += s;
3220
+ if (!this.kind) return;
3221
+ this.budget?.add(s);
3222
+ this.value += s;
2840
3223
  }
2841
3224
  };
2842
3225
  // src/internal/read/reader.ts
@@ -2915,8 +3298,9 @@ function openZipChecked(bytes, limits) {
2915
3298
  } });
2916
3299
  }
2917
3300
  async function parseWorkbook(pkg, part) {
2918
- const wb = new WorkbookParser();
2919
- await pkg.ctx.parse(pkg.part(part), wb);
3301
+ const ctx = pkg.ctx;
3302
+ const wb = new WorkbookParser(ctx.limits.maxSheets, part, () => ctx.checkAbort(), (n) => ctx.charge(n), ctx.limits.maxCellTextLength);
3303
+ await ctx.parse(pkg.part(part), wb);
2920
3304
  return wb;
2921
3305
  }
2922
3306
  /** Detects the file format from the bytes. Never throws for unreadable input. */
@@ -2948,25 +3332,65 @@ async function readSheetNamesImpl(bytes, options) {
2948
3332
  const { pkg, workbookPart } = await openPackage(bytes, limits, (zip) => new ReadContext(zip, limits, options?.signal, void 0, void 0));
2949
3333
  const wb = await parseWorkbook(pkg, workbookPart);
2950
3334
  const rels = await pkg.rels(workbookPart);
2951
- return worksheetsOf(wb.sheets, rels).map((s, index) => ({
3335
+ return (await worksheetsOf(pkg.ctx, wb.sheets, rels)).map((s, index) => ({
2952
3336
  name: s.entry.name,
2953
3337
  index,
2954
3338
  state: s.entry.state
2955
3339
  }));
2956
3340
  }
2957
- function worksheetsOf(sheets, rels) {
3341
+ /**
3342
+ * The worksheets among the workbook's sheet entries, with their relationships,
3343
+ * in book order. Relationships are looked up by id in a map built once (the
3344
+ * first relationship of an id wins, as a linear search found it), so this is
3345
+ * linear in sheets plus relationships (JSE-52). The signal is consulted per
3346
+ * entry. `other` is called, in book order, for each entry whose relationship
3347
+ * is not a worksheet (chart, dialog and macro sheets).
3348
+ */
3349
+ async function worksheetsOf(ctx, sheets, rels, other) {
3350
+ const byId = /* @__PURE__ */ new Map();
3351
+ for (let i = 0; i < rels.length; i++) {
3352
+ if ((i & 4095) === 4095) ctx.checkAbort();
3353
+ const r = rels[i];
3354
+ if (!byId.has(r.id)) byId.set(r.id, r);
3355
+ }
2958
3356
  const out = [];
2959
- sheets.forEach((entry, bookIndex) => {
2960
- const rel = entry.relId ? rels.find((r) => r.id === entry.relId) : void 0;
2961
- if (rel && rel.kind !== "worksheet") return;
3357
+ for (let bookIndex = 0; bookIndex < sheets.length; bookIndex++) {
3358
+ const pause = ctx.step();
3359
+ if (pause) await pause;
3360
+ const entry = sheets[bookIndex];
3361
+ const rel = entry.relId ? byId.get(entry.relId) : void 0;
3362
+ if (rel && rel.kind !== "worksheet") {
3363
+ other?.(rel);
3364
+ continue;
3365
+ }
2962
3366
  out.push({
2963
3367
  entry,
2964
3368
  rel,
2965
3369
  bookIndex
2966
3370
  });
2967
- });
3371
+ }
2968
3372
  return out;
2969
3373
  }
3374
+ /**
3375
+ * One UNSUPPORTED_PART warning per kind of part the model does not represent
3376
+ * (`seen` holds the kinds already reported). Consults the signal every 4,096
3377
+ * relationships (JSE-52).
3378
+ */
3379
+ function warnUnsupportedParts(ctx, rels, part, seen) {
3380
+ for (let i = 0; i < rels.length; i++) {
3381
+ if ((i & 4095) === 4095) ctx.checkAbort();
3382
+ const r = rels[i];
3383
+ const kind = r.kind;
3384
+ const what = UNSUPPORTED.get(kind);
3385
+ if (what && !seen.has(r.kind)) {
3386
+ seen.add(r.kind);
3387
+ ctx.warn("UNSUPPORTED_PART", `The workbook contains ${what}, which are not read.`, {
3388
+ part: r.external ? part : r.target,
3389
+ partKind: kind
3390
+ });
3391
+ }
3392
+ }
3393
+ }
2970
3394
  /** Reads an .xlsx-family file into the model. */
2971
3395
  async function readImpl(input, options, internal) {
2972
3396
  const o = options ?? {};
@@ -2991,19 +3415,7 @@ async function readImpl(input, options, internal) {
2991
3415
  const wbp = await parseWorkbook(pkg, workbookPart);
2992
3416
  const wbRels = await pkg.rels(workbookPart);
2993
3417
  const seen = /* @__PURE__ */ new Set();
2994
- const warnUnsupported = (rels, part) => {
2995
- for (const r of rels) {
2996
- const kind = r.kind;
2997
- const what = UNSUPPORTED.get(kind);
2998
- if (what && !seen.has(r.kind)) {
2999
- seen.add(r.kind);
3000
- ctx.warn("UNSUPPORTED_PART", `The workbook contains ${what}, which are not read.`, {
3001
- part: r.external ? part : r.target,
3002
- partKind: kind
3003
- });
3004
- }
3005
- }
3006
- };
3418
+ const warnUnsupported = (rels, part) => warnUnsupportedParts(ctx, rels, part, seen);
3007
3419
  if (format.macros) {
3008
3420
  seen.add("vbaProject");
3009
3421
  ctx.warn("UNSUPPORTED_PART", `The workbook is a ${format.label}; its VBA macros are not read or run.`, {
@@ -3017,12 +3429,12 @@ async function readImpl(input, options, internal) {
3017
3429
  const stylesRel = relOf("styles");
3018
3430
  if (stylesRel) {
3019
3431
  const entry = pkg.part(stylesRel.target);
3020
- if (!entry) ctx.warn("MISSING_PART", `The styles part ${stylesRel.target} is missing; default styles were used.`, {
3432
+ if (!entry) ctx.warn("MISSING_PART", `The styles part ${excerpt(stylesRel.target)} is missing; default styles were used.`, {
3021
3433
  part: stylesRel.target,
3022
3434
  partKind: "styles"
3023
3435
  });
3024
3436
  else {
3025
- const sp = new StylesParser(o.styles !== false);
3437
+ const sp = new StylesParser(o.styles !== false, (n) => ctx.charge(n));
3026
3438
  await ctx.parse(entry, sp);
3027
3439
  styles = sp.result();
3028
3440
  }
@@ -3035,7 +3447,7 @@ async function readImpl(input, options, internal) {
3035
3447
  const themeRel = relOf("theme");
3036
3448
  if (themeRel && o.styles !== false) {
3037
3449
  const entry = pkg.part(themeRel.target);
3038
- if (!entry) ctx.warn("MISSING_PART", `The theme part ${themeRel.target} is missing; the default theme applies.`, {
3450
+ if (!entry) ctx.warn("MISSING_PART", `The theme part ${excerpt(themeRel.target)} is missing; the default theme applies.`, {
3039
3451
  part: themeRel.target,
3040
3452
  partKind: "theme"
3041
3453
  });
@@ -3050,28 +3462,31 @@ async function readImpl(input, options, internal) {
3050
3462
  const sstRel = relOf("sharedStrings");
3051
3463
  if (sstRel) {
3052
3464
  const entry = pkg.part(sstRel.target);
3053
- if (!entry) ctx.warn("MISSING_PART", `The shared strings part ${sstRel.target} is missing; cells that use it are empty.`, {
3465
+ if (!entry) ctx.warn("MISSING_PART", `The shared strings part ${excerpt(sstRel.target)} is missing; cells that use it are empty.`, {
3054
3466
  part: sstRel.target,
3055
3467
  partKind: "sharedStrings"
3056
3468
  });
3057
3469
  else if (deferred) sstEntry = entry;
3058
3470
  else {
3059
- const sp = new SharedStringsParser(o.richText ?? "runs", limits.maxSharedStrings);
3471
+ const sp = new SharedStringsParser(o.richText ?? "runs", limits.maxSharedStrings, 1e400, (n) => ctx.charge(n), limits.maxCellTextLength);
3060
3472
  await ctx.parse(entry, sp);
3061
3473
  sst = sp.strings;
3062
3474
  }
3063
3475
  }
3064
3476
  const properties = await readProperties(pkg, ctx);
3065
- const listed = worksheetsOf(wbp.sheets, wbRels);
3066
- for (const s of wbp.sheets) {
3067
- const rel = s.relId ? wbRels.find((r) => r.id === s.relId) : void 0;
3068
- if (rel && rel.kind !== "worksheet") warnUnsupported([rel], workbookPart);
3069
- }
3477
+ const listed = await worksheetsOf(ctx, wbp.sheets, wbRels, (rel) => warnUnsupported([rel], workbookPart));
3070
3478
  const wanted = selector(o.sheets);
3071
- const totalBytes = listed.reduce((n, s) => n + (s.rel && wanted(s.entry.name, listed.indexOf(s)) ? pkg.part(s.rel.target)?.size ?? 0 : 0), 0) || 1;
3479
+ let totalBytes = 0;
3480
+ for (let i = 0; i < listed.length; i++) {
3481
+ const s = listed[i];
3482
+ if (s.rel && wanted(s.entry.name, i)) totalBytes += pkg.part(s.rel.target)?.size ?? 0;
3483
+ }
3484
+ totalBytes ||= 1;
3072
3485
  let doneBytes = 0;
3073
3486
  const sheets = [];
3074
3487
  for (let i = 0; i < listed.length; i++) {
3488
+ const pause = ctx.step();
3489
+ if (pause) await pause;
3075
3490
  const { entry, rel } = listed[i];
3076
3491
  const parser = new SheetParser(entry.name, entry.state, ctx, styles, {
3077
3492
  formulas: o.formulas !== false,
@@ -3086,7 +3501,7 @@ async function readImpl(input, options, internal) {
3086
3501
  parser.deferred = deferred;
3087
3502
  const part = rel ? pkg.part(rel.target) : void 0;
3088
3503
  if (!part) {
3089
- ctx.warn("MISSING_PART", `The part for sheet "${entry.name}" is missing; the sheet is empty.`, {
3504
+ ctx.warn("MISSING_PART", `The part for sheet "${excerpt(entry.name)}" is missing; the sheet is empty.`, {
3090
3505
  sheet: entry.name,
3091
3506
  partKind: "worksheet"
3092
3507
  });
@@ -3120,7 +3535,7 @@ async function readImpl(input, options, internal) {
3120
3535
  if (sstEntry && deferred && deferred.cells.length === 0) ctx.consumed.add(sstEntry.name);
3121
3536
  if (deferred && deferred.cells.length > 0) {
3122
3537
  if (sstEntry) {
3123
- const sp = new SharedStringsParser(o.richText ?? "runs", limits.maxSharedStrings, deferred.maxIndex + 1);
3538
+ const sp = new SharedStringsParser(o.richText ?? "runs", limits.maxSharedStrings, deferred.maxIndex + 1, (n) => ctx.charge(n), limits.maxCellTextLength);
3124
3539
  await ctx.parse(sstEntry, sp);
3125
3540
  sst = sp.strings;
3126
3541
  }
@@ -3128,12 +3543,14 @@ async function readImpl(input, options, internal) {
3128
3543
  part,
3129
3544
  sheet,
3130
3545
  ref
3131
- }));
3546
+ }), () => ctx.checkAbort());
3132
3547
  }
3133
3548
  const bookToSheet = /* @__PURE__ */ new Map();
3134
3549
  listed.forEach((s, i) => bookToSheet.set(s.bookIndex, i));
3135
3550
  const definedNames = [];
3136
3551
  for (const d of wbp.definedNames) {
3552
+ const pause = ctx.step();
3553
+ if (pause) await pause;
3137
3554
  const local = d.sheet === void 0 ? void 0 : bookToSheet.get(d.sheet);
3138
3555
  if (d.sheet !== void 0 && local === void 0) continue;
3139
3556
  const sheet = local === void 0 ? void 0 : sheets[local];
@@ -3210,7 +3627,7 @@ async function optional(ctx, part, partKind, fn) {
3210
3627
  return true;
3211
3628
  } catch (err) {
3212
3629
  if (err instanceof require_errors.FormatError && err.code === "XML_MALFORMED") {
3213
- ctx.warn("BROKEN_OPTIONAL_PART", `${part} is not well-formed XML and was skipped.`, {
3630
+ ctx.warn("BROKEN_OPTIONAL_PART", `${excerpt(part)} is not well-formed XML and was skipped.`, {
3214
3631
  part,
3215
3632
  partKind
3216
3633
  });
@@ -3230,13 +3647,13 @@ async function readProperties(pkg, ctx) {
3230
3647
  const rel = rels.find((r) => (r.kind === kind || r.type.endsWith(`/${kind}`)) && !r.external);
3231
3648
  const entry = rel ? pkg.part(rel.target) : void 0;
3232
3649
  if (!entry) continue;
3233
- const handler = new PropsParser(props);
3650
+ const handler = new PropsParser(props, ctx.limits.maxCellTextLength);
3234
3651
  await optional(ctx, entry.name, partKind, () => ctx.parse(entry, handler));
3235
3652
  }
3236
3653
  const customRel = rels.find((r) => r.kind === "custom-properties" && !r.external);
3237
3654
  const custom = customRel ? pkg.part(customRel.target) : void 0;
3238
3655
  if (custom) {
3239
- const cp = new CustomPropsParser();
3656
+ const cp = new CustomPropsParser((n) => ctx.charge(n), ctx.limits.maxCellTextLength);
3240
3657
  if (await optional(ctx, custom.name, "customProperties", () => ctx.parse(custom, cp)) && cp.items.length) props.custom = cp.items;
3241
3658
  }
3242
3659
  return Object.keys(props).length ? props : void 0;
@@ -3272,6 +3689,18 @@ Object.defineProperty(exports, "detectFormat", {
3272
3689
  return detectFormat;
3273
3690
  }
3274
3691
  });
3692
+ Object.defineProperty(exports, "excerpt", {
3693
+ enumerable: true,
3694
+ get: function() {
3695
+ return excerpt;
3696
+ }
3697
+ });
3698
+ Object.defineProperty(exports, "quoted", {
3699
+ enumerable: true,
3700
+ get: function() {
3701
+ return quoted;
3702
+ }
3703
+ });
3275
3704
  Object.defineProperty(exports, "read", {
3276
3705
  enumerable: true,
3277
3706
  get: function() {