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
|
@@ -0,0 +1,831 @@
|
|
|
1
|
+
import { o as ValidationError } from "./errors-CvGlfw0E.js";
|
|
2
|
+
import { t as isoDate } from "./iso-date-B22IvwL1.js";
|
|
3
|
+
// src/internal/xml.ts
|
|
4
|
+
/**
|
|
5
|
+
* XML text helpers for the writer.
|
|
6
|
+
*
|
|
7
|
+
* Two escapings:
|
|
8
|
+
* - `xstring` for SpreadsheetML text that is an ST_Xstring (cell text, shared
|
|
9
|
+
* strings, formulas): characters XML 1.0 cannot carry, and CR (which XML
|
|
10
|
+
* parsers normalise to LF), are written as `_xHHHH_`. Text that already
|
|
11
|
+
* contains a literal `_xHHHH_` is protected as `_x005F_xHHHH_`
|
|
12
|
+
* (ECMA-376 Part 1, §22.9.2.19).
|
|
13
|
+
* - `xmlText` / `xmlAttr` for ordinary XML (document properties, sheet names):
|
|
14
|
+
* only the markup characters are escaped, and characters XML 1.0 cannot
|
|
15
|
+
* carry are dropped, because those parts have no escape convention.
|
|
16
|
+
*/
|
|
17
|
+
const INVALID_XML_CHAR = /[\u0000-\u0008\u000B\u000C\u000E-\u001F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g;
|
|
18
|
+
const NEEDS_XSTRING = /[\u0000-\u0008\u000B-\u001F\uD800-\uDFFF\uFFFE\uFFFF]|_x[0-9A-Fa-f]{4}_/;
|
|
19
|
+
const MARKUP_TEXT = /[&<>]/g;
|
|
20
|
+
const MARKUP_ATTR = /[&<>"\t\n\r]/g;
|
|
21
|
+
const ENTITY = {
|
|
22
|
+
"&": "&",
|
|
23
|
+
"<": "<",
|
|
24
|
+
">": ">",
|
|
25
|
+
"\"": """,
|
|
26
|
+
" ": "	",
|
|
27
|
+
"\n": " ",
|
|
28
|
+
"\r": " "
|
|
29
|
+
};
|
|
30
|
+
const entity = (c) => ENTITY[c];
|
|
31
|
+
const hex4 = (code) => code.toString(16).toUpperCase().padStart(4, "0");
|
|
32
|
+
/** Applies the ST_Xstring encoding (no markup escaping). */
|
|
33
|
+
function encodeXstring(s) {
|
|
34
|
+
if (!NEEDS_XSTRING.test(s)) return s;
|
|
35
|
+
let out = s.replace(/_(?=x[0-9A-Fa-f]{4}_)/g, "_x005F_");
|
|
36
|
+
out = out.replace(/\r/g, "_x000D_");
|
|
37
|
+
out = out.replace(INVALID_XML_CHAR, (c) => `_x${hex4(c.charCodeAt(0))}_`);
|
|
38
|
+
return out;
|
|
39
|
+
}
|
|
40
|
+
/** ST_Xstring text content: `_xHHHH_` encoding, then markup escaping. */
|
|
41
|
+
function xstring(s) {
|
|
42
|
+
return encodeXstring(s).replace(MARKUP_TEXT, entity);
|
|
43
|
+
}
|
|
44
|
+
/** Plain XML text content. Characters XML 1.0 cannot carry are dropped. */
|
|
45
|
+
function xmlText(s) {
|
|
46
|
+
return s.replace(INVALID_XML_CHAR, "").replace(MARKUP_TEXT, entity);
|
|
47
|
+
}
|
|
48
|
+
/** Plain XML attribute value. Characters XML 1.0 cannot carry are dropped. */
|
|
49
|
+
function xmlAttr(s) {
|
|
50
|
+
return s.replace(INVALID_XML_CHAR, "").replace(MARKUP_ATTR, entity);
|
|
51
|
+
}
|
|
52
|
+
/** True when text needs `xml:space="preserve"` to keep its whitespace. */
|
|
53
|
+
function needsPreserve(s) {
|
|
54
|
+
return s.length > 0 && (/^\s/.test(s) || /\s$/.test(s) || s.includes("\n") || s.includes(" "));
|
|
55
|
+
}
|
|
56
|
+
const XML_DECL = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n";
|
|
57
|
+
/**
|
|
58
|
+
* Formats a number for `<v>` and numeric attributes: shortest round-trip form,
|
|
59
|
+
* which is valid xsd:double lexical form. -0 is written as 0.
|
|
60
|
+
*/
|
|
61
|
+
function num(n) {
|
|
62
|
+
return Object.is(n, -0) ? "0" : String(n);
|
|
63
|
+
}
|
|
64
|
+
// src/address.ts
|
|
65
|
+
/**
|
|
66
|
+
* A1 address helpers (docs/api.md §4.1). Indices are zero-based.
|
|
67
|
+
*/
|
|
68
|
+
/** Rows per sheet in the xlsx format. */
|
|
69
|
+
const MAX_ROWS = 1048576;
|
|
70
|
+
/** Columns per sheet in the xlsx format (A..XFD). */
|
|
71
|
+
const MAX_COLS = 16384;
|
|
72
|
+
function invalidRef(ref, why) {
|
|
73
|
+
return new ValidationError("INVALID_REF", `Invalid reference ${JSON.stringify(ref)}: ${why}.`, { details: { ref } });
|
|
74
|
+
}
|
|
75
|
+
function checkIndex(n, max, what) {
|
|
76
|
+
if (!Number.isInteger(n) || n < 0 || n >= max) throw new ValidationError("OUT_OF_BOUNDS", `${what} index ${n} is outside 0..${max - 1}.`, { details: {
|
|
77
|
+
index: n,
|
|
78
|
+
max: max - 1
|
|
79
|
+
} });
|
|
80
|
+
}
|
|
81
|
+
/** Column index to letters: 0 → 'A', 16383 → 'XFD'. */
|
|
82
|
+
function encodeCol(col) {
|
|
83
|
+
checkIndex(col, MAX_COLS, "Column");
|
|
84
|
+
let s = "";
|
|
85
|
+
for (let n = col + 1; n > 0; n = Math.floor((n - 1) / 26)) s = String.fromCharCode(65 + (n - 1) % 26) + s;
|
|
86
|
+
return s;
|
|
87
|
+
}
|
|
88
|
+
/** Column letters to index: 'A' → 0, 'XFD' → 16383. Case-insensitive. */
|
|
89
|
+
function decodeCol(letters) {
|
|
90
|
+
if (typeof letters !== "string" || !/^[A-Za-z]{1,3}$/.test(letters)) throw invalidRef(letters, "expected column letters");
|
|
91
|
+
let n = 0;
|
|
92
|
+
for (const ch of letters.toUpperCase()) n = n * 26 + (ch.charCodeAt(0) - 64);
|
|
93
|
+
if (n > 16384) throw invalidRef(letters, "beyond column XFD");
|
|
94
|
+
return n - 1;
|
|
95
|
+
}
|
|
96
|
+
/** { row: 0, col: 1 } → 'B1'. */
|
|
97
|
+
function encodeCell(a) {
|
|
98
|
+
checkIndex(a.row, MAX_ROWS, "Row");
|
|
99
|
+
return encodeCol(a.col) + String(a.row + 1);
|
|
100
|
+
}
|
|
101
|
+
const CELL_RE = /^\$?([A-Za-z]{1,3})\$?([1-9][0-9]{0,6})$/;
|
|
102
|
+
/** 'B1' or '$B$1' → { row: 0, col: 1 }. */
|
|
103
|
+
function decodeCell(ref) {
|
|
104
|
+
const m = typeof ref === "string" ? CELL_RE.exec(ref) : null;
|
|
105
|
+
if (!m) throw invalidRef(ref, "expected an A1 cell reference");
|
|
106
|
+
const row = Number(m[2]) - 1;
|
|
107
|
+
if (row >= 1048576) throw invalidRef(ref, "beyond row 1048576");
|
|
108
|
+
return {
|
|
109
|
+
row,
|
|
110
|
+
col: decodeCol(m[1])
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
/** Range to 'A1:C3' (a single cell gives 'A1'). */
|
|
114
|
+
function encodeRange(r) {
|
|
115
|
+
const a = encodeCell(r.start);
|
|
116
|
+
const b = encodeCell(r.end);
|
|
117
|
+
return a === b ? a : `${a}:${b}`;
|
|
118
|
+
}
|
|
119
|
+
/** 'A1:C3' or 'A1' → range, normalised so start is top-left. */
|
|
120
|
+
function decodeRange(ref) {
|
|
121
|
+
if (typeof ref !== "string") throw invalidRef(ref, "expected an A1 range");
|
|
122
|
+
const parts = ref.split(":");
|
|
123
|
+
if (parts.length > 2) throw invalidRef(ref, "expected an A1 range");
|
|
124
|
+
const a = decodeCell(parts[0]);
|
|
125
|
+
const b = parts.length === 2 ? decodeCell(parts[1]) : a;
|
|
126
|
+
return {
|
|
127
|
+
start: {
|
|
128
|
+
row: Math.min(a.row, b.row),
|
|
129
|
+
col: Math.min(a.col, b.col)
|
|
130
|
+
},
|
|
131
|
+
end: {
|
|
132
|
+
row: Math.max(a.row, b.row),
|
|
133
|
+
col: Math.max(a.col, b.col)
|
|
134
|
+
}
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
// src/styles.ts
|
|
138
|
+
/** Copies `b`'s defined fields over a copy of `a`. */
|
|
139
|
+
function mergeFields(a, b) {
|
|
140
|
+
const out = { ...a };
|
|
141
|
+
for (const key of Object.keys(b)) {
|
|
142
|
+
const v = b[key];
|
|
143
|
+
if (v !== void 0) out[key] = v;
|
|
144
|
+
}
|
|
145
|
+
return out;
|
|
146
|
+
}
|
|
147
|
+
const SIDES = [
|
|
148
|
+
"left",
|
|
149
|
+
"right",
|
|
150
|
+
"top",
|
|
151
|
+
"bottom",
|
|
152
|
+
"diagonal"
|
|
153
|
+
];
|
|
154
|
+
function mergeBorder(a, b) {
|
|
155
|
+
const out = { ...a };
|
|
156
|
+
for (const side of SIDES) {
|
|
157
|
+
const next = b[side];
|
|
158
|
+
if (next) out[side] = mergeFields(a?.[side], next);
|
|
159
|
+
}
|
|
160
|
+
if (b.diagonalUp !== void 0) out.diagonalUp = b.diagonalUp;
|
|
161
|
+
if (b.diagonalDown !== void 0) out.diagonalDown = b.diagonalDown;
|
|
162
|
+
return out;
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* Deep-merges styles, later ones winning field by field. `font`, `alignment`,
|
|
166
|
+
* `protection` and each `border` side merge by field; `fill` and `numFmt`
|
|
167
|
+
* replace as a whole. `undefined` layers and `undefined` fields are skipped.
|
|
168
|
+
* The inputs are not modified.
|
|
169
|
+
*/
|
|
170
|
+
function mergeStyles(...styles) {
|
|
171
|
+
const out = {};
|
|
172
|
+
for (const s of styles) {
|
|
173
|
+
if (!s) continue;
|
|
174
|
+
if (s.font) out.font = mergeFields(out.font, s.font);
|
|
175
|
+
if (s.alignment) out.alignment = mergeFields(out.alignment, s.alignment);
|
|
176
|
+
if (s.protection) out.protection = mergeFields(out.protection, s.protection);
|
|
177
|
+
if (s.border) out.border = mergeBorder(out.border, s.border);
|
|
178
|
+
if (s.fill !== void 0) out.fill = s.fill;
|
|
179
|
+
if (s.numFmt !== void 0) out.numFmt = s.numFmt;
|
|
180
|
+
}
|
|
181
|
+
return out;
|
|
182
|
+
}
|
|
183
|
+
// src/cells.ts
|
|
184
|
+
/**
|
|
185
|
+
* Cell helpers (docs/api.md §4.2).
|
|
186
|
+
*/
|
|
187
|
+
function valueText(v, zone) {
|
|
188
|
+
if (v === null || v === void 0) return "";
|
|
189
|
+
if (typeof v === "string") return v;
|
|
190
|
+
if (typeof v === "number") return String(v);
|
|
191
|
+
if (typeof v === "boolean") return v ? "TRUE" : "FALSE";
|
|
192
|
+
if (v instanceof Date) return Number.isFinite(v.getTime()) ? isoDate(v, zone) : "";
|
|
193
|
+
if (typeof v === "object" && "error" in v) return String(v.error);
|
|
194
|
+
if (typeof v === "object" && "richText" in v && Array.isArray(v.richText)) return v.richText.map((r) => r.text).join("");
|
|
195
|
+
return "";
|
|
196
|
+
}
|
|
197
|
+
/**
|
|
198
|
+
* Plain text of a cell: strings as they are, numbers as `String(n)`, booleans
|
|
199
|
+
* as TRUE/FALSE, dates as ISO 8601, errors as their code, rich text joined.
|
|
200
|
+
* A formula cell gives its cached value's text ('' when there is none).
|
|
201
|
+
* Number formats are not applied.
|
|
202
|
+
*/
|
|
203
|
+
function cellText(cell, options) {
|
|
204
|
+
const zone = options?.dateZone ?? "local";
|
|
205
|
+
if (cell === null || cell === void 0) return "";
|
|
206
|
+
if (typeof cell !== "object" || cell instanceof Date || "error" in cell || "richText" in cell) return valueText(cell, zone);
|
|
207
|
+
return valueText(cell.value, zone);
|
|
208
|
+
}
|
|
209
|
+
// src/internal/write/package.ts
|
|
210
|
+
/**
|
|
211
|
+
* The OPC package: which parts exist, their content types and the
|
|
212
|
+
* relationships between them.
|
|
213
|
+
*
|
|
214
|
+
* Parts register themselves here instead of being hard-coded into
|
|
215
|
+
* [Content_Types].xml and the .rels files, so later features (comments,
|
|
216
|
+
* drawings and images, tables, preserved unknown parts) can add parts and
|
|
217
|
+
* relationships without touching the existing ones.
|
|
218
|
+
*/
|
|
219
|
+
const NS_CONTENT_TYPES = "http://schemas.openxmlformats.org/package/2006/content-types";
|
|
220
|
+
const NS_PKG_REL = "http://schemas.openxmlformats.org/package/2006/relationships";
|
|
221
|
+
const REL = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
|
|
222
|
+
const CT = "application/vnd.openxmlformats-officedocument";
|
|
223
|
+
const REL_TYPE = {
|
|
224
|
+
officeDocument: `${REL}/officeDocument`,
|
|
225
|
+
coreProperties: "http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties",
|
|
226
|
+
extendedProperties: `${REL}/extended-properties`,
|
|
227
|
+
customProperties: `${REL}/custom-properties`,
|
|
228
|
+
worksheet: `${REL}/worksheet`,
|
|
229
|
+
theme: `${REL}/theme`,
|
|
230
|
+
styles: `${REL}/styles`,
|
|
231
|
+
sharedStrings: `${REL}/sharedStrings`,
|
|
232
|
+
hyperlink: `${REL}/hyperlink`
|
|
233
|
+
};
|
|
234
|
+
/** Content types used by the writer. */
|
|
235
|
+
const CONTENT_TYPE = {
|
|
236
|
+
relationships: "application/vnd.openxmlformats-package.relationships+xml",
|
|
237
|
+
xml: "application/xml",
|
|
238
|
+
workbook: `${CT}.spreadsheetml.sheet.main+xml`,
|
|
239
|
+
worksheet: `${CT}.spreadsheetml.worksheet+xml`,
|
|
240
|
+
theme: `${CT}.theme+xml`,
|
|
241
|
+
styles: `${CT}.spreadsheetml.styles+xml`,
|
|
242
|
+
sharedStrings: `${CT}.spreadsheetml.sharedStrings+xml`,
|
|
243
|
+
coreProperties: "application/vnd.openxmlformats-package.core-properties+xml",
|
|
244
|
+
extendedProperties: `${CT}.extended-properties+xml`,
|
|
245
|
+
customProperties: `${CT}.custom-properties+xml`
|
|
246
|
+
};
|
|
247
|
+
/** One .rels part. Ids are allocated in order (rId1, rId2, ...); an identical relationship is reused. */
|
|
248
|
+
var Rels = class {
|
|
249
|
+
rels = [];
|
|
250
|
+
add(type, target, external = false) {
|
|
251
|
+
const found = this.rels.find((r) => r.type === type && r.target === target && r.external === external);
|
|
252
|
+
if (found) return found.id;
|
|
253
|
+
const id = `rId${this.rels.length + 1}`;
|
|
254
|
+
this.rels.push({
|
|
255
|
+
id,
|
|
256
|
+
type,
|
|
257
|
+
target,
|
|
258
|
+
external
|
|
259
|
+
});
|
|
260
|
+
return id;
|
|
261
|
+
}
|
|
262
|
+
get size() {
|
|
263
|
+
return this.rels.length;
|
|
264
|
+
}
|
|
265
|
+
/** The .rels XML, or undefined when there are no relationships. */
|
|
266
|
+
xml() {
|
|
267
|
+
if (this.rels.length === 0) return void 0;
|
|
268
|
+
let x = `${XML_DECL}<Relationships xmlns="${NS_PKG_REL}">`;
|
|
269
|
+
for (const r of this.rels) x += `<Relationship Id="${r.id}" Type="${r.type}" Target="${xmlAttr(r.target)}"${r.external ? " TargetMode=\"External\"" : ""}/>`;
|
|
270
|
+
return `${x}</Relationships>`;
|
|
271
|
+
}
|
|
272
|
+
};
|
|
273
|
+
/** Content types plus the package-level and workbook-level relationships. */
|
|
274
|
+
var PackageParts = class {
|
|
275
|
+
defaults = /* @__PURE__ */ new Map([["rels", CONTENT_TYPE.relationships], ["xml", CONTENT_TYPE.xml]]);
|
|
276
|
+
overrides = /* @__PURE__ */ new Map();
|
|
277
|
+
/** _rels/.rels */
|
|
278
|
+
root = new Rels();
|
|
279
|
+
/** xl/_rels/workbook.xml.rels */
|
|
280
|
+
workbook = new Rels();
|
|
281
|
+
/** A content type for every part with this extension (e.g. 'png' for images). */
|
|
282
|
+
addDefault(extension, contentType) {
|
|
283
|
+
this.defaults.set(extension.toLowerCase(), contentType);
|
|
284
|
+
}
|
|
285
|
+
/** A content type for one part, by its package path without a leading '/' ('xl/styles.xml'). */
|
|
286
|
+
addOverride(partName, contentType) {
|
|
287
|
+
this.overrides.set(`/${partName}`, contentType);
|
|
288
|
+
}
|
|
289
|
+
contentTypesXml() {
|
|
290
|
+
let x = `${XML_DECL}<Types xmlns="${NS_CONTENT_TYPES}">`;
|
|
291
|
+
for (const [ext, ct] of this.defaults) x += `<Default Extension="${xmlAttr(ext)}" ContentType="${xmlAttr(ct)}"/>`;
|
|
292
|
+
for (const [part, ct] of this.overrides) x += `<Override PartName="${xmlAttr(part)}" ContentType="${xmlAttr(ct)}"/>`;
|
|
293
|
+
return `${x}</Types>`;
|
|
294
|
+
}
|
|
295
|
+
};
|
|
296
|
+
/** Auto width bounds and padding, in characters. The 60 maximum is a readability choice, not a measurement. */
|
|
297
|
+
const AUTO_WIDTH = {
|
|
298
|
+
min: 8.43,
|
|
299
|
+
max: 60,
|
|
300
|
+
padding: 2
|
|
301
|
+
};
|
|
302
|
+
/** Characters (as Excel's UI shows them) to the file's `width` (ECMA-376 §18.3.1.13). */
|
|
303
|
+
function charsToFileWidth(chars) {
|
|
304
|
+
if (chars <= 0) return 0;
|
|
305
|
+
return Math.trunc((chars * 7 + 5) / 7 * 256) / 256;
|
|
306
|
+
}
|
|
307
|
+
/** Pixels at 96 dpi to characters (ECMA-376 §18.3.1.13). */
|
|
308
|
+
function pixelsToChars(px) {
|
|
309
|
+
return Math.max(0, Math.trunc((px - 5) / 7 * 100 + .5) / 100);
|
|
310
|
+
}
|
|
311
|
+
/** East Asian wide and fullwidth characters, and emoji, count as two. */
|
|
312
|
+
function isWide(cp) {
|
|
313
|
+
return cp >= 4352 && cp <= 4447 || cp >= 11904 && cp <= 42191 || cp >= 44032 && cp <= 55203 || cp >= 63744 && cp <= 64255 || cp >= 65072 && cp <= 65103 || cp >= 65280 && cp <= 65376 || cp >= 65504 && cp <= 65510 || cp >= 127744 && cp <= 129791 || cp >= 131072 && cp <= 262141;
|
|
314
|
+
}
|
|
315
|
+
/** Estimated display width of text in characters: the widest line, wide characters counting two. */
|
|
316
|
+
function textWidth(s) {
|
|
317
|
+
let max = 0;
|
|
318
|
+
for (const line of s.split(/\r\n|\r|\n/)) {
|
|
319
|
+
let w = 0;
|
|
320
|
+
for (const ch of line) w += isWide(ch.codePointAt(0)) ? 2 : 1;
|
|
321
|
+
if (w > max) max = w;
|
|
322
|
+
}
|
|
323
|
+
return max;
|
|
324
|
+
}
|
|
325
|
+
function sheetError(sheet, path, value, why, code = "INVALID_SHEET_PROPERTY") {
|
|
326
|
+
return new ValidationError(code, `Sheet ${sheet}: ${path} ${why}.`, { details: {
|
|
327
|
+
sheet,
|
|
328
|
+
path,
|
|
329
|
+
value
|
|
330
|
+
} });
|
|
331
|
+
}
|
|
332
|
+
function checkNumber(sheet, path, v, min, max, integer = false) {
|
|
333
|
+
if (v === void 0) return void 0;
|
|
334
|
+
if (typeof v !== "number" || !Number.isFinite(v) || v < min || v > max || integer && !Number.isInteger(v)) throw sheetError(sheet, path, v, `must be ${integer ? "an integer" : "a number"} from ${min} to ${max}`);
|
|
335
|
+
return v;
|
|
336
|
+
}
|
|
337
|
+
function checkBool(sheet, path, v) {
|
|
338
|
+
if (v === void 0) return void 0;
|
|
339
|
+
if (typeof v !== "boolean") throw sheetError(sheet, path, v, "must be a boolean");
|
|
340
|
+
return v;
|
|
341
|
+
}
|
|
342
|
+
function checkRange(sheet, path, v) {
|
|
343
|
+
try {
|
|
344
|
+
return decodeRange(v);
|
|
345
|
+
} catch {
|
|
346
|
+
throw sheetError(sheet, path, v, "must be an A1 range such as 'A1:C3'", "INVALID_REF");
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
function checkCellRef(sheet, path, v) {
|
|
350
|
+
try {
|
|
351
|
+
return encodeCell(decodeCell(v));
|
|
352
|
+
} catch {
|
|
353
|
+
throw sheetError(sheet, path, v, "must be an A1 cell reference", "INVALID_REF");
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
const absRange = (r) => {
|
|
357
|
+
const a = `$${encodeCol(r.start.col)}$${r.start.row + 1}`;
|
|
358
|
+
const b = `$${encodeCol(r.end.col)}$${r.end.row + 1}`;
|
|
359
|
+
return a === b ? a : `${a}:${b}`;
|
|
360
|
+
};
|
|
361
|
+
const plainRange = (r) => {
|
|
362
|
+
const a = encodeCell(r.start);
|
|
363
|
+
const b = encodeCell(r.end);
|
|
364
|
+
return a === b ? a : `${a}:${b}`;
|
|
365
|
+
};
|
|
366
|
+
/** A sheet name as it appears in a formula reference: always quoted, quotes doubled. */
|
|
367
|
+
function quoteSheet(name) {
|
|
368
|
+
return `'${name.replace(/'/g, "''")}'`;
|
|
369
|
+
}
|
|
370
|
+
/** Validated sheet features. Column widths marked 'auto' are measured during the cell scan. */
|
|
371
|
+
var SheetFeatures = class {
|
|
372
|
+
name;
|
|
373
|
+
autoCols = /* @__PURE__ */ new Map();
|
|
374
|
+
cols = [];
|
|
375
|
+
/** Row attributes (without r) for rows with properties. */
|
|
376
|
+
rowAttrs = /* @__PURE__ */ new Map();
|
|
377
|
+
maxPropRow = -1;
|
|
378
|
+
defaultColStyle;
|
|
379
|
+
defaultColFileWidth;
|
|
380
|
+
maxOutlineCol = 0;
|
|
381
|
+
maxOutlineRow = 0;
|
|
382
|
+
defaultRowHeight;
|
|
383
|
+
defaultColWidthChars;
|
|
384
|
+
merges = [];
|
|
385
|
+
autoFilter;
|
|
386
|
+
sheetPr;
|
|
387
|
+
views;
|
|
388
|
+
print;
|
|
389
|
+
builtinNames = [];
|
|
390
|
+
constructor(sheet, index, tabSelected, styles) {
|
|
391
|
+
const name = sheet.name;
|
|
392
|
+
this.name = name;
|
|
393
|
+
this.defaultColWidthChars = checkNumber(name, "defaultColWidth", sheet.defaultColWidth, 0, 255);
|
|
394
|
+
this.defaultRowHeight = checkNumber(name, "defaultRowHeight", sheet.defaultRowHeight, 0, 409);
|
|
395
|
+
this.defaultColFileWidth = charsToFileWidth(this.defaultColWidthChars ?? 8.43);
|
|
396
|
+
this.defaultColStyle = sheet.defaultStyle ? styles.xfFor([sheet.defaultStyle], false, { sheet: name }) : 0;
|
|
397
|
+
const colProps = sheet.colProps;
|
|
398
|
+
if (colProps !== void 0) {
|
|
399
|
+
if (!Array.isArray(colProps)) throw sheetError(name, "colProps", colProps, "must be an array");
|
|
400
|
+
if (colProps.length > 16384) throw sheetError(name, "colProps", colProps.length, `has more than ${MAX_COLS} entries`, "OUT_OF_BOUNDS");
|
|
401
|
+
for (let c = 0; c < colProps.length; c++) {
|
|
402
|
+
const p = colProps[c];
|
|
403
|
+
if (p === void 0 || p === null) continue;
|
|
404
|
+
const path = `colProps[${c}]`;
|
|
405
|
+
if (typeof p !== "object") throw sheetError(name, path, p, "must be an object");
|
|
406
|
+
const width = p.width;
|
|
407
|
+
if (width !== void 0) this.checkWidth(`${path}.width`, width);
|
|
408
|
+
if (width === "auto") this.autoCols.set(c, 0);
|
|
409
|
+
const outlineLevel = checkNumber(name, `${path}.outlineLevel`, p.outlineLevel, 0, 7, true) ?? 0;
|
|
410
|
+
this.maxOutlineCol = Math.max(this.maxOutlineCol, outlineLevel);
|
|
411
|
+
const style = p.style ? styles.xfFor([sheet.defaultStyle, p.style], false, {
|
|
412
|
+
sheet: name,
|
|
413
|
+
ref: `${encodeCol(c)}:${encodeCol(c)}`
|
|
414
|
+
}) : this.defaultColStyle;
|
|
415
|
+
this.cols.push({
|
|
416
|
+
col: c,
|
|
417
|
+
width,
|
|
418
|
+
spec: {
|
|
419
|
+
style,
|
|
420
|
+
hidden: checkBool(name, `${path}.hidden`, p.hidden) === true,
|
|
421
|
+
outlineLevel,
|
|
422
|
+
collapsed: checkBool(name, `${path}.collapsed`, p.collapsed) === true
|
|
423
|
+
}
|
|
424
|
+
});
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
const rowProps = sheet.rowProps;
|
|
428
|
+
if (rowProps !== void 0) {
|
|
429
|
+
if (!Array.isArray(rowProps)) throw sheetError(name, "rowProps", rowProps, "must be an array");
|
|
430
|
+
for (let r = 0; r < rowProps.length; r++) {
|
|
431
|
+
const p = rowProps[r];
|
|
432
|
+
if (p === void 0 || p === null) continue;
|
|
433
|
+
const path = `rowProps[${r}]`;
|
|
434
|
+
if (r >= 1048576) throw sheetError(name, path, r, `is beyond row ${MAX_ROWS}`, "OUT_OF_BOUNDS");
|
|
435
|
+
if (typeof p !== "object") throw sheetError(name, path, p, "must be an object");
|
|
436
|
+
let attrs = "";
|
|
437
|
+
if (p.style) attrs += ` s="${styles.xfFor([sheet.defaultStyle, p.style], false, {
|
|
438
|
+
sheet: name,
|
|
439
|
+
ref: `${r + 1}:${r + 1}`
|
|
440
|
+
})}" customFormat="1"`;
|
|
441
|
+
const height = checkNumber(name, `${path}.height`, p.height, 0, 409);
|
|
442
|
+
if (height !== void 0) attrs += ` ht="${num(height)}" customHeight="1"`;
|
|
443
|
+
if (checkBool(name, `${path}.hidden`, p.hidden) || height === 0) attrs += " hidden=\"1\"";
|
|
444
|
+
const level = checkNumber(name, `${path}.outlineLevel`, p.outlineLevel, 0, 7, true);
|
|
445
|
+
if (level) {
|
|
446
|
+
attrs += ` outlineLevel="${level}"`;
|
|
447
|
+
this.maxOutlineRow = Math.max(this.maxOutlineRow, level);
|
|
448
|
+
}
|
|
449
|
+
if (checkBool(name, `${path}.collapsed`, p.collapsed)) attrs += " collapsed=\"1\"";
|
|
450
|
+
if (attrs) {
|
|
451
|
+
this.rowAttrs.set(r, attrs);
|
|
452
|
+
this.maxPropRow = r;
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
if (sheet.merges !== void 0) {
|
|
457
|
+
if (!Array.isArray(sheet.merges)) throw sheetError(name, "merges", sheet.merges, "must be an array of A1 ranges");
|
|
458
|
+
const ranges = sheet.merges.map((m, i) => ({
|
|
459
|
+
r: checkRange(name, `merges[${i}]`, m),
|
|
460
|
+
i
|
|
461
|
+
}));
|
|
462
|
+
const sorted = [...ranges].sort((a, b) => a.r.start.row - b.r.start.row);
|
|
463
|
+
for (let i = 0; i < sorted.length; i++) {
|
|
464
|
+
const a = sorted[i].r;
|
|
465
|
+
for (let j = i + 1; j < sorted.length; j++) {
|
|
466
|
+
const b = sorted[j].r;
|
|
467
|
+
if (b.start.row > a.end.row) break;
|
|
468
|
+
if (b.start.col <= a.end.col && b.end.col >= a.start.col) throw new ValidationError("OVERLAPPING_MERGE", `Sheet ${name}: merges ${plainRange(a)} and ${plainRange(b)} overlap.`, { details: {
|
|
469
|
+
sheet: name,
|
|
470
|
+
merges: [plainRange(a), plainRange(b)]
|
|
471
|
+
} });
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
for (const { r } of ranges) {
|
|
475
|
+
if (r.start.row === r.end.row && r.start.col === r.end.col) continue;
|
|
476
|
+
this.merges.push(plainRange(r));
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
if (sheet.autoFilter !== void 0) {
|
|
480
|
+
const r = checkRange(name, "autoFilter", sheet.autoFilter);
|
|
481
|
+
this.autoFilter = plainRange(r);
|
|
482
|
+
this.builtinNames.push({
|
|
483
|
+
name: "_xlnm._FilterDatabase",
|
|
484
|
+
ref: `${quoteSheet(name)}!${absRange(r)}`,
|
|
485
|
+
sheet: index,
|
|
486
|
+
hidden: true
|
|
487
|
+
});
|
|
488
|
+
}
|
|
489
|
+
let sheetPr = "";
|
|
490
|
+
if (sheet.tabColor !== void 0) sheetPr += `<tabColor${styles.colorAttrs("tabColor", sheet.tabColor, { sheet: name })}/>`;
|
|
491
|
+
if (sheet.print?.fitTo !== void 0) sheetPr += "<pageSetUpPr fitToPage=\"1\"/>";
|
|
492
|
+
this.sheetPr = sheetPr ? `<sheetPr>${sheetPr}</sheetPr>` : "";
|
|
493
|
+
this.views = this.viewXml(sheet.view, tabSelected);
|
|
494
|
+
this.print = this.printXml(sheet.print, index);
|
|
495
|
+
}
|
|
496
|
+
checkWidth(path, w) {
|
|
497
|
+
if (w === "auto") return;
|
|
498
|
+
if (typeof w === "number") {
|
|
499
|
+
checkNumber(this.name, path, w, 0, 255);
|
|
500
|
+
return;
|
|
501
|
+
}
|
|
502
|
+
if (typeof w === "object" && w !== null && "wch" in w) {
|
|
503
|
+
checkNumber(this.name, `${path}.wch`, w.wch, 0, 255);
|
|
504
|
+
return;
|
|
505
|
+
}
|
|
506
|
+
if (typeof w === "object" && w !== null && "wpx" in w) {
|
|
507
|
+
checkNumber(this.name, `${path}.wpx`, w.wpx, 0, 1790);
|
|
508
|
+
return;
|
|
509
|
+
}
|
|
510
|
+
throw sheetError(this.name, path, w, "must be a number of characters, { wch }, { wpx } or 'auto'");
|
|
511
|
+
}
|
|
512
|
+
/** Records a cell's text width for 'auto' columns. */
|
|
513
|
+
measure(col, text) {
|
|
514
|
+
const cur = this.autoCols.get(col);
|
|
515
|
+
if (cur === void 0) return;
|
|
516
|
+
const w = textWidth(text);
|
|
517
|
+
if (w > cur) this.autoCols.set(col, w);
|
|
518
|
+
}
|
|
519
|
+
viewXml(view, tabSelected) {
|
|
520
|
+
const name = this.name;
|
|
521
|
+
let attrs = tabSelected ? " tabSelected=\"1\"" : "";
|
|
522
|
+
let inner = "";
|
|
523
|
+
if (view !== void 0) {
|
|
524
|
+
if (typeof view !== "object" || view === null) throw sheetError(name, "view", view, "must be an object");
|
|
525
|
+
if (checkBool(name, "view.showGridLines", view.showGridLines) === false) attrs += " showGridLines=\"0\"";
|
|
526
|
+
if (checkBool(name, "view.showRowColHeaders", view.showRowColHeaders) === false) attrs += " showRowColHeaders=\"0\"";
|
|
527
|
+
if (checkBool(name, "view.rightToLeft", view.rightToLeft)) attrs += " rightToLeft=\"1\"";
|
|
528
|
+
const zoom = checkNumber(name, "view.zoom", view.zoom, 10, 400, true);
|
|
529
|
+
if (zoom !== void 0 && zoom !== 100) attrs += ` zoomScale="${zoom}" zoomScaleNormal="${zoom}"`;
|
|
530
|
+
const activeCell = view.activeCell === void 0 ? void 0 : checkCellRef(name, "view.activeCell", view.activeCell);
|
|
531
|
+
const selection = view.selection === void 0 ? void 0 : plainRange(checkRange(name, "view.selection", view.selection));
|
|
532
|
+
const rows = checkNumber(name, "view.freeze.rows", view.freeze?.rows, 0, 1048575, true) ?? 0;
|
|
533
|
+
const cols = checkNumber(name, "view.freeze.cols", view.freeze?.cols, 0, 16383, true) ?? 0;
|
|
534
|
+
if (view.freeze !== void 0 && (typeof view.freeze !== "object" || view.freeze === null)) throw sheetError(name, "view.freeze", view.freeze, "must be { rows?, cols? }");
|
|
535
|
+
if (rows > 0 || cols > 0) {
|
|
536
|
+
const topLeft = encodeCell({
|
|
537
|
+
row: rows,
|
|
538
|
+
col: cols
|
|
539
|
+
});
|
|
540
|
+
const pane = rows > 0 && cols > 0 ? "bottomRight" : rows > 0 ? "bottomLeft" : "topRight";
|
|
541
|
+
inner += `<pane${cols > 0 ? ` xSplit="${cols}"` : ""}${rows > 0 ? ` ySplit="${rows}"` : ""} topLeftCell="${topLeft}" activePane="${pane}" state="frozen"/>`;
|
|
542
|
+
const ac = activeCell ?? topLeft;
|
|
543
|
+
inner += `<selection pane="${pane}" activeCell="${ac}" sqref="${selection ?? ac}"/>`;
|
|
544
|
+
} else if (activeCell !== void 0 || selection !== void 0) {
|
|
545
|
+
const ac = activeCell ?? selection.split(":")[0];
|
|
546
|
+
inner += `<selection activeCell="${ac}" sqref="${selection ?? ac}"/>`;
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
attrs += " workbookViewId=\"0\"";
|
|
550
|
+
return `<sheetViews><sheetView${attrs}${inner ? `>${inner}</sheetView>` : "/>"}</sheetViews>`;
|
|
551
|
+
}
|
|
552
|
+
printXml(print, index) {
|
|
553
|
+
const name = this.name;
|
|
554
|
+
const out = {
|
|
555
|
+
options: "",
|
|
556
|
+
margins: "",
|
|
557
|
+
setup: "",
|
|
558
|
+
headerFooter: ""
|
|
559
|
+
};
|
|
560
|
+
const p = print ?? {};
|
|
561
|
+
if (typeof p !== "object" || p === null) throw sheetError(name, "print", print, "must be an object");
|
|
562
|
+
let options = "";
|
|
563
|
+
if (checkBool(name, "print.center.horizontal", p.center?.horizontal)) options += " horizontalCentered=\"1\"";
|
|
564
|
+
if (checkBool(name, "print.center.vertical", p.center?.vertical)) options += " verticalCentered=\"1\"";
|
|
565
|
+
if (checkBool(name, "print.headings", p.headings)) options += " headings=\"1\"";
|
|
566
|
+
if (checkBool(name, "print.gridLines", p.gridLines)) options += " gridLines=\"1\"";
|
|
567
|
+
if (options) out.options = `<printOptions${options}/>`;
|
|
568
|
+
const m = {
|
|
569
|
+
left: .7,
|
|
570
|
+
right: .7,
|
|
571
|
+
top: .75,
|
|
572
|
+
bottom: .75,
|
|
573
|
+
header: .3,
|
|
574
|
+
footer: .3
|
|
575
|
+
};
|
|
576
|
+
for (const k of Object.keys(m)) {
|
|
577
|
+
const v = checkNumber(name, `print.margins.${k}`, p.margins?.[k], 0, 49);
|
|
578
|
+
if (v !== void 0) m[k] = v;
|
|
579
|
+
}
|
|
580
|
+
out.margins = `<pageMargins left="${num(m.left)}" right="${num(m.right)}" top="${num(m.top)}" bottom="${num(m.bottom)}" header="${num(m.header)}" footer="${num(m.footer)}"/>`;
|
|
581
|
+
let setup = "";
|
|
582
|
+
const paper = checkNumber(name, "print.paperSize", p.paperSize, 1, 255, true);
|
|
583
|
+
if (paper !== void 0) setup += ` paperSize="${paper}"`;
|
|
584
|
+
const scale = checkNumber(name, "print.scale", p.scale, 10, 400, true);
|
|
585
|
+
if (scale !== void 0) setup += ` scale="${scale}"`;
|
|
586
|
+
if (p.fitTo !== void 0) {
|
|
587
|
+
if (typeof p.fitTo !== "object" || p.fitTo === null) throw sheetError(name, "print.fitTo", p.fitTo, "must be { width?, height? }");
|
|
588
|
+
const w = checkNumber(name, "print.fitTo.width", p.fitTo.width, 0, 32767, true) ?? 0;
|
|
589
|
+
const h = checkNumber(name, "print.fitTo.height", p.fitTo.height, 0, 32767, true) ?? 0;
|
|
590
|
+
setup += ` fitToWidth="${w}" fitToHeight="${h}"`;
|
|
591
|
+
}
|
|
592
|
+
if (p.orientation !== void 0) {
|
|
593
|
+
if (p.orientation !== "portrait" && p.orientation !== "landscape") throw sheetError(name, "print.orientation", p.orientation, "must be 'portrait' or 'landscape'");
|
|
594
|
+
setup += ` orientation="${p.orientation}"`;
|
|
595
|
+
}
|
|
596
|
+
if (setup) out.setup = `<pageSetup${setup}/>`;
|
|
597
|
+
const hf = (key, part) => {
|
|
598
|
+
const v = p[key]?.[part];
|
|
599
|
+
if (v === void 0) return "";
|
|
600
|
+
if (typeof v !== "string") throw sheetError(name, `print.${key}.${part}`, v, "must be a string");
|
|
601
|
+
const tag = `${part}${key === "header" ? "Header" : "Footer"}`;
|
|
602
|
+
return `<${tag}>${xstring(v)}</${tag}>`;
|
|
603
|
+
};
|
|
604
|
+
const parts = [
|
|
605
|
+
hf("header", "odd"),
|
|
606
|
+
hf("footer", "odd"),
|
|
607
|
+
hf("header", "even"),
|
|
608
|
+
hf("footer", "even"),
|
|
609
|
+
hf("header", "first"),
|
|
610
|
+
hf("footer", "first")
|
|
611
|
+
];
|
|
612
|
+
if (parts.some(Boolean)) out.headerFooter = `<headerFooter${parts[2] || parts[3] ? " differentOddEven=\"1\"" : ""}${parts[4] || parts[5] ? " differentFirst=\"1\"" : ""}>${parts.join("")}</headerFooter>`;
|
|
613
|
+
if (p.printArea !== void 0) {
|
|
614
|
+
const r = checkRange(name, "print.printArea", p.printArea);
|
|
615
|
+
this.builtinNames.push({
|
|
616
|
+
name: "_xlnm.Print_Area",
|
|
617
|
+
ref: `${quoteSheet(name)}!${absRange(r)}`,
|
|
618
|
+
sheet: index,
|
|
619
|
+
hidden: false
|
|
620
|
+
});
|
|
621
|
+
}
|
|
622
|
+
if (p.printTitles !== void 0) {
|
|
623
|
+
const refs = [];
|
|
624
|
+
const t = p.printTitles;
|
|
625
|
+
if (typeof t !== "object" || t === null) throw sheetError(name, "print.printTitles", t, "must be { rows?, cols? }");
|
|
626
|
+
if (t.cols !== void 0) {
|
|
627
|
+
const m2 = typeof t.cols === "string" ? /^\$?([A-Za-z]{1,3}):\$?([A-Za-z]{1,3})$/.exec(t.cols) : null;
|
|
628
|
+
if (!m2) throw sheetError(name, "print.printTitles.cols", t.cols, "must be a column range such as 'A:B'", "INVALID_REF");
|
|
629
|
+
const [a, b] = [decodeCol(m2[1]), decodeCol(m2[2])].sort((x, y) => x - y);
|
|
630
|
+
refs.push(`${quoteSheet(name)}!$${encodeCol(a)}:$${encodeCol(b)}`);
|
|
631
|
+
}
|
|
632
|
+
if (t.rows !== void 0) {
|
|
633
|
+
const m2 = typeof t.rows === "string" ? /^\$?([1-9]\d{0,6}):\$?([1-9]\d{0,6})$/.exec(t.rows) : null;
|
|
634
|
+
const [a, b] = m2 ? [Number(m2[1]), Number(m2[2])].sort((x, y) => x - y) : [0, 0];
|
|
635
|
+
if (!m2 || b > 1048576) throw sheetError(name, "print.printTitles.rows", t.rows, "must be a row range such as '1:2'", "INVALID_REF");
|
|
636
|
+
refs.push(`${quoteSheet(name)}!$${a}:$${b}`);
|
|
637
|
+
}
|
|
638
|
+
if (refs.length) this.builtinNames.push({
|
|
639
|
+
name: "_xlnm.Print_Titles",
|
|
640
|
+
ref: refs.join(","),
|
|
641
|
+
sheet: index,
|
|
642
|
+
hidden: false
|
|
643
|
+
});
|
|
644
|
+
}
|
|
645
|
+
return out;
|
|
646
|
+
}
|
|
647
|
+
get sheetPrXml() {
|
|
648
|
+
return this.sheetPr;
|
|
649
|
+
}
|
|
650
|
+
get sheetViewsXml() {
|
|
651
|
+
return this.views;
|
|
652
|
+
}
|
|
653
|
+
get sheetFormatPrXml() {
|
|
654
|
+
let x = "<sheetFormatPr";
|
|
655
|
+
if (this.defaultColWidthChars !== void 0) x += ` defaultColWidth="${num(charsToFileWidth(this.defaultColWidthChars))}"`;
|
|
656
|
+
x += ` defaultRowHeight="${num(this.defaultRowHeight ?? 15)}"`;
|
|
657
|
+
if (this.defaultRowHeight !== void 0) x += " customHeight=\"1\"";
|
|
658
|
+
if (this.maxOutlineRow) x += ` outlineLevelRow="${this.maxOutlineRow}"`;
|
|
659
|
+
if (this.maxOutlineCol) x += ` outlineLevelCol="${this.maxOutlineCol}"`;
|
|
660
|
+
return `${x}/>`;
|
|
661
|
+
}
|
|
662
|
+
/** <cols>, after the cell scan (auto widths are known then). Consecutive identical columns share one <col>. */
|
|
663
|
+
colsXml() {
|
|
664
|
+
const specs = [];
|
|
665
|
+
const defaultSpec = () => ({
|
|
666
|
+
width: this.defaultColFileWidth,
|
|
667
|
+
custom: false,
|
|
668
|
+
bestFit: false,
|
|
669
|
+
style: this.defaultColStyle,
|
|
670
|
+
hidden: false,
|
|
671
|
+
outlineLevel: 0,
|
|
672
|
+
collapsed: false
|
|
673
|
+
});
|
|
674
|
+
let next = 0;
|
|
675
|
+
const fillDefault = (until) => {
|
|
676
|
+
if (this.defaultColStyle !== 0 && until > next) specs.push({
|
|
677
|
+
min: next,
|
|
678
|
+
max: until - 1,
|
|
679
|
+
spec: defaultSpec()
|
|
680
|
+
});
|
|
681
|
+
};
|
|
682
|
+
for (const { col, width, spec } of this.cols) {
|
|
683
|
+
fillDefault(col);
|
|
684
|
+
let fileWidth = this.defaultColFileWidth;
|
|
685
|
+
let custom = false;
|
|
686
|
+
let bestFit = false;
|
|
687
|
+
if (width === "auto") {
|
|
688
|
+
fileWidth = charsToFileWidth(Math.min(AUTO_WIDTH.max, Math.max(AUTO_WIDTH.min, (this.autoCols.get(col) ?? 0) + AUTO_WIDTH.padding)));
|
|
689
|
+
custom = true;
|
|
690
|
+
bestFit = true;
|
|
691
|
+
} else if (width !== void 0) {
|
|
692
|
+
fileWidth = charsToFileWidth(typeof width === "number" ? width : "wch" in width ? width.wch : pixelsToChars(width.wpx));
|
|
693
|
+
custom = true;
|
|
694
|
+
}
|
|
695
|
+
const hidden = spec.hidden || custom && fileWidth === 0;
|
|
696
|
+
specs.push({
|
|
697
|
+
min: col,
|
|
698
|
+
max: col,
|
|
699
|
+
spec: {
|
|
700
|
+
...spec,
|
|
701
|
+
hidden,
|
|
702
|
+
width: fileWidth,
|
|
703
|
+
custom,
|
|
704
|
+
bestFit
|
|
705
|
+
}
|
|
706
|
+
});
|
|
707
|
+
next = col + 1;
|
|
708
|
+
}
|
|
709
|
+
fillDefault(MAX_COLS);
|
|
710
|
+
if (specs.length === 0) return "";
|
|
711
|
+
const merged = [];
|
|
712
|
+
for (const s of specs) {
|
|
713
|
+
const last = merged[merged.length - 1];
|
|
714
|
+
if (last && last.max + 1 === s.min && JSON.stringify(last.spec) === JSON.stringify(s.spec)) last.max = s.max;
|
|
715
|
+
else merged.push({ ...s });
|
|
716
|
+
}
|
|
717
|
+
let x = "<cols>";
|
|
718
|
+
for (const { min, max, spec } of merged) {
|
|
719
|
+
x += `<col min="${min + 1}" max="${max + 1}" width="${num(spec.width)}"`;
|
|
720
|
+
if (spec.style) x += ` style="${spec.style}"`;
|
|
721
|
+
if (spec.hidden) x += " hidden=\"1\"";
|
|
722
|
+
if (spec.bestFit) x += " bestFit=\"1\"";
|
|
723
|
+
if (spec.custom) x += " customWidth=\"1\"";
|
|
724
|
+
if (spec.outlineLevel) x += ` outlineLevel="${spec.outlineLevel}"`;
|
|
725
|
+
if (spec.collapsed) x += " collapsed=\"1\"";
|
|
726
|
+
x += "/>";
|
|
727
|
+
}
|
|
728
|
+
return `${x}</cols>`;
|
|
729
|
+
}
|
|
730
|
+
/** Everything after <sheetData>, in schema order. */
|
|
731
|
+
afterDataXml(links) {
|
|
732
|
+
let x = "";
|
|
733
|
+
if (this.autoFilter) x += `<autoFilter ref="${this.autoFilter}"/>`;
|
|
734
|
+
if (this.merges.length) x += `<mergeCells count="${this.merges.length}">${this.merges.map((m) => `<mergeCell ref="${m}"/>`).join("")}</mergeCells>`;
|
|
735
|
+
x += links.xml();
|
|
736
|
+
x += this.print.options + this.print.margins + this.print.setup + this.print.headerFooter;
|
|
737
|
+
return x;
|
|
738
|
+
}
|
|
739
|
+
};
|
|
740
|
+
/** Default hyperlink scheme allowlist (§8, §12 Q16). */
|
|
741
|
+
const DEFAULT_HYPERLINK_SCHEMES = [
|
|
742
|
+
"http",
|
|
743
|
+
"https",
|
|
744
|
+
"mailto"
|
|
745
|
+
];
|
|
746
|
+
/** Normalises the `hyperlinkSchemes` option. */
|
|
747
|
+
function hyperlinkSchemes(option) {
|
|
748
|
+
if (option === void 0) return new Set(DEFAULT_HYPERLINK_SCHEMES);
|
|
749
|
+
if (!Array.isArray(option) || option.some((s) => typeof s !== "string" || !/^[A-Za-z][A-Za-z0-9+.-]*:?$/.test(s))) throw new ValidationError("INVALID_HYPERLINK", "hyperlinkSchemes must be an array of URL scheme names such as 'https'.", { details: { value: option } });
|
|
750
|
+
return new Set(option.map((s) => s.toLowerCase().replace(/:$/, "")));
|
|
751
|
+
}
|
|
752
|
+
/**
|
|
753
|
+
* The hyperlinks of one sheet. External targets are added to the sheet's
|
|
754
|
+
* relationships (`rels`), which later sheet-level parts (comments, drawings)
|
|
755
|
+
* share.
|
|
756
|
+
*/
|
|
757
|
+
var SheetLinks = class {
|
|
758
|
+
sheet;
|
|
759
|
+
schemes;
|
|
760
|
+
rels;
|
|
761
|
+
items = [];
|
|
762
|
+
constructor(sheet, schemes, rels) {
|
|
763
|
+
this.sheet = sheet;
|
|
764
|
+
this.schemes = schemes;
|
|
765
|
+
this.rels = rels;
|
|
766
|
+
}
|
|
767
|
+
add(ref, link) {
|
|
768
|
+
if (link === void 0) return;
|
|
769
|
+
const fail = (why) => {
|
|
770
|
+
throw new ValidationError("INVALID_HYPERLINK", `Hyperlink in ${this.sheet}!${ref}: ${why}.`, { details: {
|
|
771
|
+
sheet: this.sheet,
|
|
772
|
+
ref,
|
|
773
|
+
hyperlink: link
|
|
774
|
+
} });
|
|
775
|
+
};
|
|
776
|
+
const obj = typeof link === "string" ? { target: link } : link;
|
|
777
|
+
if (typeof obj !== "object" || obj === null) return fail("expected a URL string, { target } or { location }");
|
|
778
|
+
const tooltip = obj.tooltip;
|
|
779
|
+
if (tooltip !== void 0 && typeof tooltip !== "string") fail("tooltip must be a string");
|
|
780
|
+
const tip = tooltip ? ` tooltip="${xmlAttr(tooltip)}"` : "";
|
|
781
|
+
if ("location" in obj && obj.location !== void 0) {
|
|
782
|
+
if (typeof obj.location !== "string" || obj.location.length === 0) fail("location must be a non-empty string");
|
|
783
|
+
this.items.push(`<hyperlink ref="${ref}" location="${xmlAttr(obj.location)}"${tip}/>`);
|
|
784
|
+
return;
|
|
785
|
+
}
|
|
786
|
+
const target = obj.target;
|
|
787
|
+
if (typeof target !== "string" || target.length === 0) return fail("target must be a non-empty URL");
|
|
788
|
+
if (/[\u0000-\u001F\u007F]/.test(target)) fail("the URL contains control characters");
|
|
789
|
+
const scheme = /^([A-Za-z][A-Za-z0-9+.-]*):/.exec(target)?.[1]?.toLowerCase();
|
|
790
|
+
if (!scheme) fail(`the URL has no scheme; allowed schemes: ${[...this.schemes].join(", ")}`);
|
|
791
|
+
if (!this.schemes.has(scheme)) fail(`scheme '${scheme}:' is not allowed (allowed: ${[...this.schemes].join(", ")}; see WriteOptions.hyperlinkSchemes)`);
|
|
792
|
+
const id = this.rels.add(REL_TYPE.hyperlink, target, true);
|
|
793
|
+
this.items.push(`<hyperlink ref="${ref}" r:id="${id}"${tip}/>`);
|
|
794
|
+
}
|
|
795
|
+
xml() {
|
|
796
|
+
return this.items.length ? `<hyperlinks>${this.items.join("")}</hyperlinks>` : "";
|
|
797
|
+
}
|
|
798
|
+
};
|
|
799
|
+
/** The hyperlink of a cell input, if any. */
|
|
800
|
+
function hyperlinkOf(input) {
|
|
801
|
+
if (typeof input !== "object" || input === null || input instanceof Date) return void 0;
|
|
802
|
+
return input.hyperlink;
|
|
803
|
+
}
|
|
804
|
+
// src/sheet-names.ts
|
|
805
|
+
const FORBIDDEN = /[\\/?*[\]:]/;
|
|
806
|
+
const FORBIDDEN_ALL = /[\\/?*[\]:]/g;
|
|
807
|
+
/** Returns null when `name` is a valid sheet name, or the reason it is not. */
|
|
808
|
+
function validateSheetName(name) {
|
|
809
|
+
if (typeof name !== "string" || name.length === 0) return "empty";
|
|
810
|
+
if (name.length > 31) return "too-long";
|
|
811
|
+
if (FORBIDDEN.test(name)) return "forbidden-char";
|
|
812
|
+
if (name.startsWith("'") || name.endsWith("'")) return "apostrophe";
|
|
813
|
+
if (name.toLowerCase() === "history") return "reserved";
|
|
814
|
+
return null;
|
|
815
|
+
}
|
|
816
|
+
/**
|
|
817
|
+
* Makes any string a valid sheet name: forbidden characters become '_',
|
|
818
|
+
* leading and trailing apostrophes are removed, the result is cut to 31
|
|
819
|
+
* characters (without splitting a surrogate pair), and an empty or reserved
|
|
820
|
+
* result becomes 'Sheet'. Uniqueness is the caller's job.
|
|
821
|
+
*/
|
|
822
|
+
function sanitizeSheetName(name) {
|
|
823
|
+
let s = String(name ?? "").replace(FORBIDDEN_ALL, "_").replace(/^'+|'+$/g, "");
|
|
824
|
+
if (s.length > 31) {
|
|
825
|
+
s = s.slice(0, 31);
|
|
826
|
+
if (/[\uD800-\uDBFF]$/.test(s)) s = s.slice(0, 30);
|
|
827
|
+
s = s.replace(/'+$/, "");
|
|
828
|
+
}
|
|
829
|
+
return s.length === 0 || s.toLowerCase() === "history" ? "Sheet" : s;
|
|
830
|
+
}
|
|
831
|
+
export { encodeRange as C, xmlAttr as D, num as E, xmlText as O, encodeCol as S, needsPreserve as T, MAX_ROWS as _, SheetFeatures as a, decodeRange as b, hyperlinkSchemes as c, PackageParts as d, REL_TYPE as f, MAX_COLS as g, mergeStyles as h, DEFAULT_HYPERLINK_SCHEMES as i, xstring as k, textWidth as l, cellText as m, validateSheetName as n, SheetLinks as o, Rels as p, AUTO_WIDTH as r, hyperlinkOf as s, sanitizeSheetName as t, CONTENT_TYPE as u, decodeCell as v, XML_DECL as w, encodeCell as x, decodeCol as y };
|