xls-reader 0.1.2 → 0.1.3

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.
package/dist/index.cjs CHANGED
@@ -1,752 +1,777 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
-
20
- // src/index.ts
21
- var index_exports = {};
22
- __export(index_exports, {
23
- XlsError: () => XlsError,
24
- excelSerialToDate: () => excelSerialToDate,
25
- readFirstSheet: () => readFirstSheet,
26
- readXls: () => readXls
27
- });
28
- module.exports = __toCommonJS(index_exports);
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
29
2
 
30
- // src/errors.ts
3
+ //#region src/errors.ts
31
4
  var XlsError = class extends Error {
32
- constructor(message) {
33
- super(message);
34
- this.name = "XlsError";
35
- }
5
+ constructor(message) {
6
+ super(message);
7
+ this.name = "XlsError";
8
+ }
36
9
  };
37
10
 
38
- // src/biff/record-stream.ts
11
+ //#endregion
12
+ //#region src/biff/record-stream.ts
39
13
  function readRecords(stream) {
40
- const view = new DataView(stream.buffer, stream.byteOffset, stream.byteLength);
41
- const records = [];
42
- let pos = 0;
43
- while (pos + 4 <= stream.length) {
44
- const type = view.getUint16(pos, true);
45
- const length = view.getUint16(pos + 2, true);
46
- if (pos + 4 + length > stream.length) break;
47
- records.push({ type, data: stream.subarray(pos + 4, pos + 4 + length), offset: pos });
48
- pos += 4 + length;
49
- }
50
- return records;
14
+ const view = new DataView(stream.buffer, stream.byteOffset, stream.byteLength);
15
+ const records = [];
16
+ let pos = 0;
17
+ while (pos + 4 <= stream.length) {
18
+ const type = view.getUint16(pos, true);
19
+ const length = view.getUint16(pos + 2, true);
20
+ if (pos + 4 + length > stream.length) break;
21
+ records.push({
22
+ type,
23
+ data: stream.subarray(pos + 4, pos + 4 + length),
24
+ offset: pos
25
+ });
26
+ pos += 4 + length;
27
+ }
28
+ return records;
51
29
  }
52
30
 
53
- // src/byte-reader.ts
31
+ //#endregion
32
+ //#region src/byte-reader.ts
54
33
  var ByteReader = class {
55
- constructor(bytes, start = 0) {
56
- this.bytes = bytes;
57
- this.view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
58
- this.cursor = start;
59
- }
60
- get position() {
61
- return this.cursor;
62
- }
63
- set position(value) {
64
- this.cursor = value;
65
- }
66
- get remaining() {
67
- return this.bytes.length - this.cursor;
68
- }
69
- u8() {
70
- this.require(1);
71
- const value = this.view.getUint8(this.cursor);
72
- this.cursor += 1;
73
- return value;
74
- }
75
- u16() {
76
- this.require(2);
77
- const value = this.view.getUint16(this.cursor, true);
78
- this.cursor += 2;
79
- return value;
80
- }
81
- u32() {
82
- this.require(4);
83
- const value = this.view.getUint32(this.cursor, true);
84
- this.cursor += 4;
85
- return value;
86
- }
87
- f64() {
88
- this.require(8);
89
- const value = this.view.getFloat64(this.cursor, true);
90
- this.cursor += 8;
91
- return value;
92
- }
93
- // Returns a view (not a copy) over the next `length` bytes and advances.
94
- slice(length) {
95
- this.require(length);
96
- const view = this.bytes.subarray(this.cursor, this.cursor + length);
97
- this.cursor += length;
98
- return view;
99
- }
100
- skip(length) {
101
- this.cursor += length;
102
- }
103
- require(length) {
104
- if (this.cursor + length > this.bytes.length) {
105
- throw new XlsError(
106
- `Unexpected end of data: needed ${length} byte(s) at offset ${this.cursor}, but only ${this.remaining} remain`
107
- );
108
- }
109
- }
34
+ constructor(bytes, start = 0) {
35
+ this.bytes = bytes;
36
+ this.view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
37
+ this.cursor = start;
38
+ }
39
+ get position() {
40
+ return this.cursor;
41
+ }
42
+ set position(value) {
43
+ this.cursor = value;
44
+ }
45
+ get remaining() {
46
+ return this.bytes.length - this.cursor;
47
+ }
48
+ u8() {
49
+ this.require(1);
50
+ const value = this.view.getUint8(this.cursor);
51
+ this.cursor += 1;
52
+ return value;
53
+ }
54
+ u16() {
55
+ this.require(2);
56
+ const value = this.view.getUint16(this.cursor, true);
57
+ this.cursor += 2;
58
+ return value;
59
+ }
60
+ u32() {
61
+ this.require(4);
62
+ const value = this.view.getUint32(this.cursor, true);
63
+ this.cursor += 4;
64
+ return value;
65
+ }
66
+ f64() {
67
+ this.require(8);
68
+ const value = this.view.getFloat64(this.cursor, true);
69
+ this.cursor += 8;
70
+ return value;
71
+ }
72
+ slice(length) {
73
+ this.require(length);
74
+ const view = this.bytes.subarray(this.cursor, this.cursor + length);
75
+ this.cursor += length;
76
+ return view;
77
+ }
78
+ skip(length) {
79
+ this.cursor += length;
80
+ }
81
+ require(length) {
82
+ if (!Number.isInteger(this.cursor) || this.cursor < 0) throw new XlsError(`Invalid read offset ${this.cursor}: corrupt structure`);
83
+ if (this.cursor + length > this.bytes.length) throw new XlsError(`Unexpected end of data: needed ${length} byte(s) at offset ${this.cursor}, but only ${this.remaining} remain`);
84
+ }
110
85
  };
111
86
 
112
- // src/biff/rk-number.ts
87
+ //#endregion
88
+ //#region src/biff/rk-number.ts
113
89
  function decodeRk(rk) {
114
- const dividedBy100 = (rk & 1) !== 0;
115
- const isInteger = (rk & 2) !== 0;
116
- const value = isInteger ? rk >> 2 : rkAsDouble(rk);
117
- return dividedBy100 ? value / 100 : value;
90
+ const dividedBy100 = (rk & 1) !== 0;
91
+ const value = (rk & 2) !== 0 ? rk >> 2 : rkAsDouble(rk);
92
+ return dividedBy100 ? value / 100 : value;
118
93
  }
119
94
  function rkAsDouble(rk) {
120
- const buffer = new ArrayBuffer(8);
121
- const view = new DataView(buffer);
122
- view.setUint32(4, rk & 4294967292, true);
123
- return view.getFloat64(0, true);
95
+ const view = /* @__PURE__ */ new DataView(/* @__PURE__ */ new ArrayBuffer(8));
96
+ view.setUint32(4, rk & 4294967292, true);
97
+ return view.getFloat64(0, true);
124
98
  }
125
99
 
126
- // src/biff/unicode-string.ts
127
- var F_WIDE = 1;
128
- var F_EXT = 4;
129
- var F_RICH = 8;
130
- var BYTES_PER_RUN = 4;
100
+ //#endregion
101
+ //#region src/biff/unicode-string.ts
102
+ const F_WIDE$1 = 1;
103
+ const F_EXT$1 = 4;
104
+ const F_RICH$1 = 8;
105
+ const BYTES_PER_RUN$1 = 4;
131
106
  function readUnicodeString(reader, shortLength) {
132
- const charCount = shortLength ? reader.u8() : reader.u16();
133
- const flags = reader.u8();
134
- const wide = (flags & F_WIDE) !== 0;
135
- const runCount = (flags & F_RICH) !== 0 ? reader.u16() : 0;
136
- const extSize = (flags & F_EXT) !== 0 ? reader.u32() : 0;
137
- let text = "";
138
- for (let i = 0; i < charCount; i++)
139
- text += String.fromCharCode(wide ? reader.u16() : reader.u8());
140
- reader.skip(runCount * BYTES_PER_RUN + extSize);
141
- return text;
107
+ const charCount = shortLength ? reader.u8() : reader.u16();
108
+ const flags = reader.u8();
109
+ const wide = (flags & F_WIDE$1) !== 0;
110
+ const runCount = (flags & F_RICH$1) !== 0 ? reader.u16() : 0;
111
+ const extSize = (flags & F_EXT$1) !== 0 ? reader.u32() : 0;
112
+ let text = "";
113
+ for (let i = 0; i < charCount; i++) text += String.fromCharCode(wide ? reader.u16() : reader.u8());
114
+ reader.skip(runCount * BYTES_PER_RUN$1 + extSize);
115
+ return text;
142
116
  }
143
117
 
144
- // src/biff/cell-records.ts
118
+ //#endregion
119
+ //#region src/biff/cell-records.ts
145
120
  function decodeLabelSst(data, ctx) {
146
- const reader = new ByteReader(data);
147
- const { row, col } = readHead(reader);
148
- const index = reader.u32();
149
- return { row, col, value: ctx.sharedStrings[index] ?? "" };
121
+ const reader = new ByteReader(data);
122
+ const { row, col } = readHead(reader);
123
+ const index = reader.u32();
124
+ return {
125
+ row,
126
+ col,
127
+ value: ctx.sharedStrings[index] ?? ""
128
+ };
150
129
  }
151
130
  function decodeLabel(data) {
152
- const reader = new ByteReader(data);
153
- const { row, col } = readHead(reader);
154
- return { row, col, value: readUnicodeString(reader, false) };
131
+ const reader = new ByteReader(data);
132
+ const { row, col } = readHead(reader);
133
+ return {
134
+ row,
135
+ col,
136
+ value: readUnicodeString(reader, false)
137
+ };
155
138
  }
156
139
  function decodeNumber(data, ctx) {
157
- const reader = new ByteReader(data);
158
- const { row, col, xf } = readHead(reader);
159
- return { row, col, value: ctx.numeric(xf, reader.f64()) };
140
+ const reader = new ByteReader(data);
141
+ const { row, col, xf } = readHead(reader);
142
+ return {
143
+ row,
144
+ col,
145
+ value: ctx.numeric(xf, reader.f64())
146
+ };
160
147
  }
161
148
  function decodeRkCell(data, ctx) {
162
- const reader = new ByteReader(data);
163
- const { row, col, xf } = readHead(reader);
164
- return { row, col, value: ctx.numeric(xf, decodeRk(reader.u32())) };
149
+ const reader = new ByteReader(data);
150
+ const { row, col, xf } = readHead(reader);
151
+ return {
152
+ row,
153
+ col,
154
+ value: ctx.numeric(xf, decodeRk(reader.u32()))
155
+ };
165
156
  }
166
157
  function decodeBlank(data) {
167
- const reader = new ByteReader(data);
168
- const { row, col } = readHead(reader);
169
- return { row, col, value: null };
158
+ const { row, col } = readHead(new ByteReader(data));
159
+ return {
160
+ row,
161
+ col,
162
+ value: null
163
+ };
170
164
  }
171
165
  function decodeBoolErr(data) {
172
- const reader = new ByteReader(data);
173
- const { row, col } = readHead(reader);
174
- const raw = reader.u8();
175
- const isError = reader.u8() !== 0;
176
- return { row, col, value: isError ? null : raw !== 0 };
166
+ const reader = new ByteReader(data);
167
+ const { row, col } = readHead(reader);
168
+ const raw = reader.u8();
169
+ return {
170
+ row,
171
+ col,
172
+ value: reader.u8() !== 0 ? null : raw !== 0
173
+ };
177
174
  }
178
175
  function decodeMulRk(data, ctx) {
179
- const reader = new ByteReader(data);
180
- const row = reader.u16();
181
- const colFirst = reader.u16();
182
- const count = (data.length - 6) / 6;
183
- const cells = [];
184
- for (let i = 0; i < count; i++) {
185
- const xf = reader.u16();
186
- cells.push({ row, col: colFirst + i, value: ctx.numeric(xf, decodeRk(reader.u32())) });
187
- }
188
- return cells;
176
+ const reader = new ByteReader(data);
177
+ const row = reader.u16();
178
+ const colFirst = reader.u16();
179
+ const count = (data.length - 6) / 6;
180
+ const cells = [];
181
+ for (let i = 0; i < count; i++) {
182
+ const xf = reader.u16();
183
+ cells.push({
184
+ row,
185
+ col: colFirst + i,
186
+ value: ctx.numeric(xf, decodeRk(reader.u32()))
187
+ });
188
+ }
189
+ return cells;
189
190
  }
190
191
  function decodeMulBlank(data) {
191
- const row = new ByteReader(data).u16();
192
- const colFirst = new ByteReader(data, 2).u16();
193
- const count = (data.length - 6) / 2;
194
- const cells = [];
195
- for (let i = 0; i < count; i++) cells.push({ row, col: colFirst + i, value: null });
196
- return cells;
192
+ const row = new ByteReader(data).u16();
193
+ const colFirst = new ByteReader(data, 2).u16();
194
+ const count = (data.length - 6) / 2;
195
+ const cells = [];
196
+ for (let i = 0; i < count; i++) cells.push({
197
+ row,
198
+ col: colFirst + i,
199
+ value: null
200
+ });
201
+ return cells;
197
202
  }
198
203
  function decodeFormula(data, ctx) {
199
- const reader = new ByteReader(data);
200
- const { row, col, xf } = readHead(reader);
201
- const result = data.subarray(reader.position, reader.position + 8);
202
- if (isNonNumericResult(result)) return nonNumericResult(row, col, result);
203
- return { kind: "value", cell: { row, col, value: ctx.numeric(xf, reader.f64()) } };
204
+ const reader = new ByteReader(data);
205
+ const { row, col, xf } = readHead(reader);
206
+ const result = data.subarray(reader.position, reader.position + 8);
207
+ if (isNonNumericResult(result)) return nonNumericResult(row, col, result);
208
+ return {
209
+ kind: "value",
210
+ cell: {
211
+ row,
212
+ col,
213
+ value: ctx.numeric(xf, reader.f64())
214
+ }
215
+ };
204
216
  }
205
217
  function isNonNumericResult(result) {
206
- return result[6] === 255 && result[7] === 255;
218
+ return result[6] === 255 && result[7] === 255;
207
219
  }
208
220
  function nonNumericResult(row, col, result) {
209
- const kind = result[0];
210
- if (kind === 0) return { kind: "pending-string", row, col };
211
- if (kind === 1) return { kind: "value", cell: { row, col, value: result[2] !== 0 } };
212
- return { kind: "value", cell: { row, col, value: null } };
221
+ const kind = result[0];
222
+ if (kind === 0) return {
223
+ kind: "pending-string",
224
+ row,
225
+ col
226
+ };
227
+ if (kind === 1) return {
228
+ kind: "value",
229
+ cell: {
230
+ row,
231
+ col,
232
+ value: result[2] !== 0
233
+ }
234
+ };
235
+ return {
236
+ kind: "value",
237
+ cell: {
238
+ row,
239
+ col,
240
+ value: null
241
+ }
242
+ };
213
243
  }
214
244
  function readHead(reader) {
215
- return { row: reader.u16(), col: reader.u16(), xf: reader.u16() };
245
+ return {
246
+ row: reader.u16(),
247
+ col: reader.u16(),
248
+ xf: reader.u16()
249
+ };
216
250
  }
217
251
 
218
- // src/biff/record-types.ts
219
- var RecordType = {
220
- BOF: 2057,
221
- // beginning of a substream (globals or a sheet)
222
- EOF: 10,
223
- // end of a substream
224
- BOUNDSHEET8: 133,
225
- // sheet name + byte offset of its BOF
226
- DATEMODE: 34,
227
- // 1900 vs 1904 date system
228
- FORMAT: 1054,
229
- // a number-format string keyed by format index
230
- XF: 224,
231
- // cell format record; carries its format index
232
- SST: 252,
233
- // shared string table
234
- CONTINUE: 60,
235
- // spillover for the preceding record (notably SST)
236
- LABELSST: 253,
237
- // string cell → index into the SST
238
- LABEL: 516,
239
- // inline string cell (old-style)
240
- RSTRING: 214,
241
- // inline rich string cell
242
- NUMBER: 515,
243
- // IEEE-754 double cell
244
- RK: 638,
245
- // compact numeric cell
246
- MULRK: 189,
247
- // run of RK cells sharing a row
248
- BLANK: 513,
249
- // formatted-but-empty cell
250
- MULBLANK: 190,
251
- // run of blank cells
252
- BOOLERR: 517,
253
- // boolean or error cell
254
- FORMULA: 6,
255
- // formula cell; result is a double or a typed sentinel
256
- STRING: 519
257
- // string result of the preceding FORMULA
252
+ //#endregion
253
+ //#region src/biff/record-types.ts
254
+ const RecordType = {
255
+ BOF: 2057,
256
+ EOF: 10,
257
+ BOUNDSHEET8: 133,
258
+ DATEMODE: 34,
259
+ FORMAT: 1054,
260
+ XF: 224,
261
+ SST: 252,
262
+ CONTINUE: 60,
263
+ LABELSST: 253,
264
+ LABEL: 516,
265
+ RSTRING: 214,
266
+ NUMBER: 515,
267
+ RK: 638,
268
+ MULRK: 189,
269
+ BLANK: 513,
270
+ MULBLANK: 190,
271
+ BOOLERR: 517,
272
+ FORMULA: 6,
273
+ STRING: 519
258
274
  };
259
275
 
260
- // src/biff/sheet-decoder.ts
261
- var DECODERS = /* @__PURE__ */ new Map([
262
- [RecordType.LABELSST, (d, c) => [decodeLabelSst(d, c)]],
263
- [RecordType.LABEL, (d) => [decodeLabel(d)]],
264
- [RecordType.RSTRING, (d) => [decodeLabel(d)]],
265
- [RecordType.NUMBER, (d, c) => [decodeNumber(d, c)]],
266
- [RecordType.RK, (d, c) => [decodeRkCell(d, c)]],
267
- [RecordType.MULRK, (d, c) => decodeMulRk(d, c)],
268
- [RecordType.BLANK, (d) => [decodeBlank(d)]],
269
- [RecordType.MULBLANK, (d) => decodeMulBlank(d)],
270
- [RecordType.BOOLERR, (d) => [decodeBoolErr(d)]]
276
+ //#endregion
277
+ //#region src/biff/sheet-decoder.ts
278
+ const DECODERS = /* @__PURE__ */ new Map([
279
+ [RecordType.LABELSST, (d, c) => [decodeLabelSst(d, c)]],
280
+ [RecordType.LABEL, (d) => [decodeLabel(d)]],
281
+ [RecordType.RSTRING, (d) => [decodeLabel(d)]],
282
+ [RecordType.NUMBER, (d, c) => [decodeNumber(d, c)]],
283
+ [RecordType.RK, (d, c) => [decodeRkCell(d, c)]],
284
+ [RecordType.MULRK, (d, c) => decodeMulRk(d, c)],
285
+ [RecordType.BLANK, (d) => [decodeBlank(d)]],
286
+ [RecordType.MULBLANK, (d) => decodeMulBlank(d)],
287
+ [RecordType.BOOLERR, (d) => [decodeBoolErr(d)]]
271
288
  ]);
272
289
  function decodeSheet(records, boundSheet, offsetToIndex, globals) {
273
- const ctx = { sharedStrings: globals.sharedStrings, numeric: globals.numeric };
274
- const cells = collectCells(records, offsetToIndex.get(boundSheet.offset), ctx);
275
- return { name: boundSheet.name, rows: toGrid(cells) };
290
+ const ctx = {
291
+ sharedStrings: globals.sharedStrings,
292
+ numeric: globals.numeric
293
+ };
294
+ const cells = collectCells(records, offsetToIndex.get(boundSheet.offset), ctx);
295
+ return {
296
+ name: boundSheet.name,
297
+ rows: toGrid(cells)
298
+ };
276
299
  }
277
300
  function collectCells(records, start, ctx) {
278
- if (start === void 0) return [];
279
- const cells = [];
280
- let pending = null;
281
- for (let i = start + 1; i < records.length; i++) {
282
- const record = records[i];
283
- if (record === void 0 || record.type === RecordType.EOF) break;
284
- pending = handleRecord(record, cells, pending, ctx);
285
- }
286
- return cells;
301
+ if (start === void 0) return [];
302
+ const cells = [];
303
+ let pending = null;
304
+ for (let i = start + 1; i < records.length; i++) {
305
+ const record = records[i];
306
+ if (record === void 0 || record.type === RecordType.EOF) break;
307
+ pending = handleRecord(record, cells, pending, ctx);
308
+ }
309
+ return cells;
287
310
  }
288
311
  function handleRecord(record, cells, pending, ctx) {
289
- if (record.type === RecordType.STRING && pending) {
290
- cells.push({ ...pending, value: readUnicodeString(new ByteReader(record.data), false) });
291
- return null;
292
- }
293
- if (record.type === RecordType.FORMULA) return appendFormula(record.data, cells, ctx);
294
- const decode = DECODERS.get(record.type);
295
- if (decode) cells.push(...decode(record.data, ctx));
296
- return null;
312
+ if (record.type === RecordType.STRING && pending) {
313
+ cells.push({
314
+ ...pending,
315
+ value: readUnicodeString(new ByteReader(record.data), false)
316
+ });
317
+ return null;
318
+ }
319
+ if (record.type === RecordType.FORMULA) return appendFormula(record.data, cells, ctx);
320
+ const decode = DECODERS.get(record.type);
321
+ if (decode) cells.push(...decode(record.data, ctx));
322
+ return null;
297
323
  }
298
324
  function appendFormula(data, cells, ctx) {
299
- const result = decodeFormula(data, ctx);
300
- if (result.kind === "value") {
301
- cells.push(result.cell);
302
- return null;
303
- }
304
- return { row: result.row, col: result.col };
305
- }
325
+ const result = decodeFormula(data, ctx);
326
+ if (result.kind === "value") {
327
+ cells.push(result.cell);
328
+ return null;
329
+ }
330
+ return {
331
+ row: result.row,
332
+ col: result.col
333
+ };
334
+ }
335
+ const MAX_ROW = 65535;
336
+ const MAX_COL = 255;
306
337
  function toGrid(cells) {
307
- if (cells.length === 0) return [];
308
- const maxRow = cells.reduce((max, cell) => Math.max(max, cell.row), 0);
309
- const maxCol = cells.reduce((max, cell) => Math.max(max, cell.col), 0);
310
- const rows = Array.from(
311
- { length: maxRow + 1 },
312
- () => new Array(maxCol + 1).fill(null)
313
- );
314
- for (const cell of cells) {
315
- const row = rows[cell.row];
316
- if (row) row[cell.col] = cell.value;
317
- }
318
- return rows;
338
+ if (cells.length === 0) return [];
339
+ const maxRow = cells.reduce((max, cell) => Math.max(max, cell.row), 0);
340
+ const maxCol = cells.reduce((max, cell) => Math.max(max, cell.col), 0);
341
+ if (maxRow > MAX_ROW || maxCol > MAX_COL) throw new XlsError(`Corrupt sheet: cell position (row ${maxRow}, col ${maxCol}) exceeds the BIFF8 limit of 65536 rows × 256 columns`);
342
+ const rows = Array.from({ length: maxRow + 1 }, () => new Array(maxCol + 1).fill(null));
343
+ for (const cell of cells) {
344
+ const row = rows[cell.row];
345
+ if (row) row[cell.col] = cell.value;
346
+ }
347
+ return rows;
319
348
  }
320
349
 
321
- // src/excel-serial-date.ts
322
- var MS_PER_DAY = 864e5;
350
+ //#endregion
351
+ //#region src/excel-serial-date.ts
352
+ const MS_PER_DAY = 864e5;
323
353
  function excelSerialToDate(serial, date1904) {
324
- const epochUtc = date1904 ? Date.UTC(1904, 0, 1) : Date.UTC(1899, 11, 30);
325
- return new Date(epochUtc + serial * MS_PER_DAY);
354
+ return new Date((date1904 ? Date.UTC(1904, 0, 1) : Date.UTC(1899, 11, 30)) + serial * MS_PER_DAY);
326
355
  }
327
356
 
328
- // src/biff/number-format.ts
329
- var BUILTIN_DATE_FORMAT_IDS = /* @__PURE__ */ new Set([
330
- 14,
331
- 15,
332
- 16,
333
- 17,
334
- 18,
335
- 19,
336
- 20,
337
- 21,
338
- 22,
339
- 27,
340
- 28,
341
- 29,
342
- 30,
343
- 31,
344
- 32,
345
- 33,
346
- 34,
347
- 35,
348
- 36,
349
- 45,
350
- 46,
351
- 47,
352
- 50,
353
- 51,
354
- 52,
355
- 53,
356
- 54,
357
- 55,
358
- 56,
359
- 57,
360
- 58
357
+ //#endregion
358
+ //#region src/biff/number-format.ts
359
+ const BUILTIN_DATE_FORMAT_IDS = /* @__PURE__ */ new Set([
360
+ 14,
361
+ 15,
362
+ 16,
363
+ 17,
364
+ 18,
365
+ 19,
366
+ 20,
367
+ 21,
368
+ 22,
369
+ 27,
370
+ 28,
371
+ 29,
372
+ 30,
373
+ 31,
374
+ 32,
375
+ 33,
376
+ 34,
377
+ 35,
378
+ 36,
379
+ 45,
380
+ 46,
381
+ 47,
382
+ 50,
383
+ 51,
384
+ 52,
385
+ 53,
386
+ 54,
387
+ 55,
388
+ 56,
389
+ 57,
390
+ 58
361
391
  ]);
362
392
  function isDateFormatIndex(formatIndex, customFormats) {
363
- if (BUILTIN_DATE_FORMAT_IDS.has(formatIndex)) return true;
364
- const format = customFormats.get(formatIndex);
365
- return format !== void 0 && looksLikeDateFormat(format);
393
+ if (BUILTIN_DATE_FORMAT_IDS.has(formatIndex)) return true;
394
+ const format = customFormats.get(formatIndex);
395
+ return format !== void 0 && looksLikeDateFormat(format);
366
396
  }
367
397
  function looksLikeDateFormat(format) {
368
- const stripped = format.replace(/\\./g, "").replace(/"[^"]*"/g, "").replace(/\[[^\]]*\]/g, "");
369
- return /[ymdhs]/i.test(stripped);
398
+ const stripped = format.replace(/\\./g, "").replace(/"[^"]*"/g, "").replace(/\[[^\]]*\]/g, "");
399
+ return /[ymdhs]/i.test(stripped);
370
400
  }
371
401
 
372
- // src/biff/continued-reader.ts
402
+ //#endregion
403
+ //#region src/biff/continued-reader.ts
373
404
  var ContinuedReader = class {
374
- constructor(chunks) {
375
- this.chunks = chunks;
376
- this.chunkIndex = 0;
377
- this.offset = 0;
378
- }
379
- get done() {
380
- this.settle();
381
- return this.chunkIndex >= this.chunks.length;
382
- }
383
- u8() {
384
- this.settle();
385
- return this.rawByte();
386
- }
387
- u16() {
388
- return this.u8() | this.u8() << 8;
389
- }
390
- u32() {
391
- return (this.u16() | this.u16() << 16) >>> 0;
392
- }
393
- // Reads a run of `count` characters, honoring the fresh grbit at every chunk
394
- // boundary crossed mid-run. `wide` is the compression of the first segment.
395
- readChars(count, wide) {
396
- let text = "";
397
- let isWide = wide;
398
- for (let i = 0; i < count; i++) {
399
- if (this.atChunkEnd()) isWide = (this.crossToNextChunk() & 1) !== 0;
400
- text += String.fromCharCode(isWide ? this.rawByte() | this.rawByte() << 8 : this.rawByte());
401
- }
402
- return text;
403
- }
404
- // Skips `length` bytes of trailing data (rich-text runs, phonetic block). These
405
- // do not re-read a grbit at boundaries — only the character array does.
406
- skip(length) {
407
- let left = length;
408
- while (left > 0) {
409
- this.settle();
410
- const chunk = this.currentChunk();
411
- const take = Math.min(left, chunk.length - this.offset);
412
- this.offset += take;
413
- left -= take;
414
- }
415
- }
416
- // Advance past any fully-consumed chunks so the cursor sits on real data.
417
- settle() {
418
- while (this.chunkIndex < this.chunks.length && this.offset >= this.chunkLength()) {
419
- this.chunkIndex += 1;
420
- this.offset = 0;
421
- }
422
- }
423
- atChunkEnd() {
424
- return this.chunkIndex < this.chunks.length && this.offset >= this.chunkLength();
425
- }
426
- crossToNextChunk() {
427
- this.chunkIndex += 1;
428
- this.offset = 0;
429
- return this.rawByte();
430
- }
431
- rawByte() {
432
- const chunk = this.currentChunk();
433
- const value = chunk[this.offset];
434
- if (value === void 0)
435
- throw new XlsError(`SST cursor past end of chunk ${this.chunkIndex} (offset ${this.offset})`);
436
- this.offset += 1;
437
- return value;
438
- }
439
- chunkLength() {
440
- return this.currentChunk().length;
441
- }
442
- currentChunk() {
443
- const chunk = this.chunks[this.chunkIndex];
444
- if (chunk === void 0)
445
- throw new XlsError(`SST reader ran past its ${this.chunks.length} chunk(s)`);
446
- return chunk;
447
- }
405
+ constructor(chunks) {
406
+ this.chunks = chunks;
407
+ this.chunkIndex = 0;
408
+ this.offset = 0;
409
+ }
410
+ get done() {
411
+ this.settle();
412
+ return this.chunkIndex >= this.chunks.length;
413
+ }
414
+ u8() {
415
+ this.settle();
416
+ return this.rawByte();
417
+ }
418
+ u16() {
419
+ return this.u8() | this.u8() << 8;
420
+ }
421
+ u32() {
422
+ return (this.u16() | this.u16() << 16) >>> 0;
423
+ }
424
+ readChars(count, wide) {
425
+ let text = "";
426
+ let isWide = wide;
427
+ for (let i = 0; i < count; i++) {
428
+ if (this.atChunkEnd()) isWide = (this.crossToNextChunk() & 1) !== 0;
429
+ text += String.fromCharCode(isWide ? this.rawByte() | this.rawByte() << 8 : this.rawByte());
430
+ }
431
+ return text;
432
+ }
433
+ skip(length) {
434
+ let left = length;
435
+ while (left > 0) {
436
+ this.settle();
437
+ const chunk = this.currentChunk();
438
+ const take = Math.min(left, chunk.length - this.offset);
439
+ this.offset += take;
440
+ left -= take;
441
+ }
442
+ }
443
+ settle() {
444
+ while (this.chunkIndex < this.chunks.length && this.offset >= this.chunkLength()) {
445
+ this.chunkIndex += 1;
446
+ this.offset = 0;
447
+ }
448
+ }
449
+ atChunkEnd() {
450
+ return this.chunkIndex < this.chunks.length && this.offset >= this.chunkLength();
451
+ }
452
+ crossToNextChunk() {
453
+ this.chunkIndex += 1;
454
+ this.offset = 0;
455
+ return this.rawByte();
456
+ }
457
+ rawByte() {
458
+ const value = this.currentChunk()[this.offset];
459
+ if (value === void 0) throw new XlsError(`SST cursor past end of chunk ${this.chunkIndex} (offset ${this.offset})`);
460
+ this.offset += 1;
461
+ return value;
462
+ }
463
+ chunkLength() {
464
+ return this.currentChunk().length;
465
+ }
466
+ currentChunk() {
467
+ const chunk = this.chunks[this.chunkIndex];
468
+ if (chunk === void 0) throw new XlsError(`SST reader ran past its ${this.chunks.length} chunk(s)`);
469
+ return chunk;
470
+ }
448
471
  };
449
472
 
450
- // src/biff/shared-strings.ts
451
- var F_WIDE2 = 1;
452
- var F_EXT2 = 4;
453
- var F_RICH2 = 8;
454
- var BYTES_PER_RUN2 = 4;
473
+ //#endregion
474
+ //#region src/biff/shared-strings.ts
475
+ const F_WIDE = 1;
476
+ const F_EXT = 4;
477
+ const F_RICH = 8;
478
+ const BYTES_PER_RUN = 4;
455
479
  function parseSharedStrings(chunks) {
456
- const reader = new ContinuedReader(chunks);
457
- reader.u32();
458
- const unique = reader.u32();
459
- const strings = [];
460
- for (let i = 0; i < unique; i++) strings.push(readString(reader));
461
- return strings;
480
+ const reader = new ContinuedReader(chunks);
481
+ reader.u32();
482
+ const unique = reader.u32();
483
+ const strings = [];
484
+ for (let i = 0; i < unique; i++) strings.push(readString(reader));
485
+ return strings;
462
486
  }
463
487
  function readString(reader) {
464
- const charCount = reader.u16();
465
- const flags = reader.u8();
466
- const runCount = (flags & F_RICH2) !== 0 ? reader.u16() : 0;
467
- const extSize = (flags & F_EXT2) !== 0 ? reader.u32() : 0;
468
- const text = reader.readChars(charCount, (flags & F_WIDE2) !== 0);
469
- reader.skip(runCount * BYTES_PER_RUN2 + extSize);
470
- return text;
488
+ const charCount = reader.u16();
489
+ const flags = reader.u8();
490
+ const runCount = (flags & F_RICH) !== 0 ? reader.u16() : 0;
491
+ const extSize = (flags & F_EXT) !== 0 ? reader.u32() : 0;
492
+ const text = reader.readChars(charCount, (flags & F_WIDE) !== 0);
493
+ reader.skip(runCount * BYTES_PER_RUN + extSize);
494
+ return text;
471
495
  }
472
496
 
473
- // src/biff/workbook-globals.ts
497
+ //#endregion
498
+ //#region src/biff/workbook-globals.ts
474
499
  function parseGlobals(records) {
475
- let date1904 = false;
476
- const customFormats = /* @__PURE__ */ new Map();
477
- const xfFormatIndex = [];
478
- let sharedStrings = [];
479
- const boundSheets = [];
480
- for (let i = 0; i < records.length; i++) {
481
- const record = records[i];
482
- if (record === void 0 || record.type === RecordType.EOF) break;
483
- if (record.type === RecordType.DATEMODE) date1904 = new ByteReader(record.data).u16() === 1;
484
- else if (record.type === RecordType.FORMAT) addFormat(record.data, customFormats);
485
- else if (record.type === RecordType.XF)
486
- xfFormatIndex.push(new ByteReader(record.data, 2).u16());
487
- else if (record.type === RecordType.SST)
488
- sharedStrings = parseSharedStrings(collectSstChunks(records, i));
489
- else if (record.type === RecordType.BOUNDSHEET8) boundSheets.push(parseBoundSheet(record.data));
490
- }
491
- return {
492
- sharedStrings,
493
- boundSheets,
494
- numeric: makeNumeric(xfFormatIndex, customFormats, date1904)
495
- };
500
+ let date1904 = false;
501
+ const customFormats = /* @__PURE__ */ new Map();
502
+ const xfFormatIndex = [];
503
+ let sharedStrings = [];
504
+ const boundSheets = [];
505
+ for (let i = 0; i < records.length; i++) {
506
+ const record = records[i];
507
+ if (record === void 0 || record.type === RecordType.EOF) break;
508
+ if (record.type === RecordType.DATEMODE) date1904 = new ByteReader(record.data).u16() === 1;
509
+ else if (record.type === RecordType.FORMAT) addFormat(record.data, customFormats);
510
+ else if (record.type === RecordType.XF) xfFormatIndex.push(new ByteReader(record.data, 2).u16());
511
+ else if (record.type === RecordType.SST) sharedStrings = parseSharedStrings(collectSstChunks(records, i));
512
+ else if (record.type === RecordType.BOUNDSHEET8) boundSheets.push(parseBoundSheet(record.data));
513
+ }
514
+ return {
515
+ sharedStrings,
516
+ boundSheets,
517
+ numeric: makeNumeric(xfFormatIndex, customFormats, date1904)
518
+ };
496
519
  }
497
520
  function addFormat(data, into) {
498
- const reader = new ByteReader(data);
499
- const formatIndex = reader.u16();
500
- into.set(formatIndex, readUnicodeString(reader, false));
521
+ const reader = new ByteReader(data);
522
+ const formatIndex = reader.u16();
523
+ into.set(formatIndex, readUnicodeString(reader, false));
501
524
  }
502
525
  function collectSstChunks(records, sstIndex) {
503
- const first = records[sstIndex];
504
- const chunks = first ? [first.data] : [];
505
- for (let j = sstIndex + 1; j < records.length; j++) {
506
- const record = records[j];
507
- if (record === void 0 || record.type !== RecordType.CONTINUE) break;
508
- chunks.push(record.data);
509
- }
510
- return chunks;
526
+ const first = records[sstIndex];
527
+ const chunks = first ? [first.data] : [];
528
+ for (let j = sstIndex + 1; j < records.length; j++) {
529
+ const record = records[j];
530
+ if (record === void 0 || record.type !== RecordType.CONTINUE) break;
531
+ chunks.push(record.data);
532
+ }
533
+ return chunks;
511
534
  }
512
535
  function parseBoundSheet(data) {
513
- const reader = new ByteReader(data);
514
- const offset = reader.u32();
515
- reader.u16();
516
- return { name: readUnicodeString(reader, true), offset };
536
+ const reader = new ByteReader(data);
537
+ const offset = reader.u32();
538
+ reader.u16();
539
+ return {
540
+ name: readUnicodeString(reader, true),
541
+ offset
542
+ };
517
543
  }
518
544
  function makeNumeric(xfFormatIndex, customFormats, date1904) {
519
- return (xfIndex, value) => {
520
- const formatIndex = xfFormatIndex[xfIndex] ?? 0;
521
- return isDateFormatIndex(formatIndex, customFormats) ? excelSerialToDate(value, date1904) : value;
522
- };
545
+ return (xfIndex, value) => {
546
+ return isDateFormatIndex(xfFormatIndex[xfIndex] ?? 0, customFormats) ? excelSerialToDate(value, date1904) : value;
547
+ };
523
548
  }
524
549
 
525
- // src/biff/parse-workbook.ts
550
+ //#endregion
551
+ //#region src/biff/parse-workbook.ts
526
552
  function parseWorkbook(stream) {
527
- const records = readRecords(stream);
528
- const globals = parseGlobals(records);
529
- const offsetToIndex = new Map(records.map((record, index) => [record.offset, index]));
530
- const sheets = globals.boundSheets.map(
531
- (sheet) => decodeSheet(records, sheet, offsetToIndex, globals)
532
- );
533
- return { sheets };
553
+ const records = readRecords(stream);
554
+ const globals = parseGlobals(records);
555
+ const offsetToIndex = new Map(records.map((record, index) => [record.offset, index]));
556
+ return { sheets: globals.boundSheets.map((sheet) => decodeSheet(records, sheet, offsetToIndex, globals)) };
534
557
  }
535
558
 
536
- // src/cfb/cfb-header.ts
537
- var SIGNATURE = [208, 207, 17, 224, 161, 177, 26, 225];
559
+ //#endregion
560
+ //#region src/cfb/cfb-header.ts
561
+ const SIGNATURE = [
562
+ 208,
563
+ 207,
564
+ 17,
565
+ 224,
566
+ 161,
567
+ 177,
568
+ 26,
569
+ 225
570
+ ];
538
571
  function parseCfbHeader(bytes) {
539
- assertSignature(bytes);
540
- const reader = new ByteReader(bytes, 30);
541
- const sectorSize = 1 << reader.u16();
542
- const miniSectorSize = 1 << reader.u16();
543
- reader.position = 44;
544
- reader.u32();
545
- const firstDirSector = reader.u32();
546
- reader.u32();
547
- const miniStreamCutoff = reader.u32();
548
- const firstMiniFatSector = reader.u32();
549
- reader.u32();
550
- const firstDifatSector = reader.u32();
551
- const numDifatSectors = reader.u32();
552
- return {
553
- sectorSize,
554
- miniSectorSize,
555
- firstDirSector,
556
- miniStreamCutoff,
557
- firstMiniFatSector,
558
- firstDifatSector,
559
- numDifatSectors,
560
- initialDifat: readInitialDifat(bytes)
561
- };
572
+ assertSignature(bytes);
573
+ const reader = new ByteReader(bytes, 30);
574
+ const sectorSize = powerOfTwoSize(reader.u16(), "sector", [9, 12]);
575
+ const miniSectorSize = powerOfTwoSize(reader.u16(), "mini-sector", [6]);
576
+ reader.position = 44;
577
+ reader.u32();
578
+ const firstDirSector = reader.u32();
579
+ reader.u32();
580
+ const miniStreamCutoff = reader.u32();
581
+ const firstMiniFatSector = reader.u32();
582
+ reader.u32();
583
+ return {
584
+ sectorSize,
585
+ miniSectorSize,
586
+ firstDirSector,
587
+ miniStreamCutoff,
588
+ firstMiniFatSector,
589
+ firstDifatSector: reader.u32(),
590
+ numDifatSectors: reader.u32(),
591
+ initialDifat: readInitialDifat(bytes)
592
+ };
593
+ }
594
+ function powerOfTwoSize(shift, kind, allowed) {
595
+ if (!allowed.includes(shift)) throw new XlsError(`Invalid CFB ${kind} shift ${shift}: expected one of [${allowed.join(", ")}]`);
596
+ return 1 << shift;
562
597
  }
563
598
  function readInitialDifat(bytes) {
564
- const reader = new ByteReader(bytes, 76);
565
- const entries = [];
566
- for (let i = 0; i < 109; i++) entries.push(reader.u32());
567
- return entries;
599
+ const reader = new ByteReader(bytes, 76);
600
+ const entries = [];
601
+ for (let i = 0; i < 109; i++) entries.push(reader.u32());
602
+ return entries;
568
603
  }
569
604
  function assertSignature(bytes) {
570
- if (bytes.length < 512) {
571
- throw new XlsError(
572
- `File too small to be an OLE2 container: ${bytes.length} bytes (need >= 512)`
573
- );
574
- }
575
- for (let i = 0; i < SIGNATURE.length; i++) {
576
- if (bytes[i] !== SIGNATURE[i]) {
577
- const got = Array.from(bytes.slice(0, 8), (b) => b.toString(16).padStart(2, "0")).join(" ");
578
- throw new XlsError(`Not an OLE2 / .xls file: expected magic D0CF11E0A1B11AE1, got ${got}`);
579
- }
580
- }
605
+ if (bytes.length < 512) throw new XlsError(`File too small to be an OLE2 container: ${bytes.length} bytes (need >= 512)`);
606
+ for (let i = 0; i < SIGNATURE.length; i++) if (bytes[i] !== SIGNATURE[i]) throw new XlsError(`Not an OLE2 / .xls file: expected magic D0CF11E0A1B11AE1, got ${Array.from(bytes.slice(0, 8), (b) => b.toString(16).padStart(2, "0")).join(" ")}`);
581
607
  }
582
608
 
583
- // src/cfb/directory.ts
584
- var DIRECTORY_ENTRY_SIZE = 128;
585
- var OBJECT_TYPE_ROOT = 5;
586
- function parseDirectory(directoryBytes2) {
587
- const entries = [];
588
- const count = Math.floor(directoryBytes2.length / DIRECTORY_ENTRY_SIZE);
589
- for (let i = 0; i < count; i++) {
590
- const entry = parseEntry(directoryBytes2.subarray(i * DIRECTORY_ENTRY_SIZE));
591
- if (entry) entries.push(entry);
592
- }
593
- return entries;
609
+ //#endregion
610
+ //#region src/cfb/directory.ts
611
+ const DIRECTORY_ENTRY_SIZE = 128;
612
+ const OBJECT_TYPE_ROOT = 5;
613
+ function parseDirectory(directoryBytes) {
614
+ const entries = [];
615
+ const count = Math.floor(directoryBytes.length / DIRECTORY_ENTRY_SIZE);
616
+ for (let i = 0; i < count; i++) {
617
+ const entry = parseEntry(directoryBytes.subarray(i * DIRECTORY_ENTRY_SIZE));
618
+ if (entry) entries.push(entry);
619
+ }
620
+ return entries;
594
621
  }
595
622
  function findRoot(entries) {
596
- return entries.find((entry) => entry.objectType === OBJECT_TYPE_ROOT);
623
+ return entries.find((entry) => entry.objectType === OBJECT_TYPE_ROOT);
597
624
  }
598
625
  function parseEntry(entryBytes) {
599
- const reader = new ByteReader(entryBytes);
600
- const nameBytes = reader.slice(64);
601
- const nameLength = reader.u16();
602
- const objectType = reader.u8();
603
- if (objectType === 0) return null;
604
- reader.position = 116;
605
- const startSector = reader.u32();
606
- const size = reader.u32();
607
- return { name: decodeName(nameBytes, nameLength), objectType, startSector, size };
626
+ const reader = new ByteReader(entryBytes);
627
+ const nameBytes = reader.slice(64);
628
+ const nameLength = reader.u16();
629
+ const objectType = reader.u8();
630
+ if (objectType === 0) return null;
631
+ reader.position = 116;
632
+ const startSector = reader.u32();
633
+ const size = reader.u32();
634
+ return {
635
+ name: decodeName(nameBytes, nameLength),
636
+ objectType,
637
+ startSector,
638
+ size
639
+ };
608
640
  }
609
641
  function decodeName(nameBytes, byteLength) {
610
- const chars = Math.max(0, byteLength / 2 - 1);
611
- const reader = new ByteReader(nameBytes);
612
- let name = "";
613
- for (let i = 0; i < chars; i++) name += String.fromCharCode(reader.u16());
614
- return name;
642
+ const chars = Math.max(0, byteLength / 2 - 1);
643
+ const reader = new ByteReader(nameBytes);
644
+ let name = "";
645
+ for (let i = 0; i < chars; i++) name += String.fromCharCode(reader.u16());
646
+ return name;
615
647
  }
616
648
 
617
- // src/cfb/sector-chains.ts
618
- var ENDOFCHAIN = 4294967294;
619
- var FREESECT = 4294967295;
649
+ //#endregion
650
+ //#region src/cfb/sector-chains.ts
651
+ const ENDOFCHAIN = 4294967294;
652
+ const FREESECT = 4294967295;
620
653
  function sectorOffset(id, sectorSize) {
621
- return (id + 1) * sectorSize;
654
+ return (id + 1) * sectorSize;
622
655
  }
623
656
  function buildFat(bytes, header) {
624
- const fatSectorIds = collectFatSectorIds(bytes, header);
625
- const fat = [];
626
- const perSector = header.sectorSize / 4;
627
- for (const id of fatSectorIds) {
628
- const reader = new ByteReader(bytes, sectorOffset(id, header.sectorSize));
629
- for (let i = 0; i < perSector; i++) fat.push(reader.u32());
630
- }
631
- return fat;
657
+ const fatSectorIds = collectFatSectorIds(bytes, header);
658
+ const fat = [];
659
+ const perSector = header.sectorSize / 4;
660
+ for (const id of fatSectorIds) {
661
+ const reader = new ByteReader(bytes, sectorOffset(id, header.sectorSize));
662
+ for (let i = 0; i < perSector; i++) fat.push(reader.u32());
663
+ }
664
+ return fat;
632
665
  }
633
666
  function collectFatSectorIds(bytes, header) {
634
- const ids = header.initialDifat.filter((id) => id !== FREESECT && id !== ENDOFCHAIN);
635
- const perSector = header.sectorSize / 4;
636
- let difatSector = header.firstDifatSector;
637
- for (let n = 0; n < header.numDifatSectors && difatSector !== ENDOFCHAIN; n++) {
638
- const reader = new ByteReader(bytes, sectorOffset(difatSector, header.sectorSize));
639
- for (let i = 0; i < perSector - 1; i++) {
640
- const id = reader.u32();
641
- if (id !== FREESECT && id !== ENDOFCHAIN) ids.push(id);
642
- }
643
- difatSector = reader.u32();
644
- }
645
- return ids;
667
+ const ids = header.initialDifat.filter((id) => id !== FREESECT && id !== ENDOFCHAIN);
668
+ const perSector = header.sectorSize / 4;
669
+ const seen = /* @__PURE__ */ new Set();
670
+ let difatSector = header.firstDifatSector;
671
+ for (let n = 0; n < header.numDifatSectors && difatSector !== ENDOFCHAIN && !seen.has(difatSector); n++) {
672
+ seen.add(difatSector);
673
+ const reader = new ByteReader(bytes, sectorOffset(difatSector, header.sectorSize));
674
+ for (let i = 0; i < perSector - 1; i++) {
675
+ const id = reader.u32();
676
+ if (id !== FREESECT && id !== ENDOFCHAIN) ids.push(id);
677
+ }
678
+ difatSector = reader.u32();
679
+ }
680
+ return ids;
646
681
  }
647
682
  function followChain(fat, start) {
648
- const chain = [];
649
- const seen = /* @__PURE__ */ new Set();
650
- let current = start;
651
- while (current !== ENDOFCHAIN && current < fat.length && !seen.has(current)) {
652
- seen.add(current);
653
- chain.push(current);
654
- current = fat[current] ?? ENDOFCHAIN;
655
- }
656
- return chain;
683
+ const chain = [];
684
+ const seen = /* @__PURE__ */ new Set();
685
+ let current = start;
686
+ while (current !== ENDOFCHAIN && current < fat.length && !seen.has(current)) {
687
+ seen.add(current);
688
+ chain.push(current);
689
+ current = fat[current] ?? ENDOFCHAIN;
690
+ }
691
+ return chain;
657
692
  }
658
693
  function readChainBytes(bytes, chain, sectorSize, size) {
659
- const out = new Uint8Array(chain.length * sectorSize);
660
- chain.forEach((id, index) => {
661
- const start = sectorOffset(id, sectorSize);
662
- out.set(bytes.subarray(start, start + sectorSize), index * sectorSize);
663
- });
664
- return out.subarray(0, size);
694
+ const out = new Uint8Array(chain.length * sectorSize);
695
+ chain.forEach((id, index) => {
696
+ const start = sectorOffset(id, sectorSize);
697
+ out.set(bytes.subarray(start, start + sectorSize), index * sectorSize);
698
+ });
699
+ return out.subarray(0, size);
665
700
  }
666
701
 
667
- // src/cfb/compound-file.ts
702
+ //#endregion
703
+ //#region src/cfb/compound-file.ts
668
704
  function openCompoundFile(bytes) {
669
- const header = parseCfbHeader(bytes);
670
- const fat = buildFat(bytes, header);
671
- const directory = parseDirectory(directoryBytes(bytes, header, fat));
672
- const file = {
673
- bytes,
674
- header,
675
- fat,
676
- directory,
677
- miniStream: readMiniStreamContainer(bytes, header, fat, directory),
678
- miniFat: buildMiniFat(bytes, header, fat)
679
- };
680
- return {
681
- readStream(name) {
682
- const entry = directory.find((e) => e.name === name);
683
- if (!entry) return void 0;
684
- return entry.size < header.miniStreamCutoff ? readMiniStream(file, entry) : readRegularStream(file, entry);
685
- }
686
- };
705
+ const header = parseCfbHeader(bytes);
706
+ const fat = buildFat(bytes, header);
707
+ const directory = parseDirectory(directoryBytes(bytes, header, fat));
708
+ const file = {
709
+ bytes,
710
+ header,
711
+ fat,
712
+ directory,
713
+ miniStream: readMiniStreamContainer(bytes, header, fat, directory),
714
+ miniFat: buildMiniFat(bytes, header, fat)
715
+ };
716
+ return { readStream(name) {
717
+ const entry = directory.find((e) => e.name === name);
718
+ if (!entry) return void 0;
719
+ return entry.size < header.miniStreamCutoff ? readMiniStream(file, entry) : readRegularStream(file, entry);
720
+ } };
687
721
  }
688
722
  function directoryBytes(bytes, header, fat) {
689
- const chain = followChain(fat, header.firstDirSector);
690
- return readChainBytes(bytes, chain, header.sectorSize, chain.length * header.sectorSize);
723
+ const chain = followChain(fat, header.firstDirSector);
724
+ return readChainBytes(bytes, chain, header.sectorSize, chain.length * header.sectorSize);
691
725
  }
692
726
  function readRegularStream(file, entry) {
693
- const chain = followChain(file.fat, entry.startSector);
694
- return readChainBytes(file.bytes, chain, file.header.sectorSize, entry.size);
727
+ const chain = followChain(file.fat, entry.startSector);
728
+ return readChainBytes(file.bytes, chain, file.header.sectorSize, entry.size);
695
729
  }
696
730
  function readMiniStreamContainer(bytes, header, fat, directory) {
697
- const root = findRoot(directory);
698
- if (!root) return new Uint8Array(0);
699
- const chain = followChain(fat, root.startSector);
700
- return readChainBytes(bytes, chain, header.sectorSize, root.size);
731
+ const root = findRoot(directory);
732
+ if (!root) return /* @__PURE__ */ new Uint8Array(0);
733
+ return readChainBytes(bytes, followChain(fat, root.startSector), header.sectorSize, root.size);
701
734
  }
702
735
  function buildMiniFat(bytes, header, fat) {
703
- const chain = followChain(fat, header.firstMiniFatSector);
704
- const raw = readChainBytes(bytes, chain, header.sectorSize, chain.length * header.sectorSize);
705
- return toU32Array(raw);
736
+ const chain = followChain(fat, header.firstMiniFatSector);
737
+ return toU32Array(readChainBytes(bytes, chain, header.sectorSize, chain.length * header.sectorSize));
706
738
  }
707
739
  function readMiniStream(file, entry) {
708
- const { miniStream, miniFat, header } = file;
709
- const chain = followChain(miniFat, entry.startSector);
710
- const out = new Uint8Array(chain.length * header.miniSectorSize);
711
- chain.forEach((id, index) => {
712
- const start = id * header.miniSectorSize;
713
- out.set(
714
- miniStream.subarray(start, start + header.miniSectorSize),
715
- index * header.miniSectorSize
716
- );
717
- });
718
- return out.subarray(0, entry.size);
740
+ const { miniStream, miniFat, header } = file;
741
+ const chain = followChain(miniFat, entry.startSector);
742
+ const out = new Uint8Array(chain.length * header.miniSectorSize);
743
+ chain.forEach((id, index) => {
744
+ const start = id * header.miniSectorSize;
745
+ out.set(miniStream.subarray(start, start + header.miniSectorSize), index * header.miniSectorSize);
746
+ });
747
+ return out.subarray(0, entry.size);
719
748
  }
720
749
  function toU32Array(raw) {
721
- const reader = new ByteReader(raw);
722
- const values = [];
723
- const count = Math.floor(raw.length / 4);
724
- for (let i = 0; i < count; i++) values.push(reader.u32());
725
- return values;
750
+ const reader = new ByteReader(raw);
751
+ const values = [];
752
+ const count = Math.floor(raw.length / 4);
753
+ for (let i = 0; i < count; i++) values.push(reader.u32());
754
+ return values;
726
755
  }
727
756
 
728
- // src/reader.ts
757
+ //#endregion
758
+ //#region src/reader.ts
729
759
  function readXls(data) {
730
- const cfb = openCompoundFile(toBytes(data));
731
- const stream = cfb.readStream("Workbook") ?? cfb.readStream("Book");
732
- if (!stream) {
733
- throw new XlsError(
734
- "No 'Workbook' or 'Book' stream in the OLE2 file \u2014 not a BIFF .xls workbook"
735
- );
736
- }
737
- return parseWorkbook(stream);
760
+ const cfb = openCompoundFile(toBytes(data));
761
+ const stream = cfb.readStream("Workbook") ?? cfb.readStream("Book");
762
+ if (!stream) throw new XlsError("No 'Workbook' or 'Book' stream in the OLE2 file — not a BIFF .xls workbook");
763
+ return parseWorkbook(stream);
738
764
  }
739
765
  function readFirstSheet(data) {
740
- return readXls(data).sheets[0];
766
+ return readXls(data).sheets[0];
741
767
  }
742
768
  function toBytes(data) {
743
- return data instanceof Uint8Array ? data : new Uint8Array(data);
744
- }
745
- // Annotate the CommonJS export names for ESM import in node:
746
- 0 && (module.exports = {
747
- XlsError,
748
- excelSerialToDate,
749
- readFirstSheet,
750
- readXls
751
- });
769
+ return data instanceof Uint8Array ? data : new Uint8Array(data);
770
+ }
771
+
772
+ //#endregion
773
+ exports.XlsError = XlsError;
774
+ exports.excelSerialToDate = excelSerialToDate;
775
+ exports.readFirstSheet = readFirstSheet;
776
+ exports.readXls = readXls;
752
777
  //# sourceMappingURL=index.cjs.map