javascript-excel 2.3.0 → 2.5.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.
Files changed (58) hide show
  1. package/README.md +5 -3
  2. package/dist/{address-DUn7-5OS.js → address-BGH42dEg.js} +1 -1
  3. package/dist/{address-DZBHchLv.cjs → address-DKd_3EGf.cjs} +1 -1
  4. package/dist/{csv-Bck8eW_D.js → csv-5jVhfM5l.js} +204 -33
  5. package/dist/{csv-f4P3fGs-.cjs → csv-BkVmMYQq.cjs} +204 -33
  6. package/dist/csv.cjs +1 -1
  7. package/dist/csv.d.cts +50 -3
  8. package/dist/csv.d.ts +50 -3
  9. package/dist/csv.js +1 -1
  10. package/dist/{dataset-DzoMeOG1.cjs → dataset-B4-SEdCn.cjs} +49 -5
  11. package/dist/{dataset-BLo9CwB-.js → dataset-Dh598YSG.js} +49 -5
  12. package/dist/{dates-BXcSWf9_.js → dates-CIL1z9EY.js} +1 -1
  13. package/dist/{dates-CA1dCizp.cjs → dates-DcdgnJto.cjs} +1 -1
  14. package/dist/dom.cjs +2 -2
  15. package/dist/dom.d.cts +1 -1
  16. package/dist/dom.d.ts +1 -1
  17. package/dist/dom.js +2 -2
  18. package/dist/{dos-time-BsH7f0ef.js → dos-time-BEAyK3U8.js} +1 -1
  19. package/dist/{dos-time-CxEs--rI.cjs → dos-time-BUWyklco.cjs} +1 -1
  20. package/dist/{errors-CvGlfw0E.js → errors-BQE62PFo.js} +1 -1
  21. package/dist/{errors-DOPrrGS4.cjs → errors-CKYdpCoB.cjs} +1 -1
  22. package/dist/format.cjs +1 -1
  23. package/dist/format.js +1 -1
  24. package/dist/import.cjs +1 -1
  25. package/dist/import.d.cts +2 -2
  26. package/dist/import.d.ts +2 -2
  27. package/dist/import.js +1 -1
  28. package/dist/index.cjs +7 -7
  29. package/dist/index.d.cts +5 -5
  30. package/dist/index.d.ts +5 -5
  31. package/dist/index.js +7 -7
  32. package/dist/{infer-BniOucP6.cjs → infer-B950M3-F.cjs} +27 -0
  33. package/dist/{infer-DcUyZ1T-.js → infer-DuSahY5i.js} +16 -1
  34. package/dist/{pipeline-2dgQM9E9.js → pipeline-1AVJbbqT.js} +39 -12
  35. package/dist/{pipeline-LCTU0Eg_.cjs → pipeline-C9zhwGAV.cjs} +39 -12
  36. package/dist/{pipeline-D1eAhqJu.d.cts → pipeline-CJWE3NWg.d.cts} +12 -5
  37. package/dist/{pipeline-Bh7FUyzW.d.ts → pipeline-DVgO1aGC.d.ts} +12 -5
  38. package/dist/{read-BnXzPjGc.js → read-B6tY0ooT.js} +2479 -869
  39. package/dist/{read-BYI7EVMo.cjs → read-Dgw9kMzh.cjs} +2489 -861
  40. package/dist/read.cjs +2 -1
  41. package/dist/read.d.cts +73 -3
  42. package/dist/read.d.ts +73 -3
  43. package/dist/read.js +2 -2
  44. package/dist/render.cjs +2 -2
  45. package/dist/render.js +2 -2
  46. package/dist/{sheet-names-DDY64-dt.cjs → sheet-names-D8sYcjSd.cjs} +2 -2
  47. package/dist/{sheet-names-BLrwcn33.js → sheet-names-RoFkpk_R.js} +2 -2
  48. package/dist/{warnings-DhonqJ7A.d.ts → warnings-DEsTp6rd.d.cts} +13 -2
  49. package/dist/{warnings-DhonqJ7A.d.cts → warnings-DEsTp6rd.d.ts} +13 -2
  50. package/dist/worker.cjs +5 -5
  51. package/dist/worker.d.cts +4 -4
  52. package/dist/worker.d.ts +4 -4
  53. package/dist/worker.js +5 -5
  54. package/dist/{write-DKXhuvKR.cjs → write-Bgl_QfA8.cjs} +5 -5
  55. package/dist/{write-BaMv1Z7W.d.ts → write-BylKqAmD.d.ts} +1 -1
  56. package/dist/{write-BVXB2_2C.js → write-DFz-h8gz.js} +5 -5
  57. package/dist/{write-Izl2NG0Y.d.cts → write-JvXRv63d.d.cts} +1 -1
  58. package/package.json +1 -1
@@ -1,8 +1,8 @@
1
- const require_infer = require("./infer-BniOucP6.cjs");
2
- const require_errors = require("./errors-DOPrrGS4.cjs");
3
- const require_dos_time = require("./dos-time-CxEs--rI.cjs");
1
+ const require_infer = require("./infer-B950M3-F.cjs");
2
+ const require_errors = require("./errors-CKYdpCoB.cjs");
3
+ const require_dos_time = require("./dos-time-BUWyklco.cjs");
4
4
  const require_numfmt = require("./numfmt-DwsnhZKe.cjs");
5
- const require_dates = require("./dates-CA1dCizp.cjs");
5
+ const require_dates = require("./dates-DcdgnJto.cjs");
6
6
  // src/internal/read/limits.ts
7
7
  /** Default limits (docs/api.md §5.2; the measurements behind each value are listed there). */
8
8
  const DEFAULT_LIMITS = Object.freeze({
@@ -18,6 +18,7 @@ const DEFAULT_LIMITS = Object.freeze({
18
18
  maxItems: 1e7,
19
19
  maxSharedStrings: 5e6,
20
20
  maxCellTextLength: 1048576,
21
+ maxColumns: 16384,
21
22
  maxWarnings: 1e3
22
23
  });
23
24
  function head(s) {
@@ -34,503 +35,197 @@ function excerpt(s) {
34
35
  function quoted(s) {
35
36
  return s.length <= 128 ? JSON.stringify(s) : `${JSON.stringify(head(s))}… (${s.length} characters)`;
36
37
  }
37
- // src/internal/zip/read.ts
38
+ // src/internal/read/xml-reader.ts
38
39
  /**
39
- * Zip container reader (docs/api.md §6, §8). Internal.
40
- *
41
- * `openZip` parses the central directory synchronously and validates the whole
42
- * layout before any data is inflated:
43
- * - end-of-central-directory record, with zip64 records when present;
44
- * - single-disk archives only;
45
- * - every entry's local header must agree with its central record;
46
- * - entry data must not overlap other entries or the central directory;
47
- * - duplicate names, encryption and methods other than 0 and 8 are rejected.
40
+ * Streaming XML pull tokenizer for the reader (docs/api.md §5.2, §8). Internal.
48
41
  *
49
- * Reading an entry counts the actual decompressed bytes against the limits
50
- * (never trusting declared sizes), stops when an entry produces more than it
51
- * declared, and verifies its CRC-32.
42
+ * - Push-fed: `feed()` text chunks as they are inflated, then `end()`. Only
43
+ * the unfinished tail of a chunk is kept, so a part is never held whole.
44
+ * - Linear in the input, however the chunks fall (JSE-43). An unfinished
45
+ * token (tag, comment, CDATA section, PI) is collected as a list of chunks;
46
+ * each new chunk alone is searched for the token's end, with the scan state
47
+ * (the open quote of a start tag, or the last characters that may begin a
48
+ * `-->`) carried over. The chunks are joined once, when the end is found.
49
+ * One token is limited to `maxXmlTokenLength` characters while it is read.
50
+ * Text is never collected: it is passed on chunk by chunk.
51
+ * - Iterative, never recursive. Element depth is limited (`maxXmlDepth`).
52
+ * - Any `<!DOCTYPE` is rejected (XML_DTD_FORBIDDEN), so there is no entity
53
+ * expansion and nothing external is ever fetched. Only the five predefined
54
+ * entities and numeric character references are decoded.
55
+ * - Well-formedness is checked as far as the reader needs: tags must nest and
56
+ * match, attributes must be quoted, references must be valid.
57
+ * - Names are reported without their namespace prefix (`x:row` -> `row`), so
58
+ * prefixed SpreadsheetML and ISO 29500 Strict parts read like transitional
59
+ * ones. Attributes keep their qualified names; see `XmlAttrs`.
52
60
  */
53
- /** The zip-related defaults of docs/api.md §5.2, the same values as DEFAULT_READ_LIMITS (measured in JSE-6). */
54
- const DEFAULT_ZIP_LIMITS = Object.freeze({
55
- maxInputBytes: 268435456,
56
- maxEntries: 1e4,
57
- maxEntryBytes: 536870912,
58
- maxTotalBytes: 1073741824,
59
- maxRatio: 1e3
60
- });
61
- const SIG_LOCAL = 67324752;
62
- const SIG_CENTRAL = 33639248;
63
- const SIG_EOCD = 101010256;
64
- const SIG_ZIP64_EOCD = 101075792;
65
- const SIG_ZIP64_LOCATOR = 117853008;
66
- const FLAG_ENCRYPTED = 1;
67
- const FLAG_DATA_DESCRIPTOR = 8;
68
- const FLAG_UTF8 = 2048;
69
- const EXTRA_ZIP64 = 1;
70
- const EXTRA_UNICODE_PATH = 28789;
71
- const METHOD_AES = 99;
72
- /** Code page 437, bytes 0x80..0xFF: the spec's default encoding for names without bit 11. */
73
- const CP437_HIGH = "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■\xA0";
74
- function invalid(message, details) {
75
- return new require_errors.FormatError("ZIP_INVALID", message, details ? { details } : void 0);
61
+ /** Attributes of one start tag. Names are never used as object keys. */
62
+ var XmlAttrs = class {
63
+ items;
64
+ /** Flat [qname, value, qname, value, ...]. */
65
+ constructor(items) {
66
+ this.items = items;
67
+ }
68
+ /** Value of the unprefixed attribute `local`. */
69
+ get(local) {
70
+ const items = this.items;
71
+ for (let i = 0; i < items.length; i += 2) if (items[i] === local) return items[i + 1];
72
+ }
73
+ /**
74
+ * Value of a prefixed attribute with local name `local` (e.g. `r:id` for
75
+ * "id"), whatever the prefix; `xml:` and `xmlns:` are skipped.
76
+ */
77
+ getPrefixed(local) {
78
+ const items = this.items;
79
+ for (let i = 0; i < items.length; i += 2) {
80
+ const q = items[i];
81
+ const colon = q.indexOf(":");
82
+ if (colon <= 0 || q.slice(colon + 1) !== local) continue;
83
+ const prefix = q.slice(0, colon);
84
+ if (prefix === "xml" || prefix === "xmlns") continue;
85
+ return items[i + 1];
86
+ }
87
+ }
88
+ /** Value of the attribute with exactly this qualified name (e.g. `xml:space`, `xmlns`). */
89
+ getQualified(qname) {
90
+ return this.get(qname);
91
+ }
92
+ /** Every [qualified name, value] pair, in document order. */
93
+ *entries() {
94
+ for (let i = 0; i < this.items.length; i += 2) yield [this.items[i], this.items[i + 1]];
95
+ }
96
+ };
97
+ function malformed(message) {
98
+ return new require_errors.FormatError("XML_MALFORMED", message);
76
99
  }
77
- function limitError(limit, value, max, what) {
78
- return new require_errors.LimitError("LIMIT_EXCEEDED", `${what} exceeds the ${limit} limit (${max}).`, { details: {
79
- limit,
80
- value,
100
+ const EMPTY_ATTRS = new XmlAttrs([]);
101
+ const Wait = {
102
+ None: 0,
103
+ /** A plain terminator: `delim`. */
104
+ Delim: 1,
105
+ /** The '>' that ends a start tag (or a '<', which is an error), outside quoted values. */
106
+ Tag: 2
107
+ };
108
+ /** The longest reference pump() may keep unfinished: `&` plus 11 characters (a `;` after that makes it invalid anyway). */
109
+ const MAX_REF_TAIL = 12;
110
+ /**
111
+ * `details.value` is `max + 1`, meaning "more than max": the limit trips
112
+ * before the token's end is read, so its real length is not known, and how
113
+ * much of it was buffered depends on how the chunks fell.
114
+ */
115
+ function tokenLimit(max) {
116
+ return new require_errors.LimitError("LIMIT_EXCEEDED", `An XML tag, comment, CDATA section or processing instruction is longer than maxXmlTokenLength (${max}).`, { details: {
117
+ limit: "maxXmlTokenLength",
118
+ value: max + 1,
81
119
  max
82
120
  } });
83
121
  }
84
- var Cursor = class {
85
- bytes;
86
- pos;
87
- view;
88
- constructor(bytes, pos) {
89
- this.bytes = bytes;
90
- this.pos = pos;
91
- this.view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
122
+ /** Unfinished-token chunks shorter than this are appended to the previous one, so 1-character chunks do not make a huge parts list. */
123
+ const MIN_PART = 4096;
124
+ var XmlTokenizer = class {
125
+ handler;
126
+ maxDepth;
127
+ maxToken;
128
+ onDeclaration;
129
+ buf = "";
130
+ stack = [];
131
+ /** While skipping: the end tag being searched for ("</qname"), and the depth to keep. */
132
+ skipTag;
133
+ skipDepth = 0;
134
+ /** While skipping: how many characters of `skipTag` the input seen so far ends with. */
135
+ skipMatched = 0;
136
+ rootSeen = false;
137
+ rootClosed = false;
138
+ pendingCR = false;
139
+ /** An unfinished token, from its '<': the chunks fed so far (`buf` is empty meanwhile). */
140
+ wait = Wait.None;
141
+ parts = [];
142
+ partsLength = 0;
143
+ /** Wait.Delim: the terminator, and the end of the searched text that may begin it. */
144
+ delim = "";
145
+ carry = "";
146
+ /** Wait.Tag: the open quote (34 or 39), or 0. */
147
+ quote = 0;
148
+ /** Characters examined or copied so far. A test hook for proving the scan is linear. */
149
+ work = 0;
150
+ constructor(handler, maxDepth, maxToken = DEFAULT_LIMITS.maxXmlTokenLength, onDeclaration) {
151
+ this.handler = handler;
152
+ this.maxDepth = maxDepth;
153
+ this.maxToken = maxToken;
154
+ this.onDeclaration = onDeclaration;
155
+ handler.attach?.(this);
92
156
  }
93
- need(n) {
94
- if (this.pos < 0 || this.pos + n > this.bytes.length) throw invalid("Unexpected end of zip data.");
157
+ depth() {
158
+ return this.stack.length;
95
159
  }
96
- u16() {
97
- this.need(2);
98
- const v = this.view.getUint16(this.pos, true);
99
- this.pos += 2;
100
- return v;
160
+ skipToEndOf(depth) {
161
+ if (depth < 1 || depth > this.stack.length) throw new RangeError(`skipToEndOf: no open element at depth ${depth}`);
162
+ this.skipTag = `</${this.stack[depth - 1]}`;
163
+ this.skipDepth = depth;
164
+ this.skipMatched = 0;
101
165
  }
102
- u32() {
103
- this.need(4);
104
- const v = this.view.getUint32(this.pos, true);
105
- this.pos += 4;
106
- return v;
166
+ feed(chunk) {
167
+ if (this.wait !== Wait.None) {
168
+ if (!this.resume(chunk)) return;
169
+ } else if (this.buf.length === 0) this.buf = chunk;
170
+ else {
171
+ this.work += this.buf.length + chunk.length;
172
+ this.buf += chunk;
173
+ }
174
+ this.pump(false);
107
175
  }
108
- u64() {
109
- const lo = this.u32();
110
- const v = this.u32() * 4294967296 + lo;
111
- if (!Number.isSafeInteger(v)) throw invalid("Zip64 value out of range.");
112
- return v;
176
+ end() {
177
+ if (this.wait !== Wait.None) this.unsuspend();
178
+ this.pump(true);
179
+ if (this.skipTag !== void 0) throw malformed(`Element <${excerpt(this.skipTag.slice(2))}> is not closed.`);
180
+ if (this.buf.trim() !== "") throw malformed("Unexpected end of XML data.");
181
+ if (this.stack.length > 0) throw malformed(`Element <${excerpt(this.stack.at(-1))}> is not closed.`);
182
+ if (!this.rootSeen) throw malformed("XML part has no root element.");
113
183
  }
114
- take(n) {
115
- this.need(n);
116
- const out = this.bytes.subarray(this.pos, this.pos + n);
117
- this.pos += n;
118
- return out;
184
+ /**
185
+ * Feeds one chunk to the unfinished token: only `chunk` is searched. Returns
186
+ * true when the token's end is in it; the chunks are then joined into `buf`
187
+ * and pump() reads the token from its start, exactly as if it had arrived
188
+ * whole. Throws when the token grows past maxXmlTokenLength.
189
+ */
190
+ resume(chunk) {
191
+ this.work += chunk.length;
192
+ const last = this.parts.length - 1;
193
+ if (this.parts[last].length < MIN_PART) this.parts[last] += chunk;
194
+ else this.parts.push(chunk);
195
+ this.partsLength += chunk.length;
196
+ let found;
197
+ if (this.wait === Wait.Tag) {
198
+ const e = scanTag(chunk, 0, chunk.length, this.quote);
199
+ found = e >= 0;
200
+ if (!found) this.quote = -1 - e;
201
+ } else {
202
+ const s = this.carry + chunk;
203
+ found = s.indexOf(this.delim) !== -1;
204
+ if (!found) this.carry = s.slice(Math.max(0, s.length - (this.delim.length - 1)));
205
+ }
206
+ if (!found) {
207
+ if (this.partsLength > this.maxToken) throw tokenLimit(this.maxToken);
208
+ return false;
209
+ }
210
+ this.unsuspend();
211
+ return true;
119
212
  }
120
- };
121
- function decodeName(raw, flags, extra) {
122
- if (flags & FLAG_UTF8) try {
123
- return require_dos_time.decodeUtf8Strict(raw);
124
- } catch {
125
- throw invalid("Entry name is not valid UTF-8.");
213
+ /** Parks the unfinished token that starts at `buf[i]`. */
214
+ suspend(buf, i, wait, delim = "", searchFrom = 0) {
215
+ this.wait = wait;
216
+ this.parts = [buf.slice(i)];
217
+ this.partsLength = buf.length - i;
218
+ this.delim = delim;
219
+ this.carry = wait === Wait.Delim ? buf.slice(Math.max(searchFrom, buf.length - (delim.length - 1))) : "";
220
+ this.buf = "";
126
221
  }
127
- const unicode = findExtra(extra, EXTRA_UNICODE_PATH);
128
- if (unicode && unicode.length >= 5 && unicode[0] === 1) {
129
- if (new Cursor(unicode, 1).u32() === require_dos_time.crc32(raw)) try {
130
- return require_dos_time.decodeUtf8Strict(unicode.subarray(5));
131
- } catch {}
132
- }
133
- let s = "";
134
- for (const b of raw) s += b < 128 ? String.fromCharCode(b) : CP437_HIGH[b - 128];
135
- return s;
136
- }
137
- function findExtra(extra, id) {
138
- const c = new Cursor(extra, 0);
139
- while (c.pos + 4 <= extra.length) {
140
- const tag = c.u16();
141
- const len = c.u16();
142
- if (c.pos + len > extra.length) return void 0;
143
- const body = c.take(len);
144
- if (tag === id) return body;
145
- }
146
- }
147
- function findEocd(bytes) {
148
- const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
149
- const last = bytes.length - 22;
150
- const first = Math.max(0, last - 65535);
151
- for (let p = last; p >= first; p--) if (view.getUint32(p, true) === SIG_EOCD) {
152
- const commentLength = view.getUint16(p + 20, true);
153
- if (p + 22 + commentLength <= bytes.length) return p;
154
- }
155
- throw invalid("Not a zip file: no end-of-central-directory record.");
156
- }
157
- /** Bytes of a stored entry checksummed between two abort checks. */
158
- const STORED_CRC_STEP = 1048576;
159
- /** Parses and validates the archive layout. Does not inflate anything. */
160
- function openZip(bytes, options = {}) {
161
- const limits = {
162
- ...DEFAULT_ZIP_LIMITS,
163
- ...options.limits
164
- };
165
- const codec = options.codec ?? require_dos_time.nativeCodec;
166
- if (bytes.length > limits.maxInputBytes) throw limitError("maxInputBytes", bytes.length, limits.maxInputBytes, "Input size");
167
- if (bytes.length < 22) throw invalid("Not a zip file: too short.");
168
- const eocdPos = findEocd(bytes);
169
- const e = new Cursor(bytes, eocdPos + 4);
170
- const disk = e.u16();
171
- const cdDisk = e.u16();
172
- const entriesOnDisk = e.u16();
173
- let entryCount = e.u16();
174
- let cdSize = e.u32();
175
- let cdOffset = e.u32();
176
- let cdLimit = eocdPos;
177
- if (eocdPos >= 20 && new Cursor(bytes, eocdPos - 20).u32() === SIG_ZIP64_LOCATOR) {
178
- const l = new Cursor(bytes, eocdPos - 16);
179
- const z64Disk = l.u32();
180
- const z64Pos = l.u64();
181
- const totalDisks = l.u32();
182
- if (z64Disk !== 0 || totalDisks > 1) throw invalid("Multi-disk zip archives are not supported.");
183
- if (z64Pos + 56 > eocdPos - 20) throw invalid("Zip64 end-of-central-directory record out of range.");
184
- const z = new Cursor(bytes, z64Pos);
185
- if (z.u32() !== SIG_ZIP64_EOCD) throw invalid("Bad zip64 end-of-central-directory signature.");
186
- z.u64();
187
- z.u16();
188
- z.u16();
189
- const z64ThisDisk = z.u32();
190
- const z64CdDisk = z.u32();
191
- z.u64();
192
- entryCount = z.u64();
193
- cdSize = z.u64();
194
- cdOffset = z.u64();
195
- if (z64ThisDisk !== 0 || z64CdDisk !== 0) throw invalid("Multi-disk zip archives are not supported.");
196
- cdLimit = z64Pos;
197
- } else {
198
- if (disk !== 0 || cdDisk !== 0 || entriesOnDisk !== entryCount) throw invalid("Multi-disk zip archives are not supported.");
199
- if (entryCount === 65535 || cdSize === 4294967295 || cdOffset === 4294967295) throw invalid("Zip64 values without a zip64 end-of-central-directory locator.");
200
- }
201
- if (entryCount > limits.maxEntries) throw limitError("maxEntries", entryCount, limits.maxEntries, "Entry count");
202
- if (cdOffset + cdSize > cdLimit) throw invalid("Central directory out of range.");
203
- if (entryCount * 46 > cdSize) throw invalid("Central directory too small for its entry count.");
204
- const entries = [];
205
- const byName = /* @__PURE__ */ new Map();
206
- const spans = [];
207
- const c = new Cursor(bytes.subarray(0, cdOffset + cdSize), cdOffset);
208
- for (let i = 0; i < entryCount; i++) {
209
- if (c.u32() !== SIG_CENTRAL) throw invalid("Bad central directory signature.", { index: i });
210
- c.u16();
211
- c.u16();
212
- const flags = c.u16();
213
- const method = c.u16();
214
- const time = c.u16();
215
- const date = c.u16();
216
- const crc = c.u32();
217
- let compressedSize = c.u32();
218
- let size = c.u32();
219
- const nameLength = c.u16();
220
- const extraLength = c.u16();
221
- const commentLength = c.u16();
222
- let diskStart = c.u16();
223
- c.u16();
224
- c.u32();
225
- let localOffset = c.u32();
226
- const rawName = c.take(nameLength);
227
- const extra = c.take(extraLength);
228
- c.take(commentLength);
229
- const z64 = findExtra(extra, EXTRA_ZIP64);
230
- if (z64) {
231
- const x = new Cursor(z64, 0);
232
- if (size === 4294967295) size = x.u64();
233
- if (compressedSize === 4294967295) compressedSize = x.u64();
234
- if (localOffset === 4294967295) localOffset = x.u64();
235
- if (diskStart === 65535) diskStart = x.u32();
236
- }
237
- if (diskStart !== 0) throw invalid("Multi-disk zip archives are not supported.");
238
- const name = decodeName(rawName, flags, extra);
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: {
241
- entry: name,
242
- method
243
- } });
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 });
246
- const l = new Cursor(bytes, localOffset);
247
- if (localOffset + 30 > cdOffset || l.u32() !== SIG_LOCAL) throw invalid(`Bad local header for ${excerpt(name)}.`, { entry: name });
248
- l.u16();
249
- const lFlags = l.u16();
250
- const lMethod = l.u16();
251
- l.u16();
252
- l.u16();
253
- const lCrc = l.u32();
254
- const lCompressed = l.u32();
255
- const lSize = l.u32();
256
- const lNameLength = l.u16();
257
- const lExtraLength = l.u16();
258
- const lName = l.take(lNameLength);
259
- l.take(lExtraLength);
260
- let agrees = lNameLength === nameLength && lName.every((b, k) => b === rawName[k]) && lMethod === method && (lFlags & FLAG_ENCRYPTED) === 0;
261
- if (agrees && !(lFlags & FLAG_DATA_DESCRIPTOR)) agrees = lCrc === crc && (lCompressed === compressedSize || lCompressed === 4294967295) && (lSize === size || lSize === 4294967295);
262
- if (!agrees) throw invalid(`Local header disagrees with the central directory for ${excerpt(name)}.`, { entry: name });
263
- const dataOffset = l.pos;
264
- const dataEnd = dataOffset + compressedSize;
265
- if (dataEnd > cdOffset) throw invalid(`Data of ${excerpt(name)} runs into the central directory.`, { entry: name });
266
- spans.push({
267
- start: localOffset,
268
- end: dataEnd,
269
- name
270
- });
271
- const info = Object.freeze({
272
- name,
273
- method,
274
- flags,
275
- crc32: crc,
276
- compressedSize,
277
- size,
278
- modified: require_dos_time.fromDosDateTime(date, time),
279
- dataOffset
280
- });
281
- entries.push(info);
282
- byName.set(name, info);
283
- }
284
- spans.sort((a, b) => a.start - b.start);
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.`);
286
- let totalBytesRead = 0;
287
- const resolve = (entry) => {
288
- const info = typeof entry === "string" ? byName.get(entry) : entry;
289
- if (!info || byName.get(info.name) !== info) throw new Error(`No such zip entry: ${typeof entry === "string" ? entry : entry.name}`);
290
- return info;
291
- };
292
- const countTotal = (n) => {
293
- totalBytesRead += n;
294
- if (totalBytesRead > limits.maxTotalBytes) throw limitError("maxTotalBytes", totalBytesRead, limits.maxTotalBytes, "Total decompressed size");
295
- };
296
- async function* stream(entry, signal) {
297
- const info = resolve(entry);
298
- require_dos_time.throwIfAborted(signal);
299
- if (info.size > limits.maxEntryBytes) throw limitError("maxEntryBytes", info.size, limits.maxEntryBytes, `Entry ${excerpt(info.name)}`);
300
- const data = bytes.subarray(info.dataOffset, info.dataOffset + info.compressedSize);
301
- let crc = 0;
302
- let produced = 0;
303
- if (info.method === 0) {
304
- countTotal(data.length);
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
- }
309
- produced = data.length;
310
- if (crc !== info.crc32) throw crcMismatch(info);
311
- yield data;
312
- return;
313
- }
314
- const chunks = codec.inflateRaw(data, {
315
- maxOutputBytes: limits.maxEntryBytes,
316
- maxRatio: limits.maxRatio
317
- }, signal);
318
- for await (const chunk of chunks) {
319
- produced += chunk.length;
320
- if (produced > info.size) throw invalid(`Entry ${excerpt(info.name)} is larger than declared.`, { entry: info.name });
321
- countTotal(chunk.length);
322
- crc = require_dos_time.crc32(chunk, crc);
323
- yield chunk;
324
- }
325
- if (produced !== info.size) throw invalid(`Entry ${excerpt(info.name)} is smaller than declared.`, { entry: info.name });
326
- if (crc !== info.crc32) throw crcMismatch(info);
327
- }
328
- return {
329
- entries,
330
- get: (name) => byName.get(name),
331
- stream,
332
- async read(entry, signal) {
333
- const parts = [];
334
- for await (const chunk of stream(entry, signal)) parts.push(chunk);
335
- return require_dos_time.concatBytes(parts);
336
- },
337
- get totalBytesRead() {
338
- return totalBytesRead;
339
- }
340
- };
341
- }
342
- function crcMismatch(info) {
343
- return new require_errors.FormatError("ZIP_CRC_MISMATCH", `CRC-32 mismatch in ${excerpt(info.name)}.`, { details: { entry: info.name } });
344
- }
345
- // src/internal/read/xml-reader.ts
346
- /**
347
- * Streaming XML pull tokenizer for the reader (docs/api.md §5.2, §8). Internal.
348
- *
349
- * - Push-fed: `feed()` text chunks as they are inflated, then `end()`. Only
350
- * the unfinished tail of a chunk is kept, so a part is never held whole.
351
- * - Linear in the input, however the chunks fall (JSE-43). An unfinished
352
- * token (tag, comment, CDATA section, PI) is collected as a list of chunks;
353
- * each new chunk alone is searched for the token's end, with the scan state
354
- * (the open quote of a start tag, or the last characters that may begin a
355
- * `-->`) carried over. The chunks are joined once, when the end is found.
356
- * One token is limited to `maxXmlTokenLength` characters while it is read.
357
- * Text is never collected: it is passed on chunk by chunk.
358
- * - Iterative, never recursive. Element depth is limited (`maxXmlDepth`).
359
- * - Any `<!DOCTYPE` is rejected (XML_DTD_FORBIDDEN), so there is no entity
360
- * expansion and nothing external is ever fetched. Only the five predefined
361
- * entities and numeric character references are decoded.
362
- * - Well-formedness is checked as far as the reader needs: tags must nest and
363
- * match, attributes must be quoted, references must be valid.
364
- * - Names are reported without their namespace prefix (`x:row` -> `row`), so
365
- * prefixed SpreadsheetML and ISO 29500 Strict parts read like transitional
366
- * ones. Attributes keep their qualified names; see `XmlAttrs`.
367
- */
368
- /** Attributes of one start tag. Names are never used as object keys. */
369
- var XmlAttrs = class {
370
- items;
371
- /** Flat [qname, value, qname, value, ...]. */
372
- constructor(items) {
373
- this.items = items;
374
- }
375
- /** Value of the unprefixed attribute `local`. */
376
- get(local) {
377
- const items = this.items;
378
- for (let i = 0; i < items.length; i += 2) if (items[i] === local) return items[i + 1];
379
- }
380
- /**
381
- * Value of a prefixed attribute with local name `local` (e.g. `r:id` for
382
- * "id"), whatever the prefix; `xml:` and `xmlns:` are skipped.
383
- */
384
- getPrefixed(local) {
385
- const items = this.items;
386
- for (let i = 0; i < items.length; i += 2) {
387
- const q = items[i];
388
- const colon = q.indexOf(":");
389
- if (colon <= 0 || q.slice(colon + 1) !== local) continue;
390
- const prefix = q.slice(0, colon);
391
- if (prefix === "xml" || prefix === "xmlns") continue;
392
- return items[i + 1];
393
- }
394
- }
395
- /** Value of the attribute with exactly this qualified name (e.g. `xml:space`, `xmlns`). */
396
- getQualified(qname) {
397
- return this.get(qname);
398
- }
399
- /** Every [qualified name, value] pair, in document order. */
400
- *entries() {
401
- for (let i = 0; i < this.items.length; i += 2) yield [this.items[i], this.items[i + 1]];
402
- }
403
- };
404
- function malformed(message) {
405
- return new require_errors.FormatError("XML_MALFORMED", message);
406
- }
407
- const EMPTY_ATTRS = new XmlAttrs([]);
408
- const Wait = {
409
- None: 0,
410
- /** A plain terminator: `delim`. */
411
- Delim: 1,
412
- /** The '>' that ends a start tag (or a '<', which is an error), outside quoted values. */
413
- Tag: 2
414
- };
415
- /** The longest reference pump() may keep unfinished: `&` plus 11 characters (a `;` after that makes it invalid anyway). */
416
- const MAX_REF_TAIL = 12;
417
- /**
418
- * `details.value` is `max + 1`, meaning "more than max": the limit trips
419
- * before the token's end is read, so its real length is not known, and how
420
- * much of it was buffered depends on how the chunks fell.
421
- */
422
- function tokenLimit(max) {
423
- return new require_errors.LimitError("LIMIT_EXCEEDED", `An XML tag, comment, CDATA section or processing instruction is longer than maxXmlTokenLength (${max}).`, { details: {
424
- limit: "maxXmlTokenLength",
425
- value: max + 1,
426
- max
427
- } });
428
- }
429
- /** Unfinished-token chunks shorter than this are appended to the previous one, so 1-character chunks do not make a huge parts list. */
430
- const MIN_PART = 4096;
431
- var XmlTokenizer = class {
432
- handler;
433
- maxDepth;
434
- maxToken;
435
- buf = "";
436
- stack = [];
437
- /** While skipping: the end tag being searched for ("</qname"), and the depth to keep. */
438
- skipTag;
439
- skipDepth = 0;
440
- /** While skipping: how many characters of `skipTag` the input seen so far ends with. */
441
- skipMatched = 0;
442
- rootSeen = false;
443
- rootClosed = false;
444
- pendingCR = false;
445
- /** An unfinished token, from its '<': the chunks fed so far (`buf` is empty meanwhile). */
446
- wait = Wait.None;
447
- parts = [];
448
- partsLength = 0;
449
- /** Wait.Delim: the terminator, and the end of the searched text that may begin it. */
450
- delim = "";
451
- carry = "";
452
- /** Wait.Tag: the open quote (34 or 39), or 0. */
453
- quote = 0;
454
- /** Characters examined or copied so far. A test hook for proving the scan is linear. */
455
- work = 0;
456
- constructor(handler, maxDepth, maxToken = DEFAULT_LIMITS.maxXmlTokenLength) {
457
- this.handler = handler;
458
- this.maxDepth = maxDepth;
459
- this.maxToken = maxToken;
460
- handler.attach?.(this);
461
- }
462
- depth() {
463
- return this.stack.length;
464
- }
465
- skipToEndOf(depth) {
466
- if (depth < 1 || depth > this.stack.length) throw new RangeError(`skipToEndOf: no open element at depth ${depth}`);
467
- this.skipTag = `</${this.stack[depth - 1]}`;
468
- this.skipDepth = depth;
469
- this.skipMatched = 0;
470
- }
471
- feed(chunk) {
472
- if (this.wait !== Wait.None) {
473
- if (!this.resume(chunk)) return;
474
- } else if (this.buf.length === 0) this.buf = chunk;
475
- else {
476
- this.work += this.buf.length + chunk.length;
477
- this.buf += chunk;
478
- }
479
- this.pump(false);
480
- }
481
- end() {
482
- if (this.wait !== Wait.None) this.unsuspend();
483
- this.pump(true);
484
- if (this.skipTag !== void 0) throw malformed(`Element <${excerpt(this.skipTag.slice(2))}> is not closed.`);
485
- if (this.buf.trim() !== "") throw malformed("Unexpected end of XML data.");
486
- if (this.stack.length > 0) throw malformed(`Element <${excerpt(this.stack.at(-1))}> is not closed.`);
487
- if (!this.rootSeen) throw malformed("XML part has no root element.");
488
- }
489
- /**
490
- * Feeds one chunk to the unfinished token: only `chunk` is searched. Returns
491
- * true when the token's end is in it; the chunks are then joined into `buf`
492
- * and pump() reads the token from its start, exactly as if it had arrived
493
- * whole. Throws when the token grows past maxXmlTokenLength.
494
- */
495
- resume(chunk) {
496
- this.work += chunk.length;
497
- const last = this.parts.length - 1;
498
- if (this.parts[last].length < MIN_PART) this.parts[last] += chunk;
499
- else this.parts.push(chunk);
500
- this.partsLength += chunk.length;
501
- let found;
502
- if (this.wait === Wait.Tag) {
503
- const e = scanTag(chunk, 0, chunk.length, this.quote);
504
- found = e >= 0;
505
- if (!found) this.quote = -1 - e;
506
- } else {
507
- const s = this.carry + chunk;
508
- found = s.indexOf(this.delim) !== -1;
509
- if (!found) this.carry = s.slice(Math.max(0, s.length - (this.delim.length - 1)));
510
- }
511
- if (!found) {
512
- if (this.partsLength > this.maxToken) throw tokenLimit(this.maxToken);
513
- return false;
514
- }
515
- this.unsuspend();
516
- return true;
517
- }
518
- /** Parks the unfinished token that starts at `buf[i]`. */
519
- suspend(buf, i, wait, delim = "", searchFrom = 0) {
520
- this.wait = wait;
521
- this.parts = [buf.slice(i)];
522
- this.partsLength = buf.length - i;
523
- this.delim = delim;
524
- this.carry = wait === Wait.Delim ? buf.slice(Math.max(searchFrom, buf.length - (delim.length - 1))) : "";
525
- this.buf = "";
526
- }
527
- unsuspend() {
528
- this.buf = this.parts.length === 1 ? this.parts[0] : this.parts.join("");
529
- this.work += this.buf.length;
530
- this.wait = Wait.None;
531
- this.parts = [];
532
- this.partsLength = 0;
533
- this.carry = "";
222
+ unsuspend() {
223
+ this.buf = this.parts.length === 1 ? this.parts[0] : this.parts.join("");
224
+ this.work += this.buf.length;
225
+ this.wait = Wait.None;
226
+ this.parts = [];
227
+ this.partsLength = 0;
228
+ this.carry = "";
534
229
  }
535
230
  /** A token of `length` characters (from '<' to the end of its terminator) is complete. */
536
231
  checkToken(length) {
@@ -593,6 +288,7 @@ var XmlTokenizer = class {
593
288
  const e = buf.indexOf("?>", i + 2);
594
289
  if (e === -1) return this.unfinished(buf, i, final, "Unterminated processing instruction.", Wait.Delim, "?>", i + 2);
595
290
  this.checkToken(e + 2 - i);
291
+ if (this.onDeclaration && /^<\?xml(?:[ \t\r\n?]|$)/i.test(buf.slice(i, i + 6))) this.onDeclaration(buf.slice(i, e + 2));
596
292
  i = e + 2;
597
293
  continue;
598
294
  }
@@ -837,6 +533,16 @@ var ReadContext = class {
837
533
  this.warnings = this.cap.warnings;
838
534
  }
839
535
  onProgress;
536
+ /** Sees every warning before the cap applies (inspect collects UNSUPPORTED_PART with it, JSE-71). */
537
+ tap;
538
+ /**
539
+ * inspect (JSE-71): for every part parsed as XML, a sniffer that sees its
540
+ * inflated bytes (however the inflater splits them) and, from the tokenizer,
541
+ * every processing instruction whose target is `xml` in any case.
542
+ */
543
+ sniff;
544
+ /** inspect (JSE-71): sees every relationship part the package parses, with its relationships. */
545
+ relsParsed;
840
546
  /** Returns to the event loop about every 16 ms between chunks, so a big read does not freeze the page (JSE-24). */
841
547
  pause = require_dos_time.createYielder();
842
548
  /**
@@ -853,6 +559,8 @@ var ReadContext = class {
853
559
  if (where?.sheet !== void 0) w.sheet = where.sheet;
854
560
  if (where?.ref !== void 0) w.ref = where.ref;
855
561
  if (where?.partKind !== void 0) w.partKind = where.partKind;
562
+ if (where?.parts !== void 0) w.parts = where.parts;
563
+ this.tap?.(w);
856
564
  if (this.cap.add(w, (dropped) => {
857
565
  const t = {
858
566
  code: "WARNINGS_TRUNCATED",
@@ -921,10 +629,12 @@ var ReadContext = class {
921
629
  */
922
630
  async parse(entry, handler, onChunk) {
923
631
  this.consumed.add(entry.name);
924
- const tok = new XmlTokenizer(handler, this.limits.maxXmlDepth, this.limits.maxXmlTokenLength);
632
+ const sniffer = this.sniff?.(entry.name);
633
+ const tok = new XmlTokenizer(handler, this.limits.maxXmlDepth, this.limits.maxXmlTokenLength, sniffer && ((pi) => sniffer.pi(pi)));
925
634
  let decoder;
926
635
  try {
927
636
  for await (const chunk of this.zip.stream(entry, this.signal)) {
637
+ sniffer?.feed(chunk);
928
638
  let bytes = chunk;
929
639
  if (!decoder) {
930
640
  decoder = newDecoder(chunk);
@@ -943,249 +653,794 @@ var ReadContext = class {
943
653
  this.checkAbort();
944
654
  }
945
655
  }
946
- onChunk?.(chunk.length);
947
- this.checkAbort();
948
- const pause = this.pause();
949
- if (pause) {
950
- await pause;
951
- this.checkAbort();
656
+ onChunk?.(chunk.length);
657
+ this.checkAbort();
658
+ const pause = this.pause();
659
+ if (pause) {
660
+ await pause;
661
+ this.checkAbort();
662
+ }
663
+ }
664
+ if (decoder) tok.feed(decoder.decode());
665
+ tok.end();
666
+ sniffer?.end();
667
+ } catch (err) {
668
+ throw withPart(err, entry.name);
669
+ }
670
+ }
671
+ };
672
+ function withPart(err, part) {
673
+ 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}`, {
674
+ details: {
675
+ ...err.details,
676
+ part
677
+ },
678
+ cause: err
679
+ });
680
+ const limit = err instanceof require_errors.LimitError ? err.details?.["limit"] : void 0;
681
+ 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}`, {
682
+ details: {
683
+ ...err.details,
684
+ part
685
+ },
686
+ cause: err
687
+ });
688
+ return err;
689
+ }
690
+ function newDecoder(first) {
691
+ const Ctor = globalThis.TextDecoder;
692
+ if (first[0] === 255 && first[1] === 254) return new Ctor("utf-16le");
693
+ if (first[0] === 254 && first[1] === 255) return new Ctor("utf-16be");
694
+ return new Ctor("utf-8");
695
+ }
696
+ function stripBom(b) {
697
+ if (b[0] === 239 && b[1] === 187 && b[2] === 191) return b.subarray(3);
698
+ if (b[0] === 255 && b[1] === 254 || b[0] === 254 && b[1] === 255) return b.subarray(2);
699
+ return b;
700
+ }
701
+ var Package = class {
702
+ ctx;
703
+ /** partKey(name) -> entry. */
704
+ parts = /* @__PURE__ */ new Map();
705
+ /** entry -> partKey(entry.name), computed once. */
706
+ keys = /* @__PURE__ */ new Map();
707
+ /**
708
+ * Names OPC forbids, in the order found: zip entries (see `forbiddenName`),
709
+ * then `[Content_Types].xml` when one of its PartNames is forbidden.
710
+ */
711
+ forbiddenNames = [];
712
+ /**
713
+ * Relationships that are not well-formed, by relationships part (entry
714
+ * name): an element without `Id` (or with an empty one) or without
715
+ * `Target`. They are left out of `rels()`, so the model ignores them as
716
+ * 2.4.0 did, but the package scan classifies them. One without `Type` is
717
+ * listed with type '' (nothing to classify).
718
+ */
719
+ malformedRels = /* @__PURE__ */ new Map();
720
+ /** 2.4.0's override table (raw lower-case PartName, last wins), for format detection only. */
721
+ legacyOverrides = /* @__PURE__ */ new Map();
722
+ /** partKey(part name) -> content types, in the order [Content_Types].xml lists them. */
723
+ overrides = /* @__PURE__ */ new Map();
724
+ /** Extension (lower case) -> content types. */
725
+ defaults = /* @__PURE__ */ new Map();
726
+ /**
727
+ * Indexes the zip entries by part name. Two entries whose names are
728
+ * equivalent (equal in canonical form, case-insensitively) make the package
729
+ * invalid: ZIP_INVALID, as OPC requires. Consults the signal for every
730
+ * entry (each costs work linear in its name, up to 64 KB).
731
+ */
732
+ constructor(ctx) {
733
+ this.ctx = ctx;
734
+ const entries = ctx.zip.entries;
735
+ for (let i = 0; i < entries.length; i++) {
736
+ ctx.checkAbort();
737
+ const e = entries[i];
738
+ if (e.name.endsWith("/")) continue;
739
+ const key = partKey(e.name);
740
+ const earlier = this.parts.get(key);
741
+ if (earlier) {
742
+ const how = earlier.name.toLowerCase() === e.name.toLowerCase() ? "differ only in case" : "are equivalent (they differ only in case or percent-encoding)";
743
+ throw new require_errors.FormatError("ZIP_INVALID", `Part names ${excerpt(earlier.name)} and ${excerpt(e.name)} ${how}.`, { details: { entry: e.name } });
744
+ }
745
+ this.parts.set(key, e);
746
+ this.keys.set(e, key);
747
+ if (forbiddenName(e.name, false)) this.forbiddenNames.push(e.name);
748
+ }
749
+ ctx.checkAbort();
750
+ }
751
+ /** The lookup key of a zip entry of this package (partKey of its name, computed once). */
752
+ keyOf(entry) {
753
+ return this.keys.get(entry) ?? partKey(entry.name);
754
+ }
755
+ part(name) {
756
+ if (name.length > 196605) return void 0;
757
+ return this.parts.get(partKey(name));
758
+ }
759
+ get partNames() {
760
+ return [...this.parts.values()].map((e) => e.name);
761
+ }
762
+ async loadContentTypes() {
763
+ const entry = this.part("[Content_Types].xml");
764
+ if (!entry) return;
765
+ let badPartName = false;
766
+ await this.ctx.parse(entry, {
767
+ open: (name, a) => {
768
+ if (name === "Default") {
769
+ const ext = a.get("Extension");
770
+ const type = a.get("ContentType");
771
+ if (ext && type) push(this.defaults, ext.toLowerCase(), type);
772
+ } else if (name === "Override") {
773
+ const part = a.get("PartName");
774
+ const type = a.get("ContentType");
775
+ if (!part || !type) return;
776
+ this.legacyOverrides.set(stripSlash(part).toLowerCase(), type);
777
+ if (part.length > 196605) {
778
+ badPartName = true;
779
+ return;
780
+ }
781
+ if (forbiddenName(part, false)) badPartName = true;
782
+ const key = partKey(part);
783
+ push(this.overrides, key, type);
784
+ const decoded = partKey(resolveTarget("", part));
785
+ if (decoded !== key) push(this.overrides, decoded, type);
786
+ }
787
+ },
788
+ close: () => {},
789
+ text: () => {}
790
+ });
791
+ if (badPartName) this.forbiddenNames.push(entry.name);
792
+ }
793
+ /** The content type of a part for format decisions, exactly as 2.4.0: the last Override with the same raw PartName (case-insensitive), else the last Default for its extension. */
794
+ contentType(name) {
795
+ const key = stripSlash(name).toLowerCase();
796
+ const o = this.legacyOverrides.get(key);
797
+ if (o) return o;
798
+ const dot = key.lastIndexOf(".");
799
+ return dot === -1 ? void 0 : this.defaults.get(key.slice(dot + 1))?.at(-1);
800
+ }
801
+ /**
802
+ * Every content type [Content_Types].xml gives the part: all Overrides with
803
+ * an equivalent part name, else all Defaults for its extension. The package
804
+ * scan checks each, so a later passive entry cannot hide an active one.
805
+ */
806
+ contentTypes(name) {
807
+ if (name.length > 196605) return [];
808
+ const key = partKey(name);
809
+ const o = this.overrides.get(key);
810
+ if (o) return o;
811
+ const dot = key.lastIndexOf(".");
812
+ return (dot > key.lastIndexOf("/") ? this.defaults.get(key.slice(dot + 1)) : void 0) ?? [];
813
+ }
814
+ /** Content types of the overrides for format detection: one per raw PartName, the last given, exactly as 2.4.0. */
815
+ get overrideTypes() {
816
+ return [...this.legacyOverrides.values()];
817
+ }
818
+ /** The relationships part of `source` ('' for the package), whether or not it exists. */
819
+ relsPartOf(source) {
820
+ const src = stripSlash(source);
821
+ const slash = src.lastIndexOf("/");
822
+ return `${slash === -1 ? "" : src.slice(0, slash + 1)}_rels/${slash === -1 ? src : src.slice(slash + 1)}.rels`;
823
+ }
824
+ /**
825
+ * Relationships of `source` ('' for the package). Missing rels part: [].
826
+ * Each relationships part is parsed once per read and the result shared, so
827
+ * callers must not change the array. With `peek`, a part not read before is
828
+ * not marked as consumed (InternalReadOptions.retainParts still keeps it).
829
+ */
830
+ async rels(source, options) {
831
+ const entry = this.part(this.relsPartOf(source));
832
+ if (!entry) return [];
833
+ const consumed = this.ctx.consumed;
834
+ const cached = this.relsCache.get(entry.name);
835
+ if (cached) {
836
+ if (!options?.peek) consumed.add(entry.name);
837
+ return cached;
838
+ }
839
+ const wasConsumed = consumed.has(entry.name);
840
+ try {
841
+ const out = await this.parseRels(entry, source);
842
+ this.relsCache.set(entry.name, out);
843
+ return out;
844
+ } finally {
845
+ if (options?.peek && !wasConsumed) consumed.delete(entry.name);
846
+ }
847
+ }
848
+ relsCache = /* @__PURE__ */ new Map();
849
+ async parseRels(entry, source) {
850
+ const src = stripSlash(source);
851
+ const slash = src.lastIndexOf("/");
852
+ const dir = slash === -1 ? "" : src.slice(0, slash + 1);
853
+ const out = [];
854
+ const malformed = [];
855
+ await this.ctx.parse(entry, {
856
+ open: (name, a) => {
857
+ if (name !== "Relationship") return;
858
+ const id = a.get("Id");
859
+ const type = a.get("Type") ?? "";
860
+ const target = a.get("Target");
861
+ const external = (a.get("TargetMode") ?? "").toLowerCase() === "external";
862
+ const rel = {
863
+ id: id ?? "",
864
+ type,
865
+ kind: type.slice(type.lastIndexOf("/") + 1),
866
+ target: "",
867
+ external
868
+ };
869
+ if (target === void 0) {
870
+ malformed.push(rel);
871
+ return;
872
+ }
873
+ if (external) rel.target = target;
874
+ else if (target.trim().length > 196605) {
875
+ rel.tooLong = true;
876
+ rel.forbidden = true;
877
+ } else {
878
+ const readings = resolveReadings(dir, target);
879
+ rel.target = readings.target;
880
+ const key = partKey(rel.target);
881
+ if (forbiddenName(stripFragment(target), true) || isPackageMetadata(key)) rel.forbidden = true;
882
+ if (readings.alt !== void 0) {
883
+ const altKey = partKey(readings.alt);
884
+ if (altKey !== key) {
885
+ rel.altTarget = readings.alt;
886
+ if (isPackageMetadata(altKey)) rel.forbidden = true;
887
+ }
888
+ }
952
889
  }
953
- }
954
- if (decoder) tok.feed(decoder.decode());
955
- tok.end();
956
- } catch (err) {
957
- throw withPart(err, entry.name);
958
- }
890
+ if (!id || !type) malformed.push(rel);
891
+ else out.push(rel);
892
+ },
893
+ close: () => {},
894
+ text: () => {}
895
+ });
896
+ if (malformed.length) this.malformedRels.set(entry.name, malformed);
897
+ this.ctx.relsParsed?.(entry.name, out);
898
+ return out;
959
899
  }
960
900
  };
961
- function withPart(err, part) {
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}`, {
963
- details: {
964
- ...err.details,
965
- part
966
- },
967
- cause: err
968
- });
969
- const limit = err instanceof require_errors.LimitError ? err.details?.["limit"] : void 0;
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}`, {
971
- details: {
972
- ...err.details,
973
- part
974
- },
975
- cause: err
976
- });
977
- return err;
901
+ /**
902
+ * A relationships part (`…/_rels/<name>.rels`) or `[Content_Types].xml`, by
903
+ * part key: package metadata that OPC forbids as a relationship target.
904
+ */
905
+ function isPackageMetadata(key) {
906
+ if (key === "[content_types].xml") return true;
907
+ if (!key.endsWith(".rels")) return false;
908
+ const slash = key.lastIndexOf("/");
909
+ const parent = key.slice(0, slash === -1 ? 0 : slash);
910
+ return parent === "_rels" || parent.endsWith("/_rels");
978
911
  }
979
- function newDecoder(first) {
980
- const Ctor = globalThis.TextDecoder;
981
- if (first[0] === 255 && first[1] === 254) return new Ctor("utf-16le");
982
- if (first[0] === 254 && first[1] === 255) return new Ctor("utf-16be");
983
- return new Ctor("utf-8");
912
+ /** The owner of a relationships part (`a/_rels/b.xml.rels` -> `a/b.xml`, `_rels/.rels` -> ''), or undefined if `name` is not one. */
913
+ function relsOwner(name) {
914
+ const slash = name.lastIndexOf("/");
915
+ const file = name.slice(slash + 1);
916
+ if (slash === -1 || !/\.rels$/i.test(file)) return void 0;
917
+ const parent = name.slice(0, slash);
918
+ const parentSlash = parent.lastIndexOf("/");
919
+ if (parent.slice(parentSlash + 1).toLowerCase() !== "_rels") return void 0;
920
+ return parent.slice(0, parentSlash + 1) + file.slice(0, -5);
984
921
  }
985
- function stripBom(b) {
986
- if (b[0] === 239 && b[1] === 187 && b[2] === 191) return b.subarray(3);
987
- if (b[0] === 255 && b[1] === 254 || b[0] === 254 && b[1] === 255) return b.subarray(2);
988
- return b;
922
+ function stripSlash(name) {
923
+ return name.startsWith("/") ? name.slice(1) : name;
989
924
  }
990
- // src/internal/read/formats.ts
991
- /** Container signatures, checked in order. */
992
- const CONTAINERS = [
993
- {
994
- kind: "cfb",
995
- magic: [
996
- 208,
997
- 207,
998
- 17,
999
- 224,
1000
- 161,
1001
- 177,
1002
- 26,
1003
- 225
1004
- ]
1005
- },
1006
- {
1007
- kind: "zip",
1008
- magic: [
1009
- 80,
1010
- 75,
1011
- 3,
1012
- 4
1013
- ]
1014
- },
1015
- {
1016
- kind: "zip",
1017
- magic: [
1018
- 80,
1019
- 75,
1020
- 5,
1021
- 6
1022
- ]
925
+ function push(map, key, value) {
926
+ const list = map.get(key);
927
+ if (list) list.push(value);
928
+ else map.set(key, [value]);
929
+ }
930
+ function stripFragment(target) {
931
+ const hash = target.indexOf("#");
932
+ return hash === -1 ? target : target.slice(0, hash);
933
+ }
934
+ /**
935
+ * True when a part name or relationship target uses a segment OPC forbids
936
+ * (ECMA-376 Part 2 §6.2.2): one containing `%2F` or `%5C`, a percent-encoded
937
+ * dot segment (`%2E`, `%2E%2E`, `.%2E`, `%2E.`), or one ending in a dot. For
938
+ * a relationship target (`isTarget`), the literal `.` and `..` segments of a
939
+ * relative reference are allowed; in a zip entry name they are forbidden too.
940
+ * Segments are split on `/` and, in a target, on `\`. Linear in the length.
941
+ */
942
+ function forbiddenName(name, isTarget) {
943
+ const n = name.length;
944
+ let segStart = 0;
945
+ for (let i = 0; i <= n; i++) {
946
+ const c = i < n ? name.charCodeAt(i) : 47;
947
+ if (c !== 47 && !(isTarget && c === 92)) continue;
948
+ if (i > segStart && forbiddenSegment(name, segStart, i, isTarget)) return true;
949
+ segStart = i + 1;
950
+ }
951
+ return false;
952
+ }
953
+ function forbiddenSegment(s, from, to, isTarget) {
954
+ let lastIsDot = false;
955
+ let literalDotSegment = true;
956
+ for (let i = from; i < to; i++) {
957
+ const c = s.charCodeAt(i);
958
+ if (c === 37 && i + 2 < to) {
959
+ const h = s.charCodeAt(i + 1) << 8 | (s.charCodeAt(i + 2) | 32);
960
+ if (h === 12902 || h === 13667) return true;
961
+ if (h === 12901) {
962
+ lastIsDot = true;
963
+ literalDotSegment = false;
964
+ i += 2;
965
+ continue;
966
+ }
967
+ }
968
+ lastIsDot = c === 46;
969
+ if (!lastIsDot) literalDotSegment = false;
1023
970
  }
1024
- ];
1025
- /** OPC workbook formats by the content type of their workbook part. */
1026
- const WORKBOOK_FORMATS = [
1027
- {
1028
- format: "xlsx",
1029
- contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml",
1030
- decoder: "spreadsheetml",
1031
- label: "Excel workbook (.xlsx)"
1032
- },
1033
- {
1034
- format: "xltx",
1035
- contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml",
1036
- decoder: "spreadsheetml",
1037
- label: "Excel template (.xltx)"
1038
- },
1039
- {
1040
- format: "xlsm",
1041
- contentType: "application/vnd.ms-excel.sheet.macroEnabled.main+xml",
1042
- decoder: "spreadsheetml",
1043
- macros: true,
1044
- label: "macro-enabled workbook (.xlsm)"
1045
- },
1046
- {
1047
- format: "xltm",
1048
- contentType: "application/vnd.ms-excel.template.macroEnabled.main+xml",
1049
- decoder: "spreadsheetml",
1050
- macros: true,
1051
- label: "macro-enabled template (.xltm)"
1052
- },
1053
- {
1054
- format: "xlsb",
1055
- contentType: "application/vnd.ms-excel.sheet.binary.macroEnabled.main",
1056
- macros: true,
1057
- label: "binary workbook (.xlsb)"
971
+ if (!lastIsDot) return false;
972
+ if (isTarget && literalDotSegment && to - from <= 2) return false;
973
+ return true;
974
+ }
975
+ /**
976
+ * Part-name equivalence (OPC, ECMA-376 Part 2 §6.2.2.3 and the zip mapping of
977
+ * §7.3.4): `name` with its percent-escapes decoded once, as UTF-8. Kept
978
+ * encoded (upper-case hex), so that nothing decoded can act as structure or
979
+ * as a new escape: `%2F`, `%5C`, `%25`, a `%` that does not start an escape
980
+ * (written `%25`), and each byte that is not part of a valid UTF-8 sequence.
981
+ * Not lower-cased. Idempotent: canonicalPartName(canonicalPartName(s)) ===
982
+ * canonicalPartName(s). One linear pass, no decoder calls.
983
+ */
984
+ function canonicalPartName(name) {
985
+ let i = name.indexOf("%");
986
+ if (i === -1) return name;
987
+ const n = name.length;
988
+ let out = "";
989
+ /** Start of the input not yet copied: text that canonicalises to itself is copied in one slice. */
990
+ let from = 0;
991
+ const emit = (end, text, next) => {
992
+ out += name.slice(from, end) + text;
993
+ from = next;
994
+ };
995
+ while (i < n) {
996
+ if (name.charCodeAt(i) !== 37) {
997
+ i = name.indexOf("%", i);
998
+ if (i === -1) break;
999
+ continue;
1000
+ }
1001
+ const b = hexByte(name, i);
1002
+ if (b < 0) {
1003
+ emit(i, "%25", i + 1);
1004
+ i++;
1005
+ continue;
1006
+ }
1007
+ if (b === 37 || b === 47 || b === 92 || b >= 128) {
1008
+ const len = b >= 128 ? utf8Length(name, i, b) : 0;
1009
+ if (len) {
1010
+ let cp = len === 2 ? b & 31 : len === 3 ? b & 15 : b & 7;
1011
+ for (let k = 1; k < len; k++) cp = cp << 6 | hexByte(name, i + 3 * k) & 63;
1012
+ emit(i, String.fromCodePoint(cp), i + 3 * len);
1013
+ i += 3 * len;
1014
+ } else {
1015
+ if (name.charCodeAt(i + 1) > 96 || name.charCodeAt(i + 2) > 96) emit(i, HEX[b], i + 3);
1016
+ i += 3;
1017
+ }
1018
+ continue;
1019
+ }
1020
+ emit(i, String.fromCharCode(b), i + 3);
1021
+ i += 3;
1058
1022
  }
1059
- ];
1060
- /** Formats recognised by something other than a workbook content type. */
1061
- const OTHER_FORMATS = {
1062
- ods: { label: "OpenDocument spreadsheet (.ods)" },
1063
- cfb: { label: "legacy .xls file or a password-protected (encrypted) workbook" },
1064
- unknown: { label: "file that is not a spreadsheet package" }
1065
- };
1066
- function sniffContainer(b) {
1067
- for (const c of CONTAINERS) if (c.magic.every((x, i) => b[i] === x)) return c.kind;
1068
- return "unknown";
1023
+ return from === 0 ? name : out + name.slice(from);
1069
1024
  }
1025
+ const HEX = Array.from({ length: 256 }, (_, b) => `%${b.toString(16).toUpperCase().padStart(2, "0")}`);
1070
1026
  /**
1071
- * The workbook format for a workbook part, from its content type; when the
1072
- * content type is missing or unknown, from the part's extension (.bin is
1073
- * binary, anything else is read as SpreadsheetML).
1027
+ * The length in bytes of the valid UTF-8 sequence whose lead byte `b` is the
1028
+ * escape at `i` (its continuation bytes are the escapes that follow), or 0.
1029
+ * Rejects overlong forms, surrogates and code points above U+10FFFF.
1074
1030
  */
1075
- function workbookFormat(contentType, partName) {
1076
- const ct = (contentType ?? "").toLowerCase();
1077
- const known = WORKBOOK_FORMATS.find((f) => f.contentType.toLowerCase() === ct);
1078
- if (known) return known;
1079
- if (partName.toLowerCase().endsWith(".bin")) return WORKBOOK_FORMATS.find((f) => f.format === "xlsb");
1080
- return WORKBOOK_FORMATS[0];
1031
+ function utf8Length(name, i, b) {
1032
+ const len = b >= 194 && b <= 223 ? 2 : b >= 224 && b <= 239 ? 3 : b >= 240 && b <= 244 ? 4 : 0;
1033
+ for (let k = 1; k < len; k++) {
1034
+ const cb = hexByte(name, i + 3 * k);
1035
+ if (cb < 0 || (cb & 192) !== 128) return 0;
1036
+ if (k === 1 && (b === 224 && cb < 160 || b === 237 && cb > 159 || b === 240 && cb < 144 || b === 244 && cb > 143)) return 0;
1037
+ }
1038
+ return len;
1039
+ }
1040
+ /** The byte of the escape `%XX` at `i`, or -1. */
1041
+ function hexByte(s, i) {
1042
+ if (s.charCodeAt(i) !== 37 || i + 2 >= s.length) return -1;
1043
+ const h = hexDigit(s.charCodeAt(i + 1));
1044
+ const l = hexDigit(s.charCodeAt(i + 2));
1045
+ return h < 0 || l < 0 ? -1 : h << 4 | l;
1046
+ }
1047
+ function hexDigit(c) {
1048
+ if (c >= 48 && c <= 57) return c - 48;
1049
+ const l = c | 32;
1050
+ return l >= 97 && l <= 102 ? l - 97 + 10 : -1;
1051
+ }
1052
+ /** The lookup key of a part name: canonical, no leading '/', lower case (part names compare case-insensitively). */
1053
+ function partKey(name) {
1054
+ return canonicalPartName(stripSlash(name)).toLowerCase();
1081
1055
  }
1082
- // src/internal/read/opc.ts
1083
1056
  /**
1084
- * Open Packaging Conventions for the reader: part lookup (case-insensitive,
1085
- * as OPC requires), [Content_Types].xml and relationship parts. Internal.
1057
+ * Resolves a relationship target against the source part's folder, as a
1058
+ * decoder reads it (and as 2.4.0 did): `/`, `\`, `%2F` and `%5C` separate
1059
+ * segments, and a segment that is `.` or `..` once `%2E` is decoded is a dot
1060
+ * segment. Each other segment is put in canonical form once. For a target
1061
+ * OPC allows this is the only reading; for others, see resolveTargetLiteral.
1086
1062
  */
1087
- var Package = class {
1088
- ctx;
1089
- parts = /* @__PURE__ */ new Map();
1090
- /** Part name (lower case, no leading '/') -> content type. */
1091
- overrides = /* @__PURE__ */ new Map();
1092
- /** Extension (lower case) -> content type. */
1093
- defaults = /* @__PURE__ */ new Map();
1094
- constructor(ctx) {
1095
- this.ctx = ctx;
1096
- for (const e of ctx.zip.entries) {
1097
- if (e.name.endsWith("/")) continue;
1098
- const key = e.name.toLowerCase();
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 } });
1100
- this.parts.set(key, e);
1063
+ function resolveTarget(baseDir, target) {
1064
+ return resolveReadings(baseDir, target).target;
1065
+ }
1066
+ /**
1067
+ * Both readings of a relationship target. `target` is the one `read` uses,
1068
+ * as 2.4.0 resolved it: decoded (resolveTargetDecoded), or, when the target
1069
+ * has an escape that is not valid UTF-8 or a `%` that starts no escape (2.4.0's
1070
+ * decodeURIComponent threw and the target was kept raw), literal
1071
+ * (resolveTargetLiteral). `alt` is the other reading, when the target has
1072
+ * an escape that can change its structure (`%2F`, `%5C`, `%2E`).
1073
+ */
1074
+ function resolveReadings(baseDir, target) {
1075
+ const t = stripFragment(target);
1076
+ const structural = /%(2f|5c|2e)/i.test(t);
1077
+ if (malformedEscapes(t)) {
1078
+ const literal = resolveTargetLiteral(baseDir, t);
1079
+ return structural ? {
1080
+ target: literal,
1081
+ alt: resolveTargetDecoded(baseDir, t)
1082
+ } : { target: literal };
1083
+ }
1084
+ const decoded = resolveTargetDecoded(baseDir, t);
1085
+ return structural ? {
1086
+ target: decoded,
1087
+ alt: resolveTargetLiteral(baseDir, t)
1088
+ } : { target: decoded };
1089
+ }
1090
+ /** True when decodeURIComponent would throw: a `%` that starts no escape, or escapes that are not valid UTF-8. Linear. */
1091
+ function malformedEscapes(name) {
1092
+ let i = name.indexOf("%");
1093
+ while (i !== -1) {
1094
+ const b = hexByte(name, i);
1095
+ if (b < 0) return true;
1096
+ if (b < 128) i += 3;
1097
+ else {
1098
+ const len = utf8Length(name, i, b);
1099
+ if (!len) return true;
1100
+ i += 3 * len;
1101
1101
  }
1102
+ i = name.indexOf("%", i);
1103
+ }
1104
+ return false;
1105
+ }
1106
+ /**
1107
+ * The decoder's reading: `/`, `\`, `%2F` and `%5C` separate segments, and a
1108
+ * segment that is `.` or `..` once `%2E` is decoded is a dot segment. Each
1109
+ * other segment is put in canonical form once.
1110
+ */
1111
+ function resolveTargetDecoded(baseDir, target) {
1112
+ const t = stripFragment(target).replace(/%2f|%5c|\\/gi, "/");
1113
+ const segments = t.startsWith("/") ? [] : baseDir.split("/").filter((s) => s !== "");
1114
+ for (const seg of t.split("/")) {
1115
+ const dots = seg.length <= 6 ? seg.replace(/%2e/gi, ".") : seg;
1116
+ if (dots === "" || dots === ".") continue;
1117
+ if (dots === "..") segments.pop();
1118
+ else segments.push(canonicalPartName(seg));
1119
+ }
1120
+ return segments.join("/");
1121
+ }
1122
+ /**
1123
+ * Resolves a relationship target taking every escape literally: only `/` and
1124
+ * `\` separate segments and only literal `.` and `..` are dot segments, so
1125
+ * `%2E%2E`, `%2F` and `%5C` stay part of a name.
1126
+ */
1127
+ function resolveTargetLiteral(baseDir, target) {
1128
+ const t = stripFragment(target).replace(/\\/g, "/");
1129
+ const segments = t.startsWith("/") ? [] : baseDir.split("/").filter((s) => s !== "");
1130
+ for (const seg of t.split("/")) {
1131
+ if (seg === "" || seg === ".") continue;
1132
+ if (seg === "..") segments.pop();
1133
+ else segments.push(canonicalPartName(seg));
1134
+ }
1135
+ return segments.join("/");
1136
+ }
1137
+ // src/internal/zip/read.ts
1138
+ /**
1139
+ * Zip container reader (docs/api.md §6, §8). Internal.
1140
+ *
1141
+ * `openZip` parses the central directory synchronously and validates the whole
1142
+ * layout before any data is inflated:
1143
+ * - end-of-central-directory record, with zip64 records when present;
1144
+ * - single-disk archives only;
1145
+ * - every entry's local header must agree with its central record;
1146
+ * - entry data must not overlap other entries or the central directory;
1147
+ * - duplicate names, encryption and methods other than 0 and 8 are rejected.
1148
+ *
1149
+ * Reading an entry counts the actual decompressed bytes against the limits
1150
+ * (never trusting declared sizes), stops when an entry produces more than it
1151
+ * declared, and verifies its CRC-32.
1152
+ */
1153
+ /** The zip-related defaults of docs/api.md §5.2, the same values as DEFAULT_READ_LIMITS (measured in JSE-6). */
1154
+ const DEFAULT_ZIP_LIMITS = Object.freeze({
1155
+ maxInputBytes: 268435456,
1156
+ maxEntries: 1e4,
1157
+ maxEntryBytes: 536870912,
1158
+ maxTotalBytes: 1073741824,
1159
+ maxRatio: 1e3
1160
+ });
1161
+ const SIG_LOCAL = 67324752;
1162
+ const SIG_CENTRAL = 33639248;
1163
+ const SIG_EOCD = 101010256;
1164
+ const SIG_ZIP64_EOCD = 101075792;
1165
+ const SIG_ZIP64_LOCATOR = 117853008;
1166
+ const FLAG_ENCRYPTED = 1;
1167
+ const FLAG_DATA_DESCRIPTOR = 8;
1168
+ const FLAG_UTF8 = 2048;
1169
+ const EXTRA_ZIP64 = 1;
1170
+ const EXTRA_UNICODE_PATH = 28789;
1171
+ const METHOD_AES = 99;
1172
+ /** Code page 437, bytes 0x80..0xFF: the spec's default encoding for names without bit 11. */
1173
+ const CP437_HIGH = "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■\xA0";
1174
+ function invalid(message, details) {
1175
+ return new require_errors.FormatError("ZIP_INVALID", message, details ? { details } : void 0);
1176
+ }
1177
+ function limitError(limit, value, max, what) {
1178
+ return new require_errors.LimitError("LIMIT_EXCEEDED", `${what} exceeds the ${limit} limit (${max}).`, { details: {
1179
+ limit,
1180
+ value,
1181
+ max
1182
+ } });
1183
+ }
1184
+ var Cursor = class {
1185
+ bytes;
1186
+ pos;
1187
+ view;
1188
+ constructor(bytes, pos) {
1189
+ this.bytes = bytes;
1190
+ this.pos = pos;
1191
+ this.view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
1102
1192
  }
1103
- part(name) {
1104
- return this.parts.get(stripSlash(name).toLowerCase());
1193
+ need(n) {
1194
+ if (this.pos < 0 || this.pos + n > this.bytes.length) throw invalid("Unexpected end of zip data.");
1105
1195
  }
1106
- get partNames() {
1107
- return [...this.parts.values()].map((e) => e.name);
1196
+ u16() {
1197
+ this.need(2);
1198
+ const v = this.view.getUint16(this.pos, true);
1199
+ this.pos += 2;
1200
+ return v;
1108
1201
  }
1109
- async loadContentTypes() {
1110
- const entry = this.part("[Content_Types].xml");
1111
- if (!entry) return;
1112
- await this.ctx.parse(entry, {
1113
- open: (name, a) => {
1114
- if (name === "Default") {
1115
- const ext = a.get("Extension");
1116
- const type = a.get("ContentType");
1117
- if (ext && type) this.defaults.set(ext.toLowerCase(), type);
1118
- } else if (name === "Override") {
1119
- const part = a.get("PartName");
1120
- const type = a.get("ContentType");
1121
- if (part && type) this.overrides.set(stripSlash(part).toLowerCase(), type);
1122
- }
1123
- },
1124
- close: () => {},
1125
- text: () => {}
1126
- });
1202
+ u32() {
1203
+ this.need(4);
1204
+ const v = this.view.getUint32(this.pos, true);
1205
+ this.pos += 4;
1206
+ return v;
1127
1207
  }
1128
- contentType(name) {
1129
- const key = stripSlash(name).toLowerCase();
1130
- const o = this.overrides.get(key);
1131
- if (o) return o;
1132
- const dot = key.lastIndexOf(".");
1133
- return dot === -1 ? void 0 : this.defaults.get(key.slice(dot + 1));
1208
+ u64() {
1209
+ const lo = this.u32();
1210
+ const v = this.u32() * 4294967296 + lo;
1211
+ if (!Number.isSafeInteger(v)) throw invalid("Zip64 value out of range.");
1212
+ return v;
1134
1213
  }
1135
- /** Content types of all overrides (for format detection). */
1136
- get overrideTypes() {
1137
- return [...this.overrides.values()];
1214
+ take(n) {
1215
+ this.need(n);
1216
+ const out = this.bytes.subarray(this.pos, this.pos + n);
1217
+ this.pos += n;
1218
+ return out;
1138
1219
  }
1139
- /** Relationships of `source` ('' for the package). Missing rels part: []. */
1140
- async rels(source) {
1141
- const src = stripSlash(source);
1142
- const slash = src.lastIndexOf("/");
1143
- const dir = slash === -1 ? "" : src.slice(0, slash + 1);
1144
- const relsName = `${dir}_rels/${slash === -1 ? src : src.slice(slash + 1)}.rels`;
1145
- const entry = this.part(relsName);
1146
- if (!entry) return [];
1147
- const out = [];
1148
- await this.ctx.parse(entry, {
1149
- open: (name, a) => {
1150
- if (name !== "Relationship") return;
1151
- const id = a.get("Id");
1152
- const type = a.get("Type");
1153
- const target = a.get("Target");
1154
- if (!id || !type || target === void 0) return;
1155
- const external = (a.get("TargetMode") ?? "").toLowerCase() === "external";
1156
- out.push({
1157
- id,
1158
- type,
1159
- kind: type.slice(type.lastIndexOf("/") + 1),
1160
- target: external ? target : resolveTarget(dir, target),
1161
- external
1162
- });
1163
- },
1164
- close: () => {},
1165
- text: () => {}
1220
+ };
1221
+ function decodeName(raw, flags, extra) {
1222
+ if (flags & FLAG_UTF8) try {
1223
+ return require_dos_time.decodeUtf8Strict(raw);
1224
+ } catch {
1225
+ throw invalid("Entry name is not valid UTF-8.");
1226
+ }
1227
+ const unicode = findExtra(extra, EXTRA_UNICODE_PATH);
1228
+ if (unicode && unicode.length >= 5 && unicode[0] === 1) {
1229
+ if (new Cursor(unicode, 1).u32() === require_dos_time.crc32(raw)) try {
1230
+ return require_dos_time.decodeUtf8Strict(unicode.subarray(5));
1231
+ } catch {}
1232
+ }
1233
+ let s = "";
1234
+ for (const b of raw) s += b < 128 ? String.fromCharCode(b) : CP437_HIGH[b - 128];
1235
+ return s;
1236
+ }
1237
+ function findExtra(extra, id) {
1238
+ const c = new Cursor(extra, 0);
1239
+ while (c.pos + 4 <= extra.length) {
1240
+ const tag = c.u16();
1241
+ const len = c.u16();
1242
+ if (c.pos + len > extra.length) return void 0;
1243
+ const body = c.take(len);
1244
+ if (tag === id) return body;
1245
+ }
1246
+ }
1247
+ function findEocd(bytes) {
1248
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
1249
+ const last = bytes.length - 22;
1250
+ const first = Math.max(0, last - 65535);
1251
+ for (let p = last; p >= first; p--) if (view.getUint32(p, true) === SIG_EOCD) {
1252
+ const commentLength = view.getUint16(p + 20, true);
1253
+ if (p + 22 + commentLength <= bytes.length) return p;
1254
+ }
1255
+ throw invalid("Not a zip file: no end-of-central-directory record.");
1256
+ }
1257
+ /** Bytes of a stored entry checksummed between two abort checks. */
1258
+ const STORED_CRC_STEP = 1048576;
1259
+ /** Parses and validates the archive layout. Does not inflate anything. */
1260
+ function openZip(bytes, options = {}) {
1261
+ const limits = {
1262
+ ...DEFAULT_ZIP_LIMITS,
1263
+ ...options.limits
1264
+ };
1265
+ const codec = options.codec ?? require_dos_time.nativeCodec;
1266
+ if (bytes.length > limits.maxInputBytes) throw limitError("maxInputBytes", bytes.length, limits.maxInputBytes, "Input size");
1267
+ if (bytes.length < 22) throw invalid("Not a zip file: too short.");
1268
+ const eocdPos = findEocd(bytes);
1269
+ const e = new Cursor(bytes, eocdPos + 4);
1270
+ const disk = e.u16();
1271
+ const cdDisk = e.u16();
1272
+ const entriesOnDisk = e.u16();
1273
+ let entryCount = e.u16();
1274
+ let cdSize = e.u32();
1275
+ let cdOffset = e.u32();
1276
+ let cdLimit = eocdPos;
1277
+ if (eocdPos >= 20 && new Cursor(bytes, eocdPos - 20).u32() === SIG_ZIP64_LOCATOR) {
1278
+ const l = new Cursor(bytes, eocdPos - 16);
1279
+ const z64Disk = l.u32();
1280
+ const z64Pos = l.u64();
1281
+ const totalDisks = l.u32();
1282
+ if (z64Disk !== 0 || totalDisks > 1) throw invalid("Multi-disk zip archives are not supported.");
1283
+ if (z64Pos + 56 > eocdPos - 20) throw invalid("Zip64 end-of-central-directory record out of range.");
1284
+ const z = new Cursor(bytes, z64Pos);
1285
+ if (z.u32() !== SIG_ZIP64_EOCD) throw invalid("Bad zip64 end-of-central-directory signature.");
1286
+ z.u64();
1287
+ z.u16();
1288
+ z.u16();
1289
+ const z64ThisDisk = z.u32();
1290
+ const z64CdDisk = z.u32();
1291
+ z.u64();
1292
+ entryCount = z.u64();
1293
+ cdSize = z.u64();
1294
+ cdOffset = z.u64();
1295
+ if (z64ThisDisk !== 0 || z64CdDisk !== 0) throw invalid("Multi-disk zip archives are not supported.");
1296
+ cdLimit = z64Pos;
1297
+ } else {
1298
+ if (disk !== 0 || cdDisk !== 0 || entriesOnDisk !== entryCount) throw invalid("Multi-disk zip archives are not supported.");
1299
+ if (entryCount === 65535 || cdSize === 4294967295 || cdOffset === 4294967295) throw invalid("Zip64 values without a zip64 end-of-central-directory locator.");
1300
+ }
1301
+ if (entryCount > limits.maxEntries) throw limitError("maxEntries", entryCount, limits.maxEntries, "Entry count");
1302
+ if (cdOffset + cdSize > cdLimit) throw invalid("Central directory out of range.");
1303
+ if (entryCount * 46 > cdSize) throw invalid("Central directory too small for its entry count.");
1304
+ const entries = [];
1305
+ const byName = /* @__PURE__ */ new Map();
1306
+ const spans = [];
1307
+ const c = new Cursor(bytes.subarray(0, cdOffset + cdSize), cdOffset);
1308
+ for (let i = 0; i < entryCount; i++) {
1309
+ if (c.u32() !== SIG_CENTRAL) throw invalid("Bad central directory signature.", { index: i });
1310
+ c.u16();
1311
+ c.u16();
1312
+ const flags = c.u16();
1313
+ const method = c.u16();
1314
+ const time = c.u16();
1315
+ const date = c.u16();
1316
+ const crc = c.u32();
1317
+ let compressedSize = c.u32();
1318
+ let size = c.u32();
1319
+ const nameLength = c.u16();
1320
+ const extraLength = c.u16();
1321
+ const commentLength = c.u16();
1322
+ let diskStart = c.u16();
1323
+ c.u16();
1324
+ c.u32();
1325
+ let localOffset = c.u32();
1326
+ const rawName = c.take(nameLength);
1327
+ const extra = c.take(extraLength);
1328
+ c.take(commentLength);
1329
+ const z64 = findExtra(extra, EXTRA_ZIP64);
1330
+ if (z64) {
1331
+ const x = new Cursor(z64, 0);
1332
+ if (size === 4294967295) size = x.u64();
1333
+ if (compressedSize === 4294967295) compressedSize = x.u64();
1334
+ if (localOffset === 4294967295) localOffset = x.u64();
1335
+ if (diskStart === 65535) diskStart = x.u32();
1336
+ }
1337
+ if (diskStart !== 0) throw invalid("Multi-disk zip archives are not supported.");
1338
+ const name = decodeName(rawName, flags, extra);
1339
+ if (flags & 65 || method === METHOD_AES) throw new require_errors.FormatError("ZIP_ENCRYPTED", `Entry ${excerpt(name)} is encrypted.`, { details: { entry: name } });
1340
+ if (method !== 0 && method !== 8) throw new require_errors.FormatError("ZIP_UNSUPPORTED_METHOD", `Entry ${excerpt(name)} uses compression method ${method}.`, { details: {
1341
+ entry: name,
1342
+ method
1343
+ } });
1344
+ if (method === 0 && compressedSize !== size) throw invalid(`Stored entry ${excerpt(name)} has mismatched sizes.`);
1345
+ if (byName.has(name)) throw invalid(`Duplicate entry name: ${excerpt(name)}`, { entry: name });
1346
+ const l = new Cursor(bytes, localOffset);
1347
+ if (localOffset + 30 > cdOffset || l.u32() !== SIG_LOCAL) throw invalid(`Bad local header for ${excerpt(name)}.`, { entry: name });
1348
+ l.u16();
1349
+ const lFlags = l.u16();
1350
+ const lMethod = l.u16();
1351
+ l.u16();
1352
+ l.u16();
1353
+ const lCrc = l.u32();
1354
+ const lCompressed = l.u32();
1355
+ const lSize = l.u32();
1356
+ const lNameLength = l.u16();
1357
+ const lExtraLength = l.u16();
1358
+ const lName = l.take(lNameLength);
1359
+ l.take(lExtraLength);
1360
+ let agrees = lNameLength === nameLength && lName.every((b, k) => b === rawName[k]) && lMethod === method && (lFlags & FLAG_ENCRYPTED) === 0;
1361
+ if (agrees && !(lFlags & FLAG_DATA_DESCRIPTOR)) agrees = lCrc === crc && (lCompressed === compressedSize || lCompressed === 4294967295) && (lSize === size || lSize === 4294967295);
1362
+ if (!agrees) throw invalid(`Local header disagrees with the central directory for ${excerpt(name)}.`, { entry: name });
1363
+ const dataOffset = l.pos;
1364
+ const dataEnd = dataOffset + compressedSize;
1365
+ if (dataEnd > cdOffset) throw invalid(`Data of ${excerpt(name)} runs into the central directory.`, { entry: name });
1366
+ spans.push({
1367
+ start: localOffset,
1368
+ end: dataEnd,
1369
+ name
1166
1370
  });
1167
- return out;
1371
+ const info = Object.freeze({
1372
+ name,
1373
+ method,
1374
+ flags,
1375
+ crc32: crc,
1376
+ compressedSize,
1377
+ size,
1378
+ modified: require_dos_time.fromDosDateTime(date, time),
1379
+ dataOffset
1380
+ });
1381
+ entries.push(info);
1382
+ byName.set(name, info);
1383
+ }
1384
+ spans.sort((a, b) => a.start - b.start);
1385
+ 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.`);
1386
+ let totalBytesRead = 0;
1387
+ const resolve = (entry) => {
1388
+ const info = typeof entry === "string" ? byName.get(entry) : entry;
1389
+ if (!info || byName.get(info.name) !== info) throw new Error(`No such zip entry: ${typeof entry === "string" ? entry : entry.name}`);
1390
+ return info;
1391
+ };
1392
+ const countTotal = (n) => {
1393
+ totalBytesRead += n;
1394
+ if (totalBytesRead > limits.maxTotalBytes) throw limitError("maxTotalBytes", totalBytesRead, limits.maxTotalBytes, "Total decompressed size");
1395
+ };
1396
+ async function* stream(entry, signal) {
1397
+ const info = resolve(entry);
1398
+ require_dos_time.throwIfAborted(signal);
1399
+ if (info.size > limits.maxEntryBytes) throw limitError("maxEntryBytes", info.size, limits.maxEntryBytes, `Entry ${excerpt(info.name)}`);
1400
+ const data = bytes.subarray(info.dataOffset, info.dataOffset + info.compressedSize);
1401
+ let crc = 0;
1402
+ let produced = 0;
1403
+ if (info.method === 0) {
1404
+ countTotal(data.length);
1405
+ for (let at = 0; at < data.length; at += STORED_CRC_STEP) {
1406
+ if (at > 0) require_dos_time.throwIfAborted(signal);
1407
+ crc = require_dos_time.crc32(data.subarray(at, at + STORED_CRC_STEP), crc);
1408
+ }
1409
+ produced = data.length;
1410
+ if (crc !== info.crc32) throw crcMismatch(info);
1411
+ yield data;
1412
+ return;
1413
+ }
1414
+ const chunks = codec.inflateRaw(data, {
1415
+ maxOutputBytes: limits.maxEntryBytes,
1416
+ maxRatio: limits.maxRatio
1417
+ }, signal);
1418
+ for await (const chunk of chunks) {
1419
+ produced += chunk.length;
1420
+ if (produced > info.size) throw invalid(`Entry ${excerpt(info.name)} is larger than declared.`, { entry: info.name });
1421
+ countTotal(chunk.length);
1422
+ crc = require_dos_time.crc32(chunk, crc);
1423
+ yield chunk;
1424
+ }
1425
+ if (produced !== info.size) throw invalid(`Entry ${excerpt(info.name)} is smaller than declared.`, { entry: info.name });
1426
+ if (crc !== info.crc32) throw crcMismatch(info);
1168
1427
  }
1169
- };
1170
- function stripSlash(name) {
1171
- return name.startsWith("/") ? name.slice(1) : name;
1428
+ return {
1429
+ entries,
1430
+ get: (name) => byName.get(name),
1431
+ stream,
1432
+ async read(entry, signal) {
1433
+ const parts = [];
1434
+ for await (const chunk of stream(entry, signal)) parts.push(chunk);
1435
+ return require_dos_time.concatBytes(parts);
1436
+ },
1437
+ get totalBytesRead() {
1438
+ return totalBytesRead;
1439
+ }
1440
+ };
1172
1441
  }
1173
- /** Resolves a relationship target against the source part's folder (RFC 3986 dot segments, '%xx' decoded). */
1174
- function resolveTarget(baseDir, target) {
1175
- let t = target;
1176
- const hash = t.indexOf("#");
1177
- if (hash !== -1) t = t.slice(0, hash);
1178
- try {
1179
- t = decodeURIComponent(t);
1180
- } catch {}
1181
- t = t.replace(/\\/g, "/");
1182
- const segments = t.startsWith("/") ? [] : baseDir.split("/").filter((s) => s !== "");
1183
- for (const seg of t.split("/")) {
1184
- if (seg === "" || seg === ".") continue;
1185
- if (seg === "..") segments.pop();
1186
- else segments.push(seg);
1187
- }
1188
- return segments.join("/");
1442
+ function crcMismatch(info) {
1443
+ return new require_errors.FormatError("ZIP_CRC_MISMATCH", `CRC-32 mismatch in ${excerpt(info.name)}.`, { details: { entry: info.name } });
1189
1444
  }
1190
1445
  // src/internal/read/formula.ts
1191
1446
  /**
@@ -1197,13 +1452,17 @@ function resolveTarget(baseDir, target) {
1197
1452
  * references, external workbook indexes) are copied unchanged. Returns
1198
1453
  * undefined when a shifted reference would leave the sheet, so the caller
1199
1454
  * keeps the cached value only.
1455
+ *
1456
+ * A master formula is scanned once (`compileFormula`) into the text between its
1457
+ * references and the references themselves; each cell that shares it then costs
1458
+ * its number of references plus the length of its own text (`shiftCompiled`),
1459
+ * and whether its references stay on the sheet is known in constant time
1460
+ * (`canShift`). Before JSE-62 every cell rescanned the master character by
1461
+ * character and built its text with `+=`, so N cells sharing a long formula
1462
+ * cost N times the master's length in time and much more in memory.
1200
1463
  */
1201
1464
  const MAX_ROW = 1048576;
1202
1465
  const MAX_COL = 16384;
1203
- const CELL = /\$?([A-Za-z]{1,3})\$?(\d{1,7})/y;
1204
- const CELL_PARTS = /^(\$?)([A-Za-z]{1,3})(\$?)(\d{1,7})$/;
1205
- const COLS = /(\$?)([A-Za-z]{1,3}):(\$?)([A-Za-z]{1,3})/y;
1206
- const ROWS = /(\$?)(\d{1,7}):(\$?)(\d{1,7})/y;
1207
1466
  function colNumber(letters) {
1208
1467
  let n = 0;
1209
1468
  for (let i = 0; i < letters.length; i++) n = n * 26 + (letters.toUpperCase().charCodeAt(i) - 64);
@@ -1218,110 +1477,482 @@ function colLetters(n) {
1218
1477
  }
1219
1478
  return s;
1220
1479
  }
1221
- function isWordChar(c) {
1222
- return c !== void 0 && /[A-Za-z0-9_.\\]/.test(c);
1480
+ /** A letter or digit, by character code (JSE-62: a regex test per character made long masters slow). */
1481
+ function isAlnumCode(c) {
1482
+ return c >= 48 && c <= 57 || c >= 65 && c <= 90 || c >= 97 && c <= 122;
1223
1483
  }
1224
- function shiftFormula(formula, dRow, dCol) {
1225
- if (dRow === 0 && dCol === 0) return formula;
1226
- let out = "";
1484
+ /** Part of a word: a letter, digit, `_`, `.` or `\\`. */
1485
+ function isWordCode(c) {
1486
+ return isAlnumCode(c) || c === 95 || c === 46 || c === 92;
1487
+ }
1488
+ /**
1489
+ * Excel's own limit on the length of a formula. A shared formula's master that
1490
+ * is longer is not expanded into the cells that share it (JSE-62): no
1491
+ * spreadsheet application writes one, and expanding it multiplied a few KB of
1492
+ * file into gigabytes.
1493
+ */
1494
+ const MAX_SHARED_FORMULA_LENGTH = 8192;
1495
+ /** Work done by the shifter, for the bounded-work tests (JSE-62). */
1496
+ const shiftWork = {
1497
+ compiles: 0,
1498
+ compiledChars: 0,
1499
+ shifts: 0,
1500
+ shiftedChars: 0
1501
+ };
1502
+ const COLS_REF = 0;
1503
+ const ROWS_REF = 1;
1504
+ const CELL_REF = 2;
1505
+ /**
1506
+ * Scans `formula` once, in time proportional to its length. With `boundsOnly`
1507
+ * only the relative bounds are kept (for `canShift`; no text can be built from
1508
+ * the result): what importDataset needs.
1509
+ */
1510
+ function compileFormula(formula, boundsOnly = false) {
1511
+ shiftWork.compiles++;
1512
+ shiftWork.compiledChars += formula.length;
1513
+ const segs = [];
1514
+ const refs = [];
1515
+ let rowMin = 1e400;
1516
+ let rowMax = -1e400;
1517
+ let colMin = 1e400;
1518
+ let colMax = -1e400;
1519
+ const relRow = (anchor, v) => {
1520
+ if (anchor === "$") return;
1521
+ if (v < rowMin) rowMin = v;
1522
+ if (v > rowMax) rowMax = v;
1523
+ };
1524
+ const relCol = (anchor, v) => {
1525
+ if (anchor === "$") return;
1526
+ if (v < colMin) colMin = v;
1527
+ if (v > colMax) colMax = v;
1528
+ };
1529
+ let segStart = 0;
1227
1530
  let i = 0;
1228
1531
  const n = formula.length;
1229
1532
  while (i < n) {
1230
- const ch = formula[i];
1231
- if (ch === "\"") {
1533
+ const code = formula.charCodeAt(i);
1534
+ if (code === 34 || code === 39) {
1232
1535
  let j = i + 1;
1233
- for (; j < n; j++) if (formula[j] === "\"") {
1234
- if (formula[j + 1] === "\"") j++;
1536
+ for (; j < n; j++) if (formula.charCodeAt(j) === code) {
1537
+ if (formula.charCodeAt(j + 1) === code) j++;
1235
1538
  else break;
1236
1539
  }
1237
- out += formula.slice(i, j + 1);
1238
1540
  i = j + 1;
1239
1541
  continue;
1240
1542
  }
1241
- if (ch === "'") {
1543
+ if (code === 91) {
1544
+ let depth = 0;
1545
+ let j = i;
1546
+ for (; j < n; j++) {
1547
+ const c = formula.charCodeAt(j);
1548
+ if (c === 91) depth++;
1549
+ else if (c === 93 && --depth === 0) break;
1550
+ }
1551
+ i = j + 1;
1552
+ continue;
1553
+ }
1554
+ const prev = i > 0 ? formula.charCodeAt(i - 1) : -1;
1555
+ if ((code === 36 || isAlnumCode(code)) && !isWordCode(prev) && prev !== 36) {
1556
+ const ref = parseRef$1(formula, i);
1557
+ if (ref) {
1558
+ const r = ref.ref;
1559
+ if (!boundsOnly) {
1560
+ segs.push(formula.slice(segStart, i));
1561
+ refs.push(r);
1562
+ }
1563
+ if (r.kind === COLS_REF) {
1564
+ relCol(r.aAnchor, r.a);
1565
+ relCol(r.bAnchor, r.b);
1566
+ } else if (r.kind === ROWS_REF) {
1567
+ relRow(r.aAnchor, r.a);
1568
+ relRow(r.bAnchor, r.b);
1569
+ } else {
1570
+ relCol(r.aAnchor, r.a);
1571
+ relRow(r.bAnchor, r.b);
1572
+ }
1573
+ i = segStart = ref.end;
1574
+ continue;
1575
+ }
1576
+ let j = i + 1;
1577
+ while (j < n && isWordCode(formula.charCodeAt(j))) j++;
1578
+ i = j;
1579
+ continue;
1580
+ }
1581
+ i++;
1582
+ }
1583
+ if (boundsOnly) return {
1584
+ source: formula,
1585
+ segs: [],
1586
+ slots: [],
1587
+ uniq: [],
1588
+ literalLength: 0,
1589
+ rowMin,
1590
+ rowMax,
1591
+ colMin,
1592
+ colMax
1593
+ };
1594
+ segs.push(formula.slice(segStart));
1595
+ const outSegs = [segs[0]];
1596
+ const slots = [];
1597
+ const uniq = [];
1598
+ const index = /* @__PURE__ */ new Map();
1599
+ for (let k = 0; k < refs.length; k++) {
1600
+ const r = refs[k];
1601
+ const next = segs[k + 1];
1602
+ if (r.aAnchor === "$" && r.bAnchor === "$") {
1603
+ outSegs[outSegs.length - 1] += refText(r, 0, 0) + next;
1604
+ continue;
1605
+ }
1606
+ const key = `${r.kind}${r.aAnchor}${r.a},${r.bAnchor}${r.b}`;
1607
+ let u = index.get(key);
1608
+ if (u === void 0) {
1609
+ u = uniq.length;
1610
+ uniq.push(r);
1611
+ index.set(key, u);
1612
+ }
1613
+ slots.push(u);
1614
+ outSegs.push(next);
1615
+ }
1616
+ let literalLength = 0;
1617
+ for (const t of outSegs) literalLength += t.length;
1618
+ return {
1619
+ source: formula,
1620
+ segs: outSegs,
1621
+ slots,
1622
+ uniq,
1623
+ literalLength,
1624
+ rowMin,
1625
+ rowMax,
1626
+ colMin,
1627
+ colMax
1628
+ };
1629
+ }
1630
+ /** Column letters, cached: shifted references format the same columns over and over. */
1631
+ const LETTERS = [];
1632
+ function letters(n) {
1633
+ return LETTERS[n] ??= colLetters(n);
1634
+ }
1635
+ /** The text of `r` shifted by (dRow, dCol); every relative part must stay on the sheet (canShift). */
1636
+ function refText(r, dRow, dCol) {
1637
+ if (r.kind === COLS_REF) return `${r.aAnchor}${letters(shiftPart(r.aAnchor, r.a, dCol, MAX_COL))}:${r.bAnchor}${letters(shiftPart(r.bAnchor, r.b, dCol, MAX_COL))}`;
1638
+ if (r.kind === ROWS_REF) return `${r.aAnchor}${shiftPart(r.aAnchor, r.a, dRow, MAX_ROW)}:${r.bAnchor}${shiftPart(r.bAnchor, r.b, dRow, MAX_ROW)}`;
1639
+ return `${r.aAnchor}${letters(shiftPart(r.aAnchor, r.a, dCol, MAX_COL))}${r.bAnchor}${shiftPart(r.bAnchor, r.b, dRow, MAX_ROW)}`;
1640
+ }
1641
+ /** Whether every relative reference of `c` stays on the sheet when shifted by (dRow, dCol). Constant time. */
1642
+ function canShift(c, dRow, dCol) {
1643
+ if (dRow === 0 && dCol === 0) return true;
1644
+ if (c.rowMin !== 1e400 && (c.rowMin + dRow < 1 || c.rowMax + dRow > MAX_ROW)) return false;
1645
+ if (c.colMin !== 1e400 && (c.colMin + dCol < 1 || c.colMax + dCol > MAX_COL)) return false;
1646
+ return true;
1647
+ }
1648
+ /**
1649
+ * The text of `c` shifted by (dRow, dCol), built once as a flat string; or,
1650
+ * when that text would be longer than `maxLength`, its length (nothing is
1651
+ * built). The caller checks `canShift` first.
1652
+ */
1653
+ function shiftCompiled(c, dRow, dCol, maxLength = 1e400) {
1654
+ if (dRow === 0 && dCol === 0) return c.source.length > maxLength ? c.source.length : c.source;
1655
+ const { segs, slots, uniq } = c;
1656
+ const texts = [];
1657
+ for (let u = 0; u < uniq.length; u++) texts.push(refText(uniq[u], dRow, dCol));
1658
+ let length = c.literalLength;
1659
+ for (let k = 0; k < slots.length; k++) length += texts[slots[k]].length;
1660
+ if (length > maxLength) return length;
1661
+ const parts = [segs[0]];
1662
+ for (let k = 0; k < slots.length; k++) parts.push(texts[slots[k]], segs[k + 1]);
1663
+ const out = parts.join("");
1664
+ shiftWork.shifts++;
1665
+ shiftWork.shiftedChars += out.length;
1666
+ return out;
1667
+ }
1668
+ /** The length of a copy shifted by (dRow, dCol), from formulaShape's `fixed` and partsOf's records; the offset must pass `canShift`. */
1669
+ function shiftedLength(fixed, parts, dRow, dCol) {
1670
+ let n = fixed;
1671
+ for (let i = 0; i < parts.length; i += 3) {
1672
+ const v = parts[i + 1] + (parts[i] ? dRow : dCol);
1673
+ n += parts[i + 2] * (parts[i] ? digitCount(v) : v <= 26 ? 1 : v <= 702 ? 2 : 3);
1674
+ }
1675
+ return n;
1676
+ }
1677
+ function digitCount(v) {
1678
+ let d = 1;
1679
+ while (v >= 10) {
1680
+ v = Math.floor(v / 10);
1681
+ d++;
1682
+ }
1683
+ return d;
1684
+ }
1685
+ /**
1686
+ * One pass over a master's text (JSE-71), allocating nothing per reference:
1687
+ * the relative bounds as compileFormula gives them, the range of a copy's
1688
+ * length and the characters that never change (the tests compute both from
1689
+ * the compiled formula too); with `collectParts`, the relative parts. It walks the text as
1690
+ * compileFormula does and recognises references as parseRef does (the tests
1691
+ * compare the two on seeded formulas), so a copy's text is the original's
1692
+ * with each reference re-printed as refText prints it.
1693
+ */
1694
+ function formulaShape(formula, collectParts) {
1695
+ let rowMin = 1e400;
1696
+ let rowMax = -1e400;
1697
+ let colMin = 1e400;
1698
+ let colMax = -1e400;
1699
+ let fixed = formula.length;
1700
+ let relCols = 0;
1701
+ let relRows = 0;
1702
+ const keys = [];
1703
+ const col = (anchored, v) => {
1704
+ if (anchored) fixed += 1 + (v <= 26 ? 1 : v <= 702 ? 2 : 3);
1705
+ else {
1706
+ relCols++;
1707
+ if (v < colMin) colMin = v;
1708
+ if (v > colMax) colMax = v;
1709
+ if (collectParts) keys.push(v * 2);
1710
+ }
1711
+ };
1712
+ const row = (anchored, v) => {
1713
+ if (anchored) fixed += 1 + digitCount(v);
1714
+ else {
1715
+ relRows++;
1716
+ if (v < rowMin) rowMin = v;
1717
+ if (v > rowMax) rowMax = v;
1718
+ if (collectParts) keys.push(v * 2 + 1);
1719
+ }
1720
+ };
1721
+ const n = formula.length;
1722
+ let i = 0;
1723
+ while (i < n) {
1724
+ const code = formula.charCodeAt(i);
1725
+ if (code === 34 || code === 39) {
1242
1726
  let j = i + 1;
1243
- for (; j < n; j++) if (formula[j] === "'") {
1244
- if (formula[j + 1] === "'") j++;
1727
+ for (; j < n; j++) if (formula.charCodeAt(j) === code) {
1728
+ if (formula.charCodeAt(j + 1) === code) j++;
1245
1729
  else break;
1246
1730
  }
1247
- out += formula.slice(i, j + 1);
1248
1731
  i = j + 1;
1249
1732
  continue;
1250
1733
  }
1251
- if (ch === "[") {
1734
+ if (code === 91) {
1252
1735
  let depth = 0;
1253
1736
  let j = i;
1254
- for (; j < n; j++) if (formula[j] === "[") depth++;
1255
- else if (formula[j] === "]" && --depth === 0) break;
1256
- out += formula.slice(i, j + 1);
1737
+ for (; j < n; j++) {
1738
+ const c = formula.charCodeAt(j);
1739
+ if (c === 91) depth++;
1740
+ else if (c === 93 && --depth === 0) break;
1741
+ }
1257
1742
  i = j + 1;
1258
1743
  continue;
1259
1744
  }
1260
- const prev = i > 0 ? formula[i - 1] : void 0;
1261
- if ((ch === "$" || /[A-Za-z0-9]/.test(ch)) && !isWordChar(prev) && prev !== "$") {
1262
- const shifted = tryRef(formula, i, dRow, dCol);
1263
- if (shifted === null) return void 0;
1264
- if (shifted !== void 0) {
1265
- out += shifted.text;
1266
- i = shifted.end;
1745
+ const prev = i > 0 ? formula.charCodeAt(i - 1) : -1;
1746
+ if ((code === 36 || isAlnumCode(code)) && !isWordCode(prev) && prev !== 36) {
1747
+ const end = refAt(formula, i);
1748
+ if (end >= 0) {
1749
+ fixed -= end - i;
1750
+ const r = REF;
1751
+ if (r.kind === COLS_REF) {
1752
+ col(r.aAnchored, r.a);
1753
+ col(r.bAnchored, r.b);
1754
+ fixed += 1;
1755
+ } else if (r.kind === ROWS_REF) {
1756
+ row(r.aAnchored, r.a);
1757
+ row(r.bAnchored, r.b);
1758
+ fixed += 1;
1759
+ } else {
1760
+ col(r.aAnchored, r.a);
1761
+ row(r.bAnchored, r.b);
1762
+ }
1763
+ i = end;
1267
1764
  continue;
1268
1765
  }
1269
1766
  let j = i + 1;
1270
- while (j < n && isWordChar(formula[j])) j++;
1271
- out += formula.slice(i, j);
1767
+ while (j < n && isWordCode(formula.charCodeAt(j))) j++;
1272
1768
  i = j;
1273
1769
  continue;
1274
1770
  }
1275
- out += ch;
1276
1771
  i++;
1277
1772
  }
1278
- return out;
1279
- }
1280
- /** A reference at `i`: { text, end }, undefined if there is none, null if shifting fails. */
1281
- function tryRef(f, i, dRow, dCol) {
1282
- const after = (end) => f[end];
1283
- const isEnd = (end) => {
1284
- const c = after(end);
1285
- return c === void 0 || !(isWordChar(c) || c === "(" || c === "!" || c === "$");
1773
+ return {
1774
+ rowMin,
1775
+ rowMax,
1776
+ colMin,
1777
+ colMax,
1778
+ min: fixed + relCols + relRows,
1779
+ max: fixed + 3 * relCols + 7 * relRows,
1780
+ fixed,
1781
+ keys
1286
1782
  };
1287
- COLS.lastIndex = i;
1288
- let m = COLS.exec(f);
1289
- if (m && isEnd(COLS.lastIndex)) {
1290
- const a = shiftPart(m[1], colNumber(m[2]), dCol, MAX_COL);
1291
- const b = shiftPart(m[3], colNumber(m[4]), dCol, MAX_COL);
1292
- if (colNumber(m[2]) > MAX_COL || colNumber(m[4]) > MAX_COL) return void 0;
1293
- if (a === void 0 || b === void 0) return null;
1294
- return {
1295
- text: `${m[1]}${colLetters(a)}:${m[3]}${colLetters(b)}`,
1296
- end: COLS.lastIndex
1297
- };
1783
+ }
1784
+ /** refAt's result, reused (formulaShape reads it before the next call). */
1785
+ const REF = {
1786
+ kind: CELL_REF,
1787
+ aAnchored: false,
1788
+ a: 0,
1789
+ bAnchored: false,
1790
+ b: 0
1791
+ };
1792
+ /** parseRef without allocating: the reference at `i` into REF and the index after it, or -1. */
1793
+ function refAt(f, i) {
1794
+ const n = f.length;
1795
+ const aAnchored = f.charCodeAt(i) === 36;
1796
+ const p = i + (aAnchored ? 1 : 0);
1797
+ let la = 0;
1798
+ while (la < 3 && p + la < n && isLetterCode(f.charCodeAt(p + la))) la++;
1799
+ let da = 0;
1800
+ if (la === 0) while (da < 7 && p + da < n && isDigitCode(f.charCodeAt(p + da))) da++;
1801
+ const first = la || da;
1802
+ if (first > 0 && f.charCodeAt(p + first) === 58) {
1803
+ const q = p + first + 1;
1804
+ const bAnchored = q < n && f.charCodeAt(q) === 36;
1805
+ const r = q + (bAnchored ? 1 : 0);
1806
+ let second = 0;
1807
+ if (la) while (second < 3 && r + second < n && isLetterCode(f.charCodeAt(r + second))) second++;
1808
+ else while (second < 7 && r + second < n && isDigitCode(f.charCodeAt(r + second))) second++;
1809
+ if (second > 0 && isEnd(f, r + second)) {
1810
+ if (la) {
1811
+ const a = colAt(f, p, la);
1812
+ const b = colAt(f, r, second);
1813
+ if (a > MAX_COL || b > MAX_COL) return -1;
1814
+ return setRef(COLS_REF, aAnchored, a, bAnchored, b, r + second);
1815
+ }
1816
+ return setRef(ROWS_REF, aAnchored, digitsAt(f, p, da), bAnchored, digitsAt(f, r, second), r + second);
1817
+ }
1298
1818
  }
1299
- ROWS.lastIndex = i;
1300
- m = ROWS.exec(f);
1301
- if (m && isEnd(ROWS.lastIndex)) {
1302
- const a = shiftPart(m[1], Number(m[2]), dRow, MAX_ROW);
1303
- const b = shiftPart(m[3], Number(m[4]), dRow, MAX_ROW);
1304
- if (a === void 0 || b === void 0) return null;
1305
- return {
1306
- text: `${m[1]}${a}:${m[3]}${b}`,
1307
- end: ROWS.lastIndex
1308
- };
1819
+ if (la > 0) {
1820
+ const q = p + la;
1821
+ const bAnchored = f.charCodeAt(q) === 36;
1822
+ const r = q + (bAnchored ? 1 : 0);
1823
+ let digits = 0;
1824
+ while (digits < 7 && r + digits < n && isDigitCode(f.charCodeAt(r + digits))) digits++;
1825
+ if (digits > 0 && isEnd(f, r + digits)) {
1826
+ const c = colAt(f, p, la);
1827
+ if (c > MAX_COL) return -1;
1828
+ return setRef(CELL_REF, aAnchored, c, bAnchored, digitsAt(f, r, digits), r + digits);
1829
+ }
1309
1830
  }
1310
- CELL.lastIndex = i;
1311
- m = CELL.exec(f);
1312
- if (m && isEnd(CELL.lastIndex)) {
1313
- const parts = CELL_PARTS.exec(m[0]);
1314
- const col = colNumber(parts[2]);
1315
- if (col > MAX_COL) return void 0;
1316
- const c = shiftPart(parts[1], col, dCol, MAX_COL);
1317
- const r = shiftPart(parts[3], Number(parts[4]), dRow, MAX_ROW);
1318
- if (c === void 0 || r === void 0) return null;
1319
- return {
1320
- text: `${parts[1]}${colLetters(c)}${parts[3]}${r}`,
1321
- end: CELL.lastIndex
1322
- };
1831
+ return -1;
1832
+ }
1833
+ function setRef(kind, aAnchored, a, bAnchored, b, end) {
1834
+ REF.kind = kind;
1835
+ REF.aAnchored = aAnchored;
1836
+ REF.a = a;
1837
+ REF.bAnchored = bAnchored;
1838
+ REF.b = b;
1839
+ return end;
1840
+ }
1841
+ /** formulaShape's keys as records: triples (isRow, value, count), one per distinct relative part. */
1842
+ /** partsOf's sort buffer, reused so that sorting allocates nothing. */
1843
+ let sortScratch = /* @__PURE__ */ new Int32Array(256);
1844
+ function partsOf(list) {
1845
+ if (sortScratch.length < list.length) sortScratch = new Int32Array(Math.max(list.length, 2 * sortScratch.length));
1846
+ const keys = sortScratch.subarray(0, list.length);
1847
+ keys.set(list);
1848
+ keys.sort();
1849
+ let distinct = 0;
1850
+ for (let i = 0; i < keys.length; i++) if (i === 0 || keys[i] !== keys[i - 1]) distinct++;
1851
+ const out = new Array(distinct * 3).fill(0);
1852
+ let o = -3;
1853
+ for (let i = 0; i < keys.length; i++) {
1854
+ const k = keys[i];
1855
+ if (i === 0 || k !== keys[i - 1]) {
1856
+ o += 3;
1857
+ out[o] = k & 1;
1858
+ out[o + 1] = Math.floor(k / 2);
1859
+ }
1860
+ out[o + 2] = out[o + 2] + 1;
1861
+ }
1862
+ return out;
1863
+ }
1864
+ /** Whether a reference may end before `end`: no word character, `(`, `!` or `$` follows. */
1865
+ /** colNumber(f.slice(at, at + n)) without the slice; `n` ASCII letters. */
1866
+ function colAt(f, at, n) {
1867
+ let v = 0;
1868
+ for (let k = 0; k < n; k++) v = v * 26 + ((f.charCodeAt(at + k) & -33) - 64);
1869
+ return v;
1870
+ }
1871
+ /** Number(f.slice(at, at + n)) without the slice; `n` (at most 7) ASCII digits. */
1872
+ function digitsAt(f, at, n) {
1873
+ let v = 0;
1874
+ for (let k = 0; k < n; k++) v = v * 10 + (f.charCodeAt(at + k) - 48);
1875
+ return v;
1876
+ }
1877
+ function isEnd(f, end) {
1878
+ if (end >= f.length) return true;
1879
+ const c = f.charCodeAt(end);
1880
+ return !(isWordCode(c) || c === 40 || c === 33 || c === 36);
1881
+ }
1882
+ /** A reference at `i`, or undefined if there is none. Does not depend on the offset. */
1883
+ function parseRef$1(f, i) {
1884
+ const n = f.length;
1885
+ const aAnchor = f.charCodeAt(i) === 36 ? "$" : "";
1886
+ const p = i + aAnchor.length;
1887
+ const la = run(f, p, isLetterCode, 3);
1888
+ const da = la === 0 ? run(f, p, isDigitCode, 7) : 0;
1889
+ const first = la || da;
1890
+ if (first > 0 && f.charCodeAt(p + first) === 58) {
1891
+ const q = p + first + 1;
1892
+ const bAnchor = q < n && f.charCodeAt(q) === 36 ? "$" : "";
1893
+ const r = q + bAnchor.length;
1894
+ const second = run(f, r, la ? isLetterCode : isDigitCode, la ? 3 : 7);
1895
+ if (second > 0 && isEnd(f, r + second)) {
1896
+ if (la) {
1897
+ const a = colNumber(f.slice(p, p + la));
1898
+ const b = colNumber(f.slice(r, r + second));
1899
+ if (a > MAX_COL || b > MAX_COL) return void 0;
1900
+ return {
1901
+ ref: {
1902
+ kind: COLS_REF,
1903
+ aAnchor,
1904
+ a,
1905
+ bAnchor,
1906
+ b
1907
+ },
1908
+ end: r + second
1909
+ };
1910
+ }
1911
+ return {
1912
+ ref: {
1913
+ kind: ROWS_REF,
1914
+ aAnchor,
1915
+ a: Number(f.slice(p, p + da)),
1916
+ bAnchor,
1917
+ b: Number(f.slice(r, r + second))
1918
+ },
1919
+ end: r + second
1920
+ };
1921
+ }
1922
+ }
1923
+ if (la > 0) {
1924
+ const q = p + la;
1925
+ const bAnchor = f.charCodeAt(q) === 36 ? "$" : "";
1926
+ const r = q + bAnchor.length;
1927
+ const digits = run(f, r, isDigitCode, 7);
1928
+ if (digits > 0 && isEnd(f, r + digits)) {
1929
+ const col = colNumber(f.slice(p, p + la));
1930
+ if (col > MAX_COL) return void 0;
1931
+ return {
1932
+ ref: {
1933
+ kind: CELL_REF,
1934
+ aAnchor,
1935
+ a: col,
1936
+ bAnchor,
1937
+ b: Number(f.slice(r, r + digits))
1938
+ },
1939
+ end: r + digits
1940
+ };
1941
+ }
1323
1942
  }
1324
1943
  }
1944
+ function isLetterCode(c) {
1945
+ return c >= 65 && c <= 90 || c >= 97 && c <= 122;
1946
+ }
1947
+ function isDigitCode(c) {
1948
+ return c >= 48 && c <= 57;
1949
+ }
1950
+ /** Length of the run of `test` characters at `i`, at most `max` (a longer run then fails on the character after: no pattern accepts it there). */
1951
+ function run(f, i, test, max) {
1952
+ let k = 0;
1953
+ while (k < max && i + k < f.length && test(f.charCodeAt(i + k))) k++;
1954
+ return k;
1955
+ }
1325
1956
  function shiftPart(anchor, value, delta, max) {
1326
1957
  if (anchor === "$") return value;
1327
1958
  const v = value + delta;
@@ -1991,7 +2622,10 @@ var SharedStringsParser = class {
1991
2622
  stopAfter;
1992
2623
  charge;
1993
2624
  maxText;
2625
+ keep;
1994
2626
  strings = [];
2627
+ /** Items decoded so far; with `keep` false, the only record of them (inspect, JSE-71). */
2628
+ count = 0;
1995
2629
  item;
1996
2630
  depth = 0;
1997
2631
  control;
@@ -1999,12 +2633,13 @@ var SharedStringsParser = class {
1999
2633
  * `stopAfter`: decode only the first `stopAfter` items, then jump to the
2000
2634
  * end of the part without tokenizing the rest (previews, ReadOptions.maxRows).
2001
2635
  */
2002
- constructor(mode, max, stopAfter = 1e400, charge = () => {}, maxText = 1e400) {
2636
+ constructor(mode, max, stopAfter = 1e400, charge = () => {}, maxText = 1e400, keep = true) {
2003
2637
  this.mode = mode;
2004
2638
  this.max = max;
2005
2639
  this.stopAfter = stopAfter;
2006
2640
  this.charge = charge;
2007
2641
  this.maxText = maxText;
2642
+ this.keep = keep;
2008
2643
  }
2009
2644
  attach(control) {
2010
2645
  this.control = control;
@@ -2012,8 +2647,10 @@ var SharedStringsParser = class {
2012
2647
  }
2013
2648
  /** True once stopAfter items were decoded and the rest of the part is skipped. */
2014
2649
  stopped = false;
2015
- pushed() {
2016
- if (this.strings.length >= this.stopAfter && !this.stopped && this.control) {
2650
+ push(item) {
2651
+ if (this.keep) this.strings.push(item);
2652
+ this.count++;
2653
+ if (this.count >= this.stopAfter && !this.stopped && this.control) {
2017
2654
  this.stopped = true;
2018
2655
  this.control.skipToEndOf(1);
2019
2656
  }
@@ -2030,15 +2667,13 @@ var SharedStringsParser = class {
2030
2667
  return;
2031
2668
  }
2032
2669
  if (name === "si") {
2033
- if (this.strings.length >= this.max) throw new require_errors.LimitError("LIMIT_EXCEEDED", `More than maxSharedStrings (${this.max}) shared strings.`, { details: {
2670
+ if (this.count >= this.max) throw new require_errors.LimitError("LIMIT_EXCEEDED", `More than maxSharedStrings (${this.max}) shared strings.`, { details: {
2034
2671
  limit: "maxSharedStrings",
2035
- value: this.strings.length + 1,
2672
+ value: this.count + 1,
2036
2673
  max: this.max
2037
2674
  } });
2038
- if (empty) {
2039
- this.strings.push("");
2040
- this.pushed();
2041
- } else {
2675
+ if (empty) this.push("");
2676
+ else {
2042
2677
  this.item = new StringItem(this.charge, this.maxText);
2043
2678
  this.depth = 0;
2044
2679
  }
@@ -2047,9 +2682,9 @@ var SharedStringsParser = class {
2047
2682
  close(name) {
2048
2683
  if (!this.item) return;
2049
2684
  if (this.depth === 0 && name === "si") {
2050
- this.strings.push(this.item.value(this.mode));
2685
+ const value = this.item.value(this.mode);
2051
2686
  this.item = void 0;
2052
- this.pushed();
2687
+ this.push(value);
2053
2688
  return;
2054
2689
  }
2055
2690
  this.depth--;
@@ -2117,6 +2752,34 @@ var DeferredStrings = class {
2117
2752
  }
2118
2753
  }
2119
2754
  };
2755
+ /** Bytes (UTF-8) of shared-formula masters a sheet keeps, at most, until a copy needs them (inspect, JSE-71). */
2756
+ const PENDING_TEXT = 8388608;
2757
+ /**
2758
+ * A shared formula's master as inspect keeps it (keepCells false, JSE-71):
2759
+ * numbers only, in one small object; the bounds are canShift's.
2760
+ */
2761
+ const UTF8 = new globalThis.TextEncoder();
2762
+ const UTF8_TEXT = new globalThis.TextDecoder();
2763
+ var LeanMaster = class {
2764
+ row;
2765
+ col;
2766
+ length;
2767
+ rowMin = 1e400;
2768
+ rowMax = -1e400;
2769
+ colMin = 1e400;
2770
+ colMax = -1e400;
2771
+ /** Whether every copy fits maxCellTextLength; `parts`, when set, decides per copy instead. */
2772
+ fits = false;
2773
+ fixed = 0;
2774
+ parts = void 0;
2775
+ /** The master's text, as UTF-8, until it is shaped (setLean); then undefined. */
2776
+ text = void 0;
2777
+ constructor(row, col, length) {
2778
+ this.row = row;
2779
+ this.col = col;
2780
+ this.length = length;
2781
+ }
2782
+ };
2120
2783
  /** Maximum digit width of Calibri 11 in pixels; the writer uses the same value (internal/write/sheet-features.ts). */
2121
2784
  const MAX_DIGIT_WIDTH = 7;
2122
2785
  /**
@@ -2200,6 +2863,7 @@ var SheetParser = class {
2200
2863
  colWork = 0;
2201
2864
  merges = [];
2202
2865
  hyperlinks = [];
2866
+ /** Shared formula masters by `si`; compiled when the first cell that shares one needs it. */
2203
2867
  shared = /* @__PURE__ */ new Map();
2204
2868
  view;
2205
2869
  print;
@@ -2223,6 +2887,20 @@ var SheetParser = class {
2223
2887
  maxCol = -1;
2224
2888
  truncated = false;
2225
2889
  control;
2890
+ /** opts.keepCells (default true). */
2891
+ keep;
2892
+ /** Cells kept (or, without keepCells, that would have been), as maxCells counts them. */
2893
+ cellCount = 0;
2894
+ /** Without keepCells: the shared-formula masters by si, their reference records, and the masters whose text is pending (setLean). */
2895
+ lean = /* @__PURE__ */ new Map();
2896
+ leanRecords = 0;
2897
+ pending = [];
2898
+ pendingHead = 0;
2899
+ /** Masters in `pending` that still wait (have text); the others are dropped by compactPending. */
2900
+ pendingLive = 0;
2901
+ pendingText = 0;
2902
+ /** Without keepCells: the rows that had properties, one bit per row (for counting each once, as `rowProps` does). */
2903
+ rowPropSeen;
2226
2904
  constructor(name, state, ctx, styles, opts, part) {
2227
2905
  this.ctx = ctx;
2228
2906
  this.styles = styles;
@@ -2233,6 +2911,7 @@ var SheetParser = class {
2233
2911
  rows: this.rows
2234
2912
  };
2235
2913
  if (state && state !== "visible") this.sheet.state = state;
2914
+ this.keep = opts.keepCells !== false;
2236
2915
  }
2237
2916
  attach(control) {
2238
2917
  this.control = control;
@@ -2278,7 +2957,7 @@ var SheetParser = class {
2278
2957
  const ref = a.get("ref");
2279
2958
  if (ref) {
2280
2959
  this.ctx.charge(1);
2281
- this.merges.push(cleanRange(ref));
2960
+ if (this.keep) this.merges.push(cleanRange(ref));
2282
2961
  }
2283
2962
  return;
2284
2963
  }
@@ -2286,7 +2965,7 @@ var SheetParser = class {
2286
2965
  if (parent === "hyperlinks") {
2287
2966
  const ref = a.get("ref");
2288
2967
  if (ref) this.ctx.charge(1);
2289
- if (ref) this.hyperlinks.push({
2968
+ if (ref && (this.keep || this.mayBeTooWide(ref))) this.hyperlinks.push({
2290
2969
  ref: cleanRange(ref),
2291
2970
  relId: a.getPrefixed("id"),
2292
2971
  location: a.get("location"),
@@ -2303,7 +2982,7 @@ var SheetParser = class {
2303
2982
  case "selection":
2304
2983
  if (parent === "sheetView" && this.viewCount === 1) {
2305
2984
  this.ctx.charge(1);
2306
- this.selections.push({
2985
+ if (this.keep) this.selections.push({
2307
2986
  pane: a.get("pane"),
2308
2987
  activeCell: a.get("activeCell"),
2309
2988
  sqref: a.get("sqref")
@@ -2464,6 +3143,13 @@ var SheetParser = class {
2464
3143
  if (st) p.style = st;
2465
3144
  }
2466
3145
  if (Object.keys(p).length) {
3146
+ if (!this.keep) {
3147
+ const seen = this.rowPropSeen ??= /* @__PURE__ */ new Uint8Array(131072);
3148
+ const bit = 1 << (this.curRow & 7);
3149
+ if (!(seen[this.curRow >> 3] & bit)) this.ctx.charge(1);
3150
+ seen[this.curRow >> 3] |= bit;
3151
+ return;
3152
+ }
2467
3153
  if (this.rowProps[this.curRow] === void 0) this.ctx.charge(1);
2468
3154
  this.rowProps[this.curRow] = p;
2469
3155
  }
@@ -2626,7 +3312,14 @@ var SheetParser = class {
2626
3312
  if (p.row < 0) return;
2627
3313
  const cell = this.convert(p);
2628
3314
  if (!cell) return;
3315
+ if (p.col >= this.ctx.limits.maxColumns) this.tooWide(p.col, p.ref);
2629
3316
  this.ctx.countCell();
3317
+ this.cellCount++;
3318
+ if (!this.keep) {
3319
+ this.pendingIndex = -1;
3320
+ this.extend(p.row, p.col);
3321
+ return;
3322
+ }
2630
3323
  let row = this.rows[p.row];
2631
3324
  if (!row) row = this.rows[p.row] = [];
2632
3325
  if (row[p.col] !== void 0) this.ctx.warn("DUPLICATE_CELL", `Cell ${p.ref} appears more than once; the last one was kept.`, {
@@ -2647,10 +3340,33 @@ var SheetParser = class {
2647
3340
  if (this.pendingIndex > d.maxIndex) d.maxIndex = this.pendingIndex;
2648
3341
  this.pendingIndex = -1;
2649
3342
  }
2650
- if (p.row < this.minRow) this.minRow = p.row;
2651
- if (p.row > this.maxRow) this.maxRow = p.row;
2652
- if (p.col < this.minCol) this.minCol = p.col;
2653
- if (p.col > this.maxCol) this.maxCol = p.col;
3343
+ this.extend(p.row, p.col);
3344
+ }
3345
+ /** Widens the sheet's dimension to a kept cell. */
3346
+ extend(row, col) {
3347
+ if (row < this.minRow) this.minRow = row;
3348
+ if (row > this.maxRow) this.maxRow = row;
3349
+ if (col < this.minCol) this.minCol = col;
3350
+ if (col > this.maxCol) this.maxCol = col;
3351
+ }
3352
+ /** Without keepCells: whether a hyperlink on `ref` could fail maxColumns when the sheet is finished (attachHyperlink). */
3353
+ mayBeTooWide(ref) {
3354
+ const pos = parseRef(cleanRange(ref).split(":")[0]);
3355
+ return pos !== void 0 && pos[1] >= this.ctx.limits.maxColumns;
3356
+ }
3357
+ /**
3358
+ * A kept cell in a column past maxColumns (JSE-68). Counted on the cells the
3359
+ * sheet actually has, as each is kept, never on `<dimension>`.
3360
+ */
3361
+ tooWide(col, ref) {
3362
+ const max = this.ctx.limits.maxColumns;
3363
+ throw new require_errors.LimitError("LIMIT_EXCEEDED", `Sheet "${excerpt(this.sheet.name)}" has a cell in column ${colLetters(col + 1)} (${col + 1}); maxColumns is ${max}.`, { details: {
3364
+ limit: "maxColumns",
3365
+ value: col + 1,
3366
+ max,
3367
+ part: this.part,
3368
+ ref
3369
+ } });
2654
3370
  }
2655
3371
  convert(p) {
2656
3372
  const style = this.styles.style(p.s);
@@ -2671,8 +3387,10 @@ var SheetParser = class {
2671
3387
  break;
2672
3388
  }
2673
3389
  const sst = this.sharedStrings;
2674
- const str = Number.isInteger(idx) && idx >= 0 ? sst[idx] : void 0;
3390
+ const count = this.sharedStringCount;
3391
+ const str = Number.isInteger(idx) && idx >= 0 ? count === void 0 ? sst[idx] : idx < count ? "" : void 0 : void 0;
2675
3392
  if (str === void 0) {
3393
+ if (p.col >= this.ctx.limits.maxColumns) this.tooWide(p.col, p.ref);
2676
3394
  this.ctx.warn("INVALID_SHARED_STRING", `Cell ${p.ref} refers to shared string ${excerpt(v)}, which does not exist; the cell was left empty.`, {
2677
3395
  part: this.part,
2678
3396
  sheet: this.sheet.name,
@@ -2772,25 +3490,38 @@ var SheetParser = class {
2772
3490
  formula(p) {
2773
3491
  if (p.f === void 0 || !this.opts.formulas) return void 0;
2774
3492
  if (p.fType === "shared" && p.fSi !== void 0) {
3493
+ if (!this.keep) return this.leanFormula(p);
2775
3494
  if (p.f !== "") {
2776
3495
  this.shared.set(p.fSi, {
2777
3496
  formula: p.f,
2778
3497
  row: p.row,
2779
- col: p.col
3498
+ col: p.col,
3499
+ ref: p.ref,
3500
+ compiled: void 0
2780
3501
  });
2781
3502
  return { text: p.f };
2782
3503
  }
2783
3504
  const master = this.shared.get(p.fSi);
2784
- const shifted = master ? shiftFormula(master.formula, p.row - master.row, p.col - master.col) : void 0;
2785
- if (shifted === void 0) {
2786
- this.ctx.warn("SHARED_FORMULA_UNRESOLVED", `The shared formula of cell ${p.ref} could not be resolved; only its cached value was read.`, {
2787
- part: this.part,
2788
- sheet: this.sheet.name,
2789
- ref: p.ref
2790
- });
3505
+ const masterText = this.opts.sharedFormulaText === "master";
3506
+ if (master && !masterText && master.formula.length > 8192) {
3507
+ this.unresolved(p, `: its master formula in cell ${master.ref} has ${master.formula.length} characters, more than Excel's limit of ${MAX_SHARED_FORMULA_LENGTH}`);
3508
+ return;
3509
+ }
3510
+ const dRow = master ? p.row - master.row : 0;
3511
+ const dCol = master ? p.col - master.col : 0;
3512
+ const compiled = master && (dRow !== 0 || dCol !== 0) ? master.compiled ??= compileFormula(master.formula, masterText) : void 0;
3513
+ if (!master || compiled && !canShift(compiled, dRow, dCol)) {
3514
+ this.unresolved(p, "");
3515
+ return;
3516
+ }
3517
+ if (!compiled || masterText) return { text: master.formula };
3518
+ const max = this.ctx.limits.maxCellTextLength;
3519
+ const text = shiftCompiled(compiled, dRow, dCol, max);
3520
+ if (typeof text === "number") {
3521
+ this.unresolved(p, `: shifted, it would have ${text} characters, more than maxCellTextLength (${max})`);
2791
3522
  return;
2792
3523
  }
2793
- return { text: shifted };
3524
+ return { text };
2794
3525
  }
2795
3526
  if (p.fType === "dataTable") return void 0;
2796
3527
  if (p.f === "") return void 0;
@@ -2800,8 +3531,142 @@ var SheetParser = class {
2800
3531
  };
2801
3532
  return { text: p.f };
2802
3533
  }
3534
+ /**
3535
+ * keepCells false (JSE-71): a shared formula decided as formula() decides
3536
+ * it, in the same order, from a LeanMaster instead of the master's text.
3537
+ * Only whether the cell has a formula matters here, so a resolved one
3538
+ * returns an empty text.
3539
+ */
3540
+ leanFormula(p) {
3541
+ const si = p.fSi;
3542
+ if (p.f !== "") {
3543
+ this.setLean(si, p);
3544
+ return { text: "" };
3545
+ }
3546
+ const m = this.lean.get(si);
3547
+ if (m && m.length > 8192) {
3548
+ this.unresolved(p, `: its master formula in cell ${colLetters(m.col + 1)}${m.row + 1} has ${m.length} characters, more than Excel's limit of ${MAX_SHARED_FORMULA_LENGTH}`);
3549
+ return;
3550
+ }
3551
+ if (!m) {
3552
+ this.unresolved(p, "");
3553
+ return;
3554
+ }
3555
+ const dRow = p.row - m.row;
3556
+ const dCol = p.col - m.col;
3557
+ if (dRow === 0 && dCol === 0) return { text: "" };
3558
+ if (m.text !== void 0) this.shape(m, p);
3559
+ if (!canShift(m, dRow, dCol)) {
3560
+ this.unresolved(p, "");
3561
+ return;
3562
+ }
3563
+ const max = this.ctx.limits.maxCellTextLength;
3564
+ if (m.parts ? shiftedLength(m.fixed, m.parts, dRow, dCol) <= max : m.fits) return { text: "" };
3565
+ this.unresolved(p, `: shifted, it would have more than maxCellTextLength (${max}) characters`);
3566
+ }
3567
+ /**
3568
+ * Keeps a master as a LeanMaster. Its text is kept only until a copy needs
3569
+ * it (as read compiles a master only then), and only while the text pending
3570
+ * on this sheet is at most PENDING_TEXT characters; past that, the oldest
3571
+ * pending masters are shaped and their text dropped. Shaping (formula.ts
3572
+ * formulaShape) keeps numbers only: the bounds, and whether copies fit
3573
+ * maxCellTextLength from the range of lengths a copy can have, or, when the
3574
+ * limit falls inside that range, records of the relative parts (partsOf).
3575
+ * Every live master (one per si: a redefinition replaces it, its pending
3576
+ * text and its records) and every record counts against maxItems (budget()).
3577
+ */
3578
+ setLean(si, p) {
3579
+ const f = p.f;
3580
+ const old = this.lean.get(si);
3581
+ if (old) this.release(old);
3582
+ const m = new LeanMaster(p.row, p.col, f.length);
3583
+ this.lean.set(si, m);
3584
+ if (f.length <= 8192) {
3585
+ m.text = f.length > 12 ? UTF8.encode(f) : (" " + f).slice(1);
3586
+ this.pendingText += m.text.length;
3587
+ this.pending.push(m);
3588
+ this.pendingLive++;
3589
+ while (this.pendingText > PENDING_TEXT) {
3590
+ const next = this.pending[this.pendingHead++];
3591
+ if (next.text !== void 0) this.shape(next, p);
3592
+ }
3593
+ this.compactPending();
3594
+ }
3595
+ this.budget(p);
3596
+ }
3597
+ /** A master's numbers from its text, which is then dropped (setLean). */
3598
+ shape(m, p) {
3599
+ const bytes = m.text;
3600
+ m.text = void 0;
3601
+ this.pendingText -= bytes.length;
3602
+ this.pendingLive--;
3603
+ const f = typeof bytes === "string" ? bytes : UTF8_TEXT.decode(bytes);
3604
+ const limit = this.ctx.limits.maxCellTextLength;
3605
+ const shape = formulaShape(f, 7 * f.length > limit);
3606
+ if (shape.min <= limit && shape.max > limit) {
3607
+ m.parts = partsOf(shape.keys);
3608
+ this.leanRecords += m.parts.length / 3;
3609
+ }
3610
+ m.rowMin = shape.rowMin;
3611
+ m.rowMax = shape.rowMax;
3612
+ m.colMin = shape.colMin;
3613
+ m.colMax = shape.colMax;
3614
+ m.fixed = shape.fixed;
3615
+ m.fits = shape.max <= limit;
3616
+ if (m.parts) this.budget(p);
3617
+ }
3618
+ /** A replaced master: its pending text and its records no longer count. */
3619
+ release(m) {
3620
+ if (m.text !== void 0) {
3621
+ this.pendingText -= m.text.length;
3622
+ this.pendingLive--;
3623
+ m.text = void 0;
3624
+ }
3625
+ if (m.parts) this.leanRecords -= m.parts.length / 3;
3626
+ m.parts = void 0;
3627
+ }
3628
+ /**
3629
+ * Drops the masters that no longer wait (shaped, or replaced by a
3630
+ * redefinition) from `pending` once they outnumber the waiting ones, so a
3631
+ * replaced master is unreachable and nothing is kept per redefinition.
3632
+ * Amortised constant time per master.
3633
+ */
3634
+ compactPending() {
3635
+ if (this.pending.length - this.pendingHead <= 2 * this.pendingLive + 64) return;
3636
+ const live = [];
3637
+ for (let i = this.pendingHead; i < this.pending.length; i++) if (this.pending[i].text !== void 0) live.push(this.pending[i]);
3638
+ this.pending = live;
3639
+ this.pendingHead = 0;
3640
+ }
3641
+ /**
3642
+ * inspect's own budget, the one documented exception to "the same error as
3643
+ * read" (docs/api.md §5.2.1): live masters and reference records, with the
3644
+ * items the read built besides cells, may not pass maxItems.
3645
+ */
3646
+ budget(p) {
3647
+ const most = this.ctx.limits.maxItems;
3648
+ if (this.ctx.items + this.lean.size + this.leanRecords <= most) return;
3649
+ throw new require_errors.LimitError("LIMIT_EXCEEDED", `Sheet "${excerpt(this.sheet.name)}": its shared formulas need more than maxItems (${most}) masters and reference records, with the items the read built besides cells, to be checked without their text.`, { details: {
3650
+ limit: "maxItems",
3651
+ value: most + 1,
3652
+ max: most,
3653
+ part: this.part,
3654
+ ref: p.ref,
3655
+ sharedFormulaMasters: this.lean.size,
3656
+ sharedFormulaReferences: this.leanRecords
3657
+ } });
3658
+ }
3659
+ unresolved(p, why) {
3660
+ this.ctx.warn("SHARED_FORMULA_UNRESOLVED", `The shared formula of cell ${p.ref} could not be resolved${why}; only its cached value was read.`, {
3661
+ part: this.part,
3662
+ sheet: this.sheet.name,
3663
+ ref: p.ref
3664
+ });
3665
+ }
2803
3666
  /** Set before parsing; the shared strings table. */
2804
3667
  sharedStrings = [];
3668
+ /** Set instead of `sharedStrings` when they were counted, not kept (inspect, JSE-71). */
3669
+ sharedStringCount;
2805
3670
  /** When set, shared-string cells are collected here and filled in later (ReadOptions.maxRows). */
2806
3671
  deferred;
2807
3672
  openView(a) {
@@ -2934,29 +3799,378 @@ var SheetParser = class {
2934
3799
  sheet: this.sheet.name,
2935
3800
  ref: h.ref
2936
3801
  });
2937
- let link;
2938
- if (h.relId) {
2939
- const rel = rels.get(h.relId);
2940
- if (rel) {
2941
- const target = h.location ? `${rel.target}#${h.location}` : rel.target;
2942
- link = h.tooltip !== void 0 ? {
2943
- target,
2944
- tooltip: h.tooltip
2945
- } : { target };
3802
+ let link;
3803
+ if (h.relId) {
3804
+ const rel = rels.get(h.relId);
3805
+ if (rel) {
3806
+ const target = h.location ? `${rel.target}#${h.location}` : rel.target;
3807
+ link = h.tooltip !== void 0 ? {
3808
+ target,
3809
+ tooltip: h.tooltip
3810
+ } : { target };
3811
+ }
3812
+ } else if (h.location !== void 0) link = h.tooltip !== void 0 ? {
3813
+ location: h.location,
3814
+ tooltip: h.tooltip
3815
+ } : { location: h.location };
3816
+ if (!link) return;
3817
+ const [r, c] = pos;
3818
+ if (r >= 1048576 || c >= 16384) return;
3819
+ if (c >= this.ctx.limits.maxColumns) this.tooWide(c, `${colLetters(c + 1)}${r + 1}`);
3820
+ if (!this.keep) return;
3821
+ let row = this.rows[r];
3822
+ if (!row) row = this.rows[r] = [];
3823
+ const cell = row[c] ?? (row[c] = { type: "empty" });
3824
+ cell.hyperlink = link;
3825
+ }
3826
+ };
3827
+ // src/internal/read/scan.ts
3828
+ /**
3829
+ * The package scan (JSE-72): walks the whole relationship graph from the
3830
+ * package root and classifies every part the model does not represent, and
3831
+ * lists the parts no relationship reaches. `read` uses it; it is kept in one
3832
+ * function so that other entry points can reuse it. Internal.
3833
+ */
3834
+ /**
3835
+ * Relationship kinds (the type URI's last segment) of parts the model does not
3836
+ * represent, with the words the UNSUPPORTED_PART message uses for them.
3837
+ */
3838
+ const UNSUPPORTED_RELATIONSHIPS = /* @__PURE__ */ new Map([
3839
+ ["drawing", "drawings (charts, images, shapes)"],
3840
+ ["vmlDrawing", "legacy drawings (VML)"],
3841
+ ["comments", "comments"],
3842
+ ["threadedComment", "threaded comments"],
3843
+ ["pivotTable", "pivot tables"],
3844
+ ["pivotCacheDefinition", "pivot caches"],
3845
+ ["table", "tables (ListObjects)"],
3846
+ ["oleObject", "embedded OLE objects"],
3847
+ ["ctrlProp", "form controls"],
3848
+ ["image", "images"],
3849
+ ["vbaProject", "VBA macros"],
3850
+ ["externalLink", "external links"],
3851
+ ["connections", "data connections"],
3852
+ ["queryTable", "query tables"],
3853
+ ["slicer", "slicers"],
3854
+ ["slicerCache", "slicer caches"],
3855
+ ["timeline", "timelines"],
3856
+ ["chartsheet", "chart sheets"],
3857
+ ["dialogsheet", "dialog sheets"],
3858
+ ["macrosheet", "macro sheets"]
3859
+ ]);
3860
+ /** Words for the kinds the scan adds (since 2.5). `unreferencedPart` has its own message. */
3861
+ const SCANNED_KINDS = /* @__PURE__ */ new Map([
3862
+ ["activeX", "ActiveX controls"],
3863
+ ["embeddedPackage", "embedded packages (files such as documents embedded in the workbook)"],
3864
+ ["customUI", "custom ribbon UI (customUI)"],
3865
+ ["webExtension", "Office web add-ins"]
3866
+ ]);
3867
+ /**
3868
+ * Relationship kinds, lower case (relationship types compare
3869
+ * case-insensitively), that name a kind other than their own last segment.
3870
+ */
3871
+ const RELATIONSHIP_ALIASES = /* @__PURE__ */ new Map([
3872
+ ["control", "activeX"],
3873
+ ["activexcontrolbinary", "activeX"],
3874
+ ["package", "embeddedPackage"],
3875
+ ["xlmacrosheet", "macrosheet"],
3876
+ ["xlintlmacrosheet", "macrosheet"],
3877
+ ["webextensiontaskpanes", "webExtension"],
3878
+ ["webextension", "webExtension"],
3879
+ ["attachedtoolbars", "vbaProject"],
3880
+ ["vbaprojectsignature", "vbaProject"],
3881
+ ["vbaprojectsignatureagile", "vbaProject"],
3882
+ ["vbaprojectsignaturev3", "vbaProject"],
3883
+ ["wordvbadata", "vbaProject"]
3884
+ ]);
3885
+ /** UNSUPPORTED_RELATIONSHIPS keyed by lower-case kind. */
3886
+ const RELATIONSHIP_KINDS = new Map([...UNSUPPORTED_RELATIONSHIPS.keys()].map((k) => [k.toLowerCase(), k]));
3887
+ /**
3888
+ * Content types (lower case) of active or embedded content: a part with one
3889
+ * of these is reported as its kind whatever relationship reaches it.
3890
+ */
3891
+ const CONTENT_TYPES = /* @__PURE__ */ new Map([
3892
+ ["application/vnd.ms-office.activex+xml", "activeX"],
3893
+ ["application/vnd.ms-office.activex", "activeX"],
3894
+ ["application/vnd.openxmlformats-officedocument.oleobject", "oleObject"],
3895
+ ["application/vnd.ms-office.oleobject", "oleObject"],
3896
+ ["application/vnd.ms-office.vbaproject", "vbaProject"],
3897
+ ["application/vnd.ms-office.vbaprojectsignature", "vbaProject"],
3898
+ ["application/vnd.ms-excel.attachedtoolbars", "vbaProject"],
3899
+ ["application/vnd.ms-excel.macrosheet+xml", "macrosheet"],
3900
+ ["application/vnd.ms-excel.intlmacrosheet+xml", "macrosheet"],
3901
+ ["application/vnd.ms-office.webextension+xml", "webExtension"],
3902
+ ["application/vnd.ms-office.webextensiontaskpanes+xml", "webExtension"],
3903
+ ["application/vnd.openxmlformats-officedocument.wordprocessingml.document", "embeddedPackage"],
3904
+ ["application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "embeddedPackage"],
3905
+ ["application/vnd.openxmlformats-officedocument.presentationml.presentation", "embeddedPackage"],
3906
+ ["application/vnd.openxmlformats-officedocument.presentationml.slideshow", "embeddedPackage"],
3907
+ ["application/vnd.ms-word.document.macroenabled.12", "embeddedPackage"],
3908
+ ["application/vnd.ms-excel.sheet.macroenabled.12", "embeddedPackage"],
3909
+ ["application/vnd.ms-excel.sheet.binary.macroenabled.12", "embeddedPackage"],
3910
+ ["application/vnd.ms-powerpoint.presentation.macroenabled.12", "embeddedPackage"],
3911
+ ["application/vnd.ms-powerpoint.slideshow.macroenabled.12", "embeddedPackage"],
3912
+ ["application/vnd.openxmlformats-officedocument.spreadsheetml.template", "embeddedPackage"],
3913
+ ["application/vnd.openxmlformats-officedocument.wordprocessingml.template", "embeddedPackage"],
3914
+ ["application/vnd.openxmlformats-officedocument.presentationml.template", "embeddedPackage"],
3915
+ ["application/vnd.openxmlformats-officedocument.presentationml.slide", "embeddedPackage"],
3916
+ ["application/vnd.ms-excel.template.macroenabled.12", "embeddedPackage"],
3917
+ ["application/vnd.ms-excel.addin.macroenabled.12", "embeddedPackage"],
3918
+ ["application/vnd.ms-word.template.macroenabled.12", "embeddedPackage"],
3919
+ ["application/vnd.ms-powerpoint.template.macroenabled.12", "embeddedPackage"],
3920
+ ["application/vnd.ms-powerpoint.slide.macroenabled.12", "embeddedPackage"],
3921
+ ["application/vnd.ms-powerpoint.addin.macroenabled.12", "embeddedPackage"]
3922
+ ]);
3923
+ /**
3924
+ * Kinds `read` reports wherever the scan finds them: on any sheet (also one
3925
+ * left out by `sheets`) and under any part (a drawing, a table, ...). These are
3926
+ * active or embedded content and links out of the file. The other kinds
3927
+ * (drawings, images, comments, tables, pivots, ...) are reported, as before
3928
+ * 2.5, from the workbook's and the read sheets' own relationships only.
3929
+ */
3930
+ const REPORTED_ANYWHERE = /* @__PURE__ */ new Set([
3931
+ "activeX",
3932
+ "embeddedPackage",
3933
+ "customUI",
3934
+ "oleObject",
3935
+ "vbaProject",
3936
+ "externalLink",
3937
+ "connections",
3938
+ "queryTable",
3939
+ "macrosheet",
3940
+ "webExtension"
3941
+ ]);
3942
+ /**
3943
+ * The kind a relationship names, by its type alone: the last segment of the
3944
+ * type URI, compared without regard to case, or an alias (RELATIONSHIP_ALIASES).
3945
+ * customUI is matched on the whole type (`.../ui/extensibility`).
3946
+ */
3947
+ function relationshipKindOf(rel) {
3948
+ const kind = rel.kind.toLowerCase();
3949
+ if (kind === "extensibility" && /\/ui\/extensibility$/i.test(rel.type)) return "customUI";
3950
+ return RELATIONSHIP_ALIASES.get(kind) ?? RELATIONSHIP_KINDS.get(kind);
3951
+ }
3952
+ /**
3953
+ * What a relationship and its target's content type make of a part; undefined
3954
+ * for parts the model reads or that need no report. A kind in REPORTED_ANYWHERE
3955
+ * wins: an active content type behind a passive or unknown relationship (an
3956
+ * `image` relationship to an OLE object) is reported by its content type.
3957
+ */
3958
+ function partKindOf(rel, contentTypes) {
3959
+ const byRel = relationshipKindOf(rel);
3960
+ if (byRel !== void 0 && REPORTED_ANYWHERE.has(byRel)) return byRel;
3961
+ for (const t of contentTypes) {
3962
+ const byType = CONTENT_TYPES.get(t.toLowerCase().split(";")[0].trim());
3963
+ if (byType) return byType;
3964
+ }
3965
+ return byRel;
3966
+ }
3967
+ /**
3968
+ * Walks the relationship graph of `pkg` from the package root, breadth first.
3969
+ * Reads only relationships parts (each at most once per read, through the
3970
+ * zip and XML limits of `pkg.ctx`, without marking them consumed) and the
3971
+ * content types already loaded; never inflates the parts it classifies.
3972
+ * A target OPC forbids is followed both as a decoder reads it and literally,
3973
+ * so content behind it is found either way. Consults the signal per part and
3974
+ * every 4,096 relationships or zip entries. A relationships part that is not
3975
+ * well-formed XML is treated as unreferenced instead of failing the read;
3976
+ * limit and DTD errors are thrown as anywhere else.
3977
+ */
3978
+ async function scanPackageParts(pkg) {
3979
+ const ctx = pkg.ctx;
3980
+ const found = [];
3981
+ const foundKeys = /* @__PURE__ */ new Set();
3982
+ const forbidden = new Set(pkg.forbiddenNames);
3983
+ /** partKey of the parts accounted for (reached from the package root). */
3984
+ const reached = /* @__PURE__ */ new Set([partKey("[Content_Types].xml")]);
3985
+ /** partKey of the parts whose relationships are queued: a part reached as a target is queued even if it was accounted for otherwise (a relationships part, [Content_Types].xml). */
3986
+ const queued = /* @__PURE__ */ new Set([""]);
3987
+ /** Relationships parts parsed, by partKey. */
3988
+ const parsed = /* @__PURE__ */ new Set();
3989
+ const queue = [{
3990
+ source: "",
3991
+ counts: true
3992
+ }];
3993
+ const visit = (target, counts) => {
3994
+ const entry = pkg.part(target);
3995
+ if (!entry) return;
3996
+ const key = pkg.keyOf(entry);
3997
+ if (counts) reached.add(key);
3998
+ if (queued.has(key)) return;
3999
+ queued.add(key);
4000
+ queue.push({
4001
+ source: entry.name,
4002
+ counts
4003
+ });
4004
+ };
4005
+ const classify = (rel, source, relsPart) => {
4006
+ const targets = rel.external || rel.tooLong || rel.target === "" ? [] : rel.altTarget === void 0 ? [rel.target] : [rel.target, rel.altTarget];
4007
+ for (const target of targets.length ? targets : [void 0]) {
4008
+ const kind = partKindOf(rel, target === void 0 ? [] : pkg.contentTypes(target));
4009
+ if (!kind) continue;
4010
+ const part = target ?? (rel.external ? source || relsPart : relsPart);
4011
+ const key = `${kind}\u0000${partKey(part)}`;
4012
+ if (foundKeys.has(key)) continue;
4013
+ foundKeys.add(key);
4014
+ found.push({
4015
+ kind,
4016
+ part,
4017
+ source,
4018
+ external: rel.external
4019
+ });
4020
+ }
4021
+ };
4022
+ const drain = async () => {
4023
+ for (let q = 0; q < queue.length; q++) {
4024
+ const pause = ctx.step();
4025
+ if (pause) await pause;
4026
+ const { source, counts } = queue[q];
4027
+ const relsEntry = pkg.part(pkg.relsPartOf(source));
4028
+ if (!relsEntry) continue;
4029
+ const relsKey = pkg.keyOf(relsEntry);
4030
+ if (parsed.has(relsKey)) continue;
4031
+ parsed.add(relsKey);
4032
+ let rels;
4033
+ try {
4034
+ rels = await pkg.rels(source, { peek: true });
4035
+ } catch (err) {
4036
+ if (err instanceof require_errors.FormatError && err.code === "XML_MALFORMED") continue;
4037
+ throw err;
2946
4038
  }
2947
- } else if (h.location !== void 0) link = h.tooltip !== void 0 ? {
2948
- location: h.location,
2949
- tooltip: h.tooltip
2950
- } : { location: h.location };
2951
- if (!link) return;
2952
- const [r, c] = pos;
2953
- if (r >= 1048576 || c >= 16384) return;
2954
- let row = this.rows[r];
2955
- if (!row) row = this.rows[r] = [];
2956
- const cell = row[c] ?? (row[c] = { type: "empty" });
2957
- cell.hyperlink = link;
4039
+ if (counts) reached.add(relsKey);
4040
+ const malformed = pkg.malformedRels.get(relsEntry.name) ?? [];
4041
+ if (malformed.length) forbidden.add(relsEntry.name);
4042
+ const all = malformed.length ? [...rels, ...malformed] : rels;
4043
+ for (let i = 0; i < all.length; i++) {
4044
+ if ((i & 4095) === 4095) ctx.checkAbort();
4045
+ const rel = all[i];
4046
+ if (rel.forbidden) forbidden.add(relsEntry.name);
4047
+ classify(rel, source, relsEntry.name);
4048
+ if (rel.external || rel.tooLong) continue;
4049
+ visit(rel.target, counts);
4050
+ if (rel.altTarget !== void 0) visit(rel.altTarget, counts);
4051
+ }
4052
+ }
4053
+ queue.length = 0;
4054
+ };
4055
+ await drain();
4056
+ const entries = ctx.zip.entries;
4057
+ for (let i = 0; i < entries.length; i++) {
4058
+ if ((i & 4095) === 4095) ctx.checkAbort();
4059
+ const e = entries[i];
4060
+ if (e.name.endsWith("/") || parsed.has(pkg.keyOf(e))) continue;
4061
+ const owner = relsOwner(pkg.keyOf(e));
4062
+ if (owner === void 0) continue;
4063
+ queue.push({
4064
+ source: owner,
4065
+ counts: false
4066
+ });
4067
+ await drain();
4068
+ }
4069
+ const unreferenced = [];
4070
+ for (let i = 0; i < entries.length; i++) {
4071
+ if ((i & 4095) === 4095) ctx.checkAbort();
4072
+ const e = entries[i];
4073
+ if (e.name.endsWith("/")) continue;
4074
+ if (!reached.has(pkg.keyOf(e))) unreferenced.push(e.name);
4075
+ }
4076
+ return {
4077
+ found,
4078
+ unreferenced,
4079
+ forbidden: [...forbidden]
4080
+ };
4081
+ }
4082
+ // src/internal/read/formats.ts
4083
+ /** Container signatures, checked in order. */
4084
+ const CONTAINERS = [
4085
+ {
4086
+ kind: "cfb",
4087
+ magic: [
4088
+ 208,
4089
+ 207,
4090
+ 17,
4091
+ 224,
4092
+ 161,
4093
+ 177,
4094
+ 26,
4095
+ 225
4096
+ ]
4097
+ },
4098
+ {
4099
+ kind: "zip",
4100
+ magic: [
4101
+ 80,
4102
+ 75,
4103
+ 3,
4104
+ 4
4105
+ ]
4106
+ },
4107
+ {
4108
+ kind: "zip",
4109
+ magic: [
4110
+ 80,
4111
+ 75,
4112
+ 5,
4113
+ 6
4114
+ ]
4115
+ }
4116
+ ];
4117
+ /** OPC workbook formats by the content type of their workbook part. */
4118
+ const WORKBOOK_FORMATS = [
4119
+ {
4120
+ format: "xlsx",
4121
+ contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml",
4122
+ decoder: "spreadsheetml",
4123
+ label: "Excel workbook (.xlsx)"
4124
+ },
4125
+ {
4126
+ format: "xltx",
4127
+ contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml",
4128
+ decoder: "spreadsheetml",
4129
+ label: "Excel template (.xltx)"
4130
+ },
4131
+ {
4132
+ format: "xlsm",
4133
+ contentType: "application/vnd.ms-excel.sheet.macroEnabled.main+xml",
4134
+ decoder: "spreadsheetml",
4135
+ macros: true,
4136
+ label: "macro-enabled workbook (.xlsm)"
4137
+ },
4138
+ {
4139
+ format: "xltm",
4140
+ contentType: "application/vnd.ms-excel.template.macroEnabled.main+xml",
4141
+ decoder: "spreadsheetml",
4142
+ macros: true,
4143
+ label: "macro-enabled template (.xltm)"
4144
+ },
4145
+ {
4146
+ format: "xlsb",
4147
+ contentType: "application/vnd.ms-excel.sheet.binary.macroEnabled.main",
4148
+ macros: true,
4149
+ label: "binary workbook (.xlsb)"
2958
4150
  }
4151
+ ];
4152
+ /** Formats recognised by something other than a workbook content type. */
4153
+ const OTHER_FORMATS = {
4154
+ ods: { label: "OpenDocument spreadsheet (.ods)" },
4155
+ cfb: { label: "legacy .xls file or a password-protected (encrypted) workbook" },
4156
+ unknown: { label: "file that is not a spreadsheet package" }
2959
4157
  };
4158
+ function sniffContainer(b) {
4159
+ for (const c of CONTAINERS) if (c.magic.every((x, i) => b[i] === x)) return c.kind;
4160
+ return "unknown";
4161
+ }
4162
+ /**
4163
+ * The workbook format for a workbook part, from its content type; when the
4164
+ * content type is missing or unknown, from the part's extension (.bin is
4165
+ * binary, anything else is read as SpreadsheetML).
4166
+ */
4167
+ function workbookFormat(contentType, partName) {
4168
+ const ct = (contentType ?? "").toLowerCase();
4169
+ const known = WORKBOOK_FORMATS.find((f) => f.contentType.toLowerCase() === ct);
4170
+ if (known) return known;
4171
+ if (partName.toLowerCase().endsWith(".bin")) return WORKBOOK_FORMATS.find((f) => f.format === "xlsb");
4172
+ return WORKBOOK_FORMATS[0];
4173
+ }
2960
4174
  var WorkbookParser = class {
2961
4175
  maxSheets;
2962
4176
  part;
@@ -3223,29 +4437,6 @@ var CustomPropsParser = class {
3223
4437
  }
3224
4438
  };
3225
4439
  // src/internal/read/reader.ts
3226
- /** Friendly names for parts the model does not represent, keyed by relationship kind. */
3227
- const UNSUPPORTED = /* @__PURE__ */ new Map([
3228
- ["drawing", "drawings (charts, images, shapes)"],
3229
- ["vmlDrawing", "legacy drawings (VML)"],
3230
- ["comments", "comments"],
3231
- ["threadedComment", "threaded comments"],
3232
- ["pivotTable", "pivot tables"],
3233
- ["pivotCacheDefinition", "pivot caches"],
3234
- ["table", "tables (ListObjects)"],
3235
- ["oleObject", "embedded OLE objects"],
3236
- ["ctrlProp", "form controls"],
3237
- ["image", "images"],
3238
- ["vbaProject", "VBA macros"],
3239
- ["externalLink", "external links"],
3240
- ["connections", "data connections"],
3241
- ["queryTable", "query tables"],
3242
- ["slicer", "slicers"],
3243
- ["slicerCache", "slicer caches"],
3244
- ["timeline", "timelines"],
3245
- ["chartsheet", "chart sheets"],
3246
- ["dialogsheet", "dialog sheets"],
3247
- ["macrosheet", "macro sheets"]
3248
- ]);
3249
4440
  function unsupported(format, message) {
3250
4441
  return new require_errors.FormatError("UNSUPPORTED_FORMAT", message, { details: { format } });
3251
4442
  }
@@ -3380,10 +4571,10 @@ function warnUnsupportedParts(ctx, rels, part, seen) {
3380
4571
  for (let i = 0; i < rels.length; i++) {
3381
4572
  if ((i & 4095) === 4095) ctx.checkAbort();
3382
4573
  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);
4574
+ const kind = relationshipKindOf(r);
4575
+ const what = kind === void 0 ? void 0 : UNSUPPORTED_RELATIONSHIPS.get(kind);
4576
+ if (kind && what && !seen.has(kind)) {
4577
+ seen.add(kind);
3387
4578
  ctx.warn("UNSUPPORTED_PART", `The workbook contains ${what}, which are not read.`, {
3388
4579
  part: r.external ? part : r.target,
3389
4580
  partKind: kind
@@ -3391,6 +4582,46 @@ function warnUnsupportedParts(ctx, rels, part, seen) {
3391
4582
  }
3392
4583
  }
3393
4584
  }
4585
+ /**
4586
+ * After the sheets (JSE-72): the kinds in REPORTED_ANYWHERE that the
4587
+ * workbook's and the read sheets' relationships did not already report,
4588
+ * wherever the package scan found them, then one `invalidPartName` warning
4589
+ * for all names OPC forbids and one `unreferencedPart` warning for all parts
4590
+ * no relationship reaches, each listing every name in `parts`.
4591
+ */
4592
+ async function warnScannedParts(pkg, seen) {
4593
+ const ctx = pkg.ctx;
4594
+ const scan = await scanPackageParts(pkg);
4595
+ for (const f of scan.found) {
4596
+ if (!REPORTED_ANYWHERE.has(f.kind) || seen.has(f.kind)) continue;
4597
+ seen.add(f.kind);
4598
+ const what = SCANNED_KINDS.get(f.kind) ?? UNSUPPORTED_RELATIONSHIPS.get(f.kind);
4599
+ ctx.warn("UNSUPPORTED_PART", `The workbook contains ${what}, which are not read.`, {
4600
+ part: f.part,
4601
+ partKind: f.kind
4602
+ });
4603
+ }
4604
+ const bad = scan.forbidden;
4605
+ if (bad.length > 0) {
4606
+ const first = bad[0];
4607
+ const message = bad.length === 1 ? `The package uses a part name or relationship target that OPC forbids (in "${excerpt(first)}"); it is not read.` : `The package uses ${bad.length} part names or relationship targets that OPC forbids (first in "${excerpt(first)}"); they are not read.`;
4608
+ ctx.warn("UNSUPPORTED_PART", message, {
4609
+ part: first,
4610
+ partKind: "invalidPartName",
4611
+ parts: bad
4612
+ });
4613
+ }
4614
+ const n = scan.unreferenced.length;
4615
+ if (n > 0) {
4616
+ const first = scan.unreferenced[0];
4617
+ const message = n === 1 ? `The package contains 1 part that no relationship refers to ("${excerpt(first)}"), which is not read.` : `The package contains ${n} parts that no relationship refers to (first: "${excerpt(first)}"), which are not read.`;
4618
+ ctx.warn("UNSUPPORTED_PART", message, {
4619
+ part: first,
4620
+ partKind: "unreferencedPart",
4621
+ parts: scan.unreferenced
4622
+ });
4623
+ }
4624
+ }
3394
4625
  /** Reads an .xlsx-family file into the model. */
3395
4626
  async function readImpl(input, options, internal) {
3396
4627
  const o = options ?? {};
@@ -3406,12 +4637,26 @@ async function readImpl(input, options, internal) {
3406
4637
  let ctx;
3407
4638
  const { pkg, workbookPart, format } = await openPackage(bytes, limits, (zip) => {
3408
4639
  ctx = new ReadContext(zip, limits, o.signal, o.onWarning, o.onProgress);
4640
+ if (internal?.inspect) {
4641
+ ctx.sniff = internal.inspect.sniff;
4642
+ ctx.relsParsed = internal.inspect.relsParsed;
4643
+ }
3409
4644
  return ctx;
3410
4645
  });
3411
4646
  ctx.progress({
3412
4647
  phase: "unzip",
3413
4648
  ratio: .02
3414
4649
  });
4650
+ const inspect = internal?.inspect;
4651
+ if (inspect) {
4652
+ inspect.ctx = ctx;
4653
+ inspect.pkg = pkg;
4654
+ inspect.format = format;
4655
+ ctx.tap = (w) => {
4656
+ if (w.code === "UNSUPPORTED_PART") inspect.unsupported.push(w);
4657
+ else if (w.code === "BROKEN_OPTIONAL_PART" && w.part !== void 0) inspect.broken.add(w.part);
4658
+ };
4659
+ }
3415
4660
  const wbp = await parseWorkbook(pkg, workbookPart);
3416
4661
  const wbRels = await pkg.rels(workbookPart);
3417
4662
  const seen = /* @__PURE__ */ new Set();
@@ -3468,9 +4713,10 @@ async function readImpl(input, options, internal) {
3468
4713
  });
3469
4714
  else if (deferred) sstEntry = entry;
3470
4715
  else {
3471
- const sp = new SharedStringsParser(o.richText ?? "runs", limits.maxSharedStrings, 1e400, (n) => ctx.charge(n), limits.maxCellTextLength);
4716
+ const sp = new SharedStringsParser(o.richText ?? "runs", limits.maxSharedStrings, 1e400, (n) => ctx.charge(n), limits.maxCellTextLength, !inspect);
3472
4717
  await ctx.parse(entry, sp);
3473
4718
  sst = sp.strings;
4719
+ if (inspect) inspect.sharedStrings = sp.count;
3474
4720
  }
3475
4721
  }
3476
4722
  const properties = await readProperties(pkg, ctx);
@@ -3484,20 +4730,30 @@ async function readImpl(input, options, internal) {
3484
4730
  totalBytes ||= 1;
3485
4731
  let doneBytes = 0;
3486
4732
  const sheets = [];
4733
+ const done = (parser, part, sheet) => {
4734
+ sheets.push(sheet);
4735
+ inspect?.sheets.push({
4736
+ part: part?.name,
4737
+ cells: parser.cellCount
4738
+ });
4739
+ };
3487
4740
  for (let i = 0; i < listed.length; i++) {
3488
4741
  const pause = ctx.step();
3489
4742
  if (pause) await pause;
3490
4743
  const { entry, rel } = listed[i];
3491
4744
  const parser = new SheetParser(entry.name, entry.state, ctx, styles, {
3492
4745
  formulas: o.formulas !== false,
4746
+ sharedFormulaText: internal?.sharedFormulaText ?? "shifted",
3493
4747
  dates: o.dates ?? "date",
3494
4748
  dateZone: o.dateZone ?? "local",
3495
4749
  richText: o.richText ?? "runs",
3496
4750
  rawText: o.rawText === true,
3497
4751
  date1904: wbp.date1904,
3498
- maxRows: o.maxRows ?? 1048576
4752
+ maxRows: o.maxRows ?? 1048576,
4753
+ keepCells: !inspect
3499
4754
  }, rel?.target ?? workbookPart);
3500
4755
  parser.sharedStrings = sst;
4756
+ if (inspect) parser.sharedStringCount = inspect.sharedStrings;
3501
4757
  parser.deferred = deferred;
3502
4758
  const part = rel ? pkg.part(rel.target) : void 0;
3503
4759
  if (!part) {
@@ -3505,11 +4761,11 @@ async function readImpl(input, options, internal) {
3505
4761
  sheet: entry.name,
3506
4762
  partKind: "worksheet"
3507
4763
  });
3508
- sheets.push(parser.finish([]));
4764
+ done(parser, part, parser.finish([]));
3509
4765
  continue;
3510
4766
  }
3511
4767
  if (!wanted(entry.name, i)) {
3512
- sheets.push(parser.finish([]));
4768
+ done(parser, part, parser.finish([]));
3513
4769
  continue;
3514
4770
  }
3515
4771
  const sheetRels = await pkg.rels(part.name);
@@ -3530,8 +4786,9 @@ async function readImpl(input, options, internal) {
3530
4786
  });
3531
4787
  });
3532
4788
  doneBytes += part.size;
3533
- sheets.push(parser.finish(sheetRels));
4789
+ done(parser, part, parser.finish(sheetRels));
3534
4790
  }
4791
+ await warnScannedParts(pkg, seen);
3535
4792
  if (sstEntry && deferred && deferred.cells.length === 0) ctx.consumed.add(sstEntry.name);
3536
4793
  if (deferred && deferred.cells.length > 0) {
3537
4794
  if (sstEntry) {
@@ -3658,6 +4915,349 @@ async function readProperties(pkg, ctx) {
3658
4915
  }
3659
4916
  return Object.keys(props).length ? props : void 0;
3660
4917
  }
4918
+ // src/internal/read/inspect.ts
4919
+ /**
4920
+ * inspect (docs/api.md §5.2.1, JSE-71): checks a workbook part by part with
4921
+ * read's zip and XML safety, without building cells. Internal.
4922
+ *
4923
+ * The workbook is read by readImpl itself, with every check read makes, in
4924
+ * the same order, but with no cells and no shared strings kept (the sheet
4925
+ * and shared-strings parsers count instead). So inspect refuses what read
4926
+ * refuses, with the same error, and reports the part kinds read reports;
4927
+ * whatever readImpl learns to check or report, inspect does too. Only once
4928
+ * that read has succeeded come the checks read does not make:
4929
+ * - every XML part (by content type, by name, or as the target of a
4930
+ * relationship of a kind that is not binary, from the relationships read's
4931
+ * package scan parsed), including the parts read parses, must be in UTF-8
4932
+ * or UTF-16, as OPC requires;
4933
+ * - every zip entry the read did not parse, or parsed only up to an error it
4934
+ * forgave (a broken optional part), is inflated (zip limits, CRC) and its
4935
+ * bytes searched for `<!DOCTYPE`, whatever its name or content type.
4936
+ */
4937
+ /**
4938
+ * `<!DOCTYPE` in the bytes of a part, read one byte per character: ASCII and
4939
+ * UTF-8 text, UTF-16 (one NUL between the characters) and UTF-32 (three), in
4940
+ * either byte order; and UTF-7, where `<` and `!` are base64 runs. In any
4941
+ * case, as the tokenizer refuses it.
4942
+ */
4943
+ const DOCTYPE = /<(\u0000{0,3})!\1d\1o\1c\1t\1y\1p\1e|\+ADw(?:-!|AIQ-|-\+ACE-)doctype/i;
4944
+ /** A processing instruction whose target is `xml` in any case, in the same byte forms as DOCTYPE. */
4945
+ const XML_PI = /<(\u0000{0,3})\?\1x\1m\1l\1[ \t\r\n?]/gi;
4946
+ /** Reads bytes as characters one to one (windows-1252: ASCII and NUL map to themselves). */
4947
+ const BYTES = new TextDecoder("latin1");
4948
+ /** Relationship kinds (lower case) whose target is not XML. Every other internal target is treated as an XML part. */
4949
+ const BINARY_KINDS = /* @__PURE__ */ new Set([
4950
+ "image",
4951
+ "oleobject",
4952
+ "package",
4953
+ "vbaproject",
4954
+ "vbaprojectsignature",
4955
+ "vbaprojectsignatureagile",
4956
+ "vbaprojectsignaturev3",
4957
+ "attachedtoolbars",
4958
+ "printersettings",
4959
+ "activexcontrolbinary",
4960
+ "thumbnail",
4961
+ "font",
4962
+ "media",
4963
+ "audio",
4964
+ "video",
4965
+ "hyperlink",
4966
+ "attachedtemplate",
4967
+ "externallinkpath",
4968
+ "xlbinaryindex"
4969
+ ]);
4970
+ /** Parts whose content type or name says XML. */
4971
+ function isXmlByName(pkg, name) {
4972
+ const type = (pkg.contentType(name) ?? "").toLowerCase();
4973
+ return /[+/]xml\s*(;|$)/.test(type) || type.endsWith("vmldrawing") || /\.(xml|rels|vml|svg)$/i.test(name);
4974
+ }
4975
+ /**
4976
+ * The encoding a part's first four bytes show when OPC does not allow it
4977
+ * (ECMA-376 Part 2: UTF-8 or UTF-16), else undefined: a UTF-32 or UCS-4 byte
4978
+ * order mark or `<`, the EBCDIC bytes of `<?xml`, the UTF-7 signature
4979
+ * (`+/v`) or a UTF-7 `<` (`+ADw`).
4980
+ */
4981
+ function signatureEncoding(b) {
4982
+ const [b0, b1, b2, b3] = [
4983
+ b[0],
4984
+ b[1],
4985
+ b[2],
4986
+ b[3]
4987
+ ];
4988
+ if (b0 === 0 && b1 === 0 && b2 === 254 && b3 === 255) return "UTF-32BE";
4989
+ if (b0 === 255 && b1 === 254 && b2 === 0 && b3 === 0) return "UTF-32LE";
4990
+ if (b0 === 0 && b1 === 0 && b2 === 0 && b3 === 60) return "UTF-32BE";
4991
+ if (b0 === 60 && b1 === 0 && b2 === 0 && b3 === 0) return "UTF-32LE";
4992
+ if (b0 === 0 && b1 === 0 && b2 === 60 && b3 === 0 || b0 === 0 && b1 === 60 && b2 === 0 && b3 === 0) return "UCS-4";
4993
+ if (b0 === 76 && b1 === 111 && b2 === 167 && b3 === 148) return "EBCDIC";
4994
+ if (b0 === 43 && b1 === 47 && b2 === 118) return "UTF-7";
4995
+ if (b0 === 43 && b1 === 65 && b2 === 68 && (b3 === 119 || b3 === 120)) return "UTF-7";
4996
+ }
4997
+ /**
4998
+ * The XMLDecl production (XML 1.0 §2.8), strictly: `<?xml`, then version,
4999
+ * encoding and standalone in that order, each once, quoted, only the first
5000
+ * required, with spaces as XML counts them.
5001
+ */
5002
+ const XML_DECLARATION = /^<\?xml[ \t\r\n]+version[ \t\r\n]*=[ \t\r\n]*(?:"1\.[0-9]+"|'1\.[0-9]+')(?:[ \t\r\n]+encoding[ \t\r\n]*=[ \t\r\n]*(?:"([A-Za-z][A-Za-z0-9._-]*)"|'([A-Za-z][A-Za-z0-9._-]*)'))?(?:[ \t\r\n]+standalone[ \t\r\n]*=[ \t\r\n]*(?:"(?:yes|no)"|'(?:yes|no)'))?[ \t\r\n]*\?>$/;
5003
+ /** A whole declaration at the start of a part: undefined when it is well-formed and names UTF-8, UTF-16 or nothing. */
5004
+ function checkDeclaration(part, declaration) {
5005
+ const m = XML_DECLARATION.exec(declaration);
5006
+ if (!m) return new require_errors.FormatError("XML_MALFORMED", `${excerpt(part)}: the XML declaration is not well-formed (XML 1.0 XMLDecl).`, { details: {
5007
+ part,
5008
+ declaration: printable(declaration)
5009
+ } });
5010
+ const name = m[1] ?? m[2];
5011
+ return name === void 0 || /^utf-?(8|16(le|be)?)$/i.test(name) ? void 0 : encodingError(part, printable(name));
5012
+ }
5013
+ function misplacedDeclaration(part) {
5014
+ return new require_errors.FormatError("XML_MALFORMED", `${excerpt(part)}: an XML declaration (<?xml …?>) appears other than at the very start of the part.`, { details: { part } });
5015
+ }
5016
+ /** File text for `details`: printable ASCII only, at most 40 characters. */
5017
+ function printable(s) {
5018
+ const clean = s.replace(/[^\x20-\x7e]/g, "?");
5019
+ return clean.length > 40 ? `${clean.slice(0, 37)}...` : clean;
5020
+ }
5021
+ function encodingError(part, encoding) {
5022
+ return new require_errors.FormatError("XML_MALFORMED", `${excerpt(part)}: the part is encoded in ${encoding}; XML parts must be UTF-8 or UTF-16.`, { details: {
5023
+ part,
5024
+ encoding
5025
+ } });
5026
+ }
5027
+ function doctype() {
5028
+ return new require_errors.FormatError("XML_DTD_FORBIDDEN", "XML parts must not contain a document type declaration (<!DOCTYPE).");
5029
+ }
5030
+ async function inspectImpl(bytes, options) {
5031
+ let deferred;
5032
+ const maxToken = options?.limits?.maxXmlTokenLength ?? DEFAULT_LIMITS.maxXmlTokenLength;
5033
+ const xmlTargets = /* @__PURE__ */ new Set();
5034
+ const relsDone = /* @__PURE__ */ new Set();
5035
+ const sink = {
5036
+ unsupported: [],
5037
+ broken: /* @__PURE__ */ new Set(),
5038
+ sharedStrings: 0,
5039
+ sheets: [],
5040
+ sniff: (part) => new PartCheck(part, maxToken, (err) => deferred ??= err),
5041
+ relsParsed: (part, rels) => {
5042
+ relsDone.add(part);
5043
+ for (const r of rels) {
5044
+ if (r.external || r.tooLong || r.target === "" || BINARY_KINDS.has(r.kind.toLowerCase())) continue;
5045
+ xmlTargets.add(partKey(r.target));
5046
+ if (r.altTarget !== void 0) xmlTargets.add(partKey(r.altTarget));
5047
+ }
5048
+ }
5049
+ };
5050
+ const { workbook } = await readImpl(bytes, {
5051
+ limits: options?.limits,
5052
+ signal: options?.signal
5053
+ }, { inspect: sink });
5054
+ const ctx = sink.ctx;
5055
+ const pkg = sink.pkg;
5056
+ if (deferred !== void 0) throw deferred;
5057
+ for (const entry of ctx.zip.entries) {
5058
+ if ((ctx.consumed.has(entry.name) || relsDone.has(entry.name)) && !sink.broken.has(entry.name)) continue;
5059
+ const pause = ctx.step();
5060
+ if (pause) await pause;
5061
+ await scanPart(ctx, entry, isXmlByName(pkg, entry.name) || xmlTargets.has(pkg.keyOf(entry)));
5062
+ }
5063
+ const kinds = /* @__PURE__ */ new Set();
5064
+ for (const w of sink.unsupported) if (w.partKind !== void 0) kinds.add(w.partKind);
5065
+ const sheets = workbook.sheets.map((s, index) => {
5066
+ const out = {
5067
+ name: s.name,
5068
+ index,
5069
+ state: s.state ?? "visible",
5070
+ cells: sink.sheets[index].cells
5071
+ };
5072
+ const part = sink.sheets[index].part;
5073
+ if (part !== void 0) out.part = part;
5074
+ if (s.dimension !== void 0) out.dimension = s.dimension;
5075
+ return out;
5076
+ });
5077
+ return {
5078
+ format: sink.format.format,
5079
+ sheets,
5080
+ partKinds: [...kinds],
5081
+ warnings: sink.unsupported,
5082
+ parts: pkg.partNames.length,
5083
+ inflatedBytes: ctx.zip.totalBytesRead,
5084
+ cells: ctx.cells,
5085
+ sharedStrings: sink.sharedStrings
5086
+ };
5087
+ }
5088
+ /**
5089
+ * Inflates one entry to its end, so the zip limits and its CRC are checked;
5090
+ * searches its bytes for `<!DOCTYPE`; and, for an XML part, checks the
5091
+ * encoding of its first bytes. The bytes are searched in PARSE_SLICE pieces
5092
+ * with the signal consulted and the event loop given a turn between them, as
5093
+ * ctx.parse does, so a large stored entry is not one long step.
5094
+ */
5095
+ async function scanPart(ctx, entry, xml) {
5096
+ let tail = "";
5097
+ let offset = 0;
5098
+ let lastPi = -1;
5099
+ let failure;
5100
+ const check = xml ? new PartCheck(entry.name, ctx.limits.maxXmlTokenLength, (err) => failure ??= err) : void 0;
5101
+ try {
5102
+ for await (const chunk of ctx.zip.stream(entry, ctx.signal)) {
5103
+ check?.feed(chunk);
5104
+ if (failure !== void 0) throw failure;
5105
+ for (let at = 0; at < chunk.length;) {
5106
+ const piece = chunk.subarray(at, at + PARSE_SLICE);
5107
+ const s = tail + BYTES.decode(piece);
5108
+ if (DOCTYPE.test(s)) throw doctype();
5109
+ if (check) {
5110
+ const base = offset + at - tail.length;
5111
+ XML_PI.lastIndex = 0;
5112
+ for (let m = XML_PI.exec(s); m; m = XML_PI.exec(s)) if (base + m.index > lastPi) {
5113
+ lastPi = base + m.index;
5114
+ check.pi();
5115
+ }
5116
+ }
5117
+ at += piece.length;
5118
+ tail = s.slice(-32);
5119
+ if (at < chunk.length) {
5120
+ const pause = ctx.step();
5121
+ if (pause) await pause;
5122
+ }
5123
+ }
5124
+ offset += chunk.length;
5125
+ const pause = ctx.step();
5126
+ if (pause) await pause;
5127
+ }
5128
+ check?.end();
5129
+ if (failure !== void 0) throw failure;
5130
+ } catch (err) {
5131
+ throw withPart(err, entry.name);
5132
+ }
5133
+ }
5134
+ /**
5135
+ * The checks of one XML part, parsed by read (through ctx.sniff) or not
5136
+ * (scanPart): its first bytes and its declaration (DeclarationReader), and
5137
+ * that no `<?xml` processing instruction stands anywhere but at the very start.
5138
+ * What it finds is reported once, through `fail`.
5139
+ */
5140
+ var PartCheck = class {
5141
+ part;
5142
+ fail;
5143
+ reader;
5144
+ instructions = 0;
5145
+ failed = false;
5146
+ constructor(part, maxToken, fail) {
5147
+ this.part = part;
5148
+ this.fail = fail;
5149
+ this.reader = new DeclarationReader(part, maxToken);
5150
+ }
5151
+ feed(chunk) {
5152
+ if (!this.failed) this.report(() => this.reader.feed(chunk));
5153
+ }
5154
+ pi() {
5155
+ this.instructions++;
5156
+ }
5157
+ end() {
5158
+ if (!this.failed) this.report(() => this.reader.end());
5159
+ if (!this.failed && this.instructions > (this.reader.hasDeclaration ? 1 : 0)) this.report(() => misplacedDeclaration(this.part));
5160
+ }
5161
+ report(step) {
5162
+ let err;
5163
+ try {
5164
+ err = step();
5165
+ } catch (thrown) {
5166
+ err = withPart(thrown, this.part);
5167
+ }
5168
+ if (err !== void 0) {
5169
+ this.failed = true;
5170
+ this.fail(err);
5171
+ }
5172
+ }
5173
+ };
5174
+ /**
5175
+ * Reads the start of an XML part, however it is chunked: its first four bytes
5176
+ * (signatureEncoding), then, decoded as UTF-8 or UTF-16 by its byte order mark
5177
+ * or, without one, by `<?` in UTF-16, its XML declaration up to `?>`, bounded
5178
+ * like any token by maxXmlTokenLength, which must stand at the very start
5179
+ * (checkDeclaration). Linear: each chunk is decoded and searched once.
5180
+ */
5181
+ var DeclarationReader = class {
5182
+ part;
5183
+ maxToken;
5184
+ hasDeclaration = false;
5185
+ pending = [];
5186
+ pendingLength = 0;
5187
+ decoder;
5188
+ text = "";
5189
+ searched = 0;
5190
+ done = false;
5191
+ constructor(part, maxToken) {
5192
+ this.part = part;
5193
+ this.maxToken = maxToken;
5194
+ }
5195
+ feed(chunk) {
5196
+ if (this.done) return void 0;
5197
+ if (!this.decoder) {
5198
+ this.pending.push(chunk);
5199
+ this.pendingLength += chunk.length;
5200
+ if (this.pendingLength < 4) return void 0;
5201
+ return this.start();
5202
+ }
5203
+ return this.more(this.decoder.decode(chunk, { stream: true }));
5204
+ }
5205
+ end() {
5206
+ if (this.done) return void 0;
5207
+ if (!this.decoder) {
5208
+ const found = this.start();
5209
+ if (found !== void 0 || this.done) return found;
5210
+ }
5211
+ return this.more(this.decoder.decode(), true);
5212
+ }
5213
+ start() {
5214
+ const head = new Uint8Array(this.pendingLength);
5215
+ let at = 0;
5216
+ for (const p of this.pending) {
5217
+ head.set(p, at);
5218
+ at += p.length;
5219
+ }
5220
+ this.pending = [];
5221
+ const sig = signatureEncoding(head);
5222
+ if (sig !== void 0) {
5223
+ this.done = true;
5224
+ return encodingError(this.part, sig);
5225
+ }
5226
+ const Ctor = globalThis.TextDecoder;
5227
+ if (head[0] === 60 && head[1] === 0 && head[2] === 63 && head[3] === 0) this.decoder = new Ctor("utf-16le");
5228
+ else if (head[0] === 0 && head[1] === 60 && head[2] === 0 && head[3] === 63) this.decoder = new Ctor("utf-16be");
5229
+ else this.decoder = newDecoder(head);
5230
+ return this.more(this.decoder.decode(head, { stream: true }));
5231
+ }
5232
+ more(text, final = false) {
5233
+ this.text += text;
5234
+ const t = this.text;
5235
+ if (t.length < 6 && !final && "<?xml".startsWith(t.slice(0, 5).toLowerCase())) return this.bound();
5236
+ if (!/^<\?xml[ \t\r\n?]/i.test(t)) {
5237
+ this.done = true;
5238
+ return;
5239
+ }
5240
+ this.hasDeclaration = true;
5241
+ const close = t.indexOf("?>", Math.max(0, this.searched - 1));
5242
+ if (close === -1) {
5243
+ this.searched = t.length;
5244
+ if (!final) return this.bound();
5245
+ this.done = true;
5246
+ return checkDeclaration(this.part, t);
5247
+ }
5248
+ this.done = true;
5249
+ if (close + 2 > this.maxToken) this.bound(true);
5250
+ return checkDeclaration(this.part, t.slice(0, close + 2));
5251
+ }
5252
+ /** A declaration longer than maxXmlTokenLength is refused, as the tokenizer refuses a token. */
5253
+ bound(over = false) {
5254
+ if (over || this.text.length > this.maxToken) throw new require_errors.LimitError("LIMIT_EXCEEDED", `An XML tag, comment, CDATA section or processing instruction is longer than maxXmlTokenLength (${this.maxToken}).`, { details: {
5255
+ limit: "maxXmlTokenLength",
5256
+ value: this.maxToken + 1,
5257
+ max: this.maxToken
5258
+ } });
5259
+ }
5260
+ };
3661
5261
  // src/read.ts
3662
5262
  /** Default limits (docs/api.md §5.2; the measurements behind each value are listed there). */
3663
5263
  const DEFAULT_READ_LIMITS = DEFAULT_LIMITS;
@@ -3677,6 +5277,22 @@ async function read(input, options) {
3677
5277
  warnings
3678
5278
  };
3679
5279
  }
5280
+ /**
5281
+ * Checks an .xlsx, .xlsm, .xltx or .xltm file part by part without building
5282
+ * its cells: every part `read` parses is parsed with the same checks and
5283
+ * limits (every sheet to its end), every other part is inflated and its
5284
+ * bytes searched for a DOCTYPE, and XML parts must be UTF-8 or UTF-16. Throws what `read` throws for any file
5285
+ * `read` refuses under the same limits (docs/api.md §5.2.1).
5286
+ */
5287
+ async function inspect(input, options) {
5288
+ return inspectImpl(await require_infer.toBytes(input, "inspect"), options);
5289
+ }
5290
+ Object.defineProperty(exports, "DEFAULT_LIMITS", {
5291
+ enumerable: true,
5292
+ get: function() {
5293
+ return DEFAULT_LIMITS;
5294
+ }
5295
+ });
3680
5296
  Object.defineProperty(exports, "DEFAULT_READ_LIMITS", {
3681
5297
  enumerable: true,
3682
5298
  get: function() {
@@ -3695,6 +5311,12 @@ Object.defineProperty(exports, "excerpt", {
3695
5311
  return excerpt;
3696
5312
  }
3697
5313
  });
5314
+ Object.defineProperty(exports, "inspect", {
5315
+ enumerable: true,
5316
+ get: function() {
5317
+ return inspect;
5318
+ }
5319
+ });
3698
5320
  Object.defineProperty(exports, "quoted", {
3699
5321
  enumerable: true,
3700
5322
  get: function() {
@@ -3707,6 +5329,12 @@ Object.defineProperty(exports, "read", {
3707
5329
  return read;
3708
5330
  }
3709
5331
  });
5332
+ Object.defineProperty(exports, "readImpl", {
5333
+ enumerable: true,
5334
+ get: function() {
5335
+ return readImpl;
5336
+ }
5337
+ });
3710
5338
  Object.defineProperty(exports, "readSheetNames", {
3711
5339
  enumerable: true,
3712
5340
  get: function() {