sheetr 0.0.1 → 1.0.0
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/CHANGELOG.md +19 -0
- package/README.md +194 -4
- package/dist/index.cjs +1154 -0
- package/dist/index.d.cts +65 -0
- package/dist/index.d.ts +65 -0
- package/dist/index.js +1131 -0
- package/package.json +36 -9
- package/index.d.ts +0 -1
- package/index.js +0 -2
package/dist/index.js
ADDED
|
@@ -0,0 +1,1131 @@
|
|
|
1
|
+
// src/dates.ts
|
|
2
|
+
var MS_PER_DAY = 864e5;
|
|
3
|
+
var EPOCH_1900 = 25569;
|
|
4
|
+
var EPOCH_1904 = 24107;
|
|
5
|
+
function wallClockMs(d, utc) {
|
|
6
|
+
if (utc) return d.getTime();
|
|
7
|
+
return Date.UTC(
|
|
8
|
+
d.getFullYear(),
|
|
9
|
+
d.getMonth(),
|
|
10
|
+
d.getDate(),
|
|
11
|
+
d.getHours(),
|
|
12
|
+
d.getMinutes(),
|
|
13
|
+
d.getSeconds(),
|
|
14
|
+
d.getMilliseconds()
|
|
15
|
+
);
|
|
16
|
+
}
|
|
17
|
+
function dateToSerial(d, utc) {
|
|
18
|
+
const year = utc ? d.getUTCFullYear() : d.getFullYear();
|
|
19
|
+
if (year < 1900 || year > 9999) return null;
|
|
20
|
+
const serial = wallClockMs(d, utc) / MS_PER_DAY + EPOCH_1900;
|
|
21
|
+
return serial < 61 ? serial - 1 : serial;
|
|
22
|
+
}
|
|
23
|
+
function isDateOnly(d, utc) {
|
|
24
|
+
return wallClockMs(d, utc) % MS_PER_DAY === 0;
|
|
25
|
+
}
|
|
26
|
+
function serialToDate(serial, utc, date1904) {
|
|
27
|
+
let ms;
|
|
28
|
+
if (date1904) {
|
|
29
|
+
ms = Math.round((serial - EPOCH_1904) * MS_PER_DAY);
|
|
30
|
+
} else {
|
|
31
|
+
const s = serial >= 1 && serial < 61 ? serial + 1 : serial;
|
|
32
|
+
ms = Math.round((s - EPOCH_1900) * MS_PER_DAY);
|
|
33
|
+
}
|
|
34
|
+
if (utc) return new Date(ms);
|
|
35
|
+
const u = new Date(ms);
|
|
36
|
+
const local = new Date(
|
|
37
|
+
u.getUTCFullYear(),
|
|
38
|
+
u.getUTCMonth(),
|
|
39
|
+
u.getUTCDate(),
|
|
40
|
+
u.getUTCHours(),
|
|
41
|
+
u.getUTCMinutes(),
|
|
42
|
+
u.getUTCSeconds(),
|
|
43
|
+
u.getUTCMilliseconds()
|
|
44
|
+
);
|
|
45
|
+
return local;
|
|
46
|
+
}
|
|
47
|
+
var BUILTIN_DATE_FORMATS = /* @__PURE__ */ new Set([14, 15, 16, 17, 18, 19, 20, 21, 22, 45, 46, 47]);
|
|
48
|
+
function isDateFormat(id, code) {
|
|
49
|
+
if (BUILTIN_DATE_FORMATS.has(id)) return true;
|
|
50
|
+
if (!code) return false;
|
|
51
|
+
if (/\[[hms]+\]/i.test(code)) return false;
|
|
52
|
+
const stripped = code.replace(/"[^"]*"/g, "").replace(/\\./g, "").replace(/[_*]./g, "").replace(/\[[^\]]*\]/g, "");
|
|
53
|
+
const first = stripped.split(";")[0] ?? "";
|
|
54
|
+
return /[dmyhs]/i.test(first) && !/^\s*general\s*$/i.test(first);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// src/xml.ts
|
|
58
|
+
function cleanXmlText(s) {
|
|
59
|
+
let out = null;
|
|
60
|
+
let last = 0;
|
|
61
|
+
for (let i = 0; i < s.length; i++) {
|
|
62
|
+
const c = s.charCodeAt(i);
|
|
63
|
+
let bad = false;
|
|
64
|
+
if (c < 32) {
|
|
65
|
+
bad = c !== 9 && c !== 10 && c !== 13;
|
|
66
|
+
} else if (c >= 55296 && c <= 57343) {
|
|
67
|
+
if (c <= 56319) {
|
|
68
|
+
const next = s.charCodeAt(i + 1);
|
|
69
|
+
if (next >= 56320 && next <= 57343) {
|
|
70
|
+
i++;
|
|
71
|
+
continue;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
bad = true;
|
|
75
|
+
} else if (c === 65534 || c === 65535) {
|
|
76
|
+
bad = true;
|
|
77
|
+
}
|
|
78
|
+
if (bad) {
|
|
79
|
+
out = (out ?? "") + s.slice(last, i);
|
|
80
|
+
last = i + 1;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
return out === null ? s : out + s.slice(last);
|
|
84
|
+
}
|
|
85
|
+
function stripControls(s) {
|
|
86
|
+
let out = "";
|
|
87
|
+
for (let i = 0; i < s.length; i++) {
|
|
88
|
+
if (s.charCodeAt(i) >= 32) out += s[i];
|
|
89
|
+
}
|
|
90
|
+
return out;
|
|
91
|
+
}
|
|
92
|
+
var ESCAPES = {
|
|
93
|
+
"&": "&",
|
|
94
|
+
"<": "<",
|
|
95
|
+
">": ">",
|
|
96
|
+
'"': """,
|
|
97
|
+
"\r": " "
|
|
98
|
+
};
|
|
99
|
+
var ESCAPE_RE = /[&<>"\r]/g;
|
|
100
|
+
var NEEDS_ESCAPE = /[&<>"\r]/;
|
|
101
|
+
function escapeXml(s) {
|
|
102
|
+
const clean = cleanXmlText(s);
|
|
103
|
+
return NEEDS_ESCAPE.test(clean) ? clean.replace(ESCAPE_RE, (ch) => ESCAPES[ch] ?? ch) : clean;
|
|
104
|
+
}
|
|
105
|
+
var EXCEL_ESCAPE_RE = /_x[0-9A-Fa-f]{4}_/g;
|
|
106
|
+
var EXCEL_UNESCAPE_RE = /_x([0-9A-Fa-f]{4})_/g;
|
|
107
|
+
function escapeCellText(s) {
|
|
108
|
+
const protectedText = s.indexOf("_x") === -1 ? s : s.replace(EXCEL_ESCAPE_RE, "_x005F$&");
|
|
109
|
+
return escapeXml(protectedText);
|
|
110
|
+
}
|
|
111
|
+
function unescapeCellText(s) {
|
|
112
|
+
if (s.indexOf("_x") === -1) return s;
|
|
113
|
+
return s.replace(EXCEL_UNESCAPE_RE, (_m, hex) => String.fromCharCode(parseInt(hex, 16)));
|
|
114
|
+
}
|
|
115
|
+
var NAMED = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'" };
|
|
116
|
+
var ENTITY_RE = /&(?:#([0-9]{1,7})|#[xX]([0-9a-fA-F]{1,6})|(amp|lt|gt|quot|apos));/g;
|
|
117
|
+
function decodeXml(s) {
|
|
118
|
+
let text = s;
|
|
119
|
+
if (text.indexOf("\r") !== -1) text = text.replace(/\r\n?/g, "\n");
|
|
120
|
+
if (text.indexOf("&") === -1) return text;
|
|
121
|
+
return text.replace(ENTITY_RE, (match, dec, hex, name) => {
|
|
122
|
+
if (name) return NAMED[name] ?? match;
|
|
123
|
+
const cp = dec !== void 0 ? parseInt(dec, 10) : parseInt(hex ?? "", 16);
|
|
124
|
+
return cp >= 0 && cp <= 1114111 ? String.fromCodePoint(cp) : match;
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
var attrCache = /* @__PURE__ */ new Map();
|
|
128
|
+
function getAttr(attrs, name) {
|
|
129
|
+
let re = attrCache.get(name);
|
|
130
|
+
if (!re) {
|
|
131
|
+
re = new RegExp(`(?:^|\\s)${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)')`);
|
|
132
|
+
attrCache.set(name, re);
|
|
133
|
+
}
|
|
134
|
+
const m = re.exec(attrs);
|
|
135
|
+
if (!m) return void 0;
|
|
136
|
+
return decodeXml(m[1] ?? m[2] ?? "");
|
|
137
|
+
}
|
|
138
|
+
var P = "(?:[\\w.-]+:)?";
|
|
139
|
+
function startTagRe(name) {
|
|
140
|
+
return new RegExp(`<${P}${name}\\b([^>]*)>`, "g");
|
|
141
|
+
}
|
|
142
|
+
function elementRe(name) {
|
|
143
|
+
return new RegExp(`<${P}${name}\\b[^>]*?(?:\\/>|>([\\s\\S]*?)<\\/${P}${name}>)`, "g");
|
|
144
|
+
}
|
|
145
|
+
var T_RE = elementRe("t");
|
|
146
|
+
var RPH_RE = elementRe("rPh");
|
|
147
|
+
function richText(xml) {
|
|
148
|
+
const source = xml.indexOf("rPh") === -1 ? xml : xml.replace(RPH_RE, "");
|
|
149
|
+
let text = "";
|
|
150
|
+
T_RE.lastIndex = 0;
|
|
151
|
+
let m;
|
|
152
|
+
while ((m = T_RE.exec(source)) !== null) {
|
|
153
|
+
if (m[1]) text += m[1];
|
|
154
|
+
}
|
|
155
|
+
return unescapeCellText(decodeXml(text));
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
// src/inflate.ts
|
|
159
|
+
var LEN_BASE = [3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258];
|
|
160
|
+
var LEN_EXTRA = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0];
|
|
161
|
+
var DIST_BASE = [
|
|
162
|
+
1,
|
|
163
|
+
2,
|
|
164
|
+
3,
|
|
165
|
+
4,
|
|
166
|
+
5,
|
|
167
|
+
7,
|
|
168
|
+
9,
|
|
169
|
+
13,
|
|
170
|
+
17,
|
|
171
|
+
25,
|
|
172
|
+
33,
|
|
173
|
+
49,
|
|
174
|
+
65,
|
|
175
|
+
97,
|
|
176
|
+
129,
|
|
177
|
+
193,
|
|
178
|
+
257,
|
|
179
|
+
385,
|
|
180
|
+
513,
|
|
181
|
+
769,
|
|
182
|
+
1025,
|
|
183
|
+
1537,
|
|
184
|
+
2049,
|
|
185
|
+
3073,
|
|
186
|
+
4097,
|
|
187
|
+
6145,
|
|
188
|
+
8193,
|
|
189
|
+
12289,
|
|
190
|
+
16385,
|
|
191
|
+
24577
|
|
192
|
+
];
|
|
193
|
+
var DIST_EXTRA = [0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13];
|
|
194
|
+
var CODE_LENGTH_ORDER = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
|
|
195
|
+
function buildHuffman(lengths) {
|
|
196
|
+
const counts = new Uint16Array(16);
|
|
197
|
+
const symbols = new Uint16Array(lengths.length);
|
|
198
|
+
for (let i = 0; i < lengths.length; i++) counts[lengths[i]]++;
|
|
199
|
+
counts[0] = 0;
|
|
200
|
+
const offsets = new Uint16Array(16);
|
|
201
|
+
for (let i = 1; i < 15; i++) offsets[i + 1] = offsets[i] + counts[i];
|
|
202
|
+
for (let i = 0; i < lengths.length; i++) {
|
|
203
|
+
const len = lengths[i];
|
|
204
|
+
if (len) symbols[offsets[len]++] = i;
|
|
205
|
+
}
|
|
206
|
+
return { counts, symbols };
|
|
207
|
+
}
|
|
208
|
+
var fixedLit;
|
|
209
|
+
var fixedDist;
|
|
210
|
+
function fixedTables() {
|
|
211
|
+
if (!fixedLit || !fixedDist) {
|
|
212
|
+
const lit = new Uint8Array(288);
|
|
213
|
+
lit.fill(8, 0, 144).fill(9, 144, 256).fill(7, 256, 280).fill(8, 280, 288);
|
|
214
|
+
fixedLit = buildHuffman(lit);
|
|
215
|
+
fixedDist = buildHuffman(new Uint8Array(30).fill(5));
|
|
216
|
+
}
|
|
217
|
+
return [fixedLit, fixedDist];
|
|
218
|
+
}
|
|
219
|
+
function corrupt() {
|
|
220
|
+
return new Error("sheetr: corrupt compressed data");
|
|
221
|
+
}
|
|
222
|
+
function inflateRawSync(src, size) {
|
|
223
|
+
const out = new Uint8Array(size);
|
|
224
|
+
let op = 0;
|
|
225
|
+
let pos = 0;
|
|
226
|
+
let bitBuf = 0;
|
|
227
|
+
let bitCount = 0;
|
|
228
|
+
const bits = (n) => {
|
|
229
|
+
while (bitCount < n) {
|
|
230
|
+
if (pos >= src.length) throw corrupt();
|
|
231
|
+
bitBuf |= src[pos++] << bitCount;
|
|
232
|
+
bitCount += 8;
|
|
233
|
+
}
|
|
234
|
+
const v = bitBuf & (1 << n) - 1;
|
|
235
|
+
bitBuf >>>= n;
|
|
236
|
+
bitCount -= n;
|
|
237
|
+
return v;
|
|
238
|
+
};
|
|
239
|
+
const decode = (h) => {
|
|
240
|
+
let code = 0;
|
|
241
|
+
let first = 0;
|
|
242
|
+
let index = 0;
|
|
243
|
+
for (let len = 1; len < 16; len++) {
|
|
244
|
+
code |= bits(1);
|
|
245
|
+
const count = h.counts[len];
|
|
246
|
+
if (code - first < count) return h.symbols[index + code - first];
|
|
247
|
+
index += count;
|
|
248
|
+
first = first + count << 1;
|
|
249
|
+
code <<= 1;
|
|
250
|
+
}
|
|
251
|
+
throw corrupt();
|
|
252
|
+
};
|
|
253
|
+
let last = 0;
|
|
254
|
+
while (!last) {
|
|
255
|
+
last = bits(1);
|
|
256
|
+
const type = bits(2);
|
|
257
|
+
if (type === 0) {
|
|
258
|
+
bitBuf = 0;
|
|
259
|
+
bitCount = 0;
|
|
260
|
+
if (pos + 4 > src.length) throw corrupt();
|
|
261
|
+
const len = src[pos] | src[pos + 1] << 8;
|
|
262
|
+
const nlen = src[pos + 2] | src[pos + 3] << 8;
|
|
263
|
+
pos += 4;
|
|
264
|
+
if (len !== (~nlen & 65535) || pos + len > src.length || op + len > size) throw corrupt();
|
|
265
|
+
out.set(src.subarray(pos, pos + len), op);
|
|
266
|
+
pos += len;
|
|
267
|
+
op += len;
|
|
268
|
+
continue;
|
|
269
|
+
}
|
|
270
|
+
let lit;
|
|
271
|
+
let dist;
|
|
272
|
+
if (type === 1) {
|
|
273
|
+
[lit, dist] = fixedTables();
|
|
274
|
+
} else if (type === 2) {
|
|
275
|
+
const hlit = bits(5) + 257;
|
|
276
|
+
const hdist = bits(5) + 1;
|
|
277
|
+
const hclen = bits(4) + 4;
|
|
278
|
+
const clLengths = new Uint8Array(19);
|
|
279
|
+
for (let i = 0; i < hclen; i++) clLengths[CODE_LENGTH_ORDER[i]] = bits(3);
|
|
280
|
+
const clTable = buildHuffman(clLengths);
|
|
281
|
+
const lengths = new Uint8Array(hlit + hdist);
|
|
282
|
+
for (let i = 0; i < hlit + hdist; ) {
|
|
283
|
+
const sym = decode(clTable);
|
|
284
|
+
if (sym < 16) {
|
|
285
|
+
lengths[i++] = sym;
|
|
286
|
+
continue;
|
|
287
|
+
}
|
|
288
|
+
let repeat;
|
|
289
|
+
let value = 0;
|
|
290
|
+
if (sym === 16) {
|
|
291
|
+
if (i === 0) throw corrupt();
|
|
292
|
+
value = lengths[i - 1];
|
|
293
|
+
repeat = 3 + bits(2);
|
|
294
|
+
} else if (sym === 17) {
|
|
295
|
+
repeat = 3 + bits(3);
|
|
296
|
+
} else {
|
|
297
|
+
repeat = 11 + bits(7);
|
|
298
|
+
}
|
|
299
|
+
if (i + repeat > lengths.length) throw corrupt();
|
|
300
|
+
while (repeat--) lengths[i++] = value;
|
|
301
|
+
}
|
|
302
|
+
lit = buildHuffman(lengths.subarray(0, hlit));
|
|
303
|
+
dist = buildHuffman(lengths.subarray(hlit));
|
|
304
|
+
} else {
|
|
305
|
+
throw corrupt();
|
|
306
|
+
}
|
|
307
|
+
for (; ; ) {
|
|
308
|
+
const sym = decode(lit);
|
|
309
|
+
if (sym < 256) {
|
|
310
|
+
if (op >= size) throw corrupt();
|
|
311
|
+
out[op++] = sym;
|
|
312
|
+
} else if (sym === 256) {
|
|
313
|
+
break;
|
|
314
|
+
} else {
|
|
315
|
+
const li = sym - 257;
|
|
316
|
+
if (li >= 29) throw corrupt();
|
|
317
|
+
const len = LEN_BASE[li] + bits(LEN_EXTRA[li]);
|
|
318
|
+
const di = decode(dist);
|
|
319
|
+
if (di >= 30) throw corrupt();
|
|
320
|
+
const d = DIST_BASE[di] + bits(DIST_EXTRA[di]);
|
|
321
|
+
if (d > op || op + len > size) throw corrupt();
|
|
322
|
+
for (let k = 0; k < len; k++, op++) out[op] = out[op - d];
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
if (op !== size) throw corrupt();
|
|
327
|
+
return out;
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
// src/zip.ts
|
|
331
|
+
var CRC_TABLE = /* @__PURE__ */ (() => {
|
|
332
|
+
const t = new Int32Array(256 * 8);
|
|
333
|
+
for (let n = 0; n < 256; n++) {
|
|
334
|
+
let c = n;
|
|
335
|
+
for (let k = 0; k < 8; k++) c = c & 1 ? 3988292384 ^ c >>> 1 : c >>> 1;
|
|
336
|
+
t[n] = c;
|
|
337
|
+
}
|
|
338
|
+
for (let n = 0; n < 256; n++) {
|
|
339
|
+
for (let k = 1; k < 8; k++) {
|
|
340
|
+
const prev = t[(k - 1) * 256 + n];
|
|
341
|
+
t[k * 256 + n] = prev >>> 8 ^ t[prev & 255];
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
return t;
|
|
345
|
+
})();
|
|
346
|
+
function crc32(data) {
|
|
347
|
+
const t = CRC_TABLE;
|
|
348
|
+
const len = data.length;
|
|
349
|
+
let c = -1;
|
|
350
|
+
let i = 0;
|
|
351
|
+
for (; i + 8 <= len; i += 8) {
|
|
352
|
+
c ^= data[i] | data[i + 1] << 8 | data[i + 2] << 16 | data[i + 3] << 24;
|
|
353
|
+
c = t[1792 + (c & 255)] ^ t[1536 + (c >>> 8 & 255)] ^ t[1280 + (c >>> 16 & 255)] ^ t[1024 + (c >>> 24)] ^ t[768 + data[i + 4]] ^ t[512 + data[i + 5]] ^ t[256 + data[i + 6]] ^ t[data[i + 7]];
|
|
354
|
+
}
|
|
355
|
+
for (; i < len; i++) c = t[(c ^ data[i]) & 255] ^ c >>> 8;
|
|
356
|
+
return (c ^ -1) >>> 0;
|
|
357
|
+
}
|
|
358
|
+
var DOS_TIME = 0;
|
|
359
|
+
var DOS_DATE = 0 << 9 | 1 << 5 | 1;
|
|
360
|
+
var UTF8_FLAG = 2048;
|
|
361
|
+
var MAX_U32 = 4294967295;
|
|
362
|
+
function writeZip(entries) {
|
|
363
|
+
const encoder = new TextEncoder();
|
|
364
|
+
const items = entries.map((e) => {
|
|
365
|
+
const name = encoder.encode(e.name);
|
|
366
|
+
const body = e.deflated ?? e.data;
|
|
367
|
+
return { name, body, size: e.data.length, crc: crc32(e.data), method: e.deflated ? 8 : 0 };
|
|
368
|
+
});
|
|
369
|
+
let localSize = 0;
|
|
370
|
+
let centralSize = 0;
|
|
371
|
+
for (const item of items) {
|
|
372
|
+
localSize += 30 + item.name.length + item.body.length;
|
|
373
|
+
centralSize += 46 + item.name.length;
|
|
374
|
+
}
|
|
375
|
+
const total = localSize + centralSize + 22;
|
|
376
|
+
if (items.length > 65535 || localSize + centralSize > MAX_U32 || items.some((i) => i.size > MAX_U32)) {
|
|
377
|
+
throw new RangeError("sheetr: the workbook is too large for a ZIP file without ZIP64 (over 4 GB)");
|
|
378
|
+
}
|
|
379
|
+
const out = new Uint8Array(total);
|
|
380
|
+
const view = new DataView(out.buffer);
|
|
381
|
+
const offsets = [];
|
|
382
|
+
let p = 0;
|
|
383
|
+
for (const item of items) {
|
|
384
|
+
offsets.push(p);
|
|
385
|
+
view.setUint32(p, 67324752, true);
|
|
386
|
+
view.setUint16(p + 4, 20, true);
|
|
387
|
+
view.setUint16(p + 6, UTF8_FLAG, true);
|
|
388
|
+
view.setUint16(p + 8, item.method, true);
|
|
389
|
+
view.setUint16(p + 10, DOS_TIME, true);
|
|
390
|
+
view.setUint16(p + 12, DOS_DATE, true);
|
|
391
|
+
view.setUint32(p + 14, item.crc, true);
|
|
392
|
+
view.setUint32(p + 18, item.body.length, true);
|
|
393
|
+
view.setUint32(p + 22, item.size, true);
|
|
394
|
+
view.setUint16(p + 26, item.name.length, true);
|
|
395
|
+
view.setUint16(p + 28, 0, true);
|
|
396
|
+
out.set(item.name, p + 30);
|
|
397
|
+
p += 30 + item.name.length;
|
|
398
|
+
out.set(item.body, p);
|
|
399
|
+
p += item.body.length;
|
|
400
|
+
}
|
|
401
|
+
const centralStart = p;
|
|
402
|
+
items.forEach((item, i) => {
|
|
403
|
+
view.setUint32(p, 33639248, true);
|
|
404
|
+
view.setUint16(p + 4, 20, true);
|
|
405
|
+
view.setUint16(p + 6, 20, true);
|
|
406
|
+
view.setUint16(p + 8, UTF8_FLAG, true);
|
|
407
|
+
view.setUint16(p + 10, item.method, true);
|
|
408
|
+
view.setUint16(p + 12, DOS_TIME, true);
|
|
409
|
+
view.setUint16(p + 14, DOS_DATE, true);
|
|
410
|
+
view.setUint32(p + 16, item.crc, true);
|
|
411
|
+
view.setUint32(p + 20, item.body.length, true);
|
|
412
|
+
view.setUint32(p + 24, item.size, true);
|
|
413
|
+
view.setUint16(p + 28, item.name.length, true);
|
|
414
|
+
view.setUint32(p + 42, offsets[i], true);
|
|
415
|
+
out.set(item.name, p + 46);
|
|
416
|
+
p += 46 + item.name.length;
|
|
417
|
+
});
|
|
418
|
+
view.setUint32(p, 101010256, true);
|
|
419
|
+
view.setUint16(p + 8, items.length, true);
|
|
420
|
+
view.setUint16(p + 10, items.length, true);
|
|
421
|
+
view.setUint32(p + 12, p - centralStart, true);
|
|
422
|
+
view.setUint32(p + 16, centralStart, true);
|
|
423
|
+
return out;
|
|
424
|
+
}
|
|
425
|
+
async function runStream(stream, data) {
|
|
426
|
+
const writer = stream.writable.getWriter();
|
|
427
|
+
const written = writer.write(data).then(() => writer.close());
|
|
428
|
+
written.catch(() => {
|
|
429
|
+
});
|
|
430
|
+
const reader = stream.readable.getReader();
|
|
431
|
+
const chunks = [];
|
|
432
|
+
let length = 0;
|
|
433
|
+
for (; ; ) {
|
|
434
|
+
const { done, value } = await reader.read();
|
|
435
|
+
if (done) break;
|
|
436
|
+
if (value) {
|
|
437
|
+
chunks.push(value);
|
|
438
|
+
length += value.length;
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
await written;
|
|
442
|
+
const out = new Uint8Array(length);
|
|
443
|
+
let p = 0;
|
|
444
|
+
for (const chunk of chunks) {
|
|
445
|
+
out.set(chunk, p);
|
|
446
|
+
p += chunk.length;
|
|
447
|
+
}
|
|
448
|
+
return out;
|
|
449
|
+
}
|
|
450
|
+
async function deflateRaw(data) {
|
|
451
|
+
if (typeof CompressionStream !== "function") return null;
|
|
452
|
+
let stream;
|
|
453
|
+
try {
|
|
454
|
+
stream = new CompressionStream("deflate-raw");
|
|
455
|
+
} catch {
|
|
456
|
+
return null;
|
|
457
|
+
}
|
|
458
|
+
return runStream(stream, data);
|
|
459
|
+
}
|
|
460
|
+
async function inflateRaw(data, size) {
|
|
461
|
+
let stream = null;
|
|
462
|
+
if (typeof DecompressionStream === "function") {
|
|
463
|
+
try {
|
|
464
|
+
stream = new DecompressionStream("deflate-raw");
|
|
465
|
+
} catch {
|
|
466
|
+
stream = null;
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
if (!stream) return inflateRawSync(data, size);
|
|
470
|
+
try {
|
|
471
|
+
return await runStream(stream, data);
|
|
472
|
+
} catch {
|
|
473
|
+
throw new Error("sheetr: corrupt compressed data");
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
var NOT_ZIP = "sheetr: not a valid .xlsx file (no ZIP structure found). It may be an older .xls file, a CSV file, or a password-protected workbook.";
|
|
477
|
+
function readZipDirectory(bytes) {
|
|
478
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
479
|
+
const len = bytes.length;
|
|
480
|
+
let eocd = -1;
|
|
481
|
+
for (let i = len - 22; i >= 0 && i >= len - 22 - 65535; i--) {
|
|
482
|
+
if (view.getUint32(i, true) === 101010256) {
|
|
483
|
+
eocd = i;
|
|
484
|
+
break;
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
if (eocd < 0) throw new Error(NOT_ZIP);
|
|
488
|
+
const count = view.getUint16(eocd + 10, true);
|
|
489
|
+
const cdSize = view.getUint32(eocd + 12, true);
|
|
490
|
+
const cdOffset = view.getUint32(eocd + 16, true);
|
|
491
|
+
if (count === 65535 || cdOffset === MAX_U32 || cdSize === MAX_U32) {
|
|
492
|
+
throw new Error("sheetr: ZIP64 archives are not supported");
|
|
493
|
+
}
|
|
494
|
+
if (cdOffset + cdSize > len) throw new Error("sheetr: corrupt .xlsx file (central directory is out of range)");
|
|
495
|
+
const decoder = new TextDecoder();
|
|
496
|
+
const entries = /* @__PURE__ */ new Map();
|
|
497
|
+
let p = cdOffset;
|
|
498
|
+
for (let i = 0; i < count; i++) {
|
|
499
|
+
if (p + 46 > len || view.getUint32(p, true) !== 33639248) {
|
|
500
|
+
throw new Error("sheetr: corrupt .xlsx file (bad central directory entry)");
|
|
501
|
+
}
|
|
502
|
+
const nameLen = view.getUint16(p + 28, true);
|
|
503
|
+
const extraLen = view.getUint16(p + 30, true);
|
|
504
|
+
const commentLen = view.getUint16(p + 32, true);
|
|
505
|
+
const name = decoder.decode(bytes.subarray(p + 46, p + 46 + nameLen));
|
|
506
|
+
const entry = {
|
|
507
|
+
name,
|
|
508
|
+
flags: view.getUint16(p + 8, true),
|
|
509
|
+
method: view.getUint16(p + 10, true),
|
|
510
|
+
crc: view.getUint32(p + 16, true),
|
|
511
|
+
compressedSize: view.getUint32(p + 20, true),
|
|
512
|
+
size: view.getUint32(p + 24, true),
|
|
513
|
+
offset: view.getUint32(p + 42, true)
|
|
514
|
+
};
|
|
515
|
+
entries.set(name.replace(/^\/+/, "").toLowerCase(), entry);
|
|
516
|
+
p += 46 + nameLen + extraLen + commentLen;
|
|
517
|
+
}
|
|
518
|
+
return entries;
|
|
519
|
+
}
|
|
520
|
+
async function readZipEntry(bytes, entry) {
|
|
521
|
+
if (entry.flags & 1) throw new Error("sheetr: encrypted ZIP entries are not supported");
|
|
522
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
523
|
+
const p = entry.offset;
|
|
524
|
+
if (p + 30 > bytes.length || view.getUint32(p, true) !== 67324752) {
|
|
525
|
+
throw new Error(`sheetr: corrupt .xlsx file (bad local header for ${entry.name})`);
|
|
526
|
+
}
|
|
527
|
+
const start = p + 30 + view.getUint16(p + 26, true) + view.getUint16(p + 28, true);
|
|
528
|
+
const end = start + entry.compressedSize;
|
|
529
|
+
if (end > bytes.length) throw new Error(`sheetr: corrupt .xlsx file (${entry.name} is truncated)`);
|
|
530
|
+
const raw = bytes.subarray(start, end);
|
|
531
|
+
let data;
|
|
532
|
+
if (entry.method === 0) data = raw;
|
|
533
|
+
else if (entry.method === 8) data = await inflateRaw(raw, entry.size);
|
|
534
|
+
else throw new Error(`sheetr: unsupported ZIP compression method ${entry.method} in ${entry.name}`);
|
|
535
|
+
if (data.length !== entry.size || crc32(data) !== entry.crc) {
|
|
536
|
+
throw new Error(`sheetr: corrupt .xlsx file (checksum mismatch in ${entry.name})`);
|
|
537
|
+
}
|
|
538
|
+
return data;
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
// src/write.ts
|
|
542
|
+
var XLSX_MIME_TYPE = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
|
|
543
|
+
var MAX_ROWS = 1048576;
|
|
544
|
+
var MAX_COLS = 16384;
|
|
545
|
+
var MAX_TEXT = 32767;
|
|
546
|
+
var MAX_SHEET_NAME = 31;
|
|
547
|
+
var AUTO_WIDTH_MIN = 6;
|
|
548
|
+
var AUTO_WIDTH_MAX = 60;
|
|
549
|
+
var NS_MAIN = "http://schemas.openxmlformats.org/spreadsheetml/2006/main";
|
|
550
|
+
var NS_REL = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
|
|
551
|
+
var NS_PKG_REL = "http://schemas.openxmlformats.org/package/2006/relationships";
|
|
552
|
+
var XML_HEAD = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n';
|
|
553
|
+
var STYLE_BOLD = 1;
|
|
554
|
+
var STYLE_DATE = 2;
|
|
555
|
+
var STYLE_DATETIME = 3;
|
|
556
|
+
var STYLE_BOLD_DATE = 4;
|
|
557
|
+
var STYLE_BOLD_DATETIME = 5;
|
|
558
|
+
var STYLES_XML = XML_HEAD + `<styleSheet xmlns="${NS_MAIN}"><numFmts count="2"><numFmt numFmtId="164" formatCode="yyyy-mm-dd"/><numFmt numFmtId="165" formatCode="yyyy-mm-dd hh:mm:ss"/></numFmts><fonts count="2"><font><sz val="11"/><name val="Calibri"/><family val="2"/></font><font><b/><sz val="11"/><name val="Calibri"/><family val="2"/></font></fonts><fills count="2"><fill><patternFill patternType="none"/></fill><fill><patternFill patternType="gray125"/></fill></fills><borders count="1"><border><left/><right/><top/><bottom/><diagonal/></border></borders><cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs><cellXfs count="6"><xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/><xf numFmtId="0" fontId="1" fillId="0" borderId="0" xfId="0" applyFont="1"/><xf numFmtId="164" fontId="0" fillId="0" borderId="0" xfId="0" applyNumberFormat="1"/><xf numFmtId="165" fontId="0" fillId="0" borderId="0" xfId="0" applyNumberFormat="1"/><xf numFmtId="164" fontId="1" fillId="0" borderId="0" xfId="0" applyFont="1" applyNumberFormat="1"/><xf numFmtId="165" fontId="1" fillId="0" borderId="0" xfId="0" applyFont="1" applyNumberFormat="1"/></cellXfs><cellStyles count="1"><cellStyle name="Normal" xfId="0" builtinId="0"/></cellStyles></styleSheet>`;
|
|
559
|
+
var SharedStrings = class {
|
|
560
|
+
index = /* @__PURE__ */ new Map();
|
|
561
|
+
list = [];
|
|
562
|
+
count = 0;
|
|
563
|
+
add(text) {
|
|
564
|
+
this.count++;
|
|
565
|
+
let i = this.index.get(text);
|
|
566
|
+
if (i === void 0) {
|
|
567
|
+
i = this.list.length;
|
|
568
|
+
this.index.set(text, i);
|
|
569
|
+
this.list.push(text);
|
|
570
|
+
}
|
|
571
|
+
return i;
|
|
572
|
+
}
|
|
573
|
+
get size() {
|
|
574
|
+
return this.list.length;
|
|
575
|
+
}
|
|
576
|
+
toXml() {
|
|
577
|
+
const parts = [
|
|
578
|
+
XML_HEAD,
|
|
579
|
+
`<sst xmlns="${NS_MAIN}" count="${this.count}" uniqueCount="${this.list.length}">`
|
|
580
|
+
];
|
|
581
|
+
for (const s of this.list) {
|
|
582
|
+
parts.push(needsPreserve(s) ? `<si><t xml:space="preserve">${escapeCellText(s)}</t></si>` : `<si><t>${escapeCellText(s)}</t></si>`);
|
|
583
|
+
}
|
|
584
|
+
parts.push("</sst>");
|
|
585
|
+
return parts.join("");
|
|
586
|
+
}
|
|
587
|
+
};
|
|
588
|
+
function needsPreserve(s) {
|
|
589
|
+
if (!s) return false;
|
|
590
|
+
return s.charCodeAt(0) <= 32 || s.charCodeAt(s.length - 1) <= 32 || s.indexOf("\n") !== -1 || s.indexOf(" ") !== -1;
|
|
591
|
+
}
|
|
592
|
+
var colNameCache = [];
|
|
593
|
+
function columnName(index) {
|
|
594
|
+
let name = colNameCache[index];
|
|
595
|
+
if (name === void 0) {
|
|
596
|
+
name = "";
|
|
597
|
+
let n = index + 1;
|
|
598
|
+
while (n > 0) {
|
|
599
|
+
const r = (n - 1) % 26;
|
|
600
|
+
name = String.fromCharCode(65 + r) + name;
|
|
601
|
+
n = Math.floor((n - 1) / 26);
|
|
602
|
+
}
|
|
603
|
+
colNameCache[index] = name;
|
|
604
|
+
}
|
|
605
|
+
return name;
|
|
606
|
+
}
|
|
607
|
+
function truncate(s, max) {
|
|
608
|
+
if (s.length <= max) return s;
|
|
609
|
+
let cut = max;
|
|
610
|
+
const c = s.charCodeAt(cut - 1);
|
|
611
|
+
if (c >= 55296 && c <= 56319) cut--;
|
|
612
|
+
return s.slice(0, cut);
|
|
613
|
+
}
|
|
614
|
+
var SHEET_NAME_INVALID = /[[\]:*?/\\]/g;
|
|
615
|
+
function sanitizeSheetName(name, used, index) {
|
|
616
|
+
let base = stripControls(cleanXmlText(String(name ?? ""))).replace(SHEET_NAME_INVALID, "_").trim();
|
|
617
|
+
base = truncate(base, MAX_SHEET_NAME).replace(/^'+|'+$/g, "").trim();
|
|
618
|
+
if (!base) base = `Sheet${index + 1}`;
|
|
619
|
+
if (base.toLowerCase() === "history") base = `${base}_`;
|
|
620
|
+
let result = base;
|
|
621
|
+
for (let n = 2; used.has(result.toLowerCase()); n++) {
|
|
622
|
+
const suffix = ` (${n})`;
|
|
623
|
+
result = truncate(base, MAX_SHEET_NAME - suffix.length) + suffix;
|
|
624
|
+
}
|
|
625
|
+
used.add(result.toLowerCase());
|
|
626
|
+
return result;
|
|
627
|
+
}
|
|
628
|
+
function isFormula(v) {
|
|
629
|
+
return typeof v.formula === "string";
|
|
630
|
+
}
|
|
631
|
+
function textLength(s) {
|
|
632
|
+
if (s.indexOf("\n") === -1) return s.length;
|
|
633
|
+
let max = 0;
|
|
634
|
+
for (const line of s.split("\n")) max = Math.max(max, line.length);
|
|
635
|
+
return max;
|
|
636
|
+
}
|
|
637
|
+
var EMPTY = { xml: "", width: 0 };
|
|
638
|
+
var SheetWriter = class {
|
|
639
|
+
constructor(sst, utc) {
|
|
640
|
+
this.sst = sst;
|
|
641
|
+
this.utc = utc;
|
|
642
|
+
}
|
|
643
|
+
sst;
|
|
644
|
+
utc;
|
|
645
|
+
hasFormulas = false;
|
|
646
|
+
text(ref, style, value) {
|
|
647
|
+
const text = truncate(cleanXmlText(value), MAX_TEXT);
|
|
648
|
+
return { xml: `<c r="${ref}"${style} t="s"><v>${this.sst.add(text)}</v></c>`, width: textLength(text) };
|
|
649
|
+
}
|
|
650
|
+
cell(value, ref, bold) {
|
|
651
|
+
const style = bold ? ` s="${STYLE_BOLD}"` : "";
|
|
652
|
+
switch (typeof value) {
|
|
653
|
+
case "string":
|
|
654
|
+
return this.text(ref, style, value);
|
|
655
|
+
case "number":
|
|
656
|
+
if (!Number.isFinite(value)) return this.text(ref, style, String(value));
|
|
657
|
+
return { xml: `<c r="${ref}"${style}><v>${Object.is(value, -0) ? 0 : value}</v></c>`, width: String(value).length };
|
|
658
|
+
case "boolean":
|
|
659
|
+
return { xml: `<c r="${ref}"${style} t="b"><v>${value ? 1 : 0}</v></c>`, width: 5 };
|
|
660
|
+
case "bigint":
|
|
661
|
+
return Number.isSafeInteger(Number(value)) ? { xml: `<c r="${ref}"${style}><v>${value}</v></c>`, width: String(value).length } : this.text(ref, style, String(value));
|
|
662
|
+
case "object": {
|
|
663
|
+
if (value === null) return EMPTY;
|
|
664
|
+
if (value instanceof Date) return this.date(value, ref, bold);
|
|
665
|
+
if (isFormula(value)) return this.formula(value, ref, style);
|
|
666
|
+
let json;
|
|
667
|
+
try {
|
|
668
|
+
json = JSON.stringify(value);
|
|
669
|
+
} catch {
|
|
670
|
+
json = void 0;
|
|
671
|
+
}
|
|
672
|
+
return this.text(ref, style, json ?? String(value));
|
|
673
|
+
}
|
|
674
|
+
default:
|
|
675
|
+
return EMPTY;
|
|
676
|
+
}
|
|
677
|
+
}
|
|
678
|
+
date(d, ref, bold) {
|
|
679
|
+
if (Number.isNaN(d.getTime())) return EMPTY;
|
|
680
|
+
const serial = dateToSerial(d, this.utc);
|
|
681
|
+
if (serial === null) return this.text(ref, bold ? ` s="${STYLE_BOLD}"` : "", d.toISOString());
|
|
682
|
+
const dateOnly = isDateOnly(d, this.utc);
|
|
683
|
+
const s = dateOnly ? bold ? STYLE_BOLD_DATE : STYLE_DATE : bold ? STYLE_BOLD_DATETIME : STYLE_DATETIME;
|
|
684
|
+
return { xml: `<c r="${ref}" s="${s}"><v>${serial}</v></c>`, width: dateOnly ? 10 : 19 };
|
|
685
|
+
}
|
|
686
|
+
formula(f, ref, style) {
|
|
687
|
+
const expr = f.formula.trim().replace(/^=/, "");
|
|
688
|
+
if (!expr) return EMPTY;
|
|
689
|
+
this.hasFormulas = true;
|
|
690
|
+
const fx = `<f>${escapeXml(expr)}</f>`;
|
|
691
|
+
const v = f.value;
|
|
692
|
+
if (typeof v === "number" && Number.isFinite(v)) {
|
|
693
|
+
return { xml: `<c r="${ref}"${style}>${fx}<v>${v}</v></c>`, width: String(v).length };
|
|
694
|
+
}
|
|
695
|
+
if (typeof v === "boolean") {
|
|
696
|
+
return { xml: `<c r="${ref}"${style} t="b">${fx}<v>${v ? 1 : 0}</v></c>`, width: 5 };
|
|
697
|
+
}
|
|
698
|
+
if (typeof v === "string") {
|
|
699
|
+
const text = truncate(cleanXmlText(v), MAX_TEXT);
|
|
700
|
+
return { xml: `<c r="${ref}"${style} t="str">${fx}<v>${escapeCellText(text)}</v></c>`, width: textLength(text) };
|
|
701
|
+
}
|
|
702
|
+
return { xml: `<c r="${ref}"${style}>${fx}</c>`, width: 10 };
|
|
703
|
+
}
|
|
704
|
+
};
|
|
705
|
+
function isObjectRow(row) {
|
|
706
|
+
return typeof row === "object" && row !== null && !Array.isArray(row);
|
|
707
|
+
}
|
|
708
|
+
function toTable(rows) {
|
|
709
|
+
let keys = null;
|
|
710
|
+
const seen = /* @__PURE__ */ new Set();
|
|
711
|
+
for (const row of rows) {
|
|
712
|
+
if (!isObjectRow(row)) continue;
|
|
713
|
+
keys ??= [];
|
|
714
|
+
for (const key of Object.keys(row)) {
|
|
715
|
+
if (!seen.has(key)) {
|
|
716
|
+
seen.add(key);
|
|
717
|
+
keys.push(key);
|
|
718
|
+
}
|
|
719
|
+
}
|
|
720
|
+
}
|
|
721
|
+
const table = [];
|
|
722
|
+
if (keys) table.push(keys);
|
|
723
|
+
for (const row of rows) {
|
|
724
|
+
if (Array.isArray(row)) table.push(row);
|
|
725
|
+
else if (keys && isObjectRow(row)) table.push(keys.map((k) => row[k]));
|
|
726
|
+
else table.push([]);
|
|
727
|
+
}
|
|
728
|
+
return { table, objects: keys !== null };
|
|
729
|
+
}
|
|
730
|
+
function sheetXml(rows, options, writer) {
|
|
731
|
+
const { table, objects } = toTable(rows);
|
|
732
|
+
if (table.length > MAX_ROWS) throw new RangeError(`sheetr: a sheet can have at most ${MAX_ROWS} rows`);
|
|
733
|
+
const boldHeader = options.header ?? objects;
|
|
734
|
+
const widths = [];
|
|
735
|
+
const body = [];
|
|
736
|
+
let maxCol = -1;
|
|
737
|
+
let maxRow = -1;
|
|
738
|
+
for (let r = 0; r < table.length; r++) {
|
|
739
|
+
const row = table[r];
|
|
740
|
+
if (row.length > MAX_COLS) throw new RangeError(`sheetr: a row can have at most ${MAX_COLS} columns`);
|
|
741
|
+
const bold = boldHeader && r === 0;
|
|
742
|
+
const rowNum = r + 1;
|
|
743
|
+
let cells = "";
|
|
744
|
+
for (let c = 0; c < row.length; c++) {
|
|
745
|
+
const result = writer.cell(row[c], columnName(c) + rowNum, bold);
|
|
746
|
+
if (!result.xml) continue;
|
|
747
|
+
cells += result.xml;
|
|
748
|
+
if (c > maxCol) maxCol = c;
|
|
749
|
+
const w = bold ? result.width + 1 : result.width;
|
|
750
|
+
if (w > (widths[c] ?? 0)) widths[c] = w;
|
|
751
|
+
}
|
|
752
|
+
if (cells) {
|
|
753
|
+
body.push(`<row r="${rowNum}">${cells}</row>`);
|
|
754
|
+
maxRow = r;
|
|
755
|
+
}
|
|
756
|
+
}
|
|
757
|
+
const parts = [XML_HEAD, `<worksheet xmlns="${NS_MAIN}" xmlns:r="${NS_REL}">`];
|
|
758
|
+
parts.push(`<dimension ref="${maxRow < 0 ? "A1" : `A1:${columnName(maxCol)}${maxRow + 1}`}"/>`);
|
|
759
|
+
if (options.freezeHeader && table.length > 0) {
|
|
760
|
+
parts.push(
|
|
761
|
+
'<sheetViews><sheetView workbookViewId="0"><pane ySplit="1" topLeftCell="A2" activePane="bottomLeft" state="frozen"/><selection pane="bottomLeft" activeCell="A2" sqref="A2"/></sheetView></sheetViews>'
|
|
762
|
+
);
|
|
763
|
+
} else {
|
|
764
|
+
parts.push('<sheetViews><sheetView workbookViewId="0"/></sheetViews>');
|
|
765
|
+
}
|
|
766
|
+
parts.push('<sheetFormatPr defaultRowHeight="15"/>');
|
|
767
|
+
const cols = [];
|
|
768
|
+
const custom = Array.isArray(options.columnWidths) ? options.columnWidths : [];
|
|
769
|
+
const count = Math.min(Math.max(widths.length, custom.length), MAX_COLS);
|
|
770
|
+
for (let i = 0; i < count; i++) {
|
|
771
|
+
const given = custom[i];
|
|
772
|
+
let width;
|
|
773
|
+
if (typeof given === "number" && Number.isFinite(given) && given > 0) {
|
|
774
|
+
width = Math.min(given, 255);
|
|
775
|
+
} else if (widths[i]) {
|
|
776
|
+
width = Math.min(Math.max(widths[i] + 2, AUTO_WIDTH_MIN), AUTO_WIDTH_MAX);
|
|
777
|
+
}
|
|
778
|
+
if (width !== void 0) cols.push(`<col min="${i + 1}" max="${i + 1}" width="${width}" customWidth="1"/>`);
|
|
779
|
+
}
|
|
780
|
+
if (cols.length) parts.push(`<cols>${cols.join("")}</cols>`);
|
|
781
|
+
parts.push(body.length ? `<sheetData>${body.join("")}</sheetData>` : "<sheetData/>");
|
|
782
|
+
parts.push('<pageMargins left="0.7" right="0.7" top="0.75" bottom="0.75" header="0.3" footer="0.3"/>');
|
|
783
|
+
parts.push("</worksheet>");
|
|
784
|
+
return parts.join("");
|
|
785
|
+
}
|
|
786
|
+
function sheetList(data, options) {
|
|
787
|
+
if (Array.isArray(data)) return [[options.sheetName ?? "Sheet1", data]];
|
|
788
|
+
if (typeof data === "object" && data !== null) {
|
|
789
|
+
const entries = Object.entries(data);
|
|
790
|
+
if (!entries.length) throw new TypeError("sheetr: the workbook needs at least one sheet");
|
|
791
|
+
return entries.map(([name, rows]) => {
|
|
792
|
+
if (!Array.isArray(rows)) throw new TypeError(`sheetr: sheet "${name}" must be an array of rows`);
|
|
793
|
+
return [name, rows];
|
|
794
|
+
});
|
|
795
|
+
}
|
|
796
|
+
throw new TypeError('sheetr: data must be an array of rows or an object like { "Sheet name": rows }');
|
|
797
|
+
}
|
|
798
|
+
function buildParts(data, options) {
|
|
799
|
+
const sheets = sheetList(data, options);
|
|
800
|
+
const sst = new SharedStrings();
|
|
801
|
+
const writer = new SheetWriter(sst, options.utc === true);
|
|
802
|
+
const encoder = new TextEncoder();
|
|
803
|
+
const used = /* @__PURE__ */ new Set();
|
|
804
|
+
const n = sheets.length;
|
|
805
|
+
const sheetParts = [];
|
|
806
|
+
const sheetEntries = [];
|
|
807
|
+
const sheetRels = [];
|
|
808
|
+
const overrides = [];
|
|
809
|
+
sheets.forEach(([name, rows], i) => {
|
|
810
|
+
const safeName = sanitizeSheetName(name, used, i);
|
|
811
|
+
const path = `xl/worksheets/sheet${i + 1}.xml`;
|
|
812
|
+
sheetParts.push({ name: path, data: encoder.encode(sheetXml(rows, options, writer)) });
|
|
813
|
+
sheetEntries.push(`<sheet name="${escapeXml(safeName)}" sheetId="${i + 1}" r:id="rId${i + 1}"/>`);
|
|
814
|
+
sheetRels.push(`<Relationship Id="rId${i + 1}" Type="${NS_REL}/worksheet" Target="worksheets/sheet${i + 1}.xml"/>`);
|
|
815
|
+
overrides.push(
|
|
816
|
+
`<Override PartName="/${path}" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>`
|
|
817
|
+
);
|
|
818
|
+
});
|
|
819
|
+
const hasStrings = sst.size > 0;
|
|
820
|
+
const contentTypes = XML_HEAD + '<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/>' + overrides.join("") + '<Override PartName="/xl/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"/>' + (hasStrings ? '<Override PartName="/xl/sharedStrings.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml"/>' : "") + "</Types>";
|
|
821
|
+
const rootRels = XML_HEAD + `<Relationships xmlns="${NS_PKG_REL}"><Relationship Id="rId1" Type="${NS_REL}/officeDocument" Target="xl/workbook.xml"/></Relationships>`;
|
|
822
|
+
const workbook = XML_HEAD + `<workbook xmlns="${NS_MAIN}" xmlns:r="${NS_REL}"><bookViews><workbookView xWindow="0" yWindow="0" windowWidth="16384" windowHeight="8192"/></bookViews><sheets>${sheetEntries.join("")}</sheets>` + (writer.hasFormulas ? '<calcPr calcId="0" fullCalcOnLoad="1"/>' : "") + "</workbook>";
|
|
823
|
+
const workbookRels = XML_HEAD + `<Relationships xmlns="${NS_PKG_REL}">` + sheetRels.join("") + `<Relationship Id="rId${n + 1}" Type="${NS_REL}/styles" Target="styles.xml"/>` + (hasStrings ? `<Relationship Id="rId${n + 2}" Type="${NS_REL}/sharedStrings" Target="sharedStrings.xml"/>` : "") + "</Relationships>";
|
|
824
|
+
const parts = [
|
|
825
|
+
{ name: "[Content_Types].xml", data: encoder.encode(contentTypes) },
|
|
826
|
+
{ name: "_rels/.rels", data: encoder.encode(rootRels) },
|
|
827
|
+
{ name: "xl/workbook.xml", data: encoder.encode(workbook) },
|
|
828
|
+
{ name: "xl/_rels/workbook.xml.rels", data: encoder.encode(workbookRels) },
|
|
829
|
+
{ name: "xl/styles.xml", data: encoder.encode(STYLES_XML) },
|
|
830
|
+
...sheetParts
|
|
831
|
+
];
|
|
832
|
+
if (hasStrings) parts.push({ name: "xl/sharedStrings.xml", data: encoder.encode(sst.toXml()) });
|
|
833
|
+
return parts;
|
|
834
|
+
}
|
|
835
|
+
function toXlsx(data, options = {}) {
|
|
836
|
+
return writeZip(buildParts(data, options));
|
|
837
|
+
}
|
|
838
|
+
async function toXlsxAsync(data, options = {}) {
|
|
839
|
+
const parts = buildParts(data, options);
|
|
840
|
+
for (const part of parts) {
|
|
841
|
+
const deflated = await deflateRaw(part.data);
|
|
842
|
+
if (deflated === null) break;
|
|
843
|
+
if (deflated.length < part.data.length) part.deflated = deflated;
|
|
844
|
+
}
|
|
845
|
+
return writeZip(parts);
|
|
846
|
+
}
|
|
847
|
+
|
|
848
|
+
// src/read.ts
|
|
849
|
+
var MAX_ROWS2 = 1048576;
|
|
850
|
+
var MAX_COLS2 = 16384;
|
|
851
|
+
var SHEET_TAG = startTagRe("sheet");
|
|
852
|
+
var REL_TAG = startTagRe("Relationship");
|
|
853
|
+
var NUMFMT_TAG = startTagRe("numFmt");
|
|
854
|
+
var XF_TAG = startTagRe("xf");
|
|
855
|
+
var SI_EL = elementRe("si");
|
|
856
|
+
var CELL_XFS_EL = elementRe("cellXfs");
|
|
857
|
+
var V_EL = /<(?:[\w.-]+:)?v\b[^>]*?(?:\/>|>([\s\S]*?)<\/(?:[\w.-]+:)?v>)/;
|
|
858
|
+
var IS_EL = /<(?:[\w.-]+:)?is\b[^>]*?(?:\/>|>([\s\S]*?)<\/(?:[\w.-]+:)?is>)/;
|
|
859
|
+
var SHEET_DATA = /<(?:[\w.-]+:)?sheetData\b/;
|
|
860
|
+
var ROW_OR_CELL = /<([\w.-]+:)?(row|c)\b([^>]*?)(\/?)>/g;
|
|
861
|
+
var DATE_1904 = /<(?:[\w.-]+:)?workbookPr\b[^>]*\bdate1904\s*=\s*["'](?:1|true)["']/;
|
|
862
|
+
var REL_ID = "(?:[\\w.-]+:)?id";
|
|
863
|
+
function toBytes(input) {
|
|
864
|
+
if (input instanceof Uint8Array) return input;
|
|
865
|
+
if (input instanceof ArrayBuffer) return new Uint8Array(input);
|
|
866
|
+
if (ArrayBuffer.isView(input)) return new Uint8Array(input.buffer, input.byteOffset, input.byteLength);
|
|
867
|
+
throw new TypeError("sheetr: readXlsx expects a Uint8Array or an ArrayBuffer");
|
|
868
|
+
}
|
|
869
|
+
function decodeText(bytes) {
|
|
870
|
+
if (bytes.length >= 2 && bytes[0] === 255 && bytes[1] === 254) return new TextDecoder("utf-16le").decode(bytes);
|
|
871
|
+
if (bytes.length >= 2 && bytes[0] === 254 && bytes[1] === 255) return new TextDecoder("utf-16be").decode(bytes);
|
|
872
|
+
return new TextDecoder().decode(bytes);
|
|
873
|
+
}
|
|
874
|
+
function resolvePath(baseDir, target) {
|
|
875
|
+
const raw = target.startsWith("/") ? target.slice(1) : baseDir + target;
|
|
876
|
+
const out = [];
|
|
877
|
+
for (const seg of raw.split("/")) {
|
|
878
|
+
if (seg === "..") out.pop();
|
|
879
|
+
else if (seg && seg !== ".") out.push(seg);
|
|
880
|
+
}
|
|
881
|
+
return out.join("/");
|
|
882
|
+
}
|
|
883
|
+
function dirOf(path) {
|
|
884
|
+
const i = path.lastIndexOf("/");
|
|
885
|
+
return i < 0 ? "" : path.slice(0, i + 1);
|
|
886
|
+
}
|
|
887
|
+
function parseRels(xml, baseDir) {
|
|
888
|
+
const rels = /* @__PURE__ */ new Map();
|
|
889
|
+
if (!xml) return rels;
|
|
890
|
+
REL_TAG.lastIndex = 0;
|
|
891
|
+
let m;
|
|
892
|
+
while ((m = REL_TAG.exec(xml)) !== null) {
|
|
893
|
+
const attrs = m[1] ?? "";
|
|
894
|
+
const id = getAttr(attrs, "Id");
|
|
895
|
+
const target = getAttr(attrs, "Target");
|
|
896
|
+
if (!id || target === void 0 || getAttr(attrs, "TargetMode") === "External") continue;
|
|
897
|
+
rels.set(id, { type: getAttr(attrs, "Type") ?? "", target: resolvePath(baseDir, target) });
|
|
898
|
+
}
|
|
899
|
+
return rels;
|
|
900
|
+
}
|
|
901
|
+
function parseSharedStrings(xml) {
|
|
902
|
+
const list = [];
|
|
903
|
+
if (!xml) return list;
|
|
904
|
+
SI_EL.lastIndex = 0;
|
|
905
|
+
let m;
|
|
906
|
+
while ((m = SI_EL.exec(xml)) !== null) list.push(m[1] ? richText(m[1]) : "");
|
|
907
|
+
return list;
|
|
908
|
+
}
|
|
909
|
+
function parseDateStyles(xml) {
|
|
910
|
+
if (!xml) return [];
|
|
911
|
+
const formats = /* @__PURE__ */ new Map();
|
|
912
|
+
NUMFMT_TAG.lastIndex = 0;
|
|
913
|
+
let m;
|
|
914
|
+
while ((m = NUMFMT_TAG.exec(xml)) !== null) {
|
|
915
|
+
const id = Number(getAttr(m[1] ?? "", "numFmtId"));
|
|
916
|
+
const code = getAttr(m[1] ?? "", "formatCode");
|
|
917
|
+
if (Number.isInteger(id) && code !== void 0) formats.set(id, code);
|
|
918
|
+
}
|
|
919
|
+
CELL_XFS_EL.lastIndex = 0;
|
|
920
|
+
const section = CELL_XFS_EL.exec(xml)?.[1] ?? "";
|
|
921
|
+
const result = [];
|
|
922
|
+
XF_TAG.lastIndex = 0;
|
|
923
|
+
while ((m = XF_TAG.exec(section)) !== null) {
|
|
924
|
+
const id = Number(getAttr(m[1] ?? "", "numFmtId") ?? 0);
|
|
925
|
+
result.push(isDateFormat(id, formats.get(id)));
|
|
926
|
+
}
|
|
927
|
+
return result;
|
|
928
|
+
}
|
|
929
|
+
function columnIndex(ref) {
|
|
930
|
+
let n = 0;
|
|
931
|
+
let i = 0;
|
|
932
|
+
for (; i < ref.length; i++) {
|
|
933
|
+
const c = ref.charCodeAt(i) & ~32;
|
|
934
|
+
if (c < 65 || c > 90) break;
|
|
935
|
+
n = n * 26 + (c - 64);
|
|
936
|
+
}
|
|
937
|
+
return i === 0 ? -1 : n - 1;
|
|
938
|
+
}
|
|
939
|
+
function rowIndex(ref) {
|
|
940
|
+
let n = 0;
|
|
941
|
+
let scale = 1;
|
|
942
|
+
for (let i = ref.length - 1; i >= 0; i--) {
|
|
943
|
+
const c = ref.charCodeAt(i);
|
|
944
|
+
if (c < 48 || c > 57) break;
|
|
945
|
+
n += (c - 48) * scale;
|
|
946
|
+
scale *= 10;
|
|
947
|
+
}
|
|
948
|
+
return scale > 1 ? n - 1 : -1;
|
|
949
|
+
}
|
|
950
|
+
var CELL_ATTR = /([\w.:-]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g;
|
|
951
|
+
function cellValue(type, style, inner, ctx) {
|
|
952
|
+
const vMatch = inner ? V_EL.exec(inner) : null;
|
|
953
|
+
const v = vMatch ? vMatch[1] : void 0;
|
|
954
|
+
switch (type) {
|
|
955
|
+
case "s": {
|
|
956
|
+
if (v === void 0) return null;
|
|
957
|
+
return ctx.strings[parseInt(v, 10)] ?? null;
|
|
958
|
+
}
|
|
959
|
+
case "inlineStr": {
|
|
960
|
+
const is = IS_EL.exec(inner);
|
|
961
|
+
return is ? is[1] ? richText(is[1]) : "" : null;
|
|
962
|
+
}
|
|
963
|
+
case "str":
|
|
964
|
+
return v === void 0 ? null : unescapeCellText(decodeXml(v));
|
|
965
|
+
case "b":
|
|
966
|
+
return v === void 0 ? null : v.trim() === "1" || v.trim() === "true";
|
|
967
|
+
case "e":
|
|
968
|
+
return v === void 0 ? null : decodeXml(v).trim();
|
|
969
|
+
case "d": {
|
|
970
|
+
if (v === void 0) return null;
|
|
971
|
+
const text = decodeXml(v).trim();
|
|
972
|
+
const d = new Date(text);
|
|
973
|
+
return Number.isNaN(d.getTime()) ? text : d;
|
|
974
|
+
}
|
|
975
|
+
default: {
|
|
976
|
+
if (v === void 0) {
|
|
977
|
+
const is = inner ? IS_EL.exec(inner) : null;
|
|
978
|
+
return is ? is[1] ? richText(is[1]) : "" : null;
|
|
979
|
+
}
|
|
980
|
+
const text = v.trim();
|
|
981
|
+
const n = Number(text);
|
|
982
|
+
if (text === "" || Number.isNaN(n)) return decodeXml(v);
|
|
983
|
+
if (ctx.dateStyles[style] && Number.isFinite(n)) return serialToDate(n, ctx.utc, ctx.date1904);
|
|
984
|
+
return n;
|
|
985
|
+
}
|
|
986
|
+
}
|
|
987
|
+
}
|
|
988
|
+
function parseSheet(xml, ctx) {
|
|
989
|
+
const start = SHEET_DATA.exec(xml);
|
|
990
|
+
if (!start) return [];
|
|
991
|
+
const grid = [];
|
|
992
|
+
let width = 0;
|
|
993
|
+
let row = -1;
|
|
994
|
+
let col = -1;
|
|
995
|
+
const dataEnd = xml.lastIndexOf("sheetData>");
|
|
996
|
+
ROW_OR_CELL.lastIndex = start.index;
|
|
997
|
+
let m;
|
|
998
|
+
while ((m = ROW_OR_CELL.exec(xml)) !== null) {
|
|
999
|
+
if (m.index > dataEnd) break;
|
|
1000
|
+
const prefix = m[1] ?? "";
|
|
1001
|
+
const attrs = m[3] ?? "";
|
|
1002
|
+
if (m[2] === "row") {
|
|
1003
|
+
const r = getAttr(attrs, "r");
|
|
1004
|
+
row = r ? Number(r) - 1 : row + 1;
|
|
1005
|
+
col = -1;
|
|
1006
|
+
continue;
|
|
1007
|
+
}
|
|
1008
|
+
let inner = "";
|
|
1009
|
+
if (!m[4]) {
|
|
1010
|
+
const close = `</${prefix}c>`;
|
|
1011
|
+
const end = xml.indexOf(close, ROW_OR_CELL.lastIndex);
|
|
1012
|
+
if (end < 0) break;
|
|
1013
|
+
inner = xml.slice(ROW_OR_CELL.lastIndex, end);
|
|
1014
|
+
ROW_OR_CELL.lastIndex = end + close.length;
|
|
1015
|
+
}
|
|
1016
|
+
let ref;
|
|
1017
|
+
let type;
|
|
1018
|
+
let style = 0;
|
|
1019
|
+
CELL_ATTR.lastIndex = 0;
|
|
1020
|
+
let a;
|
|
1021
|
+
while ((a = CELL_ATTR.exec(attrs)) !== null) {
|
|
1022
|
+
const value2 = a[2] ?? a[3] ?? "";
|
|
1023
|
+
if (a[1] === "r") ref = value2;
|
|
1024
|
+
else if (a[1] === "t") type = value2;
|
|
1025
|
+
else if (a[1] === "s") style = Number(value2);
|
|
1026
|
+
}
|
|
1027
|
+
if (ref) {
|
|
1028
|
+
const c = columnIndex(ref);
|
|
1029
|
+
col = c >= 0 ? c : col + 1;
|
|
1030
|
+
const r = rowIndex(ref);
|
|
1031
|
+
if (r >= 0) row = r;
|
|
1032
|
+
} else {
|
|
1033
|
+
col++;
|
|
1034
|
+
}
|
|
1035
|
+
if (!inner) continue;
|
|
1036
|
+
if (!(row >= 0 && row < MAX_ROWS2 && col >= 0 && col < MAX_COLS2)) continue;
|
|
1037
|
+
const value = cellValue(type, style, inner, ctx);
|
|
1038
|
+
if (value === null) continue;
|
|
1039
|
+
(grid[row] ??= [])[col] = value;
|
|
1040
|
+
if (col + 1 > width) width = col + 1;
|
|
1041
|
+
}
|
|
1042
|
+
const rows = new Array(grid.length);
|
|
1043
|
+
for (let r = 0; r < grid.length; r++) {
|
|
1044
|
+
const src = grid[r];
|
|
1045
|
+
const out = new Array(width);
|
|
1046
|
+
for (let c = 0; c < width; c++) out[c] = src?.[c] ?? null;
|
|
1047
|
+
rows[r] = out;
|
|
1048
|
+
}
|
|
1049
|
+
return rows;
|
|
1050
|
+
}
|
|
1051
|
+
async function readXlsx(data, options = {}) {
|
|
1052
|
+
const bytes = toBytes(data);
|
|
1053
|
+
const entries = readZipDirectory(bytes);
|
|
1054
|
+
const read = async (path) => {
|
|
1055
|
+
const entry = entries.get(path.toLowerCase());
|
|
1056
|
+
return entry ? decodeText(await readZipEntry(bytes, entry)) : null;
|
|
1057
|
+
};
|
|
1058
|
+
const rootRels = parseRels(await read("_rels/.rels"), "");
|
|
1059
|
+
let workbookPath = "xl/workbook.xml";
|
|
1060
|
+
for (const rel of rootRels.values()) {
|
|
1061
|
+
if (rel.type.endsWith("/officeDocument")) workbookPath = rel.target;
|
|
1062
|
+
}
|
|
1063
|
+
const workbookXml = await read(workbookPath);
|
|
1064
|
+
if (workbookXml === null) {
|
|
1065
|
+
throw new Error("sheetr: not a valid .xlsx file (the ZIP archive has no workbook)");
|
|
1066
|
+
}
|
|
1067
|
+
const baseDir = dirOf(workbookPath);
|
|
1068
|
+
const relsPath = `${baseDir}_rels/${workbookPath.slice(baseDir.length)}.rels`;
|
|
1069
|
+
const rels = parseRels(await read(relsPath), baseDir);
|
|
1070
|
+
let stringsPath = `${baseDir}sharedStrings.xml`;
|
|
1071
|
+
let stylesPath = `${baseDir}styles.xml`;
|
|
1072
|
+
for (const rel of rels.values()) {
|
|
1073
|
+
if (rel.type.endsWith("/sharedStrings")) stringsPath = rel.target;
|
|
1074
|
+
else if (rel.type.endsWith("/styles")) stylesPath = rel.target;
|
|
1075
|
+
}
|
|
1076
|
+
const ctx = {
|
|
1077
|
+
strings: parseSharedStrings(await read(stringsPath)),
|
|
1078
|
+
dateStyles: parseDateStyles(await read(stylesPath)),
|
|
1079
|
+
date1904: DATE_1904.test(workbookXml),
|
|
1080
|
+
utc: options.utc === true
|
|
1081
|
+
};
|
|
1082
|
+
const sheets = [];
|
|
1083
|
+
SHEET_TAG.lastIndex = 0;
|
|
1084
|
+
const tags = [];
|
|
1085
|
+
let m;
|
|
1086
|
+
while ((m = SHEET_TAG.exec(workbookXml)) !== null) tags.push(m[1] ?? "");
|
|
1087
|
+
for (const attrs of tags) {
|
|
1088
|
+
const name = getAttr(attrs, "name") ?? `Sheet${sheets.length + 1}`;
|
|
1089
|
+
const id = getAttr(attrs, REL_ID);
|
|
1090
|
+
const rel = id ? rels.get(id) : void 0;
|
|
1091
|
+
const xml = rel ? await read(rel.target) : null;
|
|
1092
|
+
sheets.push({ name, rows: xml ? parseSheet(xml, ctx) : [] });
|
|
1093
|
+
}
|
|
1094
|
+
return { sheets };
|
|
1095
|
+
}
|
|
1096
|
+
function toObjects(rows) {
|
|
1097
|
+
const [head, ...body] = rows;
|
|
1098
|
+
if (!head) return [];
|
|
1099
|
+
let width = head.length;
|
|
1100
|
+
for (const row of body) if (row.length > width) width = row.length;
|
|
1101
|
+
const keys = [];
|
|
1102
|
+
const used = /* @__PURE__ */ new Set();
|
|
1103
|
+
for (let i = 0; i < width; i++) {
|
|
1104
|
+
const cell = head[i];
|
|
1105
|
+
let key = cell === null || cell === void 0 || cell === "" ? `Column${i + 1}` : cell instanceof Date ? cell.toISOString() : String(cell);
|
|
1106
|
+
if (used.has(key)) {
|
|
1107
|
+
let n = 2;
|
|
1108
|
+
while (used.has(`${key}_${n}`)) n++;
|
|
1109
|
+
key = `${key}_${n}`;
|
|
1110
|
+
}
|
|
1111
|
+
used.add(key);
|
|
1112
|
+
keys.push(key);
|
|
1113
|
+
}
|
|
1114
|
+
const out = [];
|
|
1115
|
+
for (const row of body) {
|
|
1116
|
+
if (!row.some((v) => v !== null && v !== void 0 && v !== "")) continue;
|
|
1117
|
+
const obj = {};
|
|
1118
|
+
keys.forEach((key, i) => {
|
|
1119
|
+
obj[key] = row[i] ?? null;
|
|
1120
|
+
});
|
|
1121
|
+
out.push(obj);
|
|
1122
|
+
}
|
|
1123
|
+
return out;
|
|
1124
|
+
}
|
|
1125
|
+
export {
|
|
1126
|
+
XLSX_MIME_TYPE,
|
|
1127
|
+
readXlsx,
|
|
1128
|
+
toObjects,
|
|
1129
|
+
toXlsx,
|
|
1130
|
+
toXlsxAsync
|
|
1131
|
+
};
|