@noy-db/as-xlsx 0.1.0-pre.10
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/LICENSE +21 -0
- package/README.md +138 -0
- package/dist/index.cjs +624 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +274 -0
- package/dist/index.d.ts +274 -0
- package/dist/index.js +579 -0
- package/dist/index.js.map +1 -0
- package/package.json +75 -0
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,624 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name in all)
|
|
10
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
28
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
+
|
|
30
|
+
// src/index.ts
|
|
31
|
+
var index_exports = {};
|
|
32
|
+
__export(index_exports, {
|
|
33
|
+
XlsxDictAmbiguityError: () => XlsxDictAmbiguityError,
|
|
34
|
+
colLetter: () => colLetter,
|
|
35
|
+
download: () => download,
|
|
36
|
+
fromBytes: () => fromBytes,
|
|
37
|
+
readXlsx: () => readXlsx,
|
|
38
|
+
toBytes: () => toBytes,
|
|
39
|
+
toBytesFromCollection: () => toBytesFromCollection,
|
|
40
|
+
write: () => write,
|
|
41
|
+
writeXlsx: () => writeXlsx
|
|
42
|
+
});
|
|
43
|
+
module.exports = __toCommonJS(index_exports);
|
|
44
|
+
|
|
45
|
+
// src/xlsx.ts
|
|
46
|
+
var import_as_zip = require("@noy-db/as-zip");
|
|
47
|
+
var XML_HEADER = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>';
|
|
48
|
+
var ENCODER = new TextEncoder();
|
|
49
|
+
async function writeXlsx(sheets) {
|
|
50
|
+
if (sheets.length === 0) {
|
|
51
|
+
throw new Error("writeXlsx: at least one sheet is required");
|
|
52
|
+
}
|
|
53
|
+
const seen = /* @__PURE__ */ new Set();
|
|
54
|
+
const safeSheets = sheets.map((s, i) => {
|
|
55
|
+
let name = truncateSheetName(s.name || `Sheet${i + 1}`);
|
|
56
|
+
let n = 1;
|
|
57
|
+
while (seen.has(name)) {
|
|
58
|
+
const suffix = `(${n++})`;
|
|
59
|
+
name = truncateSheetName(name.slice(0, 31 - suffix.length) + suffix);
|
|
60
|
+
}
|
|
61
|
+
seen.add(name);
|
|
62
|
+
return { ...s, name };
|
|
63
|
+
});
|
|
64
|
+
const sharedStrings = [];
|
|
65
|
+
const stringIndex = /* @__PURE__ */ new Map();
|
|
66
|
+
const internString = (s) => {
|
|
67
|
+
const existing = stringIndex.get(s);
|
|
68
|
+
if (existing !== void 0) return existing;
|
|
69
|
+
const idx = sharedStrings.length;
|
|
70
|
+
sharedStrings.push(s);
|
|
71
|
+
stringIndex.set(s, idx);
|
|
72
|
+
return idx;
|
|
73
|
+
};
|
|
74
|
+
const sheetXmls = safeSheets.map((sheet) => {
|
|
75
|
+
const lines = [
|
|
76
|
+
XML_HEADER,
|
|
77
|
+
'<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">',
|
|
78
|
+
"<sheetData>"
|
|
79
|
+
];
|
|
80
|
+
let rowNum = 0;
|
|
81
|
+
if (sheet.header && sheet.header.length > 0) {
|
|
82
|
+
rowNum++;
|
|
83
|
+
const cells = sheet.header.map((h, i) => {
|
|
84
|
+
const idx = internString(String(h));
|
|
85
|
+
return `<c r="${colLetter(i + 1)}${rowNum}" t="s"><v>${idx}</v></c>`;
|
|
86
|
+
}).join("");
|
|
87
|
+
lines.push(`<row r="${rowNum}">${cells}</row>`);
|
|
88
|
+
}
|
|
89
|
+
for (const row of sheet.rows) {
|
|
90
|
+
rowNum++;
|
|
91
|
+
const cells = row.map((value, i) => cellXml(value, i + 1, rowNum, internString)).join("");
|
|
92
|
+
lines.push(`<row r="${rowNum}">${cells}</row>`);
|
|
93
|
+
}
|
|
94
|
+
lines.push("</sheetData>", "</worksheet>");
|
|
95
|
+
return lines.join("");
|
|
96
|
+
});
|
|
97
|
+
const sheetEntries = safeSheets.map((s, i) => ({
|
|
98
|
+
index: i + 1,
|
|
99
|
+
id: `rId${i + 1}`,
|
|
100
|
+
name: s.name,
|
|
101
|
+
path: `xl/worksheets/sheet${i + 1}.xml`
|
|
102
|
+
}));
|
|
103
|
+
const contentTypes = [
|
|
104
|
+
XML_HEADER,
|
|
105
|
+
'<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">',
|
|
106
|
+
'<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>',
|
|
107
|
+
'<Default Extension="xml" ContentType="application/xml"/>',
|
|
108
|
+
'<Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/>',
|
|
109
|
+
...sheetEntries.map(
|
|
110
|
+
(s) => `<Override PartName="/${s.path}" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>`
|
|
111
|
+
),
|
|
112
|
+
'<Override PartName="/xl/sharedStrings.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml"/>',
|
|
113
|
+
"</Types>"
|
|
114
|
+
].join("");
|
|
115
|
+
const rootRels = XML_HEADER + '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/></Relationships>';
|
|
116
|
+
const workbookXml = [
|
|
117
|
+
XML_HEADER,
|
|
118
|
+
'<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">',
|
|
119
|
+
"<sheets>",
|
|
120
|
+
...sheetEntries.map(
|
|
121
|
+
(s) => `<sheet name="${escapeXmlAttr(s.name)}" sheetId="${s.index}" r:id="${s.id}"/>`
|
|
122
|
+
),
|
|
123
|
+
"</sheets>",
|
|
124
|
+
"</workbook>"
|
|
125
|
+
].join("");
|
|
126
|
+
const workbookRels = [
|
|
127
|
+
XML_HEADER,
|
|
128
|
+
'<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">',
|
|
129
|
+
...sheetEntries.map(
|
|
130
|
+
(s) => `<Relationship Id="${s.id}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet${s.index}.xml"/>`
|
|
131
|
+
),
|
|
132
|
+
`<Relationship Id="rIdSharedStrings" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings" Target="sharedStrings.xml"/>`,
|
|
133
|
+
"</Relationships>"
|
|
134
|
+
].join("");
|
|
135
|
+
const sharedStringsXml = [
|
|
136
|
+
XML_HEADER,
|
|
137
|
+
`<sst xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" count="${sharedStrings.length}" uniqueCount="${sharedStrings.length}">`,
|
|
138
|
+
...sharedStrings.map((s) => `<si><t xml:space="preserve">${escapeXmlText(s)}</t></si>`),
|
|
139
|
+
"</sst>"
|
|
140
|
+
].join("");
|
|
141
|
+
const entries = [
|
|
142
|
+
{ path: "[Content_Types].xml", bytes: ENCODER.encode(contentTypes) },
|
|
143
|
+
{ path: "_rels/.rels", bytes: ENCODER.encode(rootRels) },
|
|
144
|
+
{ path: "xl/workbook.xml", bytes: ENCODER.encode(workbookXml) },
|
|
145
|
+
{ path: "xl/_rels/workbook.xml.rels", bytes: ENCODER.encode(workbookRels) },
|
|
146
|
+
{ path: "xl/sharedStrings.xml", bytes: ENCODER.encode(sharedStringsXml) },
|
|
147
|
+
...sheetEntries.map((s, i) => ({ path: s.path, bytes: ENCODER.encode(sheetXmls[i] ?? "") }))
|
|
148
|
+
];
|
|
149
|
+
return await (0, import_as_zip.writeZip)(entries);
|
|
150
|
+
}
|
|
151
|
+
function cellXml(value, colIdx, rowNum, intern) {
|
|
152
|
+
const ref = `${colLetter(colIdx)}${rowNum}`;
|
|
153
|
+
if (value === null || value === void 0 || value === "") return `<c r="${ref}"/>`;
|
|
154
|
+
if (typeof value === "number" && Number.isFinite(value)) {
|
|
155
|
+
return `<c r="${ref}"><v>${value}</v></c>`;
|
|
156
|
+
}
|
|
157
|
+
if (typeof value === "boolean") {
|
|
158
|
+
return `<c r="${ref}" t="b"><v>${value ? 1 : 0}</v></c>`;
|
|
159
|
+
}
|
|
160
|
+
const s = value instanceof Date ? value.toISOString() : typeof value === "string" ? value : JSON.stringify(value);
|
|
161
|
+
const idx = intern(s);
|
|
162
|
+
return `<c r="${ref}" t="s"><v>${idx}</v></c>`;
|
|
163
|
+
}
|
|
164
|
+
function colLetter(n) {
|
|
165
|
+
let s = "";
|
|
166
|
+
let x = n;
|
|
167
|
+
while (x > 0) {
|
|
168
|
+
const r = (x - 1) % 26;
|
|
169
|
+
s = String.fromCharCode(65 + r) + s;
|
|
170
|
+
x = Math.floor((x - 1) / 26);
|
|
171
|
+
}
|
|
172
|
+
return s;
|
|
173
|
+
}
|
|
174
|
+
function truncateSheetName(name) {
|
|
175
|
+
const cleaned = name.replace(/[:/\\?*[\]]/g, "_");
|
|
176
|
+
if (cleaned.length <= 31) return cleaned;
|
|
177
|
+
return cleaned.slice(0, 30) + "\u2026";
|
|
178
|
+
}
|
|
179
|
+
function escapeXmlText(s) {
|
|
180
|
+
return s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/\r/g, " ");
|
|
181
|
+
}
|
|
182
|
+
function escapeXmlAttr(s) {
|
|
183
|
+
return escapeXmlText(s).replace(/"/g, """);
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
// src/read.ts
|
|
187
|
+
var import_as_zip2 = require("@noy-db/as-zip");
|
|
188
|
+
var import_fast_xml_parser = require("fast-xml-parser");
|
|
189
|
+
var PARSER = new import_fast_xml_parser.XMLParser({
|
|
190
|
+
ignoreAttributes: false,
|
|
191
|
+
attributeNamePrefix: "@_",
|
|
192
|
+
parseTagValue: false,
|
|
193
|
+
parseAttributeValue: false,
|
|
194
|
+
trimValues: false,
|
|
195
|
+
isArray: (name) => name === "sheet" || name === "row" || name === "c" || name === "si" || name === "Relationship"
|
|
196
|
+
});
|
|
197
|
+
async function readXlsx(bytes) {
|
|
198
|
+
const entries = await (0, import_as_zip2.readZip)(bytes);
|
|
199
|
+
const partByPath = /* @__PURE__ */ new Map();
|
|
200
|
+
for (const e of entries) partByPath.set(e.path, e.bytes);
|
|
201
|
+
const sharedStrings = readSharedStrings(partByPath.get("xl/sharedStrings.xml"));
|
|
202
|
+
const sheetMeta = readWorkbook(partByPath.get("xl/workbook.xml"));
|
|
203
|
+
const rels = readWorkbookRels(partByPath.get("xl/_rels/workbook.xml.rels"));
|
|
204
|
+
const sheets = [];
|
|
205
|
+
for (const meta of sheetMeta) {
|
|
206
|
+
const target = rels.get(meta.rId);
|
|
207
|
+
if (target === void 0) {
|
|
208
|
+
throw new Error(
|
|
209
|
+
`as-xlsx.readXlsx: workbook references rId="${meta.rId}" but the rels file has no matching target`
|
|
210
|
+
);
|
|
211
|
+
}
|
|
212
|
+
const sheetPath = `xl/${target}`;
|
|
213
|
+
const sheetBytes = partByPath.get(sheetPath);
|
|
214
|
+
if (sheetBytes === void 0) {
|
|
215
|
+
throw new Error(`as-xlsx.readXlsx: missing sheet part ${sheetPath}`);
|
|
216
|
+
}
|
|
217
|
+
sheets.push({
|
|
218
|
+
name: meta.name,
|
|
219
|
+
rows: readSheet(sheetBytes, sharedStrings)
|
|
220
|
+
});
|
|
221
|
+
}
|
|
222
|
+
return { sheets };
|
|
223
|
+
}
|
|
224
|
+
function decodeXml(bytes) {
|
|
225
|
+
return new TextDecoder().decode(bytes);
|
|
226
|
+
}
|
|
227
|
+
function parseStrict(xml, where) {
|
|
228
|
+
const validation = import_fast_xml_parser.XMLValidator.validate(xml);
|
|
229
|
+
if (validation !== true) {
|
|
230
|
+
const err = validation.err;
|
|
231
|
+
throw new Error(
|
|
232
|
+
`as-xlsx.readXlsx: ${where} is not valid XML (${err.code} at line ${err.line}: ${err.msg})`
|
|
233
|
+
);
|
|
234
|
+
}
|
|
235
|
+
try {
|
|
236
|
+
return PARSER.parse(xml);
|
|
237
|
+
} catch (err) {
|
|
238
|
+
throw new Error(`as-xlsx.readXlsx: failed to parse ${where} (${err.message})`);
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
function readSharedStrings(bytes) {
|
|
242
|
+
if (bytes === void 0) return [];
|
|
243
|
+
const parsed = parseStrict(decodeXml(bytes), "xl/sharedStrings.xml");
|
|
244
|
+
const sst = parsed.sst;
|
|
245
|
+
if (sst === null || sst === void 0 || typeof sst !== "object") return [];
|
|
246
|
+
const items = sst.si ?? [];
|
|
247
|
+
if (!Array.isArray(items)) return [];
|
|
248
|
+
return items.map((si) => {
|
|
249
|
+
if (si === null || typeof si !== "object") return "";
|
|
250
|
+
const t = si.t;
|
|
251
|
+
return textValue(t);
|
|
252
|
+
});
|
|
253
|
+
}
|
|
254
|
+
function readWorkbook(bytes) {
|
|
255
|
+
if (bytes === void 0) {
|
|
256
|
+
throw new Error("as-xlsx.readXlsx: missing xl/workbook.xml");
|
|
257
|
+
}
|
|
258
|
+
const parsed = parseStrict(decodeXml(bytes), "xl/workbook.xml");
|
|
259
|
+
const workbook = parsed.workbook;
|
|
260
|
+
if (workbook === null || workbook === void 0 || typeof workbook !== "object") {
|
|
261
|
+
throw new Error("as-xlsx.readXlsx: xl/workbook.xml has no <workbook> root");
|
|
262
|
+
}
|
|
263
|
+
const sheetsObj = workbook.sheets;
|
|
264
|
+
if (sheetsObj === null || sheetsObj === void 0 || typeof sheetsObj !== "object") {
|
|
265
|
+
return [];
|
|
266
|
+
}
|
|
267
|
+
const sheetEntries = sheetsObj.sheet ?? [];
|
|
268
|
+
if (!Array.isArray(sheetEntries)) return [];
|
|
269
|
+
return sheetEntries.map((s) => {
|
|
270
|
+
const obj = s;
|
|
271
|
+
return {
|
|
272
|
+
name: stringAttr(obj["@_name"]),
|
|
273
|
+
sheetId: stringAttr(obj["@_sheetId"]),
|
|
274
|
+
rId: stringAttr(obj["@_r:id"]) || stringAttr(obj["@_id"])
|
|
275
|
+
};
|
|
276
|
+
});
|
|
277
|
+
}
|
|
278
|
+
function readWorkbookRels(bytes) {
|
|
279
|
+
if (bytes === void 0) {
|
|
280
|
+
throw new Error("as-xlsx.readXlsx: missing xl/_rels/workbook.xml.rels");
|
|
281
|
+
}
|
|
282
|
+
const parsed = parseStrict(decodeXml(bytes), "xl/_rels/workbook.xml.rels");
|
|
283
|
+
const root = parsed.Relationships;
|
|
284
|
+
if (root === null || root === void 0 || typeof root !== "object") {
|
|
285
|
+
return /* @__PURE__ */ new Map();
|
|
286
|
+
}
|
|
287
|
+
const rels = root.Relationship ?? [];
|
|
288
|
+
if (!Array.isArray(rels)) return /* @__PURE__ */ new Map();
|
|
289
|
+
const map = /* @__PURE__ */ new Map();
|
|
290
|
+
for (const r of rels) {
|
|
291
|
+
const obj = r;
|
|
292
|
+
const id = stringAttr(obj["@_Id"]);
|
|
293
|
+
const target = stringAttr(obj["@_Target"]);
|
|
294
|
+
if (id) map.set(id, target);
|
|
295
|
+
}
|
|
296
|
+
return map;
|
|
297
|
+
}
|
|
298
|
+
function readSheet(bytes, sharedStrings) {
|
|
299
|
+
const parsed = parseStrict(decodeXml(bytes), "sheet");
|
|
300
|
+
const ws = parsed.worksheet;
|
|
301
|
+
if (ws === null || ws === void 0 || typeof ws !== "object") return [];
|
|
302
|
+
const sheetData = ws.sheetData;
|
|
303
|
+
if (sheetData === null || sheetData === void 0 || typeof sheetData !== "object") return [];
|
|
304
|
+
const rowEntries = sheetData.row ?? [];
|
|
305
|
+
if (!Array.isArray(rowEntries)) return [];
|
|
306
|
+
const rows = [];
|
|
307
|
+
for (const row of rowEntries) {
|
|
308
|
+
if (row === null || typeof row !== "object") {
|
|
309
|
+
rows.push({});
|
|
310
|
+
continue;
|
|
311
|
+
}
|
|
312
|
+
const cells = row.c ?? [];
|
|
313
|
+
if (!Array.isArray(cells)) {
|
|
314
|
+
rows.push({});
|
|
315
|
+
continue;
|
|
316
|
+
}
|
|
317
|
+
const out = {};
|
|
318
|
+
for (const c of cells) {
|
|
319
|
+
if (c === null || typeof c !== "object") continue;
|
|
320
|
+
const cellObj = c;
|
|
321
|
+
const ref = stringAttr(cellObj["@_r"]);
|
|
322
|
+
if (!ref) continue;
|
|
323
|
+
const col = letterFromRef(ref);
|
|
324
|
+
const t = cellObj["@_t"];
|
|
325
|
+
const v = cellObj["v"];
|
|
326
|
+
const text = textValue(v);
|
|
327
|
+
if (text === "") {
|
|
328
|
+
if (t === "s") {
|
|
329
|
+
out[col] = "";
|
|
330
|
+
continue;
|
|
331
|
+
}
|
|
332
|
+
continue;
|
|
333
|
+
}
|
|
334
|
+
if (t === "s") {
|
|
335
|
+
const idx = Number(text);
|
|
336
|
+
if (!Number.isInteger(idx) || idx < 0 || idx >= sharedStrings.length) {
|
|
337
|
+
throw new Error(
|
|
338
|
+
`as-xlsx.readXlsx: shared-string reference ${idx} out of range (table has ${sharedStrings.length} entries)`
|
|
339
|
+
);
|
|
340
|
+
}
|
|
341
|
+
out[col] = sharedStrings[idx];
|
|
342
|
+
} else if (t === "b") {
|
|
343
|
+
out[col] = text === "1";
|
|
344
|
+
} else if (t === "str" || t === "inlineStr") {
|
|
345
|
+
out[col] = text;
|
|
346
|
+
} else {
|
|
347
|
+
const n = Number(text);
|
|
348
|
+
out[col] = Number.isFinite(n) ? n : text;
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
rows.push(out);
|
|
352
|
+
}
|
|
353
|
+
return rows;
|
|
354
|
+
}
|
|
355
|
+
function letterFromRef(ref) {
|
|
356
|
+
let i = 0;
|
|
357
|
+
while (i < ref.length && /[A-Z]/.test(ref[i])) i++;
|
|
358
|
+
return ref.slice(0, i);
|
|
359
|
+
}
|
|
360
|
+
function textValue(raw) {
|
|
361
|
+
if (raw === null || raw === void 0) return "";
|
|
362
|
+
if (typeof raw === "string") return raw;
|
|
363
|
+
if (typeof raw === "number" || typeof raw === "boolean") return String(raw);
|
|
364
|
+
if (typeof raw === "object") {
|
|
365
|
+
const txt = raw["#text"];
|
|
366
|
+
if (txt !== void 0) return textValue(txt);
|
|
367
|
+
}
|
|
368
|
+
return "";
|
|
369
|
+
}
|
|
370
|
+
function stringAttr(raw) {
|
|
371
|
+
if (raw === void 0 || raw === null) return "";
|
|
372
|
+
if (typeof raw === "string") return raw;
|
|
373
|
+
if (typeof raw === "number" || typeof raw === "boolean") return String(raw);
|
|
374
|
+
return "";
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
// src/index.ts
|
|
378
|
+
var import_hub = require("@noy-db/hub");
|
|
379
|
+
async function toBytesFromCollection(vault, collectionName) {
|
|
380
|
+
return toBytes(vault, {
|
|
381
|
+
sheets: [{ name: collectionName, collection: collectionName }]
|
|
382
|
+
});
|
|
383
|
+
}
|
|
384
|
+
async function toBytes(vault, options) {
|
|
385
|
+
vault.assertCanExport("plaintext", "xlsx");
|
|
386
|
+
if (options.sheets.length === 0) {
|
|
387
|
+
throw new Error("as-xlsx: at least one sheet is required");
|
|
388
|
+
}
|
|
389
|
+
const materialisedSheets = [];
|
|
390
|
+
for (const sheetOpt of options.sheets) {
|
|
391
|
+
const collection = vault.collection(sheetOpt.collection);
|
|
392
|
+
const list = await collection.list();
|
|
393
|
+
const records = [];
|
|
394
|
+
for (const item of list) {
|
|
395
|
+
const r = item;
|
|
396
|
+
if (sheetOpt.filter && !sheetOpt.filter(r)) continue;
|
|
397
|
+
records.push(r);
|
|
398
|
+
}
|
|
399
|
+
const columns = sheetOpt.columns ?? inferColumns(records);
|
|
400
|
+
materialisedSheets.push({
|
|
401
|
+
name: sheetOpt.name,
|
|
402
|
+
header: columns,
|
|
403
|
+
rows: records.map((r) => columns.map((c) => r[c] ?? null))
|
|
404
|
+
});
|
|
405
|
+
}
|
|
406
|
+
return writeXlsx(materialisedSheets);
|
|
407
|
+
}
|
|
408
|
+
async function download(vault, options) {
|
|
409
|
+
const bytes = await toBytes(vault, options);
|
|
410
|
+
const filename = options.filename ?? "export.xlsx";
|
|
411
|
+
const blob = new Blob([bytes], {
|
|
412
|
+
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
|
|
413
|
+
});
|
|
414
|
+
const url = URL.createObjectURL(blob);
|
|
415
|
+
const a = document.createElement("a");
|
|
416
|
+
a.href = url;
|
|
417
|
+
a.download = filename;
|
|
418
|
+
a.click();
|
|
419
|
+
URL.revokeObjectURL(url);
|
|
420
|
+
}
|
|
421
|
+
async function write(vault, path, options) {
|
|
422
|
+
if (options.acknowledgeRisks !== true) {
|
|
423
|
+
throw new Error(
|
|
424
|
+
`as-xlsx.write: acknowledgeRisks: true is required for on-disk plaintext output. This call creates a persistent plaintext xlsx outside noy-db's encrypted storage \u2014 see docs/patterns/as-exports.md \xA7"The three tiers of \\"plaintext out\\""`
|
|
425
|
+
);
|
|
426
|
+
}
|
|
427
|
+
const bytes = await toBytes(vault, options);
|
|
428
|
+
const { writeFile } = await import("fs/promises");
|
|
429
|
+
await writeFile(path, bytes);
|
|
430
|
+
}
|
|
431
|
+
function inferColumns(records) {
|
|
432
|
+
const seen = /* @__PURE__ */ new Set();
|
|
433
|
+
const out = [];
|
|
434
|
+
for (const r of records) {
|
|
435
|
+
for (const key of Object.keys(r)) {
|
|
436
|
+
if (!seen.has(key)) {
|
|
437
|
+
seen.add(key);
|
|
438
|
+
out.push(key);
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
return out;
|
|
443
|
+
}
|
|
444
|
+
var XlsxDictAmbiguityError = class extends Error {
|
|
445
|
+
constructor(column, label) {
|
|
446
|
+
super(
|
|
447
|
+
`as-xlsx.fromBytes: dict for column "${column}" has ambiguous label "${label}" \u2014 it maps to more than one key across locales. Supply a stricter dict or resolve the label conflict before importing.`
|
|
448
|
+
);
|
|
449
|
+
this.column = column;
|
|
450
|
+
this.label = label;
|
|
451
|
+
this.name = "XlsxDictAmbiguityError";
|
|
452
|
+
}
|
|
453
|
+
column;
|
|
454
|
+
label;
|
|
455
|
+
};
|
|
456
|
+
async function fromBytes(vault, bytes, options) {
|
|
457
|
+
vault.assertCanImport("plaintext", "xlsx");
|
|
458
|
+
const policy = options.policy ?? "merge";
|
|
459
|
+
const idKey = options.idKey ?? "id";
|
|
460
|
+
const types = options.fieldTypes ?? {};
|
|
461
|
+
const headerRowIdx = (options.headerRow ?? 1) - 1;
|
|
462
|
+
if (headerRowIdx < 0) {
|
|
463
|
+
throw new Error("as-xlsx.fromBytes: headerRow must be 1-based and >= 1");
|
|
464
|
+
}
|
|
465
|
+
const decoded = await readXlsx(bytes);
|
|
466
|
+
if (decoded.sheets.length === 0) {
|
|
467
|
+
return emptyXlsxPlan(vault, options.collection, policy, idKey);
|
|
468
|
+
}
|
|
469
|
+
const sheet = options.sheet === void 0 ? decoded.sheets[0] : decoded.sheets.find((s) => s.name === options.sheet);
|
|
470
|
+
if (sheet === void 0) {
|
|
471
|
+
throw new Error(
|
|
472
|
+
`as-xlsx.fromBytes: workbook has no sheet named "${options.sheet}". Available: ${decoded.sheets.map((s) => `"${s.name}"`).join(", ")}`
|
|
473
|
+
);
|
|
474
|
+
}
|
|
475
|
+
const allRows = sheet.rows;
|
|
476
|
+
if (allRows.length <= headerRowIdx) {
|
|
477
|
+
return emptyXlsxPlan(vault, options.collection, policy, idKey);
|
|
478
|
+
}
|
|
479
|
+
const headerRow = allRows[headerRowIdx];
|
|
480
|
+
const colToField = /* @__PURE__ */ new Map();
|
|
481
|
+
for (const [col, value] of Object.entries(headerRow)) {
|
|
482
|
+
const fieldName = headerCellToField(value);
|
|
483
|
+
if (fieldName === "") continue;
|
|
484
|
+
colToField.set(col, fieldName);
|
|
485
|
+
}
|
|
486
|
+
const invertMaps = /* @__PURE__ */ new Map();
|
|
487
|
+
const allFields = new Set(colToField.values());
|
|
488
|
+
for (const field of allFields) {
|
|
489
|
+
const explicitEntries = options.dicts?.[field];
|
|
490
|
+
if (explicitEntries !== void 0 && explicitEntries.length > 0) {
|
|
491
|
+
invertMaps.set(field, buildInversionMap(field, explicitEntries));
|
|
492
|
+
continue;
|
|
493
|
+
}
|
|
494
|
+
try {
|
|
495
|
+
const vaultEntries = await vault.dictionary(field).list();
|
|
496
|
+
if (vaultEntries.length > 0) {
|
|
497
|
+
invertMaps.set(field, buildInversionMap(field, vaultEntries));
|
|
498
|
+
}
|
|
499
|
+
} catch {
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
const records = [];
|
|
503
|
+
for (let i = headerRowIdx + 1; i < allRows.length; i++) {
|
|
504
|
+
const row = allRows[i];
|
|
505
|
+
const record = {};
|
|
506
|
+
let hasAny = false;
|
|
507
|
+
for (const [col, value] of Object.entries(row)) {
|
|
508
|
+
const field = colToField.get(col);
|
|
509
|
+
if (field === void 0) continue;
|
|
510
|
+
const coerced = coerceXlsxCell(value, types[field]);
|
|
511
|
+
if (coerced !== void 0) {
|
|
512
|
+
const invMap = invertMaps.get(field);
|
|
513
|
+
if (invMap !== void 0 && typeof coerced === "string") {
|
|
514
|
+
record[field] = invMap.get(coerced) ?? coerced;
|
|
515
|
+
} else {
|
|
516
|
+
record[field] = coerced;
|
|
517
|
+
}
|
|
518
|
+
hasAny = true;
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
if (hasAny) records.push(record);
|
|
522
|
+
}
|
|
523
|
+
const plan = await (0, import_hub.diffVault)(vault, { [options.collection]: records }, {
|
|
524
|
+
collections: [options.collection],
|
|
525
|
+
idKey
|
|
526
|
+
});
|
|
527
|
+
return {
|
|
528
|
+
plan,
|
|
529
|
+
policy,
|
|
530
|
+
async apply() {
|
|
531
|
+
await vault.noydb.transaction((tx) => {
|
|
532
|
+
const txVault = tx.vault(vault.name);
|
|
533
|
+
for (const entry of plan.added) {
|
|
534
|
+
txVault.collection(entry.collection).put(entry.id, entry.record);
|
|
535
|
+
}
|
|
536
|
+
if (policy !== "insert-only") {
|
|
537
|
+
for (const entry of plan.modified) {
|
|
538
|
+
txVault.collection(entry.collection).put(entry.id, entry.record);
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
if (policy === "replace") {
|
|
542
|
+
for (const entry of plan.deleted) {
|
|
543
|
+
txVault.collection(entry.collection).delete(entry.id);
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
});
|
|
547
|
+
}
|
|
548
|
+
};
|
|
549
|
+
}
|
|
550
|
+
async function emptyXlsxPlan(vault, collection, policy, idKey) {
|
|
551
|
+
const plan = await (0, import_hub.diffVault)(vault, { [collection]: [] }, { collections: [collection], idKey });
|
|
552
|
+
return { plan, policy, async apply() {
|
|
553
|
+
} };
|
|
554
|
+
}
|
|
555
|
+
function buildInversionMap(column, entries) {
|
|
556
|
+
const map = /* @__PURE__ */ new Map();
|
|
557
|
+
for (const entry of entries) {
|
|
558
|
+
for (const label of Object.values(entry.labels)) {
|
|
559
|
+
if (label === "") continue;
|
|
560
|
+
const existing = map.get(label);
|
|
561
|
+
if (existing !== void 0 && existing !== entry.key) {
|
|
562
|
+
throw new XlsxDictAmbiguityError(column, label);
|
|
563
|
+
}
|
|
564
|
+
map.set(label, entry.key);
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
return map;
|
|
568
|
+
}
|
|
569
|
+
function headerCellToField(value) {
|
|
570
|
+
if (typeof value === "string") return value;
|
|
571
|
+
if (typeof value === "number" || typeof value === "boolean") return String(value);
|
|
572
|
+
return "";
|
|
573
|
+
}
|
|
574
|
+
function coerceXlsxCell(value, type) {
|
|
575
|
+
if (value === void 0 || value === null) return void 0;
|
|
576
|
+
if (type === void 0) return value;
|
|
577
|
+
if (type === "string") {
|
|
578
|
+
if (typeof value === "string") return value;
|
|
579
|
+
if (typeof value === "number" || typeof value === "boolean") return String(value);
|
|
580
|
+
return void 0;
|
|
581
|
+
}
|
|
582
|
+
if (type === "number") {
|
|
583
|
+
if (typeof value === "number") return value;
|
|
584
|
+
const n = Number(value);
|
|
585
|
+
return Number.isFinite(n) ? n : void 0;
|
|
586
|
+
}
|
|
587
|
+
if (type === "boolean") {
|
|
588
|
+
if (typeof value === "boolean") return value;
|
|
589
|
+
if (value === "true" || value === 1) return true;
|
|
590
|
+
if (value === "false" || value === 0) return false;
|
|
591
|
+
return void 0;
|
|
592
|
+
}
|
|
593
|
+
if (type === "date") {
|
|
594
|
+
if (typeof value === "number" && Number.isFinite(value)) {
|
|
595
|
+
const ms = excelSerialToMs(value);
|
|
596
|
+
const d = new Date(ms);
|
|
597
|
+
return d.toISOString();
|
|
598
|
+
}
|
|
599
|
+
if (typeof value === "string") {
|
|
600
|
+
const d = new Date(value);
|
|
601
|
+
if (!Number.isNaN(d.getTime())) return d.toISOString();
|
|
602
|
+
}
|
|
603
|
+
return void 0;
|
|
604
|
+
}
|
|
605
|
+
return value;
|
|
606
|
+
}
|
|
607
|
+
function excelSerialToMs(serial) {
|
|
608
|
+
const EPOCH_OFFSET_DAYS = 25569;
|
|
609
|
+
const MS_PER_DAY = 864e5;
|
|
610
|
+
return Math.round((serial - EPOCH_OFFSET_DAYS) * MS_PER_DAY);
|
|
611
|
+
}
|
|
612
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
613
|
+
0 && (module.exports = {
|
|
614
|
+
XlsxDictAmbiguityError,
|
|
615
|
+
colLetter,
|
|
616
|
+
download,
|
|
617
|
+
fromBytes,
|
|
618
|
+
readXlsx,
|
|
619
|
+
toBytes,
|
|
620
|
+
toBytesFromCollection,
|
|
621
|
+
write,
|
|
622
|
+
writeXlsx
|
|
623
|
+
});
|
|
624
|
+
//# sourceMappingURL=index.cjs.map
|