javascript-excel 1.0.3 → 2.0.0-alpha.2

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 +69 -2
  2. package/dist/auto-width-2oBzjeNG.d.cts +11 -0
  3. package/dist/auto-width-CT-BihTW.d.ts +10 -0
  4. package/dist/csv-DyVH9y7S.cjs +647 -0
  5. package/dist/csv-pXfaputs.js +618 -0
  6. package/dist/csv.cjs +7 -0
  7. package/dist/csv.d.cts +89 -0
  8. package/dist/csv.d.ts +89 -0
  9. package/dist/csv.js +1 -0
  10. package/dist/dom.cjs +440 -0
  11. package/dist/dom.d.cts +78 -0
  12. package/dist/dom.d.ts +78 -0
  13. package/dist/dom.js +437 -0
  14. package/dist/errors-CvGlfw0E.js +28 -0
  15. package/dist/errors-DOPrrGS4.cjs +69 -0
  16. package/dist/index.cjs +627 -0
  17. package/dist/index.d.cts +255 -0
  18. package/dist/index.d.ts +255 -0
  19. package/dist/index.js +597 -0
  20. package/dist/infer-BR-J9BZa.js +88 -0
  21. package/dist/infer-D9EC9vJ-.cjs +105 -0
  22. package/dist/iso-date-3TY1OlGd.cjs +57 -0
  23. package/dist/iso-date-CXnn-9mT.js +46 -0
  24. package/dist/numfmt-BBgB7iQA.js +429 -0
  25. package/dist/numfmt-Dv6AjopS.cjs +512 -0
  26. package/dist/read-C6L7Nyy3.d.cts +78 -0
  27. package/dist/read-DDN5ZsPe.js +2909 -0
  28. package/dist/read-Ddkks7qC.d.ts +78 -0
  29. package/dist/read-Ym1voUct.cjs +2932 -0
  30. package/dist/read.cjs +6 -0
  31. package/dist/read.d.cts +15 -0
  32. package/dist/read.d.ts +15 -0
  33. package/dist/read.js +1 -0
  34. package/dist/sheet-names-qpXsvMpM.cjs +1005 -0
  35. package/dist/sheet-names-uT2EH5Ui.js +832 -0
  36. package/dist/signal-Dz0ZYe6d.d.cts +13 -0
  37. package/dist/signal-Dz0ZYe6d.d.ts +13 -0
  38. package/dist/warnings-C_12PT4t.d.cts +410 -0
  39. package/dist/warnings-DXJKe1lx.d.ts +410 -0
  40. package/dist/worker.cjs +240 -0
  41. package/dist/worker.d.cts +65 -0
  42. package/dist/worker.d.ts +65 -0
  43. package/dist/worker.js +238 -0
  44. package/dist/write-BOh9jfu1.cjs +1487 -0
  45. package/dist/write-C5JgeIar.d.cts +29 -0
  46. package/dist/write-CYpLGuzl.d.ts +29 -0
  47. package/dist/write-DubvcG-x.js +1470 -0
  48. package/package.json +101 -51
  49. package/.babelrc +0 -10
  50. package/.circleci/config.yml +0 -39
  51. package/lib/index.d.ts +0 -1
  52. package/lib/index.js +0 -22
  53. package/lib/javascript-excel.js +0 -17703
  54. package/src/index.tsx +0 -11
  55. package/test/unit/sample.spec.js +0 -5
  56. package/tsconfig.json +0 -54
  57. package/webpack.config.js +0 -19
  58. /package/{LICENSE.md → LICENSE} +0 -0
package/dist/index.js ADDED
@@ -0,0 +1,597 @@
1
+ import { a as LimitError, i as FormatError, n as EnvironmentError, o as ValidationError, r as ExcelError, s as isExcelError, t as CsvError } from "./errors-CvGlfw0E.js";
2
+ import { n as toBlob, r as toUint8Array, t as XLSX_MIME } from "./write-DubvcG-x.js";
3
+ import { i as serialToDate, n as isDateFormat, r as dateToSerial, t as BUILTIN_NUM_FMTS } from "./numfmt-BBgB7iQA.js";
4
+ import { C as encodeRange, S as encodeCol, _ as MAX_ROWS, b as decodeRange, g as MAX_COLS, h as mergeStyles, l as textWidth, m as cellText, n as validateSheetName, r as AUTO_WIDTH, t as sanitizeSheetName, v as decodeCell, x as encodeCell, y as decodeCol } from "./sheet-names-uT2EH5Ui.js";
5
+ import { n as parseIsoDate, t as isoDate } from "./iso-date-CXnn-9mT.js";
6
+ // src/dataset.ts
7
+ /**
8
+ * Dataset builders (docs/api.md §4.3): `{ columns, data }` ↔ Sheet.
9
+ *
10
+ * `fromDataset` lays out header rows (with header groups as merged cells),
11
+ * data rows and an optional totals row; `fromDatasets` stacks several blocks
12
+ * on one sheet; `toDataset` goes the other way for import.
13
+ */
14
+ function columnError(message, details = {}) {
15
+ return new ValidationError("INVALID_COLUMN", message, { details });
16
+ }
17
+ const FORBIDDEN_SEGMENTS = /* @__PURE__ */ new Set([
18
+ "__proto__",
19
+ "prototype",
20
+ "constructor"
21
+ ]);
22
+ /** Parses 'a.b', 'items[0].name', "a['x.y']" and 'a["x"]' into segments. */
23
+ function parsePath(path) {
24
+ const segs = [];
25
+ let i = 0;
26
+ const fail = () => {
27
+ throw columnError(`Invalid path ${JSON.stringify(path)}.`, { path });
28
+ };
29
+ if (typeof path !== "string" || path.length === 0) fail();
30
+ while (i < path.length) {
31
+ if (path[i] === "[") {
32
+ const q = path[i + 1];
33
+ if (q === "'" || q === "\"") {
34
+ const end = path.indexOf(`${q}]`, i + 2);
35
+ if (end < 0) fail();
36
+ segs.push(path.slice(i + 2, end));
37
+ i = end + 2;
38
+ } else {
39
+ const end = path.indexOf("]", i);
40
+ const n = path.slice(i + 1, end);
41
+ if (end < 0 || !/^\d+$/.test(n)) fail();
42
+ segs.push(n);
43
+ i = end + 1;
44
+ }
45
+ if (path[i] === ".") i++;
46
+ continue;
47
+ }
48
+ let j = i;
49
+ while (j < path.length && path[j] !== "." && path[j] !== "[") j++;
50
+ if (j === i) fail();
51
+ segs.push(path.slice(i, j));
52
+ i = path[j] === "." ? j + 1 : j;
53
+ if (path[j] === "." && i >= path.length) fail();
54
+ }
55
+ for (const s of segs) if (FORBIDDEN_SEGMENTS.has(s)) throw columnError(`Path ${JSON.stringify(path)} uses the forbidden segment ${s}.`, {
56
+ path,
57
+ segment: s
58
+ });
59
+ return segs;
60
+ }
61
+ const own = (o, k) => o !== null && (typeof o === "object" || typeof o === "function") && Object.prototype.hasOwnProperty.call(o, k) ? o[k] : void 0;
62
+ function accessorOf(def, position) {
63
+ if ([
64
+ def.key !== void 0,
65
+ def.path !== void 0,
66
+ def.value !== void 0,
67
+ def.index !== void 0
68
+ ].filter(Boolean).length > 1) throw columnError(`Column ${JSON.stringify(def.title ?? def.key ?? def.path)} has more than one accessor (key, path, value, index).`);
69
+ if (def.key !== void 0) {
70
+ if (typeof def.key !== "string") throw columnError("key must be a string.");
71
+ const key = def.key;
72
+ return (row) => own(row, key);
73
+ }
74
+ if (def.path !== void 0) {
75
+ const segs = parsePath(def.path);
76
+ return (row) => {
77
+ let v = row;
78
+ for (const s of segs) {
79
+ v = own(v, s);
80
+ if (v === void 0) return void 0;
81
+ }
82
+ return v;
83
+ };
84
+ }
85
+ if (def.value !== void 0) {
86
+ if (typeof def.value !== "function") throw columnError("value must be a function.");
87
+ const fn = def.value;
88
+ return (row, rowIndex) => fn(row, { rowIndex });
89
+ }
90
+ const index = def.index ?? position;
91
+ if (!Number.isInteger(index) || index < 0) throw columnError(`index must be a non-negative integer, got ${String(def.index)}.`);
92
+ const named = def.index !== void 0;
93
+ return (row) => {
94
+ if (Array.isArray(row)) return row[index];
95
+ if (named || row === null || row === void 0) return void 0;
96
+ throw columnError(`Column ${JSON.stringify(def.title ?? `#${position + 1}`)} has no accessor (key, path, value or index) and the data rows are objects.`);
97
+ };
98
+ }
99
+ const PLAIN_NUMBER = /^[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?$/;
100
+ function isCellObject(v) {
101
+ return typeof v === "object" && v !== null && !(v instanceof Date) && !("error" in v) && !("richText" in v);
102
+ }
103
+ function coerce(v, type) {
104
+ if (v === null || v === void 0 || type === void 0 || type === "auto") return {
105
+ value: v,
106
+ failed: false
107
+ };
108
+ switch (type) {
109
+ case "string":
110
+ if (v instanceof Date) return {
111
+ value: Number.isFinite(v.getTime()) ? isoDate(v, "local") : "",
112
+ failed: false
113
+ };
114
+ return {
115
+ value: typeof v === "object" ? cellText(v) : String(v),
116
+ failed: false
117
+ };
118
+ case "number":
119
+ if (typeof v === "number") return {
120
+ value: v,
121
+ failed: false
122
+ };
123
+ if (typeof v === "string" && PLAIN_NUMBER.test(v.trim())) return {
124
+ value: Number(v.trim()),
125
+ failed: false
126
+ };
127
+ return {
128
+ value: typeof v === "object" && !(v instanceof Date) ? cellText(v) : String(v instanceof Date ? isoDate(v, "local") : v),
129
+ failed: true
130
+ };
131
+ case "boolean":
132
+ if (typeof v === "boolean") return {
133
+ value: v,
134
+ failed: false
135
+ };
136
+ if (typeof v === "string" && /^(true|false)$/i.test(v.trim())) return {
137
+ value: v.trim().toLowerCase() === "true",
138
+ failed: false
139
+ };
140
+ return {
141
+ value: typeof v === "object" ? cellText(v) : String(v),
142
+ failed: true
143
+ };
144
+ case "date":
145
+ case "datetime":
146
+ if (v instanceof Date) return Number.isFinite(v.getTime()) ? {
147
+ value: v,
148
+ failed: false
149
+ } : {
150
+ value: "Invalid Date",
151
+ failed: true
152
+ };
153
+ if (typeof v === "number" && Number.isFinite(v)) return {
154
+ value: new Date(v),
155
+ failed: false
156
+ };
157
+ if (typeof v === "string") {
158
+ const d = parseIsoDate(v);
159
+ if (d) return {
160
+ value: d,
161
+ failed: false
162
+ };
163
+ }
164
+ return {
165
+ value: typeof v === "object" ? cellText(v) : String(v),
166
+ failed: true
167
+ };
168
+ default: throw columnError(`Unknown column type ${JSON.stringify(type)}.`, { type });
169
+ }
170
+ }
171
+ const set = (g, r, c, v) => {
172
+ if (r >= 1048576 || c >= 16384) throw new ValidationError("OUT_OF_BOUNDS", `Dataset does not fit the sheet: ${encodeCol(Math.min(c, MAX_COLS - 1))}${r + 1} is out of bounds.`);
173
+ (g.rows[r] ??= [])[c] = v;
174
+ };
175
+ const range = (r1, c1, r2, c2) => {
176
+ const a = encodeCell({
177
+ row: r1,
178
+ col: c1
179
+ });
180
+ const b = encodeCell({
181
+ row: r2,
182
+ col: c2
183
+ });
184
+ return a === b ? a : `${a}:${b}`;
185
+ };
186
+ function normalise(defs) {
187
+ const out = [];
188
+ for (const d of defs) {
189
+ if (!d) continue;
190
+ if (typeof d !== "object") throw columnError("A column definition must be an object.");
191
+ if ("children" in d && d.children !== void 0) {
192
+ if (!Array.isArray(d.children)) throw columnError("children must be an array.");
193
+ const children = normalise(d.children);
194
+ if (children.length) out.push({
195
+ group: d,
196
+ children
197
+ });
198
+ } else out.push({ leaf: d });
199
+ }
200
+ return out;
201
+ }
202
+ const depthOf = (n) => "group" in n ? 1 + Math.max(...n.children.map(depthOf)) : 1;
203
+ const leafCount = (n) => "group" in n ? n.children.reduce((s, c) => s + leafCount(c), 0) : 1;
204
+ function titleCell(title, style) {
205
+ if (title === void 0) return style ? {
206
+ value: "",
207
+ style
208
+ } : "";
209
+ if (isCellObject(title)) return {
210
+ ...title,
211
+ style: mergeStyles(style, title.style)
212
+ };
213
+ return style ? {
214
+ value: title,
215
+ style
216
+ } : title;
217
+ }
218
+ function layoutBlock(g, dataset, options, top, left, sheet) {
219
+ if (typeof dataset !== "object" || dataset === null || !Array.isArray(dataset.data)) throw columnError("A dataset needs a data array.");
220
+ const data = dataset.data;
221
+ let defs = dataset.columns;
222
+ let inferredArrays = false;
223
+ if (defs === void 0) {
224
+ const first = data.find((r) => r !== null && r !== void 0);
225
+ if (Array.isArray(first)) {
226
+ inferredArrays = true;
227
+ const width = data.reduce((m, r) => Array.isArray(r) ? Math.max(m, r.length) : m, 0);
228
+ defs = Array.from({ length: width }, (_, i) => ({ index: i }));
229
+ } else if (first !== void 0 && typeof first === "object") defs = Object.keys(first).map((key) => ({
230
+ title: key,
231
+ key
232
+ }));
233
+ else defs = [];
234
+ }
235
+ if (!Array.isArray(defs)) throw columnError("columns must be an array.");
236
+ const nodes = normalise(defs);
237
+ const leaves = [];
238
+ const collect = (n) => {
239
+ if ("group" in n) n.children.forEach(collect);
240
+ else {
241
+ const def = n.leaf;
242
+ leaves.push({
243
+ def,
244
+ col: leaves.length,
245
+ get: accessorOf(def, leaves.length)
246
+ });
247
+ }
248
+ };
249
+ nodes.forEach(collect);
250
+ const headerOn = options.header !== false && !inferredArrays && leaves.length > 0;
251
+ const headerRows = headerOn ? Math.max(...nodes.map(depthOf)) : 0;
252
+ const baseHeader = options.headerStyle ?? { font: { bold: true } };
253
+ for (const { def, col } of leaves) {
254
+ const c = left + col;
255
+ if (def.width === "auto" || def.width === void 0 && options.autoWidth) g.autoCols.add(c);
256
+ else if (def.width !== void 0 && !g.widths.has(c)) g.widths.set(c, def.width);
257
+ if (def.hidden) g.hidden.add(c);
258
+ }
259
+ if (headerOn) {
260
+ let next = 0;
261
+ const place = (n, level) => {
262
+ if ("group" in n) {
263
+ const span = leafCount(n);
264
+ const c = left + next;
265
+ set(g, top + level, c, titleCell(n.group.title, mergeStyles(baseHeader, n.group.headerStyle)));
266
+ if (span > 1) g.merges.push(range(top + level, c, top + level, c + span - 1));
267
+ n.children.forEach((child) => place(child, level + 1));
268
+ } else {
269
+ const def = n.leaf;
270
+ const c = left + next++;
271
+ const cell = titleCell(def.title ?? def.key ?? def.path ?? "", mergeStyles(baseHeader, def.headerStyle));
272
+ set(g, top + level, c, cell);
273
+ if (level < headerRows - 1) g.merges.push(range(top + level, c, top + headerRows - 1, c));
274
+ if (g.autoCols.has(c)) g.measured.set(c, Math.max(g.measured.get(c) ?? 0, textWidth(cellText(cell))));
275
+ }
276
+ };
277
+ nodes.forEach((n) => place(n, 0));
278
+ }
279
+ const warn = options.onWarning ?? (() => {});
280
+ const dataTop = top + headerRows;
281
+ const sampleRows = typeof options.autoWidth === "object" && options.autoWidth.sampleRows !== void 0 ? options.autoWidth.sampleRows : 1e400;
282
+ const columnValues = leaves.map(() => []);
283
+ const columnStyles = leaves.map(({ def }) => {
284
+ const typeFmt = def.type === "date" ? { numFmt: 14 } : def.type === "datetime" ? { numFmt: 22 } : void 0;
285
+ const merged = mergeStyles(typeFmt, def.style, def.numFmt !== void 0 ? { numFmt: def.numFmt } : void 0);
286
+ return Object.keys(merged).length ? merged : void 0;
287
+ });
288
+ const rowMerges = /* @__PURE__ */ new WeakMap();
289
+ const styleFor = (col, rowStyle, cellStyle) => {
290
+ if (cellStyle) return mergeStyles(columnStyles[col], rowStyle, cellStyle);
291
+ if (!rowStyle) return columnStyles[col];
292
+ let perColumn = rowMerges.get(rowStyle);
293
+ if (!perColumn) rowMerges.set(rowStyle, perColumn = []);
294
+ if (!(col in perColumn)) perColumn[col] = mergeStyles(columnStyles[col], rowStyle);
295
+ return perColumn[col];
296
+ };
297
+ data.forEach((row, i) => {
298
+ const r = dataTop + i;
299
+ const rowStyle = options.rowStyle?.(row, i);
300
+ for (const { def, col, get } of leaves) {
301
+ const c = left + col;
302
+ const refOf = () => encodeCell({
303
+ row: r,
304
+ col: c
305
+ });
306
+ const raw = get(row, i);
307
+ let cell = isCellObject(raw) ? { ...raw } : { value: raw };
308
+ if (!cell.formula) {
309
+ const { value, failed } = coerce(cell.value, def.type);
310
+ if (failed) {
311
+ const ref = refOf();
312
+ warn({
313
+ code: "COERCION_FAILED",
314
+ message: `${sheet}!${ref}: value does not fit type '${def.type}'; written as text.`,
315
+ sheet,
316
+ ref
317
+ });
318
+ }
319
+ cell.value = value;
320
+ }
321
+ if (typeof cell.value === "number" && !Number.isFinite(cell.value)) {
322
+ const ref = refOf();
323
+ warn({
324
+ code: "NON_FINITE_NUMBER",
325
+ message: `${sheet}!${ref}: ${String(cell.value)} cannot be stored; the cell is left empty.`,
326
+ sheet,
327
+ ref
328
+ });
329
+ cell = {
330
+ ...cell,
331
+ value: null
332
+ };
333
+ }
334
+ const style = styleFor(col, rowStyle, isCellObject(raw) ? raw.style : void 0);
335
+ const out = style !== void 0 && Object.keys(style).length > 0 ? {
336
+ ...cell,
337
+ style
338
+ } : Object.keys(cell).length === 1 && "value" in cell ? cell.value : cell;
339
+ if (out !== void 0 && out !== null) set(g, r, c, out);
340
+ const v = cell.value;
341
+ if (v !== null && v !== void 0) columnValues[col].push(v);
342
+ if (i < sampleRows && g.autoCols.has(c)) g.measured.set(c, Math.max(g.measured.get(c) ?? 0, textWidth(cellText(out))));
343
+ }
344
+ });
345
+ const lastDataRow = dataTop + data.length - 1;
346
+ const hasTotals = leaves.some(({ def }) => def.total !== void 0);
347
+ let lastRow = Math.max(top + headerRows - 1, lastDataRow);
348
+ if (hasTotals) {
349
+ const r = lastDataRow + 1;
350
+ const totalsStyle = options.totals?.style;
351
+ leaves.forEach(({ def, col }, k) => {
352
+ const c = left + col;
353
+ const values = columnValues[col];
354
+ const dataRange = data.length ? range(dataTop, c, lastDataRow, c) : "";
355
+ let cell;
356
+ if (def.total === void 0) {
357
+ if (k !== 0 || options.totals?.label === void 0) return;
358
+ cell = {
359
+ value: options.totals.label,
360
+ ...totalsStyle ? { style: totalsStyle } : {}
361
+ };
362
+ } else {
363
+ cell = totalCell(def.total, dataRange, values);
364
+ const base = def.total === "count" ? {
365
+ ...columnStyles[col],
366
+ numFmt: void 0
367
+ } : columnStyles[col];
368
+ const cellStyle = isCellObject(cell) ? cell.style : void 0;
369
+ const style = mergeStyles(base, totalsStyle, cellStyle);
370
+ if (Object.keys(style).length) cell = isCellObject(cell) ? {
371
+ ...cell,
372
+ style
373
+ } : {
374
+ value: cell,
375
+ style
376
+ };
377
+ }
378
+ set(g, r, c, cell);
379
+ if (g.autoCols.has(c)) g.measured.set(c, Math.max(g.measured.get(c) ?? 0, textWidth(cellText(cell))));
380
+ });
381
+ lastRow = r;
382
+ }
383
+ return {
384
+ headerRows,
385
+ firstRow: top,
386
+ lastHeaderRow: top + headerRows - 1,
387
+ lastDataRow: Math.max(lastDataRow, top + headerRows - 1),
388
+ firstCol: left,
389
+ lastCol: left + Math.max(leaves.length, 1) - 1,
390
+ lastRow
391
+ };
392
+ }
393
+ const SUBTOTAL = {
394
+ sum: 109,
395
+ average: 101,
396
+ count: 103,
397
+ min: 105,
398
+ max: 104
399
+ };
400
+ function numeric(values) {
401
+ const out = [];
402
+ for (const v of values) if (typeof v === "number") out.push(v);
403
+ else if (v instanceof Date) try {
404
+ out.push(dateToSerial(v));
405
+ } catch {}
406
+ return out;
407
+ }
408
+ function totalCell(total, dataRange, values) {
409
+ if (typeof total === "function") return total({
410
+ range: dataRange,
411
+ values
412
+ });
413
+ if (typeof total === "string" && total in SUBTOTAL) {
414
+ const nums = numeric(values);
415
+ let cached;
416
+ switch (total) {
417
+ case "sum":
418
+ cached = nums.reduce((a, b) => a + b, 0);
419
+ break;
420
+ case "average":
421
+ cached = nums.length ? nums.reduce((a, b) => a + b, 0) / nums.length : { error: "#DIV/0!" };
422
+ break;
423
+ case "count":
424
+ cached = values.length;
425
+ break;
426
+ case "min":
427
+ cached = nums.length ? Math.min(...nums) : 0;
428
+ break;
429
+ default: cached = nums.length ? Math.max(...nums) : 0;
430
+ }
431
+ return dataRange ? {
432
+ formula: `SUBTOTAL(${SUBTOTAL[total]},${dataRange})`,
433
+ value: cached
434
+ } : { value: cached };
435
+ }
436
+ return total;
437
+ }
438
+ function finish(g, options, first, name) {
439
+ const sheet = {
440
+ name,
441
+ rows: g.rows
442
+ };
443
+ if (g.merges.length) sheet.merges = g.merges;
444
+ const auto = typeof options.autoWidth === "object" ? options.autoWidth : {};
445
+ const min = auto.min ?? AUTO_WIDTH.min;
446
+ const max = Math.min(255, auto.max ?? AUTO_WIDTH.max);
447
+ const cols = /* @__PURE__ */ new Set([
448
+ ...g.widths.keys(),
449
+ ...g.autoCols,
450
+ ...g.hidden
451
+ ]);
452
+ if (cols.size) {
453
+ const colProps = [];
454
+ for (const c of [...cols].sort((a, b) => a - b)) {
455
+ const p = {};
456
+ const w = g.autoCols.has(c) ? Math.min(max, Math.max(min, (g.measured.get(c) ?? 0) + AUTO_WIDTH.padding)) : g.widths.get(c);
457
+ if (w !== void 0) p.width = w;
458
+ if (g.hidden.has(c)) p.hidden = true;
459
+ colProps[c] = p;
460
+ }
461
+ sheet.colProps = colProps;
462
+ }
463
+ const view = {};
464
+ if (options.rightToLeft) view.rightToLeft = true;
465
+ if (options.freezeHeader && first && first.headerRows > 0) view.freeze = { rows: first.lastHeaderRow + 1 };
466
+ if (Object.keys(view).length) sheet.view = view;
467
+ if (options.autoFilter && first && first.headerRows > 0) sheet.autoFilter = range(first.lastHeaderRow, first.firstCol, first.lastDataRow, first.lastCol);
468
+ return sheet;
469
+ }
470
+ function sheetName(options) {
471
+ const name = options.name ?? "Sheet1";
472
+ const problem = validateSheetName(name);
473
+ if (problem) throw new ValidationError("INVALID_SHEET_NAME", `Sheet name ${JSON.stringify(name)} is invalid (${problem}).`, { details: {
474
+ sheet: name,
475
+ problem
476
+ } });
477
+ return name;
478
+ }
479
+ function originOf(options) {
480
+ if (options.origin === void 0) return {
481
+ row: 0,
482
+ col: 0
483
+ };
484
+ return decodeCell(options.origin);
485
+ }
486
+ const newGrid = () => ({
487
+ rows: [],
488
+ merges: [],
489
+ widths: /* @__PURE__ */ new Map(),
490
+ measured: /* @__PURE__ */ new Map(),
491
+ autoCols: /* @__PURE__ */ new Set(),
492
+ hidden: /* @__PURE__ */ new Set()
493
+ });
494
+ /** Builds a sheet from `{ columns, data }`. */
495
+ function fromDataset(dataset, options = {}) {
496
+ const name = sheetName(options);
497
+ const origin = originOf(options);
498
+ const g = newGrid();
499
+ return finish(g, options, layoutBlock(g, dataset, options, origin.row, origin.col, name), name);
500
+ }
501
+ /**
502
+ * Stacks several datasets on one sheet (replaces the old xSteps/ySteps).
503
+ * Each block starts `gap` empty rows (default 1) below the previous one, or
504
+ * `offset.rows` rows when given, and `offset.cols` columns right of the
505
+ * origin. Freeze and filter apply to the first block with header rows.
506
+ */
507
+ function fromDatasets(blocks, options = {}) {
508
+ if (!Array.isArray(blocks)) throw columnError("fromDatasets needs an array of datasets.");
509
+ const name = sheetName(options);
510
+ const origin = originOf(options);
511
+ const gap = options.gap ?? 1;
512
+ if (!Number.isInteger(gap) || gap < 0) throw columnError(`gap must be a non-negative integer, got ${String(gap)}.`);
513
+ const g = newGrid();
514
+ let first;
515
+ let nextRow = origin.row;
516
+ blocks.forEach((block, i) => {
517
+ const offRows = block.offset?.rows;
518
+ const offCols = block.offset?.cols ?? 0;
519
+ const top = i === 0 ? origin.row + (offRows ?? 0) : nextRow + (offRows ?? gap);
520
+ const result = layoutBlock(g, block, options, top, origin.col + offCols, name);
521
+ if (!first && result.headerRows > 0) first = result;
522
+ nextRow = result.lastRow + 1;
523
+ });
524
+ return finish(g, options, first, name);
525
+ }
526
+ function usedRange(sheet) {
527
+ let minR = 1e400, maxR = -1, minC = 1e400, maxC = -1;
528
+ sheet.rows.forEach((row, r) => row?.forEach((c, col) => {
529
+ if (c === void 0 || c === null) return;
530
+ minR = Math.min(minR, r);
531
+ maxR = Math.max(maxR, r);
532
+ minC = Math.min(minC, col);
533
+ maxC = Math.max(maxC, col);
534
+ }));
535
+ return maxR < 0 ? void 0 : {
536
+ start: {
537
+ row: minR,
538
+ col: minC
539
+ },
540
+ end: {
541
+ row: maxR,
542
+ col: maxC
543
+ }
544
+ };
545
+ }
546
+ /**
547
+ * Reads a sheet back into `{ columns, data }` (import direction). Keys come
548
+ * from the header text, deduplicated with _2, _3...; an empty header gives the
549
+ * column letter. Empty rows are skipped. Rows are null-prototype objects, so
550
+ * a header named __proto__ in an untrusted file is just a key.
551
+ */
552
+ function toDataset(sheet, options = {}) {
553
+ const s = sheet;
554
+ const rng = options.range ? decodeRange(options.range) : s.dimension ? decodeRange(s.dimension) : usedRange(s);
555
+ if (!rng) return {
556
+ columns: [],
557
+ data: []
558
+ };
559
+ const headerRow = options.headerRow ?? 0;
560
+ if (headerRow !== false && (!Number.isInteger(headerRow) || headerRow < 0)) throw columnError(`headerRow must be a non-negative integer or false, got ${String(headerRow)}.`);
561
+ const asCell = options.values === "cell";
562
+ const columns = [];
563
+ const used = /* @__PURE__ */ new Map();
564
+ for (let c = rng.start.col; c <= rng.end.col; c++) {
565
+ const letter = encodeCol(c);
566
+ const title = headerRow === false ? letter : cellText(s.rows[headerRow]?.[c]).trim();
567
+ const base = title === "" ? letter : title;
568
+ const n = (used.get(base) ?? 0) + 1;
569
+ used.set(base, n);
570
+ columns.push({
571
+ title: headerRow === false ? letter : title,
572
+ key: n === 1 ? base : `${base}_${n}`
573
+ });
574
+ }
575
+ const data = [];
576
+ const firstData = headerRow === false ? rng.start.row : Math.max(rng.start.row, headerRow + 1);
577
+ for (let r = firstData; r <= rng.end.row; r++) {
578
+ const row = s.rows[r];
579
+ if (!row) continue;
580
+ let any = false;
581
+ const obj = Object.create(null);
582
+ columns.forEach(({ key }, k) => {
583
+ const c = row[rng.start.col + k];
584
+ if (!(c === void 0 || c === null || isCellObject(c) && (c.value === void 0 || c.value === null) && !c.formula)) any = true;
585
+ obj[key] = asCell ? c === void 0 ? null : isCellObject(c) ? c : { value: c } : c === void 0 || c === null ? null : isCellObject(c) ? c.value ?? null : c;
586
+ });
587
+ if (any) data.push(obj);
588
+ }
589
+ return {
590
+ columns,
591
+ data
592
+ };
593
+ }
594
+ // src/index.ts
595
+ /** Package version. Set from package.json by `npm run version-packages` (scripts/sync-version.mjs); a unit test checks it. */
596
+ const VERSION = "2.0.0-alpha.2";
597
+ export { BUILTIN_NUM_FMTS, CsvError, EnvironmentError, ExcelError, FormatError, LimitError, MAX_COLS, MAX_ROWS, VERSION, ValidationError, XLSX_MIME, cellText, dateToSerial, decodeCell, decodeCol, decodeRange, encodeCell, encodeCol, encodeRange, fromDataset, fromDatasets, isDateFormat, isExcelError, mergeStyles, sanitizeSheetName, serialToDate, toBlob, toDataset, toUint8Array, validateSheetName };
@@ -0,0 +1,88 @@
1
+ // src/internal/input.ts
2
+ /** Uint8Array (Node Buffer included), ArrayBuffer, any ArrayBufferView, or a Blob -> Uint8Array. */
3
+ async function toBytes(input, fn, also = "") {
4
+ if (input instanceof Uint8Array) return input;
5
+ if (input instanceof ArrayBuffer) return new Uint8Array(input);
6
+ if (typeof input === "object" && input !== null && typeof input.arrayBuffer === "function") return new Uint8Array(await input.arrayBuffer());
7
+ if (ArrayBuffer.isView(input)) {
8
+ const v = input;
9
+ return new Uint8Array(v.buffer, v.byteOffset, v.byteLength);
10
+ }
11
+ throw new TypeError(`${fn}: input must be ${also}a Uint8Array, ArrayBuffer or Blob`);
12
+ }
13
+ // src/internal/csv/infer.ts
14
+ const NUMBER = /^[+-]?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?$/;
15
+ const FRACTION = /^[+-]?\.\d+(?:[eE][+-]?\d+)?$/;
16
+ const ISO = /^(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{1,3}))?)?(Z|[+-]\d{2}:?\d{2})?)?$/;
17
+ function inferValue(text, zone) {
18
+ const len = text.length;
19
+ if (len === 0 || len > 64) return text;
20
+ const c = text.charCodeAt(0);
21
+ if (c === 84 || c === 116 || c === 70 || c === 102) {
22
+ if (text === "TRUE" || text === "true") return true;
23
+ if (text === "FALSE" || text === "false") return false;
24
+ return text;
25
+ }
26
+ if (!(c >= 48 && c <= 57 || c === 43 || c === 45 || c === 46)) return text;
27
+ if (NUMBER.test(text) || FRACTION.test(text)) {
28
+ const n = Number(text);
29
+ if (!Number.isFinite(n)) return text;
30
+ if (!/[.eE]/.test(text) && !Number.isSafeInteger(n)) return text;
31
+ return n;
32
+ }
33
+ if (len >= 10 && text.charCodeAt(4) === 45) {
34
+ const d = parseIsoDate(text, zone);
35
+ if (d) return d;
36
+ }
37
+ return text;
38
+ }
39
+ /** Parses an ISO 8601 date or date-time; without an offset, `zone` applies. */
40
+ function parseIsoDate(text, zone) {
41
+ const m = ISO.exec(text);
42
+ if (!m) return void 0;
43
+ const y = +m[1];
44
+ const mo = +m[2];
45
+ const d = +m[3];
46
+ const h = m[4] === void 0 ? 0 : +m[4];
47
+ const mi = m[5] === void 0 ? 0 : +m[5];
48
+ const s = m[6] === void 0 ? 0 : +m[6];
49
+ const ms = m[7] === void 0 ? 0 : +m[7].padEnd(3, "0");
50
+ if (mo < 1 || mo > 12 || d < 1 || d > daysInMonth(y, mo) || h > 23 || mi > 59 || s > 59) return void 0;
51
+ const offset = m[8];
52
+ let t;
53
+ if (offset === void 0) {
54
+ if (zone === "utc") t = Date.UTC(y, mo - 1, d, h, mi, s, ms);
55
+ else {
56
+ const local = new Date(y, mo - 1, d, h, mi, s, ms);
57
+ if (y < 100) local.setFullYear(y);
58
+ t = local.getTime();
59
+ }
60
+ if (zone === "utc" && y < 100) {
61
+ const u = new Date(t);
62
+ u.setUTCFullYear(y);
63
+ t = u.getTime();
64
+ }
65
+ } else {
66
+ t = Date.UTC(y, mo - 1, d, h, mi, s, ms);
67
+ if (y < 100) {
68
+ const u = new Date(t);
69
+ u.setUTCFullYear(y);
70
+ t = u.getTime();
71
+ }
72
+ if (offset !== "Z") {
73
+ const sign = offset[0] === "-" ? -1 : 1;
74
+ const digits = offset.slice(1).replace(":", "");
75
+ const oh = +digits.slice(0, 2);
76
+ const om = +digits.slice(2, 4);
77
+ if (oh > 23 || om > 59) return void 0;
78
+ t -= sign * (oh * 60 + om) * 6e4;
79
+ }
80
+ }
81
+ const date = new Date(t);
82
+ return Number.isNaN(date.getTime()) ? void 0 : date;
83
+ }
84
+ function daysInMonth(y, m) {
85
+ if (m === 2) return y % 4 === 0 && y % 100 !== 0 || y % 400 === 0 ? 29 : 28;
86
+ return m === 4 || m === 6 || m === 9 || m === 11 ? 30 : 31;
87
+ }
88
+ export { parseIsoDate as n, toBytes as r, inferValue as t };