javascript-excel 1.0.3 → 2.0.0-alpha.1
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/README.md +50 -2
- package/dist/auto-width-2oBzjeNG.d.cts +11 -0
- package/dist/auto-width-CT-BihTW.d.ts +10 -0
- package/dist/csv.cjs +623 -0
- package/dist/csv.d.cts +89 -0
- package/dist/csv.d.ts +89 -0
- package/dist/csv.js +618 -0
- package/dist/dom.cjs +464 -0
- package/dist/dom.d.cts +78 -0
- package/dist/dom.d.ts +78 -0
- package/dist/dom.js +461 -0
- package/dist/errors-CvGlfw0E.js +28 -0
- package/dist/errors-DOPrrGS4.cjs +69 -0
- package/dist/index.cjs +1424 -0
- package/dist/index.d.cts +140 -0
- package/dist/index.d.ts +140 -0
- package/dist/index.js +1397 -0
- package/dist/infer-BR-J9BZa.js +88 -0
- package/dist/infer-D9EC9vJ-.cjs +105 -0
- package/dist/iso-date-B22IvwL1.js +21 -0
- package/dist/iso-date-BSUsPSWO.cjs +26 -0
- package/dist/numfmt-B-TlCgr7.cjs +476 -0
- package/dist/numfmt-DEm0sYBJ.js +399 -0
- package/dist/read.cjs +2899 -0
- package/dist/read.d.cts +88 -0
- package/dist/read.d.ts +88 -0
- package/dist/read.js +2895 -0
- package/dist/sheet-names-CDsVK15c.js +831 -0
- package/dist/sheet-names-Cm-IhbBk.cjs +1004 -0
- package/dist/signal-Dz0ZYe6d.d.cts +13 -0
- package/dist/signal-Dz0ZYe6d.d.ts +13 -0
- package/dist/warnings-C_12PT4t.d.cts +410 -0
- package/dist/warnings-DXJKe1lx.d.ts +410 -0
- package/dist/worker.cjs +11 -0
- package/dist/worker.d.cts +8 -0
- package/dist/worker.d.ts +8 -0
- package/dist/worker.js +10 -0
- package/dist/write-C5JgeIar.d.cts +29 -0
- package/dist/write-CYpLGuzl.d.ts +29 -0
- package/package.json +67 -51
- package/.babelrc +0 -10
- package/.circleci/config.yml +0 -39
- package/lib/index.d.ts +0 -1
- package/lib/index.js +0 -22
- package/lib/javascript-excel.js +0 -17703
- package/src/index.tsx +0 -11
- package/test/unit/sample.spec.js +0 -5
- package/tsconfig.json +0 -54
- package/webpack.config.js +0 -19
- /package/{LICENSE.md → LICENSE} +0 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,1397 @@
|
|
|
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
|
+
}
|
|
231
|
+
/**
|
|
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).
|
|
287
|
+
*
|
|
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.
|
|
292
|
+
*/
|
|
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>`;
|
|
487
|
+
}
|
|
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"
|
|
883
|
+
]);
|
|
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
|
|
962
|
+
};
|
|
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 = "";
|
|
1045
|
+
}
|
|
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
|
|
1070
|
+
});
|
|
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);
|
|
1079
|
+
}
|
|
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>`;
|
|
1100
|
+
}
|
|
1101
|
+
const { t, v } = scalar(value, vtype, sheet, ref, ctx, false);
|
|
1102
|
+
return `<c r="${ref}"${sAttr}${t}><v>${v}</v></c>`;
|
|
1103
|
+
}
|
|
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);
|
|
1110
|
+
return {
|
|
1111
|
+
t: "",
|
|
1112
|
+
v: num(n)
|
|
1113
|
+
};
|
|
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
|
+
return {
|
|
1130
|
+
t: "",
|
|
1131
|
+
v: num(serial)
|
|
1132
|
+
};
|
|
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
|
+
return {
|
|
1138
|
+
t: " t=\"e\"",
|
|
1139
|
+
v: code
|
|
1140
|
+
};
|
|
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 });
|
|
1146
|
+
return {
|
|
1147
|
+
t: " t=\"str\"",
|
|
1148
|
+
v: xstring(str)
|
|
1149
|
+
};
|
|
1150
|
+
}
|
|
1151
|
+
default: throw cellError("INVALID_CELL", "Unsupported cell value", sheet, ref);
|
|
1152
|
+
}
|
|
1153
|
+
}
|
|
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
|
|
1167
|
+
});
|
|
1168
|
+
const font = ctx.styles.runFont(run.font, base, {
|
|
1169
|
+
sheet,
|
|
1170
|
+
ref
|
|
1171
|
+
});
|
|
1172
|
+
x += `<r><rPr>${fontXml(font, "rFont")}</rPr>${textElement(run.text)}</r>`;
|
|
1173
|
+
} else x += `<r>${textElement(run.text)}</r>`;
|
|
1174
|
+
}
|
|
1175
|
+
if (length > 32767) throw cellError("STRING_TOO_LONG", `Text longer than ${MAX_CELL_CHARS} characters`, sheet, ref, { length });
|
|
1176
|
+
return x;
|
|
1177
|
+
}
|
|
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"
|
|
1189
|
+
};
|
|
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: {
|
|
1193
|
+
sheet: name,
|
|
1194
|
+
index,
|
|
1195
|
+
problem
|
|
1196
|
+
} });
|
|
1197
|
+
}
|
|
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)
|
|
1227
|
+
};
|
|
1228
|
+
}
|
|
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`);
|
|
1250
|
+
});
|
|
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
|
+
});
|
|
1290
|
+
}
|
|
1291
|
+
};
|
|
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
|
|
1340
|
+
});
|
|
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
|
|
1375
|
+
});
|
|
1376
|
+
}
|
|
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 });
|
|
1393
|
+
}
|
|
1394
|
+
// 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 };
|