javascript-excel 2.0.0-alpha.1 → 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.
package/dist/index.js CHANGED
@@ -1,1397 +1,597 @@
1
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 { c as nativeCodec, d as ByteWriter, f as concatBytes, i as serialToDate, n as isDateFormat, o as toDosDateTime, p as throwIfAborted, r as dateToSerial, s as crc32, t as BUILTIN_NUM_FMTS, u as encodeUtf8 } from "./numfmt-DEm0sYBJ.js";
3
- import { C as encodeRange, D as xmlAttr, E as num, O as xmlText, S as encodeCol, T as needsPreserve, _ as MAX_ROWS, a as SheetFeatures, b as decodeRange, c as hyperlinkSchemes, d as PackageParts, f as REL_TYPE, g as MAX_COLS, h as mergeStyles, k as xstring, m as cellText, n as validateSheetName, o as SheetLinks, p as Rels, s as hyperlinkOf, t as sanitizeSheetName, u as CONTENT_TYPE, v as decodeCell, w as XML_DECL, x as encodeCell, y as decodeCol } from "./sheet-names-CDsVK15c.js";
4
- const SIG_LOCAL = 67324752;
5
- const SIG_CENTRAL = 33639248;
6
- const SIG_EOCD = 101010256;
7
- const FLAG_UTF8 = 2048;
8
- const MAX_ENTRIES = 65534;
9
- function zip64Required(what) {
10
- return new ValidationError("ZIP64_REQUIRED", `The archive needs zip64 (${what}), which the writer does not produce.`);
11
- }
12
- function isAscii(s) {
13
- for (let i = 0; i < s.length; i++) if (s.charCodeAt(i) > 127) return false;
14
- return true;
15
- }
16
- function toChunks(data) {
17
- if (typeof data === "string") return [encodeUtf8(data)];
18
- if (data instanceof Uint8Array) return [data];
19
- return data;
20
- }
21
- /** Writes the entries, in order, into one zip archive. */
22
- async function writeZip(entries, options = {}) {
23
- const codec = options.codec ?? nativeCodec;
24
- const defaultModified = options.modified ?? /* @__PURE__ */ new Date();
25
- const seen = /* @__PURE__ */ new Set();
26
- const written = [];
27
- let offset = 0;
28
- for await (const entry of entries) {
29
- throwIfAborted(options.signal);
30
- const { name } = entry;
31
- if (name.length === 0 || name.startsWith("/") || name.includes("\0") || name.includes("\\")) throw new Error(`Invalid zip entry name: ${JSON.stringify(name)}`);
32
- if (seen.has(name)) throw new Error(`Duplicate zip entry name: ${name}`);
33
- seen.add(name);
34
- if (written.length >= MAX_ENTRIES) throw zip64Required("more than 65,534 entries");
35
- const nameBytes = encodeUtf8(name);
36
- if (nameBytes.length > 65535) throw new Error(`Zip entry name too long: ${name.slice(0, 40)}...`);
37
- let size = 0;
38
- let crc = 0;
39
- let kept = [];
40
- async function* tap(src) {
41
- for await (const chunk of src) {
42
- size += chunk.length;
43
- if (size > 4294967294) throw zip64Required(`entry ${name} over 4 GiB`);
44
- crc = crc32(chunk, crc);
45
- if (kept) {
46
- if (size <= 65536) kept.push(chunk);
47
- else kept = void 0;
48
- }
49
- yield chunk;
50
- }
51
- }
52
- const compression = entry.compression ?? options.compression ?? "deflate";
53
- let method;
54
- let data;
55
- if (compression === "store") {
56
- const parts = [];
57
- for await (const chunk of tap(toChunks(entry.data))) parts.push(chunk);
58
- method = 0;
59
- data = concatBytes(parts);
60
- } else {
61
- const deflated = await codec.deflateRaw(tap(toChunks(entry.data)), options.signal);
62
- if (kept && deflated.length >= size) {
63
- method = 0;
64
- data = concatBytes(kept);
65
- } else {
66
- method = 8;
67
- data = deflated;
68
- }
69
- }
70
- const { time, date } = toDosDateTime(entry.modified ?? defaultModified);
71
- const flags = isAscii(name) ? 0 : FLAG_UTF8;
72
- written.push({
73
- nameBytes,
74
- flags,
75
- method,
76
- crc,
77
- size,
78
- data,
79
- time,
80
- date,
81
- offset
82
- });
83
- offset += 30 + nameBytes.length + data.length;
84
- if (offset > 4294967294) throw zip64Required("archive over 4 GiB");
85
- }
86
- const parts = [];
87
- for (const w of written) {
88
- const h = new ByteWriter(30 + w.nameBytes.length);
89
- h.u32(SIG_LOCAL);
90
- h.u16(w.method === 8 ? 20 : 10);
91
- h.u16(w.flags);
92
- h.u16(w.method);
93
- h.u16(w.time);
94
- h.u16(w.date);
95
- h.u32(w.crc);
96
- h.u32(w.data.length);
97
- h.u32(w.size);
98
- h.u16(w.nameBytes.length);
99
- h.u16(0);
100
- h.raw(w.nameBytes);
101
- parts.push(h.bytes, w.data);
102
- }
103
- const cdOffset = offset;
104
- let cdSize = 0;
105
- for (const w of written) {
106
- const c = new ByteWriter(46 + w.nameBytes.length);
107
- c.u32(SIG_CENTRAL);
108
- c.u16(20);
109
- c.u16(w.method === 8 ? 20 : 10);
110
- c.u16(w.flags);
111
- c.u16(w.method);
112
- c.u16(w.time);
113
- c.u16(w.date);
114
- c.u32(w.crc);
115
- c.u32(w.data.length);
116
- c.u32(w.size);
117
- c.u16(w.nameBytes.length);
118
- c.u16(0);
119
- c.u16(0);
120
- c.u16(0);
121
- c.u16(0);
122
- c.u32(0);
123
- c.u32(w.offset);
124
- c.raw(w.nameBytes);
125
- parts.push(c.bytes);
126
- cdSize += c.bytes.length;
127
- }
128
- if (cdOffset + cdSize > 4294967294) throw zip64Required("archive over 4 GiB");
129
- const e = new ByteWriter(22);
130
- e.u32(SIG_EOCD);
131
- e.u16(0);
132
- e.u16(0);
133
- e.u16(written.length);
134
- e.u16(written.length);
135
- e.u32(cdSize);
136
- e.u32(cdOffset);
137
- e.u16(0);
138
- parts.push(e.bytes);
139
- return concatBytes(parts);
140
- }
141
- // src/internal/write/parts.ts
142
- /**
143
- * workbook.xml, defined names, document properties and the default theme
144
- * (docs/api.md §5.1). Content types and relationships are in package.ts.
145
- */
146
- const NS_MAIN$2 = "http://schemas.openxmlformats.org/spreadsheetml/2006/main";
147
- const NS_REL$1 = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
148
- function workbookXml(w) {
149
- let x = `${XML_DECL}<workbook xmlns="${NS_MAIN$2}" xmlns:r="${NS_REL$1}">` + (w.date1904 ? "<workbookPr date1904=\"1\"/>" : "<workbookPr/>") + `<bookViews><workbookView${w.activeSheet > 0 ? ` activeTab="${w.activeSheet}"` : ""}/></bookViews><sheets>`;
150
- w.sheets.forEach((s, i) => {
151
- const state = s.state === "visible" ? "" : ` state="${s.state}"`;
152
- x += `<sheet name="${xmlAttr(s.name)}" sheetId="${i + 1}"${state} r:id="${s.relId}"/>`;
153
- });
154
- x += "</sheets>";
155
- if (w.definedNames) x += w.definedNames;
156
- if (w.fullCalcOnLoad) x += "<calcPr fullCalcOnLoad=\"1\"/>";
157
- return `${x}</workbook>`;
158
- }
159
- function propertyError(message, details) {
160
- return new ValidationError("INVALID_PROPERTY", message, { details });
161
- }
162
- /** W3CDTF timestamp without milliseconds, as Excel writes. */
163
- function w3cdtf(d, field) {
164
- if (!(d instanceof Date) || !Number.isFinite(d.getTime())) throw propertyError(`Document property ${field} must be a valid Date.`, { property: field });
165
- return d.toISOString().replace(/\.\d{3}Z$/, "Z");
166
- }
167
- function optString(props, key) {
168
- const v = props[key];
169
- if (v === void 0) return void 0;
170
- if (typeof v !== "string") throw propertyError(`Document property ${key} must be a string.`, { property: key });
171
- return v;
172
- }
173
- function coreXml(props, now) {
174
- const el = (tag, key) => {
175
- const v = optString(props, key);
176
- return v === void 0 ? "" : `<${tag}>${xmlText(v)}</${tag}>`;
177
- };
178
- return `${XML_DECL}<cp:coreProperties xmlns:cp="http://schemas.openxmlformats.org/package/2006/metadata/core-properties" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:dcmitype="http://purl.org/dc/dcmitype/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">` + el("dc:title", "title") + el("dc:subject", "subject") + el("dc:creator", "creator") + el("cp:keywords", "keywords") + el("dc:description", "description") + el("cp:lastModifiedBy", "lastModifiedBy") + el("cp:category", "category") + `<dcterms:created xsi:type="dcterms:W3CDTF">${w3cdtf(props.created ?? now, "created")}</dcterms:created><dcterms:modified xsi:type="dcterms:W3CDTF">${w3cdtf(props.modified ?? now, "modified")}</dcterms:modified></cp:coreProperties>`;
179
- }
180
- function appXml(props) {
181
- const el = (tag, key, fallback) => {
182
- const v = optString(props, key) ?? fallback;
183
- return v === void 0 ? "" : `<${tag}>${xmlText(v)}</${tag}>`;
184
- };
185
- return `${XML_DECL}<Properties xmlns="http://schemas.openxmlformats.org/officeDocument/2006/extended-properties" xmlns:vt="http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes">` + el("Application", "application", "javascript-excel") + el("Manager", "manager") + el("Company", "company") + "</Properties>";
186
- }
187
- /** FMTID_UserDefinedProperties, required on every custom property. */
188
- const FMTID_USER = "{D5CDD505-2E9C-101B-9397-08002B2CF9AE}";
189
- function customXml(custom) {
190
- const seen = /* @__PURE__ */ new Set();
191
- let x = `${XML_DECL}<Properties xmlns="http://schemas.openxmlformats.org/officeDocument/2006/custom-properties" xmlns:vt="http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes">`;
192
- custom.forEach((p, i) => {
193
- if (typeof p?.name !== "string" || p.name.length === 0 || p.name.length > 255) throw propertyError("Custom property names must be 1 to 255 characters.", { index: i });
194
- const key = p.name.toLowerCase();
195
- if (seen.has(key)) throw propertyError(`Duplicate custom property ${p.name}.`, { property: p.name });
196
- seen.add(key);
197
- const v = p.value;
198
- let typed;
199
- if (typeof v === "string") typed = `<vt:lpwstr>${xmlText(v)}</vt:lpwstr>`;
200
- else if (typeof v === "boolean") typed = `<vt:bool>${v ? "true" : "false"}</vt:bool>`;
201
- else if (typeof v === "number") {
202
- if (!Number.isFinite(v)) throw propertyError(`Custom property ${p.name} must be a finite number.`, { property: p.name });
203
- typed = Number.isInteger(v) && v >= -2147483648 && v <= 2147483647 ? `<vt:i4>${v}</vt:i4>` : `<vt:r8>${num(v)}</vt:r8>`;
204
- } else if (v instanceof Date) typed = `<vt:filetime>${w3cdtf(v, p.name)}</vt:filetime>`;
205
- else throw propertyError(`Custom property ${p.name} has an unsupported value.`, { property: p.name });
206
- x += `<property fmtid="${FMTID_USER}" pid="${i + 2}" name="${xmlAttr(p.name)}">${typed}</property>`;
207
- });
208
- return `${x}</Properties>`;
209
- }
210
- /**
211
- * A minimal, schema-complete DrawingML theme with the Office 2013–2022 colour
212
- * scheme and Calibri / Calibri Light fonts, so `{ theme: n }` colours resolve
213
- * to the colours users expect. The format scheme is the simplest valid one.
214
- */
215
- const THEME_XML = `${XML_DECL}<a:theme xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" name="Office Theme"><a:themeElements><a:clrScheme name="Office"><a:dk1><a:sysClr val="windowText" lastClr="000000"/></a:dk1><a:lt1><a:sysClr val="window" lastClr="FFFFFF"/></a:lt1><a:dk2><a:srgbClr val="44546A"/></a:dk2><a:lt2><a:srgbClr val="E7E6E6"/></a:lt2><a:accent1><a:srgbClr val="4472C4"/></a:accent1><a:accent2><a:srgbClr val="ED7D31"/></a:accent2><a:accent3><a:srgbClr val="A5A5A5"/></a:accent3><a:accent4><a:srgbClr val="FFC000"/></a:accent4><a:accent5><a:srgbClr val="5B9BD5"/></a:accent5><a:accent6><a:srgbClr val="70AD47"/></a:accent6><a:hlink><a:srgbClr val="0563C1"/></a:hlink><a:folHlink><a:srgbClr val="954F72"/></a:folHlink></a:clrScheme><a:fontScheme name="Office"><a:majorFont><a:latin typeface="Calibri Light"/><a:ea typeface=""/><a:cs typeface=""/></a:majorFont><a:minorFont><a:latin typeface="Calibri"/><a:ea typeface=""/><a:cs typeface=""/></a:minorFont></a:fontScheme><a:fmtScheme name="Office"><a:fillStyleLst>` + "<a:solidFill><a:schemeClr val=\"phClr\"/></a:solidFill>".repeat(3) + "</a:fillStyleLst><a:lnStyleLst><a:ln w=\"6350\"><a:solidFill><a:schemeClr val=\"phClr\"/></a:solidFill></a:ln><a:ln w=\"12700\"><a:solidFill><a:schemeClr val=\"phClr\"/></a:solidFill></a:ln><a:ln w=\"19050\"><a:solidFill><a:schemeClr val=\"phClr\"/></a:solidFill></a:ln></a:lnStyleLst><a:effectStyleLst>" + "<a:effectStyle><a:effectLst/></a:effectStyle>".repeat(3) + "</a:effectStyleLst><a:bgFillStyleLst>" + "<a:solidFill><a:schemeClr val=\"phClr\"/></a:solidFill>".repeat(3) + "</a:bgFillStyleLst></a:fmtScheme></a:themeElements></a:theme>";
216
- function nameError(message, details) {
217
- return new ValidationError("INVALID_DEFINED_NAME", message, { details });
218
- }
219
- const NAME_RE = /^[\p{L}_\\][\p{L}\p{N}_.\\?]*$/u;
220
- const A1_LIKE = /^\$?([A-Za-z]{1,3})\$?([0-9]+)$/;
221
- const R1C1_LIKE = /^[Rr]([0-9]*)([Cc]([0-9]*))?$|^[Cc][0-9]*$/;
222
- function isCellLike(name) {
223
- const m = A1_LIKE.exec(name);
224
- if (!m) return false;
225
- const letters = m[1].toUpperCase();
226
- let col = 0;
227
- for (const ch of letters) col = col * 26 + (ch.charCodeAt(0) - 64);
228
- const row = Number(m[2]);
229
- return col <= 16384 && row >= 1 && row <= 1048576;
230
- }
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
231
7
  /**
232
- * Validates user defined names and adds the built-in ones the sheets imply
233
- * (autofilter database, print area, print titles). Names are unique per scope,
234
- * case-insensitively. Returns the <definedNames> element, or ''.
235
- */
236
- function definedNamesXml(user, builtins, sheetCount) {
237
- const seen = /* @__PURE__ */ new Set();
238
- const items = [];
239
- const scopeKey = (name, sheet) => `${sheet ?? "wb"}\u0000${name.toLowerCase()}`;
240
- if (user !== void 0 && !Array.isArray(user)) throw nameError("definedNames must be an array.", {});
241
- (user ?? []).forEach((d, i) => {
242
- if (typeof d !== "object" || d === null) throw nameError(`definedNames[${i}] must be an object.`, { index: i });
243
- const { name } = d;
244
- if (typeof name !== "string" || name.length === 0 || name.length > 255 || !NAME_RE.test(name) || isCellLike(name) || R1C1_LIKE.test(name)) throw nameError(`Defined name ${JSON.stringify(name)} is not a valid Excel name (start with a letter, '_' or '\\'; letters, digits, '.', '_'; no spaces; not a cell reference).`, {
245
- index: i,
246
- name
247
- });
248
- if (name.toLowerCase().startsWith("_xlnm.")) throw nameError(`Defined name ${name} is reserved; set print.printArea, print.printTitles or autoFilter instead.`, {
249
- index: i,
250
- name
251
- });
252
- if (d.sheet !== void 0 && (!Number.isInteger(d.sheet) || d.sheet < 0 || d.sheet >= sheetCount)) throw nameError(`Defined name ${name}: sheet ${String(d.sheet)} is not a sheet index.`, {
253
- index: i,
254
- name,
255
- sheet: d.sheet
256
- });
257
- if (typeof d.ref !== "string" || d.ref.replace(/^=/, "").length === 0) throw nameError(`Defined name ${name}: ref must be a non-empty formula such as "'Sheet 1'!$A$1".`, {
258
- index: i,
259
- name
260
- });
261
- if (d.hidden !== void 0 && typeof d.hidden !== "boolean") throw nameError(`Defined name ${name}: hidden must be a boolean.`, {
262
- index: i,
263
- name
264
- });
265
- if (d.comment !== void 0 && typeof d.comment !== "string") throw nameError(`Defined name ${name}: comment must be a string.`, {
266
- index: i,
267
- name
268
- });
269
- const key = scopeKey(name, d.sheet);
270
- if (seen.has(key)) throw nameError(`Defined name ${name} is defined twice in the same scope.`, {
271
- index: i,
272
- name
273
- });
274
- seen.add(key);
275
- let attrs = ` name="${xmlAttr(name)}"`;
276
- if (d.comment) attrs += ` comment="${xmlAttr(d.comment)}"`;
277
- if (d.sheet !== void 0) attrs += ` localSheetId="${d.sheet}"`;
278
- if (d.hidden) attrs += " hidden=\"1\"";
279
- items.push(`<definedName${attrs}>${xstring(d.ref.replace(/^=/, ""))}</definedName>`);
280
- });
281
- for (const b of builtins) items.push(`<definedName name="${b.name}" localSheetId="${b.sheet}"${b.hidden ? " hidden=\"1\"" : ""}>${xstring(b.ref)}</definedName>`);
282
- return items.length ? `<definedNames>${items.join("")}</definedNames>` : "";
283
- }
284
- // src/internal/write/style-registry.ts
285
- /**
286
- * Turns model styles into styles.xml (docs/api.md §3.5).
8
+ * Dataset builders (docs/api.md §4.3): `{ columns, data }` ↔ Sheet.
287
9
  *
288
- * Every distinct resolved style becomes one `xf` in cellXfs; fonts, fills,
289
- * borders and custom number formats are deduplicated too. Index 0 of each
290
- * list is the default, and fills 0/1 are the `none` and `gray125` fills
291
- * Excel requires.
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.
292
13
  */
293
- const NS_MAIN$1 = "http://schemas.openxmlformats.org/spreadsheetml/2006/main";
294
- /** Excel's limit on unique cell formats [to verify]. */
295
- const MAX_CELL_XFS = 64e3;
296
- const PATTERNS = /* @__PURE__ */ new Set([
297
- "none",
298
- "solid",
299
- "mediumGray",
300
- "darkGray",
301
- "lightGray",
302
- "darkHorizontal",
303
- "darkVertical",
304
- "darkDown",
305
- "darkUp",
306
- "darkGrid",
307
- "darkTrellis",
308
- "lightHorizontal",
309
- "lightVertical",
310
- "lightDown",
311
- "lightUp",
312
- "lightGrid",
313
- "lightTrellis",
314
- "gray125",
315
- "gray0625"
316
- ]);
317
- const BORDER_STYLES = /* @__PURE__ */ new Set([
318
- "none",
319
- "thin",
320
- "medium",
321
- "thick",
322
- "double",
323
- "hair",
324
- "dotted",
325
- "dashed",
326
- "dashDot",
327
- "dashDotDot",
328
- "mediumDashed",
329
- "mediumDashDot",
330
- "mediumDashDotDot",
331
- "slantDashDot"
332
- ]);
333
- const UNDERLINES = /* @__PURE__ */ new Set([
334
- "single",
335
- "double",
336
- "singleAccounting",
337
- "doubleAccounting"
338
- ]);
339
- const VERT_ALIGNS = /* @__PURE__ */ new Set([
340
- "superscript",
341
- "subscript",
342
- "baseline"
343
- ]);
344
- const SCHEMES = /* @__PURE__ */ new Set([
345
- "major",
346
- "minor",
347
- "none"
348
- ]);
349
- const HORIZONTAL = /* @__PURE__ */ new Set([
350
- "general",
351
- "left",
352
- "center",
353
- "right",
354
- "fill",
355
- "justify",
356
- "centerContinuous",
357
- "distributed"
358
- ]);
359
- const VERTICAL = /* @__PURE__ */ new Set([
360
- "top",
361
- "center",
362
- "bottom",
363
- "justify",
364
- "distributed"
365
- ]);
366
- const READING_ORDER = {
367
- context: 0,
368
- ltr: 1,
369
- rtl: 2
370
- };
371
- var Checker = class {
372
- ctx;
373
- constructor(ctx) {
374
- this.ctx = ctx;
375
- }
376
- fail(path, value, why, code = "INVALID_STYLE") {
377
- const where = this.ctx.ref ? ` (${this.ctx.sheet ?? "?"}!${this.ctx.ref})` : this.ctx.sheet ? ` (${this.ctx.sheet})` : "";
378
- throw new ValidationError(code, `Invalid style ${path}: ${why}${where}.`, { details: {
379
- path,
380
- value,
381
- ...this.ctx.sheet !== void 0 && { sheet: this.ctx.sheet },
382
- ...this.ctx.ref !== void 0 && { ref: this.ctx.ref }
383
- } });
384
- }
385
- bool(path, v) {
386
- if (v === void 0) return void 0;
387
- if (typeof v !== "boolean") this.fail(path, v, "expected a boolean");
388
- return v;
389
- }
390
- number(path, v, min, max, integer = false) {
391
- if (v === void 0) return void 0;
392
- if (typeof v !== "number" || !Number.isFinite(v) || v < min || v > max || integer && !Number.isInteger(v)) this.fail(path, v, `expected ${integer ? "an integer" : "a number"} from ${min} to ${max}`);
393
- return v;
394
- }
395
- oneOf(path, v, allowed) {
396
- if (v === void 0) return void 0;
397
- if (typeof v !== "string" || !allowed.has(v)) this.fail(path, v, `expected one of ${[...allowed].join(", ")}`);
398
- return v;
399
- }
400
- color(path, c) {
401
- if (c === void 0) return void 0;
402
- if (typeof c === "string") return { rgb: this.argb(path, c) };
403
- if (typeof c !== "object" || c === null) this.fail(path, c, "expected a colour");
404
- if ("rgb" in c) return { rgb: this.argb(`${path}.rgb`, c.rgb) };
405
- if ("theme" in c) {
406
- const theme = this.number(`${path}.theme`, c.theme, 0, 11, true);
407
- const tint = this.number(`${path}.tint`, c.tint, -1, 1);
408
- return tint === void 0 || tint === 0 ? { theme } : {
409
- theme,
410
- tint
411
- };
412
- }
413
- if ("indexed" in c) return { indexed: this.number(`${path}.indexed`, c.indexed, 0, 65, true) };
414
- if ("auto" in c && c.auto === true) return { auto: true };
415
- return this.fail(path, c, "expected a string, { rgb }, { theme, tint }, { indexed } or { auto: true }");
416
- }
417
- argb(path, s) {
418
- if (typeof s !== "string") this.fail(path, s, "expected a hex colour string");
419
- const hex = s.startsWith("#") ? s.slice(1) : s;
420
- if (!/^(?:[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/.test(hex)) this.fail(path, s, "expected RRGGBB or AARRGGBB hex");
421
- return (hex.length === 6 ? `FF${hex}` : hex).toUpperCase();
422
- }
423
- };
424
- function colorAttrs(c) {
425
- if ("rgb" in c) return ` rgb="${c.rgb}"`;
426
- if ("theme" in c) return ` theme="${c.theme}"${c.tint !== void 0 ? ` tint="${num(c.tint)}"` : ""}`;
427
- if ("indexed" in c) return ` indexed="${c.indexed}"`;
428
- return ` auto="1"`;
429
- }
430
- /** Font body, shared by <font> (nameTag 'name') and rich-text <rPr> (nameTag 'rFont'). */
431
- function fontXml(f, nameTag) {
432
- let x = "";
433
- if (f.bold) x += "<b/>";
434
- if (f.italic) x += "<i/>";
435
- if (f.strike) x += "<strike/>";
436
- if (f.condense) x += "<condense/>";
437
- if (f.extend) x += "<extend/>";
438
- if (f.outline) x += "<outline/>";
439
- if (f.shadow) x += "<shadow/>";
440
- if (f.underline) x += f.underline === "single" ? "<u/>" : `<u val="${f.underline}"/>`;
441
- if (f.vertAlign) x += `<vertAlign val="${f.vertAlign}"/>`;
442
- x += `<sz val="${num(f.size)}"/>`;
443
- if (f.color) x += `<color${colorAttrs(f.color)}/>`;
444
- x += `<${nameTag} val="${xmlAttr(f.name)}"/>`;
445
- if (f.family !== void 0) x += `<family val="${f.family}"/>`;
446
- if (f.charset !== void 0) x += `<charset val="${f.charset}"/>`;
447
- if (f.scheme) x += `<scheme val="${f.scheme}"/>`;
448
- return x;
449
- }
450
- function fillXml(f) {
451
- if (f.kind === "pattern") {
452
- if (!f.fg && !f.bg) return `<fill><patternFill patternType="${f.pattern}"/></fill>`;
453
- let x = `<fill><patternFill patternType="${f.pattern}">`;
454
- if (f.fg) x += `<fgColor${colorAttrs(f.fg)}/>`;
455
- if (f.bg) x += `<bgColor${colorAttrs(f.bg)}/>`;
456
- return `${x}</patternFill></fill>`;
457
- }
458
- let attrs = f.gradient === "path" ? " type=\"path\"" : "";
459
- if (f.degree !== void 0) attrs += ` degree="${num(f.degree)}"`;
460
- for (const k of [
461
- "left",
462
- "right",
463
- "top",
464
- "bottom"
465
- ]) if (f[k] !== void 0) attrs += ` ${k}="${num(f[k])}"`;
466
- const stops = f.stops.map((s) => `<stop position="${num(s.position)}"><color${colorAttrs(s.color)}/></stop>`).join("");
467
- return `<fill><gradientFill${attrs}>${stops}</gradientFill></fill>`;
468
- }
469
- function borderXml(b) {
470
- let attrs = "";
471
- if (b.diagonalUp) attrs += " diagonalUp=\"1\"";
472
- if (b.diagonalDown) attrs += " diagonalDown=\"1\"";
473
- let x = `<border${attrs}>`;
474
- for (const side of [
475
- "left",
476
- "right",
477
- "top",
478
- "bottom",
479
- "diagonal"
480
- ]) {
481
- const s = b[side];
482
- if (!s) x += `<${side}/>`;
483
- else if (!s.color) x += `<${side} style="${s.style}"/>`;
484
- else x += `<${side} style="${s.style}"><color${colorAttrs(s.color)}/></${side}>`;
485
- }
486
- return `${x}</border>`;
14
+ function columnError(message, details = {}) {
15
+ return new ValidationError("INVALID_COLUMN", message, { details });
487
16
  }
488
- /** Stable key for deduplication (normalised objects are built with a fixed field order). */
489
- const keyOf = (v) => JSON.stringify(v);
490
- const DEFAULT_FONT = {
491
- name: "Calibri",
492
- size: 11,
493
- color: { theme: 1 },
494
- family: 2,
495
- scheme: "minor"
496
- };
497
- var StyleRegistry = class {
498
- defaultFont;
499
- fonts = [];
500
- fontIndex = /* @__PURE__ */ new Map();
501
- fills = [];
502
- fillIndex = /* @__PURE__ */ new Map();
503
- borders = [];
504
- borderIndex = /* @__PURE__ */ new Map();
505
- numFmts = /* @__PURE__ */ new Map();
506
- xfs = [];
507
- xfIndex = /* @__PURE__ */ new Map();
508
- /** Resolved-xf cache keyed by the identity of the style layers. */
509
- layerCache = /* @__PURE__ */ new Map();
510
- ids = /* @__PURE__ */ new WeakMap();
511
- nextId = 1;
512
- constructor(defaultFont) {
513
- const c = new Checker({});
514
- this.defaultFont = defaultFont ? this.normFont(c, "defaultFont", defaultFont, DEFAULT_FONT) : DEFAULT_FONT;
515
- this.addFont(this.defaultFont);
516
- this.addFill({
517
- kind: "pattern",
518
- pattern: "none"
519
- });
520
- this.addFill({
521
- kind: "pattern",
522
- pattern: "gray125"
523
- });
524
- this.addBorder({});
525
- this.addXf({
526
- numFmtId: 0,
527
- fontId: 0,
528
- fillId: 0,
529
- borderId: 0,
530
- alignment: "",
531
- protection: ""
532
- });
533
- }
534
- /** The workbook default font, normalised. */
535
- get baseFont() {
536
- return this.defaultFont;
537
- }
538
- id(o) {
539
- if (!o) return 0;
540
- let n = this.ids.get(o);
541
- if (n === void 0) {
542
- n = this.nextId++;
543
- this.ids.set(o, n);
544
- }
545
- return n;
546
- }
547
- /**
548
- * The cellXfs index for a cell, given its style layers (§3.5.7):
549
- * sheet default → column → row → cell. `isDate` adds the default date format
550
- * when no layer sets a number format.
551
- */
552
- xfFor(layers, isDate, ctx) {
553
- let key = isDate ? "d" : "";
554
- let any = isDate;
555
- for (const l of layers) {
556
- key += `:${this.id(l)}`;
557
- if (l) any = true;
558
- }
559
- if (!any) return 0;
560
- const cached = this.layerCache.get(key);
561
- if (cached !== void 0) return cached;
562
- const merged = layers.length === 1 && layers[0] ? layers[0] : mergeStyles(...layers);
563
- const index = this.resolve(merged, isDate, ctx);
564
- this.layerCache.set(key, index);
565
- return index;
566
- }
567
- /** Normalises a run font for rich text (merged over `base`), or undefined. */
568
- runFont(font, base, ctx) {
569
- if (!font) return void 0;
570
- return this.normFont(new Checker(ctx), "richText.font", font, base);
571
- }
572
- /** The resolved font of a style (its font merged over the default font). */
573
- fontOf(style, ctx) {
574
- if (!style?.font) return this.defaultFont;
575
- return this.normFont(new Checker(ctx), "font", style.font, this.defaultFont);
576
- }
577
- /** Validates a colour and returns its CT_Color attributes (e.g. ` rgb="FFFF0000"`). */
578
- colorAttrs(path, color, ctx) {
579
- const n = new Checker(ctx).color(path, color);
580
- return n ? colorAttrs(n) : "";
581
- }
582
- get cellXfCount() {
583
- return this.xfs.length;
584
- }
585
- resolve(style, isDate, ctx) {
586
- const c = new Checker(ctx);
587
- if (typeof style !== "object" || style === null) c.fail("style", style, "expected an object");
588
- let numFmtId = this.numFmtId(c, style.numFmt);
589
- if (isDate && style.numFmt === void 0) numFmtId = 14;
590
- const fontId = style.font ? this.addFont(this.normFont(c, "font", style.font, this.defaultFont)) : 0;
591
- const fill = style.fill === void 0 ? void 0 : this.normFill(c, style.fill);
592
- const fillId = fill ? this.addFill(fill) : 0;
593
- const borderId = style.border ? this.addBorder(this.normBorder(c, style.border)) : 0;
594
- const alignment = style.alignment ? this.alignmentAttrs(c, style.alignment) : "";
595
- const protection = style.protection ? this.protectionAttrs(c, style.protection) : "";
596
- return this.addXf({
597
- numFmtId,
598
- fontId,
599
- fillId,
600
- borderId,
601
- alignment,
602
- protection
603
- });
604
- }
605
- normFont(c, path, f, base) {
606
- if (typeof f !== "object" || f === null) c.fail(path, f, "expected an object");
607
- const out = { ...base };
608
- if (f.name !== void 0) {
609
- if (typeof f.name !== "string" || f.name.length === 0 || f.name.length > 31) c.fail(`${path}.name`, f.name, "expected a font name of 1 to 31 characters");
610
- if (f.name !== base.name) {
611
- delete out.scheme;
612
- delete out.family;
613
- }
614
- out.name = f.name;
615
- }
616
- const size = c.number(`${path}.size`, f.size, 1, 409);
617
- if (size !== void 0) out.size = size;
618
- const color = c.color(`${path}.color`, f.color);
619
- if (color) out.color = color;
620
- for (const k of [
621
- "bold",
622
- "italic",
623
- "strike",
624
- "outline",
625
- "shadow",
626
- "condense",
627
- "extend"
628
- ]) {
629
- const v = c.bool(`${path}.${k}`, f[k]);
630
- if (v === true) out[k] = true;
631
- else if (v === false) delete out[k];
632
- }
633
- if (f.underline !== void 0) {
634
- if (f.underline === true) out.underline = "single";
635
- else if (f.underline === false) delete out.underline;
636
- else out.underline = c.oneOf(`${path}.underline`, f.underline, UNDERLINES);
637
- }
638
- const va = c.oneOf(`${path}.vertAlign`, f.vertAlign, VERT_ALIGNS);
639
- if (va) out.vertAlign = va;
640
- const family = c.number(`${path}.family`, f.family, 0, 14, true);
641
- if (family !== void 0) out.family = family;
642
- const charset = c.number(`${path}.charset`, f.charset, 0, 255, true);
643
- if (charset !== void 0) out.charset = charset;
644
- const scheme = c.oneOf(`${path}.scheme`, f.scheme, SCHEMES);
645
- if (scheme) out.scheme = scheme;
646
- const ordered = {
647
- name: out.name,
648
- size: out.size
649
- };
650
- for (const k of [
651
- "color",
652
- "bold",
653
- "italic",
654
- "underline",
655
- "strike",
656
- "vertAlign",
657
- "family",
658
- "charset",
659
- "scheme",
660
- "outline",
661
- "shadow",
662
- "condense",
663
- "extend"
664
- ]) if (out[k] !== void 0) ordered[k] = out[k];
665
- return ordered;
666
- }
667
- normFill(c, f) {
668
- if (typeof f === "string") return {
669
- kind: "pattern",
670
- pattern: "solid",
671
- fg: { rgb: c.argb("fill", f) },
672
- bg: { indexed: 64 }
673
- };
674
- if (typeof f !== "object" || f === null) return c.fail("fill", f, "expected a colour string or a fill object");
675
- if (f.type === "gradient") {
676
- const gradient = c.oneOf("fill.gradient", f.gradient, /* @__PURE__ */ new Set(["linear", "path"]));
677
- if (!gradient) c.fail("fill.gradient", f.gradient, "required for a gradient fill");
678
- if (!Array.isArray(f.stops) || f.stops.length < 2) c.fail("fill.stops", f.stops, "a gradient needs at least two stops");
679
- const out = {
680
- kind: "gradient",
681
- gradient,
682
- stops: f.stops.map((s, i) => ({
683
- position: c.number(`fill.stops[${i}].position`, s.position, 0, 1) ?? c.fail(`fill.stops[${i}].position`, s.position, "required"),
684
- color: c.color(`fill.stops[${i}].color`, s.color) ?? c.fail(`fill.stops[${i}].color`, s.color, "required")
685
- }))
686
- };
687
- const degree = c.number("fill.degree", f.degree, -360, 360);
688
- if (degree !== void 0) out.degree = degree;
689
- for (const k of [
690
- "left",
691
- "right",
692
- "top",
693
- "bottom"
694
- ]) {
695
- const v = c.number(`fill.${k}`, f[k], 0, 1);
696
- if (v !== void 0) out[k] = v;
697
- }
698
- return out;
699
- }
700
- if (f.type !== void 0 && f.type !== "pattern") c.fail("fill.type", f.type, "expected 'pattern' or 'gradient'");
701
- const pattern = c.oneOf("fill.pattern", f.pattern, PATTERNS);
702
- if (!pattern) return c.fail("fill.pattern", f.pattern, "required for a pattern fill");
703
- if (pattern === "none") return void 0;
704
- const out = {
705
- kind: "pattern",
706
- pattern
707
- };
708
- const fg = c.color("fill.fgColor", f.fgColor);
709
- const bg = c.color("fill.bgColor", f.bgColor);
710
- if (fg) out.fg = fg;
711
- if (bg) out.bg = bg;
712
- else if (pattern === "solid") out.bg = { indexed: 64 };
713
- return out;
714
- }
715
- normSide(c, path, s) {
716
- if (s === void 0) return void 0;
717
- if (typeof s !== "object" || s === null) c.fail(path, s, "expected { style, color? }");
718
- const style = c.oneOf(`${path}.style`, s.style, BORDER_STYLES);
719
- if (!style) return c.fail(`${path}.style`, s.style, "required");
720
- if (style === "none") return void 0;
721
- const color = c.color(`${path}.color`, s.color);
722
- return color ? {
723
- style,
724
- color
725
- } : { style };
726
- }
727
- normBorder(c, b) {
728
- if (typeof b !== "object" || b === null) c.fail("border", b, "expected an object");
729
- const out = {};
730
- for (const side of [
731
- "left",
732
- "right",
733
- "top",
734
- "bottom",
735
- "diagonal"
736
- ]) {
737
- const s = this.normSide(c, `border.${side}`, b[side]);
738
- if (s) out[side] = s;
739
- }
740
- if (c.bool("border.diagonalUp", b.diagonalUp)) out.diagonalUp = true;
741
- if (c.bool("border.diagonalDown", b.diagonalDown)) out.diagonalDown = true;
742
- return out;
743
- }
744
- alignmentAttrs(c, a) {
745
- if (typeof a !== "object" || a === null) c.fail("alignment", a, "expected an object");
746
- let x = "";
747
- const h = c.oneOf("alignment.horizontal", a.horizontal, HORIZONTAL);
748
- if (h) x += ` horizontal="${h}"`;
749
- const v = c.oneOf("alignment.vertical", a.vertical, VERTICAL);
750
- if (v) x += ` vertical="${v}"`;
751
- if (a.rotation !== void 0) {
752
- let r;
753
- if (a.rotation === "vertical") r = 255;
754
- else {
755
- const deg = c.number("alignment.rotation", a.rotation, -90, 90, true);
756
- r = deg >= 0 ? deg : 90 - deg;
757
- }
758
- if (r !== 0) x += ` textRotation="${r}"`;
759
- }
760
- if (c.bool("alignment.wrapText", a.wrapText)) x += " wrapText=\"1\"";
761
- const indent = c.number("alignment.indent", a.indent, 0, 250, true);
762
- if (indent) x += ` indent="${indent}"`;
763
- if (c.bool("alignment.justifyLastLine", a.justifyLastLine)) x += " justifyLastLine=\"1\"";
764
- if (c.bool("alignment.shrinkToFit", a.shrinkToFit)) x += " shrinkToFit=\"1\"";
765
- if (a.readingOrder !== void 0) {
766
- const ro = READING_ORDER[c.oneOf("alignment.readingOrder", a.readingOrder, new Set(Object.keys(READING_ORDER)))];
767
- if (ro !== 0) x += ` readingOrder="${ro}"`;
768
- }
769
- return x;
770
- }
771
- protectionAttrs(c, p) {
772
- if (typeof p !== "object" || p === null) c.fail("protection", p, "expected an object");
773
- let x = "";
774
- if (c.bool("protection.locked", p.locked) === false) x += " locked=\"0\"";
775
- if (c.bool("protection.hidden", p.hidden) === true) x += " hidden=\"1\"";
776
- return x;
777
- }
778
- numFmtId(c, f) {
779
- if (f === void 0) return 0;
780
- if (typeof f === "number") {
781
- if (!Number.isInteger(f) || f < 0 || f > 163) c.fail("numFmt", f, "a built-in format id is an integer from 0 to 163", "INVALID_NUMFMT");
782
- return f;
783
- }
784
- if (typeof f !== "string" || f.length === 0) return c.fail("numFmt", f, "expected a built-in id or a non-empty format code", "INVALID_NUMFMT");
785
- if (f.toLowerCase() === "general") return 0;
786
- let id = this.numFmts.get(f);
787
- if (id === void 0) {
788
- id = 164 + this.numFmts.size;
789
- this.numFmts.set(f, id);
790
- }
791
- return id;
792
- }
793
- addFont(f) {
794
- const k = keyOf(f);
795
- let i = this.fontIndex.get(k);
796
- if (i === void 0) {
797
- i = this.fonts.length;
798
- this.fonts.push(`<font>${fontXml(f, "name")}</font>`);
799
- this.fontIndex.set(k, i);
800
- }
801
- return i;
802
- }
803
- addFill(f) {
804
- const k = keyOf(f);
805
- let i = this.fillIndex.get(k);
806
- if (i === void 0) {
807
- i = this.fills.length;
808
- this.fills.push(fillXml(f));
809
- this.fillIndex.set(k, i);
810
- }
811
- return i;
812
- }
813
- addBorder(b) {
814
- const k = keyOf(b);
815
- let i = this.borderIndex.get(k);
816
- if (i === void 0) {
817
- i = this.borders.length;
818
- this.borders.push(borderXml(b));
819
- this.borderIndex.set(k, i);
820
- }
821
- return i;
822
- }
823
- addXf(xf) {
824
- const k = `${xf.numFmtId},${xf.fontId},${xf.fillId},${xf.borderId},${xf.alignment},${xf.protection}`;
825
- let i = this.xfIndex.get(k);
826
- if (i === void 0) {
827
- if (this.xfs.length >= 64e3) throw new ValidationError("TOO_MANY_STYLES", `More than ${MAX_CELL_XFS} distinct cell styles.`, { details: { max: MAX_CELL_XFS } });
828
- i = this.xfs.length;
829
- this.xfs.push(xf);
830
- this.xfIndex.set(k, i);
831
- }
832
- return i;
833
- }
834
- toXml() {
835
- const parts = [XML_DECL, `<styleSheet xmlns="${NS_MAIN$1}">`];
836
- if (this.numFmts.size > 0) {
837
- parts.push(`<numFmts count="${this.numFmts.size}">`);
838
- for (const [code, id] of this.numFmts) parts.push(`<numFmt numFmtId="${id}" formatCode="${xmlAttr(code)}"/>`);
839
- parts.push("</numFmts>");
840
- }
841
- parts.push(`<fonts count="${this.fonts.length}">`, ...this.fonts, "</fonts>");
842
- parts.push(`<fills count="${this.fills.length}">`, ...this.fills, "</fills>");
843
- parts.push(`<borders count="${this.borders.length}">`, ...this.borders, "</borders>");
844
- parts.push("<cellStyleXfs count=\"1\"><xf numFmtId=\"0\" fontId=\"0\" fillId=\"0\" borderId=\"0\"/></cellStyleXfs>");
845
- parts.push(`<cellXfs count="${this.xfs.length}">`);
846
- for (const xf of this.xfs) {
847
- let attrs = `numFmtId="${xf.numFmtId}" fontId="${xf.fontId}" fillId="${xf.fillId}" borderId="${xf.borderId}" xfId="0"`;
848
- if (xf.numFmtId !== 0) attrs += " applyNumberFormat=\"1\"";
849
- if (xf.fontId !== 0) attrs += " applyFont=\"1\"";
850
- if (xf.fillId !== 0) attrs += " applyFill=\"1\"";
851
- if (xf.borderId !== 0) attrs += " applyBorder=\"1\"";
852
- if (xf.alignment) attrs += " applyAlignment=\"1\"";
853
- if (xf.protection) attrs += " applyProtection=\"1\"";
854
- const children = (xf.alignment ? `<alignment${xf.alignment}/>` : "") + (xf.protection ? `<protection${xf.protection}/>` : "");
855
- parts.push(children ? `<xf ${attrs}>${children}</xf>` : `<xf ${attrs}/>`);
856
- }
857
- parts.push("</cellXfs>");
858
- parts.push("<cellStyles count=\"1\"><cellStyle name=\"Normal\" xfId=\"0\" builtinId=\"0\"/></cellStyles>");
859
- parts.push("<dxfs count=\"0\"/><tableStyles count=\"0\"/>");
860
- parts.push("</styleSheet>");
861
- return parts.join("");
862
- }
863
- };
864
- // src/internal/write/sheet.ts
865
- /**
866
- * Worksheet XML and shared strings (docs/api.md §3.4).
867
- *
868
- * Sheet XML is produced as a stream of UTF-8 chunks, so a large sheet is never
869
- * held as one string.
870
- */
871
- const NS_MAIN = "http://schemas.openxmlformats.org/spreadsheetml/2006/main";
872
- const NS_REL = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
873
- /** Excel's limit on characters in one cell. */
874
- const MAX_CELL_CHARS = 32767;
875
- const ERROR_CODES = /* @__PURE__ */ new Set([
876
- "#NULL!",
877
- "#DIV/0!",
878
- "#VALUE!",
879
- "#REF!",
880
- "#NAME?",
881
- "#NUM!",
882
- "#N/A"
17
+ const FORBIDDEN_SEGMENTS = /* @__PURE__ */ new Set([
18
+ "__proto__",
19
+ "prototype",
20
+ "constructor"
883
21
  ]);
884
- /** Target size of each sheet XML chunk, in UTF-16 code units. */
885
- const CHUNK_CHARS = 65536;
886
- /** The shared strings table: one <si> per distinct string or rich text. */
887
- var SharedStrings = class {
888
- index = /* @__PURE__ */ new Map();
889
- items = [];
890
- /** Number of cells that reference the table. */
891
- count = 0;
892
- /** Index of a plain string. */
893
- plain(s) {
894
- this.count++;
895
- let i = this.index.get(s);
896
- if (i === void 0) {
897
- i = this.items.length;
898
- this.items.push(`<si>${textElement(s)}</si>`);
899
- this.index.set(s, i);
900
- }
901
- return i;
902
- }
903
- /** Index of rich text, given its serialised runs. */
904
- rich(runsXml) {
905
- this.count++;
906
- const key = `\u0000${runsXml}`;
907
- let i = this.index.get(key);
908
- if (i === void 0) {
909
- i = this.items.length;
910
- this.items.push(`<si>${runsXml}</si>`);
911
- this.index.set(key, i);
912
- }
913
- return i;
914
- }
915
- get uniqueCount() {
916
- return this.items.length;
917
- }
918
- toXml() {
919
- return `${XML_DECL}<sst xmlns="${NS_MAIN}" count="${this.count}" uniqueCount="${this.items.length}">${this.items.join("")}</sst>`;
920
- }
921
- };
922
- function textElement(s) {
923
- return needsPreserve(s) ? `<t xml:space="preserve">${xstring(s)}</t>` : `<t>${xstring(s)}</t>`;
924
- }
925
- function cellError(code, message, sheet, ref, extra) {
926
- return new ValidationError(code, `${message} (${sheet}!${ref}).`, { details: {
927
- sheet,
928
- ref,
929
- ...extra
930
- } });
931
- }
932
- /** A value object `{ error }` or `{ richText }`, as opposed to a Cell. */
933
- function isValueObject(v) {
934
- return "error" in v || "richText" in v;
935
- }
936
- function typeOf(v) {
937
- if (v === null || v === void 0) return "empty";
938
- if (typeof v === "string") return "string";
939
- if (typeof v === "number") return "number";
940
- if (typeof v === "boolean") return "boolean";
941
- if (v instanceof Date) return "date";
942
- if (typeof v === "object" && "error" in v) return "error";
943
- return "richText";
944
- }
945
- /**
946
- * Validates a sheet's features, scans its cells for the used range (checking
947
- * the format's row and column limits) and measures 'auto' column widths.
948
- */
949
- function planSheet(sheet, index, tabSelected, styles, schemes) {
950
- const features = new SheetFeatures(sheet, index, tabSelected, styles);
951
- const rels = new Rels();
952
- const plan = {
953
- sheet,
954
- features,
955
- rels,
956
- links: new SheetLinks(sheet.name, schemes, rels),
957
- minRow: 1e400,
958
- maxRow: -1,
959
- minCol: 1e400,
960
- maxCol: -1,
961
- tabSelected
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 });
962
28
  };
963
- const measuring = features.autoCols.size > 0;
964
- const rows = sheet.rows;
965
- if (!Array.isArray(rows)) throw new ValidationError("INVALID_CELL", `Sheet ${sheet.name}: rows must be an array of rows.`, { details: { sheet: sheet.name } });
966
- for (let r = 0; r < rows.length; r++) {
967
- const row = rows[r];
968
- if (row === void 0 || row === null) continue;
969
- if (!Array.isArray(row)) throw new ValidationError("INVALID_CELL", `Sheet ${sheet.name}: row ${r + 1} must be an array of cells.`, { details: {
970
- sheet: sheet.name,
971
- row: r
972
- } });
973
- let used = false;
974
- for (let c = 0; c < row.length; c++) {
975
- const cell = row[c];
976
- if (cell === void 0 || cell === null) continue;
977
- if (c >= 16384) throw new ValidationError("OUT_OF_BOUNDS", `Sheet ${sheet.name}: column ${c + 1} is beyond XFD.`, { details: {
978
- sheet: sheet.name,
979
- row: r,
980
- col: c
981
- } });
982
- used = true;
983
- if (measuring) features.measure(c, cellText(cell));
984
- if (c < plan.minCol) plan.minCol = c;
985
- if (c > plan.maxCol) plan.maxCol = c;
986
- }
987
- if (used) {
988
- if (r >= 1048576) throw new ValidationError("OUT_OF_BOUNDS", `Sheet ${sheet.name}: row ${r + 1} is beyond row ${MAX_ROWS}.`, { details: {
989
- sheet: sheet.name,
990
- row: r
991
- } });
992
- if (r < plan.minRow) plan.minRow = r;
993
- plan.maxRow = r;
994
- }
995
- }
996
- return plan;
997
- }
998
- function planRowCount(plan) {
999
- return plan.maxRow < 0 ? 0 : plan.maxRow - plan.minRow + 1;
1000
- }
1001
- /** First and last row to write: rows with cells and rows with properties. */
1002
- function rowSpan(plan) {
1003
- let first = plan.maxRow < 0 ? 1e400 : plan.minRow;
1004
- for (const r of plan.features.rowAttrs.keys()) if (r < first) first = r;
1005
- return [first, Math.max(plan.maxRow, plan.features.maxPropRow)];
1006
- }
1007
- /** Streams the worksheet XML as UTF-8 chunks. `onRow` is called after each row with data. */
1008
- async function* sheetXml(plan, ctx, onRow) {
1009
- const { sheet, features, links } = plan;
1010
- const name = sheet.name;
1011
- const dimension = plan.maxRow < 0 ? "A1" : plan.minRow === plan.maxRow && plan.minCol === plan.maxCol ? `${encodeCol(plan.minCol)}${plan.minRow + 1}` : `${encodeCol(plan.minCol)}${plan.minRow + 1}:${encodeCol(plan.maxCol)}${plan.maxRow + 1}`;
1012
- let buf = `${XML_DECL}<worksheet xmlns="${NS_MAIN}" xmlns:r="${NS_REL}">` + features.sheetPrXml + `<dimension ref="${dimension}"/>` + features.sheetViewsXml + features.sheetFormatPrXml + features.colsXml() + "<sheetData>";
1013
- const colLetters = [];
1014
- const letters = (c) => colLetters[c] ??= encodeCol(c);
1015
- const rows = sheet.rows;
1016
- const defaultStyle = sheet.defaultStyle;
1017
- const colProps = sheet.colProps;
1018
- const rowProps = sheet.rowProps;
1019
- const rowAttrs = features.rowAttrs;
1020
- const [firstRow, lastRow] = rowSpan(plan);
1021
- for (let r = firstRow; r <= lastRow; r++) {
1022
- const row = rows[r];
1023
- const attrs = rowAttrs.get(r) ?? "";
1024
- if (!row && !attrs) continue;
1025
- const rowStyle = rowProps?.[r]?.style;
1026
- const rowNum = r + 1;
1027
- let rowXml = "";
1028
- if (row) for (let c = 0; c < row.length; c++) {
1029
- const input = row[c];
1030
- if (input === void 0 || input === null) continue;
1031
- const ref = `${letters(c)}${rowNum}`;
1032
- rowXml += cellXml(input, ref, name, ctx, [
1033
- defaultStyle,
1034
- colProps?.[c]?.style,
1035
- rowStyle
1036
- ]);
1037
- links.add(ref, hyperlinkOf(input));
1038
- }
1039
- if (rowXml || attrs) {
1040
- buf += rowXml ? `<row r="${rowNum}"${attrs}>${rowXml}</row>` : `<row r="${rowNum}"${attrs}/>`;
1041
- if (rowXml) onRow();
1042
- if (buf.length >= CHUNK_CHARS) {
1043
- yield encodeUtf8(buf);
1044
- buf = "";
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;
1045
44
  }
1046
- }
1047
- }
1048
- buf += `</sheetData>${features.afterDataXml(links)}</worksheet>`;
1049
- yield encodeUtf8(buf);
1050
- }
1051
- /** One <c> element. */
1052
- function cellXml(input, ref, sheet, ctx, layers) {
1053
- let cell;
1054
- if (typeof input !== "object" || input instanceof Date || isValueObject(input)) cell = { value: input };
1055
- else cell = input;
1056
- const value = cell.value;
1057
- const vtype = typeOf(value);
1058
- if (cell.type !== void 0 && cell.type !== vtype) throw cellError("INVALID_CELL", `Cell type '${cell.type}' does not match its value (${vtype})`, sheet, ref, { type: cell.type });
1059
- let formula;
1060
- if (cell.formula !== void 0) {
1061
- if (typeof cell.formula !== "string") throw cellError("INVALID_CELL", "formula must be a string", sheet, ref);
1062
- formula = cell.formula.startsWith("=") ? cell.formula.slice(1) : cell.formula;
1063
- if (formula.length === 0) throw cellError("INVALID_CELL", "formula is empty", sheet, ref);
1064
- if (vtype === "richText") throw cellError("INVALID_CELL", "A formula's cached value cannot be rich text", sheet, ref);
1065
- }
1066
- if (cell.arrayRef !== void 0 && formula === void 0) throw cellError("INVALID_CELL", "arrayRef needs a formula", sheet, ref);
1067
- const s = ctx.styles.xfFor([...layers, cell.style], vtype === "date", {
1068
- sheet,
1069
- ref
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
1070
58
  });
1071
- const sAttr = s === 0 ? "" : ` s="${s}"`;
1072
- if (formula !== void 0) {
1073
- let f;
1074
- if (cell.arrayRef !== void 0) {
1075
- try {
1076
- decodeRange(cell.arrayRef);
1077
- } catch {
1078
- throw cellError("INVALID_REF", `arrayRef ${JSON.stringify(cell.arrayRef)} is not an A1 range`, sheet, ref);
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;
1079
81
  }
1080
- f = `<f t="array" ref="${cell.arrayRef}">${xstring(formula)}</f>`;
1081
- } else f = `<f>${xstring(formula)}</f>`;
1082
- if (vtype === "empty") {
1083
- ctx.formulaWithoutValue = true;
1084
- return `<c r="${ref}"${sAttr}>${f}</c>`;
1085
- }
1086
- const { t, v } = scalar(value, vtype, sheet, ref, ctx, true);
1087
- return `<c r="${ref}"${sAttr}${t}>${f}<v>${v}</v></c>`;
1088
- }
1089
- if (vtype === "empty") return `<c r="${ref}"${sAttr}/>`;
1090
- if (vtype === "string") {
1091
- const str = value;
1092
- if (str.length > 32767) throw cellError("STRING_TOO_LONG", `Text longer than ${MAX_CELL_CHARS} characters`, sheet, ref, { length: str.length });
1093
- if (ctx.strings) return `<c r="${ref}"${sAttr} t="s"><v>${ctx.strings.plain(str)}</v></c>`;
1094
- return `<c r="${ref}"${sAttr} t="inlineStr"><is>${textElement(str)}</is></c>`;
1095
- }
1096
- if (vtype === "richText") {
1097
- const runs = richRunsXml(value, [...layers, cell.style], sheet, ref, ctx);
1098
- if (ctx.strings) return `<c r="${ref}"${sAttr} t="s"><v>${ctx.strings.rich(runs)}</v></c>`;
1099
- return `<c r="${ref}"${sAttr} t="inlineStr"><is>${runs}</is></c>`;
82
+ return v;
83
+ };
1100
84
  }
1101
- const { t, v } = scalar(value, vtype, sheet, ref, ctx, false);
1102
- return `<c r="${ref}"${sAttr}${t}><v>${v}</v></c>`;
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
+ };
1103
98
  }
1104
- /** Number, boolean, date or error value (or a formula's string result). */
1105
- function scalar(value, vtype, sheet, ref, ctx, isFormula) {
1106
- switch (vtype) {
1107
- case "number": {
1108
- const n = value;
1109
- if (!Number.isFinite(n)) throw cellError("INVALID_NUMBER", `Number ${String(n)} cannot be stored`, sheet, ref);
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
+ };
1110
114
  return {
1111
- t: "",
1112
- v: num(n)
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
1113
126
  };
1114
- }
1115
- case "boolean": return {
1116
- t: " t=\"b\"",
1117
- v: value ? "1" : "0"
1118
- };
1119
- case "date": {
1120
- let serial;
1121
- try {
1122
- serial = dateToSerial(value, {
1123
- date1904: ctx.date1904,
1124
- dateZone: ctx.dateZone
1125
- });
1126
- } catch {
1127
- throw cellError("INVALID_DATE", "Date is invalid or outside 1900-01-01..9999-12-31 (1904 system: 1904-01-01..)", sheet, ref);
1128
- }
1129
127
  return {
1130
- t: "",
1131
- v: num(serial)
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
1132
139
  };
1133
- }
1134
- case "error": {
1135
- const code = value.error;
1136
- if (typeof code !== "string" || !ERROR_CODES.has(code)) throw cellError("INVALID_CELL", `Unknown error value ${JSON.stringify(code)}`, sheet, ref);
1137
140
  return {
1138
- t: " t=\"e\"",
1139
- v: code
141
+ value: typeof v === "object" ? cellText(v) : String(v),
142
+ failed: true
1140
143
  };
1141
- }
1142
- case "string": {
1143
- const str = value;
1144
- if (!isFormula) throw new Error("unreachable");
1145
- if (str.length > 32767) throw cellError("STRING_TOO_LONG", `Text longer than ${MAX_CELL_CHARS} characters`, sheet, ref, { length: str.length });
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
+ }
1146
164
  return {
1147
- t: " t=\"str\"",
1148
- v: xstring(str)
165
+ value: typeof v === "object" ? cellText(v) : String(v),
166
+ failed: true
1149
167
  };
1150
- }
1151
- default: throw cellError("INVALID_CELL", "Unsupported cell value", sheet, ref);
168
+ default: throw columnError(`Unknown column type ${JSON.stringify(type)}.`, { type });
1152
169
  }
1153
170
  }
1154
- function richRunsXml(value, layers, sheet, ref, ctx) {
1155
- const runs = value.richText;
1156
- if (!Array.isArray(runs) || runs.length === 0) throw cellError("INVALID_CELL", "richText needs at least one run", sheet, ref);
1157
- let base;
1158
- let length = 0;
1159
- let x = "";
1160
- for (const run of runs) {
1161
- if (typeof run !== "object" || run === null || typeof run.text !== "string") throw cellError("INVALID_CELL", "Each rich-text run needs a text string", sheet, ref);
1162
- length += run.text.length;
1163
- if (run.font) {
1164
- base ??= ctx.styles.fontOf(mergeStyles(...layers), {
1165
- sheet,
1166
- ref
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
1167
197
  });
1168
- const font = ctx.styles.runFont(run.font, base, {
1169
- sheet,
1170
- ref
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)
1171
246
  });
1172
- x += `<r><rPr>${fontXml(font, "rFont")}</rPr>${textElement(run.text)}</r>`;
1173
- } else x += `<r>${textElement(run.text)}</r>`;
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;
1174
382
  }
1175
- if (length > 32767) throw cellError("STRING_TOO_LONG", `Text longer than ${MAX_CELL_CHARS} characters`, sheet, ref, { length });
1176
- return x;
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
+ };
1177
392
  }
1178
- // src/write.ts
1179
- /** MIME type of an .xlsx file. */
1180
- const XLSX_MIME = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
1181
- /** Report progress at most once per this many rows. [placeholder, set in JSE-8] */
1182
- const PROGRESS_EVERY_ROWS = 1e3;
1183
- const SHEET_NAME_PROBLEMS = {
1184
- empty: "must be a non-empty string",
1185
- "too-long": "is longer than 31 characters",
1186
- "forbidden-char": "contains one of \\ / ? * [ ] :",
1187
- apostrophe: "starts or ends with an apostrophe",
1188
- reserved: "'History' is reserved by Excel"
393
+ const SUBTOTAL = {
394
+ sum: 109,
395
+ average: 101,
396
+ count: 103,
397
+ min: 105,
398
+ max: 104
1189
399
  };
1190
- function checkSheetName(name, index) {
1191
- const problem = typeof name === "string" ? validateSheetName(name) : "empty";
1192
- if (problem) throw new ValidationError("INVALID_SHEET_NAME", `Sheet ${index + 1} name ${JSON.stringify(name)} ${SHEET_NAME_PROBLEMS[problem]}.`, { details: {
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: {
1193
474
  sheet: name,
1194
- index,
1195
475
  problem
1196
476
  } });
477
+ return name;
1197
478
  }
1198
- function planWorkbook(wb, styles, schemes) {
1199
- if (typeof wb !== "object" || wb === null || !Array.isArray(wb.sheets) || wb.sheets.length === 0) throw new ValidationError("NO_SHEETS", "A workbook needs at least one sheet.");
1200
- const seen = /* @__PURE__ */ new Map();
1201
- wb.sheets.forEach((sheet, i) => {
1202
- if (typeof sheet !== "object" || sheet === null) throw new ValidationError("INVALID_SHEET_NAME", `Sheet ${i + 1} is not an object.`, { details: { index: i } });
1203
- checkSheetName(sheet.name, i);
1204
- const key = sheet.name.toLowerCase();
1205
- const prev = seen.get(key);
1206
- if (prev !== void 0) throw new ValidationError("DUPLICATE_SHEET_NAME", `Sheets ${prev + 1} and ${i + 1} are both named ${JSON.stringify(sheet.name)} (names are case-insensitive).`, { details: {
1207
- sheet: sheet.name,
1208
- index: i
1209
- } });
1210
- seen.set(key, i);
1211
- const state = sheet.state ?? "visible";
1212
- if (state !== "visible" && state !== "hidden" && state !== "veryHidden") throw new ValidationError("INVALID_SHEET_PROPERTY", `Sheet ${sheet.name}: state must be 'visible', 'hidden' or 'veryHidden'.`, { details: {
1213
- sheet: sheet.name,
1214
- path: "state",
1215
- value: state
1216
- } });
1217
- });
1218
- const activeSheet = wb.activeSheet ?? 0;
1219
- const active = wb.sheets[activeSheet];
1220
- if (!Number.isInteger(activeSheet) || !active) throw new ValidationError("INVALID_ACTIVE_SHEET", `activeSheet ${String(activeSheet)} is not a sheet index.`, { details: { activeSheet } });
1221
- if ((active.state ?? "visible") !== "visible") throw new ValidationError("INVALID_ACTIVE_SHEET", `The active sheet ${JSON.stringify(active.name)} must be visible.`, { details: { activeSheet } });
1222
- const sheets = wb.sheets.map((s, i) => planSheet(s, i, i === activeSheet, styles, schemes));
1223
- return {
1224
- sheets,
1225
- activeSheet,
1226
- totalRows: sheets.reduce((n, p) => n + planRowCount(p), 0)
479
+ function originOf(options) {
480
+ if (options.origin === void 0) return {
481
+ row: 0,
482
+ col: 0
1227
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);
1228
500
  }
1229
- /** Writes a workbook as .xlsx bytes. */
1230
- async function toUint8Array(wb, options = {}) {
1231
- const { signal, onProgress } = options;
1232
- throwIfAborted(signal);
1233
- onProgress?.({
1234
- phase: "prepare",
1235
- ratio: 0
1236
- });
1237
- const styles = new StyleRegistry(wb.defaultFont);
1238
- const plan = planWorkbook(wb, styles, hyperlinkSchemes(options.hyperlinkSchemes));
1239
- const definedNames = definedNamesXml(wb.definedNames, plan.sheets.flatMap((p) => p.features.builtinNames), plan.sheets.length);
1240
- const props = wb.properties ?? {};
1241
- const now = /* @__PURE__ */ new Date();
1242
- const modified = props.modified ?? now;
1243
- const custom = props.custom ?? [];
1244
- const sharedStrings = options.sharedStrings !== false;
1245
- const pkg = new PackageParts();
1246
- pkg.addOverride("xl/workbook.xml", CONTENT_TYPE.workbook);
1247
- const sheetRelIds = plan.sheets.map((_, i) => {
1248
- pkg.addOverride(`xl/worksheets/sheet${i + 1}.xml`, CONTENT_TYPE.worksheet);
1249
- return pkg.workbook.add(REL_TYPE.worksheet, `worksheets/sheet${i + 1}.xml`);
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;
1250
523
  });
1251
- pkg.addOverride("xl/theme/theme1.xml", CONTENT_TYPE.theme);
1252
- pkg.workbook.add(REL_TYPE.theme, "theme/theme1.xml");
1253
- pkg.addOverride("xl/styles.xml", CONTENT_TYPE.styles);
1254
- pkg.workbook.add(REL_TYPE.styles, "styles.xml");
1255
- if (sharedStrings) {
1256
- pkg.addOverride("xl/sharedStrings.xml", CONTENT_TYPE.sharedStrings);
1257
- pkg.workbook.add(REL_TYPE.sharedStrings, "sharedStrings.xml");
1258
- }
1259
- pkg.addOverride("docProps/core.xml", CONTENT_TYPE.coreProperties);
1260
- pkg.addOverride("docProps/app.xml", CONTENT_TYPE.extendedProperties);
1261
- pkg.root.add(REL_TYPE.officeDocument, "xl/workbook.xml");
1262
- pkg.root.add(REL_TYPE.coreProperties, "docProps/core.xml");
1263
- pkg.root.add(REL_TYPE.extendedProperties, "docProps/app.xml");
1264
- if (custom.length > 0) {
1265
- pkg.addOverride("docProps/custom.xml", CONTENT_TYPE.customProperties);
1266
- pkg.root.add(REL_TYPE.customProperties, "docProps/custom.xml");
1267
- }
1268
- const core = coreXml(props, now);
1269
- const app = appXml(props);
1270
- const customPart = custom.length > 0 ? customXml(custom) : void 0;
1271
- const ctx = {
1272
- styles,
1273
- strings: sharedStrings ? new SharedStrings() : void 0,
1274
- date1904: wb.date1904 === true,
1275
- dateZone: options.dateZone ?? "local",
1276
- formulaWithoutValue: false
1277
- };
1278
- let rowsDone = 0;
1279
- let lastReported = 0;
1280
- const ratioOf = () => plan.totalRows === 0 ? .9 : .9 * (rowsDone / plan.totalRows);
1281
- const onRow = (sheet) => () => {
1282
- rowsDone++;
1283
- if (onProgress && rowsDone - lastReported >= PROGRESS_EVERY_ROWS) {
1284
- lastReported = rowsDone;
1285
- onProgress({
1286
- phase: "sheets",
1287
- sheet,
1288
- ratio: ratioOf()
1289
- });
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
1290
543
  }
1291
544
  };
1292
- async function* entries() {
1293
- yield {
1294
- name: "[Content_Types].xml",
1295
- data: pkg.contentTypesXml()
1296
- };
1297
- yield {
1298
- name: "_rels/.rels",
1299
- data: pkg.root.xml()
1300
- };
1301
- yield {
1302
- name: "docProps/core.xml",
1303
- data: core
1304
- };
1305
- yield {
1306
- name: "docProps/app.xml",
1307
- data: app
1308
- };
1309
- if (customPart) yield {
1310
- name: "docProps/custom.xml",
1311
- data: customPart
1312
- };
1313
- for (let i = 0; i < plan.sheets.length; i++) {
1314
- const sp = plan.sheets[i];
1315
- const name = sp.sheet.name;
1316
- onProgress?.({
1317
- phase: "sheets",
1318
- sheet: name,
1319
- ratio: ratioOf()
1320
- });
1321
- const chunks = sheetXml(sp, ctx, onRow(name));
1322
- yield {
1323
- name: `xl/worksheets/sheet${i + 1}.xml`,
1324
- data: (async function* () {
1325
- for await (const chunk of chunks) {
1326
- throwIfAborted(signal);
1327
- yield chunk;
1328
- }
1329
- })()
1330
- };
1331
- const rels = sp.rels.xml();
1332
- if (rels) yield {
1333
- name: `xl/worksheets/_rels/sheet${i + 1}.xml.rels`,
1334
- data: rels
1335
- };
1336
- }
1337
- onProgress?.({
1338
- phase: "styles",
1339
- ratio: .9
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}`
1340
573
  });
1341
- if (ctx.strings) yield {
1342
- name: "xl/sharedStrings.xml",
1343
- data: encodeUtf8(ctx.strings.toXml())
1344
- };
1345
- yield {
1346
- name: "xl/styles.xml",
1347
- data: ctx.styles.toXml()
1348
- };
1349
- yield {
1350
- name: "xl/theme/theme1.xml",
1351
- data: THEME_XML
1352
- };
1353
- const fullCalc = wb.calc?.fullCalcOnLoad;
1354
- yield {
1355
- name: "xl/workbook.xml",
1356
- data: workbookXml({
1357
- sheets: plan.sheets.map((p, i) => ({
1358
- name: p.sheet.name,
1359
- state: p.sheet.state ?? "visible",
1360
- relId: sheetRelIds[i]
1361
- })),
1362
- activeSheet: plan.activeSheet,
1363
- date1904: ctx.date1904,
1364
- fullCalcOnLoad: fullCalc === true || (fullCalc === void 0 || fullCalc === "auto") && ctx.formulaWithoutValue,
1365
- definedNames
1366
- })
1367
- };
1368
- yield {
1369
- name: "xl/_rels/workbook.xml.rels",
1370
- data: pkg.workbook.xml()
1371
- };
1372
- onProgress?.({
1373
- phase: "zip",
1374
- ratio: .95
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;
1375
586
  });
587
+ if (any) data.push(obj);
1376
588
  }
1377
- const bytes = await writeZip(entries(), {
1378
- compression: options.compression ?? "deflate",
1379
- modified,
1380
- ...signal ? { signal } : {}
1381
- });
1382
- onProgress?.({
1383
- phase: "zip",
1384
- ratio: 1
1385
- });
1386
- return bytes;
1387
- }
1388
- /** Writes a workbook as an .xlsx Blob (type XLSX_MIME). */
1389
- async function toBlob(wb, options) {
1390
- const BlobCtor = globalThis.Blob;
1391
- if (typeof BlobCtor !== "function") throw new EnvironmentError("ENVIRONMENT_UNSUPPORTED", "Blob is not available in this runtime; use toUint8Array instead.", { details: { api: "Blob" } });
1392
- return new BlobCtor([await toUint8Array(wb, options)], { type: XLSX_MIME });
589
+ return {
590
+ columns,
591
+ data
592
+ };
1393
593
  }
1394
594
  // src/index.ts
1395
- /** Package version. Kept in sync with package.json by a unit test. */
1396
- const VERSION = "2.0.0-alpha.1";
1397
- 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, isDateFormat, isExcelError, mergeStyles, sanitizeSheetName, serialToDate, toBlob, toUint8Array, validateSheetName };
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 };