@8ms/helpers 3.0.23 → 3.0.24

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.
Files changed (66) hide show
  1. package/dist/_virtual/_rolldown/runtime.cjs +1 -1
  2. package/dist/aws/glue/server/AwsGlue.cjs +2 -1
  3. package/dist/aws/glue/server/AwsGlue.mjs +2 -1
  4. package/dist/aws/lambda/server/AwsLambda.cjs +10 -8
  5. package/dist/aws/lambda/server/AwsLambda.mjs +10 -8
  6. package/dist/aws/s3/server/AwsS3.cjs +3 -2
  7. package/dist/aws/s3/server/AwsS3.mjs +3 -2
  8. package/dist/aws/ssm/server/AwsSsm.cjs +5 -4
  9. package/dist/aws/ssm/server/AwsSsm.mjs +5 -4
  10. package/dist/brightData/serpApi/server/buildGoogleSerpUrl.cjs +0 -2
  11. package/dist/brightData/serpApi/server/buildGoogleSerpUrl.mjs +0 -2
  12. package/dist/brightData/serpApi/server/buildGoogleTrendsUrl.cjs +0 -1
  13. package/dist/brightData/serpApi/server/buildGoogleTrendsUrl.mjs +0 -1
  14. package/dist/brightData/serpApi/server/getAsyncResults.cjs +7 -4
  15. package/dist/brightData/serpApi/server/getAsyncResults.mjs +7 -4
  16. package/dist/brightData/webScraperIde/server/getRealtime.cjs +10 -6
  17. package/dist/brightData/webScraperIde/server/getRealtime.mjs +10 -6
  18. package/dist/date/calculation.cjs +27 -24
  19. package/dist/date/calculation.mjs +27 -24
  20. package/dist/emsApi/awsTs/get.cjs +2 -1
  21. package/dist/emsApi/awsTs/get.mjs +2 -1
  22. package/dist/emsApi/awsTs/post.cjs +2 -1
  23. package/dist/emsApi/awsTs/post.mjs +2 -1
  24. package/dist/emsApi/vercel/get.cjs +2 -1
  25. package/dist/emsApi/vercel/get.mjs +2 -1
  26. package/dist/emsApi/vercel/post.cjs +2 -1
  27. package/dist/emsApi/vercel/post.mjs +2 -1
  28. package/dist/googleCloud/sheets/server/GoogleCloudSheets.d.cts +1 -1
  29. package/dist/googleCloud/sheets/server/GoogleCloudSheets.d.mts +1 -1
  30. package/dist/googlePageSpeed/server/GooglePageSpeed.cjs +2 -1
  31. package/dist/googlePageSpeed/server/GooglePageSpeed.mjs +2 -1
  32. package/dist/greenDomain/server/greenDomain.cjs +2 -1
  33. package/dist/greenDomain/server/greenDomain.mjs +2 -1
  34. package/dist/littleWarden/server/LittleWarden.cjs +2 -1
  35. package/dist/littleWarden/server/LittleWarden.mjs +2 -1
  36. package/dist/lumar/api/server/buildRequest.cjs +0 -1
  37. package/dist/lumar/api/server/buildRequest.mjs +0 -1
  38. package/dist/snapchat/server/Snapchat.cjs +3 -2
  39. package/dist/snapchat/server/Snapchat.mjs +3 -2
  40. package/dist/util/defaultTo.cjs +6 -3
  41. package/dist/util/defaultTo.mjs +6 -3
  42. package/dist/xlsx/cell.cjs +102 -0
  43. package/dist/xlsx/cell.d.cts +38 -0
  44. package/dist/xlsx/cell.d.mts +38 -0
  45. package/dist/xlsx/cell.mjs +97 -0
  46. package/dist/xlsx/column.cjs +37 -0
  47. package/dist/xlsx/column.d.cts +23 -0
  48. package/dist/xlsx/column.d.mts +23 -0
  49. package/dist/xlsx/column.mjs +35 -0
  50. package/dist/xlsx/createXlsx.cjs +138 -0
  51. package/dist/xlsx/createXlsx.d.cts +18 -0
  52. package/dist/xlsx/createXlsx.d.mts +18 -0
  53. package/dist/xlsx/createXlsx.mjs +136 -0
  54. package/dist/xlsx/index.cjs +18 -0
  55. package/dist/xlsx/index.d.cts +6 -0
  56. package/dist/xlsx/index.d.mts +6 -0
  57. package/dist/xlsx/index.mjs +6 -0
  58. package/dist/xlsx/modifyXlsx.cjs +125 -0
  59. package/dist/xlsx/modifyXlsx.d.cts +24 -0
  60. package/dist/xlsx/modifyXlsx.d.mts +24 -0
  61. package/dist/xlsx/modifyXlsx.mjs +124 -0
  62. package/dist/xlsx/sheet.cjs +36 -0
  63. package/dist/xlsx/sheet.d.cts +29 -0
  64. package/dist/xlsx/sheet.d.mts +29 -0
  65. package/dist/xlsx/sheet.mjs +34 -0
  66. package/package.json +97 -51
@@ -0,0 +1,136 @@
1
+ import { getColumLetter, getColumnWidth } from "./column.mjs";
2
+ import { buildCellXml, getCellValue, getEscapedXml } from "./cell.mjs";
3
+ import { getUniqueSheetNames } from "./sheet.mjs";
4
+ //#region src/xlsx/createXlsx.ts
5
+ /**
6
+ * Builds a complete .xlsx workbook from scratch, using jszip and hand-written
7
+ * OOXML rather than a spreadsheet library.
8
+ *
9
+ * Nothing here touches `fs`, so it runs in the browser as happily as on the
10
+ * server — a page can turn data it has already loaded straight into a download.
11
+ *
12
+ * jszip is an optional peer dependency imported dynamically, so consumers that
13
+ * never build a workbook neither install it nor pay for it in their bundle.
14
+ */
15
+ /** Style index of the bold row within the cellXfs list built by buildStylesXml. */
16
+ const HEADER_STYLE_INDEX = 1;
17
+ const XML_DECLARATION = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>`;
18
+ const CONTENT_TYPE = {
19
+ SHEET: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml",
20
+ STYLES: "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml",
21
+ WORKSHEET: "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"
22
+ };
23
+ const REL_TYPE = {
24
+ OFFICE_DOCUMENT: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument",
25
+ STYLES: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles",
26
+ WORKSHEET: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet"
27
+ };
28
+ const NAMESPACES = {
29
+ MAIN: "http://schemas.openxmlformats.org/spreadsheetml/2006/main",
30
+ RELATIONSHIP: "http://schemas.openxmlformats.org/officeDocument/2006/relationships",
31
+ PACKAGE_REL: "http://schemas.openxmlformats.org/package/2006/relationships",
32
+ CONTENT_TYPES: "http://schemas.openxmlformats.org/package/2006/content-types"
33
+ };
34
+ /**
35
+ * Minimal but valid styles part. Excel requires at least one border, one
36
+ * cellStyleXf and two fills (index 0 "none", index 1 "gray125") even when
37
+ * nothing references them. cellXfs index 1 is the bold header.
38
+ */
39
+ const buildStylesXml = () => {
40
+ return XML_DECLARATION + `<styleSheet xmlns="${NAMESPACES.MAIN}"><fonts count="2"><font><sz val="11"/><name val="Calibri"/></font><font><b/><sz val="11"/><name val="Calibri"/></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="2"><xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/><xf numFmtId="0" fontId="1" fillId="0" borderId="0" xfId="0" applyFont="1"/></cellXfs><cellStyles count="1"><cellStyle name="Normal" xfId="0" builtinId="0"/></cellStyles></styleSheet>`;
41
+ };
42
+ /**
43
+ * One worksheet part: column widths, an optional heading block, a bold header row
44
+ * from the column display names, then one row per data object in column order.
45
+ *
46
+ * <cols> must precede <sheetData> or Excel treats the file as corrupt.
47
+ */
48
+ const buildWorksheetXml = (sheet) => {
49
+ const heading = sheet?.heading || [];
50
+ const headerRow = 0 === heading.length ? 1 : heading.length + 2;
51
+ const colsXml = sheet.columns.map((column, index) => {
52
+ const position = index + 1;
53
+ return `<col min="${position}" max="${position}" width="${getColumnWidth(column, sheet.data)}" customWidth="1"/>`;
54
+ }).join("");
55
+ const headingXml = heading.map((line, index) => {
56
+ const styleAttr = 0 === index ? ` s="${HEADER_STYLE_INDEX}"` : "";
57
+ return `<row r="${index + 1}">${buildCellXml(`A${index + 1}`, line, styleAttr)}</row>`;
58
+ }).join("");
59
+ const headerXml = sheet.columns.map((column, index) => {
60
+ return buildCellXml(`${getColumLetter(index + 1)}${headerRow}`, column.displayName, ` s="${HEADER_STYLE_INDEX}"`);
61
+ }).join("");
62
+ const rowsXml = sheet.data.map((row, rowIndex) => {
63
+ const rowNumber = headerRow + rowIndex + 1;
64
+ return `<row r="${rowNumber}">${sheet.columns.map((column, columnIndex) => {
65
+ return buildCellXml(`${getColumLetter(columnIndex + 1)}${rowNumber}`, getCellValue(row?.[column.id]), "");
66
+ }).join("")}</row>`;
67
+ }).join("");
68
+ return XML_DECLARATION + `<worksheet xmlns="${NAMESPACES.MAIN}">` + (colsXml ? `<cols>${colsXml}</cols>` : "") + `<sheetData>${headingXml}<row r="${headerRow}">${headerXml}</row>${rowsXml}</sheetData></worksheet>`;
69
+ };
70
+ const buildContentTypesXml = (sheetCount) => {
71
+ const overrides = Array.from({ length: sheetCount }, (unused, index) => {
72
+ return `<Override PartName="/xl/worksheets/sheet${index + 1}.xml" ContentType="${CONTENT_TYPE.WORKSHEET}"/>`;
73
+ }).join("");
74
+ return XML_DECLARATION + `<Types xmlns="${NAMESPACES.CONTENT_TYPES}"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/xl/workbook.xml" ContentType="${CONTENT_TYPE.SHEET}"/><Override PartName="/xl/styles.xml" ContentType="${CONTENT_TYPE.STYLES}"/>` + overrides + `</Types>`;
75
+ };
76
+ const buildWorkbookXml = (sheetNames) => {
77
+ const sheetsXml = sheetNames.map((name, index) => {
78
+ return `<sheet name="${getEscapedXml(name)}" sheetId="${index + 1}" r:id="rId${index + 1}"/>`;
79
+ }).join("");
80
+ return XML_DECLARATION + `<workbook xmlns="${NAMESPACES.MAIN}" xmlns:r="${NAMESPACES.RELATIONSHIP}"><sheets>${sheetsXml}</sheets></workbook>`;
81
+ };
82
+ const buildWorkbookRelsXml = (sheetCount) => {
83
+ const sheetRels = Array.from({ length: sheetCount }, (unused, index) => {
84
+ return `<Relationship Id="rId${index + 1}" Type="${REL_TYPE.WORKSHEET}" Target="worksheets/sheet${index + 1}.xml"/>`;
85
+ }).join("");
86
+ return XML_DECLARATION + `<Relationships xmlns="${NAMESPACES.PACKAGE_REL}">` + sheetRels + `<Relationship Id="rId${sheetCount + 1}" Type="${REL_TYPE.STYLES}" Target="styles.xml"/></Relationships>`;
87
+ };
88
+ const buildPackageRelsXml = () => {
89
+ return XML_DECLARATION + `<Relationships xmlns="${NAMESPACES.PACKAGE_REL}"><Relationship Id="rId1" Type="${REL_TYPE.OFFICE_DOCUMENT}" Target="xl/workbook.xml"/></Relationships>`;
90
+ };
91
+ /**
92
+ * Assemble the workbook parts. Shared by the Blob and byte-array entry points so
93
+ * the two can never drift.
94
+ */
95
+ const buildWorkbook = async (sheets) => {
96
+ if (0 === sheets.length) throw new Error("createXlsx requires at least one sheet.");
97
+ const JSZip = (await import("jszip")).default;
98
+ const zip = new JSZip();
99
+ const names = getUniqueSheetNames(sheets);
100
+ zip.file("[Content_Types].xml", buildContentTypesXml(sheets.length));
101
+ zip.file("_rels/.rels", buildPackageRelsXml());
102
+ zip.file("xl/workbook.xml", buildWorkbookXml(names));
103
+ zip.file("xl/_rels/workbook.xml.rels", buildWorkbookRelsXml(sheets.length));
104
+ zip.file("xl/styles.xml", buildStylesXml());
105
+ sheets.forEach((sheet, index) => {
106
+ zip.file(`xl/worksheets/sheet${index + 1}.xml`, buildWorksheetXml(sheet));
107
+ });
108
+ return zip;
109
+ };
110
+ /**
111
+ * Build an .xlsx workbook with one worksheet per entry in `sheets`, returned as a
112
+ * Blob ready to hand to a browser download.
113
+ *
114
+ * Every sheet gets a bold header row from its column display names, and each data
115
+ * row reads values by column `id` — so key order in the source objects does not
116
+ * matter and a missing key becomes an empty cell.
117
+ */
118
+ const createXlsx = async (sheets) => {
119
+ return (await buildWorkbook(sheets)).generateAsync({
120
+ type: "blob",
121
+ compression: "DEFLATE",
122
+ mimeType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
123
+ });
124
+ };
125
+ /**
126
+ * As createXlsx, but returns raw bytes instead of a Blob — for server-side
127
+ * callers that need to stream or write the workbook rather than download it.
128
+ */
129
+ const createXlsxBytes = async (sheets) => {
130
+ return (await buildWorkbook(sheets)).generateAsync({
131
+ type: "uint8array",
132
+ compression: "DEFLATE"
133
+ });
134
+ };
135
+ //#endregion
136
+ export { createXlsx, createXlsxBytes };
@@ -0,0 +1,18 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_xlsx_column = require("./column.cjs");
3
+ const require_xlsx_cell = require("./cell.cjs");
4
+ const require_xlsx_sheet = require("./sheet.cjs");
5
+ const require_xlsx_createXlsx = require("./createXlsx.cjs");
6
+ const require_xlsx_modifyXlsx = require("./modifyXlsx.cjs");
7
+ exports.buildCellXml = require_xlsx_cell.buildCellXml;
8
+ exports.createXlsx = require_xlsx_createXlsx.createXlsx;
9
+ exports.createXlsxBytes = require_xlsx_createXlsx.createXlsxBytes;
10
+ exports.getCellColNum = require_xlsx_cell.getCellColNum;
11
+ exports.getCellValue = require_xlsx_cell.getCellValue;
12
+ exports.getColumLetter = require_xlsx_column.getColumLetter;
13
+ exports.getColumnWidth = require_xlsx_column.getColumnWidth;
14
+ exports.getEscapedXml = require_xlsx_cell.getEscapedXml;
15
+ exports.getSanitisedSheetName = require_xlsx_sheet.getSanitisedSheetName;
16
+ exports.getUniqueSheetNames = require_xlsx_sheet.getUniqueSheetNames;
17
+ exports.modifyXlsx = require_xlsx_modifyXlsx.modifyXlsx;
18
+ exports.setCell = require_xlsx_cell.setCell;
@@ -0,0 +1,6 @@
1
+ import { XlsxCellValue, buildCellXml, getCellColNum, getCellValue, getEscapedXml, setCell } from "./cell.cjs";
2
+ import { XlsxColumn, getColumLetter, getColumnWidth } from "./column.cjs";
3
+ import { XlsxSheet, getSanitisedSheetName, getUniqueSheetNames } from "./sheet.cjs";
4
+ import { createXlsx, createXlsxBytes } from "./createXlsx.cjs";
5
+ import { XlsxSheetModifier, modifyXlsx } from "./modifyXlsx.cjs";
6
+ export { XlsxCellValue, XlsxColumn, XlsxSheet, XlsxSheetModifier, buildCellXml, createXlsx, createXlsxBytes, getCellColNum, getCellValue, getColumLetter, getColumnWidth, getEscapedXml, getSanitisedSheetName, getUniqueSheetNames, modifyXlsx, setCell };
@@ -0,0 +1,6 @@
1
+ import { XlsxCellValue, buildCellXml, getCellColNum, getCellValue, getEscapedXml, setCell } from "./cell.mjs";
2
+ import { XlsxColumn, getColumLetter, getColumnWidth } from "./column.mjs";
3
+ import { XlsxSheet, getSanitisedSheetName, getUniqueSheetNames } from "./sheet.mjs";
4
+ import { createXlsx, createXlsxBytes } from "./createXlsx.mjs";
5
+ import { XlsxSheetModifier, modifyXlsx } from "./modifyXlsx.mjs";
6
+ export { XlsxCellValue, XlsxColumn, XlsxSheet, XlsxSheetModifier, buildCellXml, createXlsx, createXlsxBytes, getCellColNum, getCellValue, getColumLetter, getColumnWidth, getEscapedXml, getSanitisedSheetName, getUniqueSheetNames, modifyXlsx, setCell };
@@ -0,0 +1,6 @@
1
+ import { getColumLetter, getColumnWidth } from "./column.mjs";
2
+ import { buildCellXml, getCellColNum, getCellValue, getEscapedXml, setCell } from "./cell.mjs";
3
+ import { getSanitisedSheetName, getUniqueSheetNames } from "./sheet.mjs";
4
+ import { createXlsx, createXlsxBytes } from "./createXlsx.mjs";
5
+ import { modifyXlsx } from "./modifyXlsx.mjs";
6
+ export { buildCellXml, createXlsx, createXlsxBytes, getCellColNum, getCellValue, getColumLetter, getColumnWidth, getEscapedXml, getSanitisedSheetName, getUniqueSheetNames, modifyXlsx, setCell };
@@ -0,0 +1,125 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_xlsx_cell = require("./cell.cjs");
3
+ //#region src/xlsx/modifyXlsx.ts
4
+ /**
5
+ * Patches an existing .xlsx template: apply per-sheet XML transformations, add
6
+ * sheets that are not in the template, and optionally embed a logo image.
7
+ *
8
+ * Takes and returns bytes rather than file paths, so it has no filesystem
9
+ * dependency and runs anywhere. Callers that work from disk read the template
10
+ * themselves and hand over the buffer.
11
+ *
12
+ * Use this when the output must keep a branded template's styling; use
13
+ * `createXlsx` when building a workbook from nothing.
14
+ */
15
+ /** 1 screen pixel at 96 DPI equals 9525 English Metric Units in OOXML. */
16
+ const PX_TO_EMU = 9525;
17
+ /** Default logo box, sized for a typical wide wordmark. */
18
+ const LOGO_WIDTH_PX = 500;
19
+ const LOGO_HEIGHT_PX = 77;
20
+ const DRAWING_REL_TYPE = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing";
21
+ const IMAGE_REL_TYPE = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image";
22
+ const WORKSHEET_REL_TYPE = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet";
23
+ const DRAWING_CONTENT_TYPE = "application/vnd.openxmlformats-officedocument.drawing+xml";
24
+ /**
25
+ * Minimal valid worksheet XML used when `createIfMissing` adds a sheet.
26
+ *
27
+ * <sheetData></sheetData> must not be self-closing: setCell's new-row path
28
+ * searches for the literal closing tag.
29
+ */
30
+ const EMPTY_SHEET_XML = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><worksheet xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\"><sheetData></sheetData></worksheet>";
31
+ /**
32
+ * Drawing XML for one embedded image, anchored to cell B2 so it sits just below
33
+ * the header row.
34
+ *
35
+ * The image relationship is assumed to be registered as "rId1" in the sibling
36
+ * .rels file.
37
+ */
38
+ const buildDrawingXml = (widthEmu, heightEmu) => {
39
+ return `<?xml version="1.0" encoding="UTF-8" standalone="yes"?><xdr:wsDr xmlns:xdr="http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><xdr:oneCellAnchor><xdr:from><xdr:col>1</xdr:col><xdr:colOff>0</xdr:colOff><xdr:row>1</xdr:row><xdr:rowOff>0</xdr:rowOff></xdr:from><xdr:ext cx="${widthEmu}" cy="${heightEmu}"/><xdr:pic><xdr:nvPicPr><xdr:cNvPr id="2" name="Logo"/><xdr:cNvPicPr><a:picLocks noChangeAspect="1"/></xdr:cNvPicPr></xdr:nvPicPr><xdr:blipFill><a:blip r:embed="rId1"/><a:stretch><a:fillRect/></a:stretch></xdr:blipFill><xdr:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="${widthEmu}" cy="${heightEmu}"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom></xdr:spPr></xdr:pic><xdr:clientData/></xdr:oneCellAnchor></xdr:wsDr>`;
40
+ };
41
+ /**
42
+ * Apply per-sheet transformations to a template workbook.
43
+ *
44
+ * @param template The .xlsx template as raw bytes.
45
+ * @param sheets One entry per sheet to touch, keyed by its 1-indexed position.
46
+ * @param logo Optional PNG bytes, embedded into sheets with `addLogo`.
47
+ */
48
+ const modifyXlsx = async (template, sheets, logo) => {
49
+ const zip = await (await import("jszip")).default.loadAsync(template);
50
+ if (logo) {
51
+ zip.file("xl/media/image1.png", logo);
52
+ const contentTypesFile = zip.file("[Content_Types].xml");
53
+ if (contentTypesFile) {
54
+ let contentTypesXml = await contentTypesFile.async("string");
55
+ if (!contentTypesXml.includes(`Extension="png"`)) contentTypesXml = contentTypesXml.replace("</Types>", () => {
56
+ return `<Default Extension="png" ContentType="image/png"/></Types>`;
57
+ });
58
+ zip.file("[Content_Types].xml", contentTypesXml);
59
+ }
60
+ }
61
+ let drawingCounter = 0;
62
+ for (const sheet of sheets) {
63
+ const filename = `xl/worksheets/sheet${sheet.index}.xml`;
64
+ let existing = zip.file(filename);
65
+ if (!existing && sheet.createIfMissing) {
66
+ const name = sheet.sheetName ?? `Sheet${sheet.index}`;
67
+ const rId = `rId${sheet.index + 10}`;
68
+ const workbookFile = zip.file("xl/workbook.xml");
69
+ if (workbookFile) {
70
+ const workbookXml = await workbookFile.async("string");
71
+ zip.file("xl/workbook.xml", workbookXml.replace("</sheets>", () => {
72
+ return `<sheet name="${require_xlsx_cell.getEscapedXml(name)}" sheetId="${sheet.index}" r:id="${rId}"/></sheets>`;
73
+ }));
74
+ }
75
+ const relsFile = zip.file("xl/_rels/workbook.xml.rels");
76
+ if (relsFile) {
77
+ const relsXml = await relsFile.async("string");
78
+ zip.file("xl/_rels/workbook.xml.rels", relsXml.replace("</Relationships>", () => {
79
+ return `<Relationship Id="${rId}" Type="${WORKSHEET_REL_TYPE}" Target="worksheets/sheet${sheet.index}.xml"/></Relationships>`;
80
+ }));
81
+ }
82
+ zip.file(filename, EMPTY_SHEET_XML);
83
+ existing = zip.file(filename);
84
+ }
85
+ if (!existing) continue;
86
+ let xml = sheet.modify(await existing.async("string"));
87
+ if (sheet.addLogo && logo) {
88
+ drawingCounter++;
89
+ const drawingNum = drawingCounter;
90
+ const logoWidthEmu = Math.round((sheet.logoWidthPx ?? LOGO_WIDTH_PX) * PX_TO_EMU);
91
+ const logoHeightEmu = Math.round((sheet.logoHeightPx ?? LOGO_HEIGHT_PX) * PX_TO_EMU);
92
+ const drawingRId = `rIdLogo${drawingNum}`;
93
+ zip.file(`xl/drawings/drawing${drawingNum}.xml`, buildDrawingXml(logoWidthEmu, logoHeightEmu));
94
+ zip.file(`xl/drawings/_rels/drawing${drawingNum}.xml.rels`, `<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="${IMAGE_REL_TYPE}" Target="../media/image1.png"/></Relationships>`);
95
+ const contentTypesFile = zip.file("[Content_Types].xml");
96
+ if (contentTypesFile) {
97
+ let contentTypesXml = await contentTypesFile.async("string");
98
+ const drawingPart = `/xl/drawings/drawing${drawingNum}.xml`;
99
+ if (!contentTypesXml.includes(drawingPart)) contentTypesXml = contentTypesXml.replace("</Types>", () => {
100
+ return `<Override PartName="${drawingPart}" ContentType="${DRAWING_CONTENT_TYPE}"/></Types>`;
101
+ });
102
+ zip.file("[Content_Types].xml", contentTypesXml);
103
+ }
104
+ const sheetRelsPath = `xl/worksheets/_rels/sheet${sheet.index}.xml.rels`;
105
+ const sheetRelsFile = zip.file(sheetRelsPath);
106
+ if (sheetRelsFile) {
107
+ const relsXml = await sheetRelsFile.async("string");
108
+ zip.file(sheetRelsPath, relsXml.replace("</Relationships>", () => {
109
+ return `<Relationship Id="${drawingRId}" Type="${DRAWING_REL_TYPE}" Target="../drawings/drawing${drawingNum}.xml"/></Relationships>`;
110
+ }));
111
+ } else zip.file(sheetRelsPath, `<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="${drawingRId}" Type="${DRAWING_REL_TYPE}" Target="../drawings/drawing${drawingNum}.xml"/></Relationships>`);
112
+ if (!xml.includes("xmlns:r=")) xml = xml.replace("<worksheet ", `<worksheet xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" `);
113
+ xml = xml.replace("</worksheet>", () => {
114
+ return `<drawing r:id="${drawingRId}"/></worksheet>`;
115
+ });
116
+ }
117
+ zip.file(filename, xml);
118
+ }
119
+ return zip.generateAsync({
120
+ type: "uint8array",
121
+ compression: "DEFLATE"
122
+ });
123
+ };
124
+ //#endregion
125
+ exports.modifyXlsx = modifyXlsx;
@@ -0,0 +1,24 @@
1
+ //#region src/xlsx/modifyXlsx.d.ts
2
+ type XlsxSheetModifier = {
3
+ /** 1-indexed sheet number inside the ZIP (sheet1.xml, sheet2.xml, …). */
4
+ index: number;
5
+ modify: (xml: string) => string;
6
+ /** Create a blank sheet when the template does not contain this index. */
7
+ createIfMissing?: boolean;
8
+ /** Sheet name used when createIfMissing creates the sheet. */
9
+ sheetName?: string;
10
+ /** Embed the logo into this sheet. Requires a logo to be passed to modifyXlsx. */
11
+ addLogo?: boolean;
12
+ logoHeightPx?: number;
13
+ logoWidthPx?: number;
14
+ };
15
+ /**
16
+ * Apply per-sheet transformations to a template workbook.
17
+ *
18
+ * @param template The .xlsx template as raw bytes.
19
+ * @param sheets One entry per sheet to touch, keyed by its 1-indexed position.
20
+ * @param logo Optional PNG bytes, embedded into sheets with `addLogo`.
21
+ */
22
+ declare const modifyXlsx: (template: Uint8Array, sheets: XlsxSheetModifier[], logo?: Uint8Array) => Promise<Uint8Array>;
23
+ //#endregion
24
+ export { XlsxSheetModifier, modifyXlsx };
@@ -0,0 +1,24 @@
1
+ //#region src/xlsx/modifyXlsx.d.ts
2
+ type XlsxSheetModifier = {
3
+ /** 1-indexed sheet number inside the ZIP (sheet1.xml, sheet2.xml, …). */
4
+ index: number;
5
+ modify: (xml: string) => string;
6
+ /** Create a blank sheet when the template does not contain this index. */
7
+ createIfMissing?: boolean;
8
+ /** Sheet name used when createIfMissing creates the sheet. */
9
+ sheetName?: string;
10
+ /** Embed the logo into this sheet. Requires a logo to be passed to modifyXlsx. */
11
+ addLogo?: boolean;
12
+ logoHeightPx?: number;
13
+ logoWidthPx?: number;
14
+ };
15
+ /**
16
+ * Apply per-sheet transformations to a template workbook.
17
+ *
18
+ * @param template The .xlsx template as raw bytes.
19
+ * @param sheets One entry per sheet to touch, keyed by its 1-indexed position.
20
+ * @param logo Optional PNG bytes, embedded into sheets with `addLogo`.
21
+ */
22
+ declare const modifyXlsx: (template: Uint8Array, sheets: XlsxSheetModifier[], logo?: Uint8Array) => Promise<Uint8Array>;
23
+ //#endregion
24
+ export { XlsxSheetModifier, modifyXlsx };
@@ -0,0 +1,124 @@
1
+ import { getEscapedXml } from "./cell.mjs";
2
+ //#region src/xlsx/modifyXlsx.ts
3
+ /**
4
+ * Patches an existing .xlsx template: apply per-sheet XML transformations, add
5
+ * sheets that are not in the template, and optionally embed a logo image.
6
+ *
7
+ * Takes and returns bytes rather than file paths, so it has no filesystem
8
+ * dependency and runs anywhere. Callers that work from disk read the template
9
+ * themselves and hand over the buffer.
10
+ *
11
+ * Use this when the output must keep a branded template's styling; use
12
+ * `createXlsx` when building a workbook from nothing.
13
+ */
14
+ /** 1 screen pixel at 96 DPI equals 9525 English Metric Units in OOXML. */
15
+ const PX_TO_EMU = 9525;
16
+ /** Default logo box, sized for a typical wide wordmark. */
17
+ const LOGO_WIDTH_PX = 500;
18
+ const LOGO_HEIGHT_PX = 77;
19
+ const DRAWING_REL_TYPE = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing";
20
+ const IMAGE_REL_TYPE = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image";
21
+ const WORKSHEET_REL_TYPE = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet";
22
+ const DRAWING_CONTENT_TYPE = "application/vnd.openxmlformats-officedocument.drawing+xml";
23
+ /**
24
+ * Minimal valid worksheet XML used when `createIfMissing` adds a sheet.
25
+ *
26
+ * <sheetData></sheetData> must not be self-closing: setCell's new-row path
27
+ * searches for the literal closing tag.
28
+ */
29
+ const EMPTY_SHEET_XML = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><worksheet xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\"><sheetData></sheetData></worksheet>";
30
+ /**
31
+ * Drawing XML for one embedded image, anchored to cell B2 so it sits just below
32
+ * the header row.
33
+ *
34
+ * The image relationship is assumed to be registered as "rId1" in the sibling
35
+ * .rels file.
36
+ */
37
+ const buildDrawingXml = (widthEmu, heightEmu) => {
38
+ return `<?xml version="1.0" encoding="UTF-8" standalone="yes"?><xdr:wsDr xmlns:xdr="http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><xdr:oneCellAnchor><xdr:from><xdr:col>1</xdr:col><xdr:colOff>0</xdr:colOff><xdr:row>1</xdr:row><xdr:rowOff>0</xdr:rowOff></xdr:from><xdr:ext cx="${widthEmu}" cy="${heightEmu}"/><xdr:pic><xdr:nvPicPr><xdr:cNvPr id="2" name="Logo"/><xdr:cNvPicPr><a:picLocks noChangeAspect="1"/></xdr:cNvPicPr></xdr:nvPicPr><xdr:blipFill><a:blip r:embed="rId1"/><a:stretch><a:fillRect/></a:stretch></xdr:blipFill><xdr:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="${widthEmu}" cy="${heightEmu}"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom></xdr:spPr></xdr:pic><xdr:clientData/></xdr:oneCellAnchor></xdr:wsDr>`;
39
+ };
40
+ /**
41
+ * Apply per-sheet transformations to a template workbook.
42
+ *
43
+ * @param template The .xlsx template as raw bytes.
44
+ * @param sheets One entry per sheet to touch, keyed by its 1-indexed position.
45
+ * @param logo Optional PNG bytes, embedded into sheets with `addLogo`.
46
+ */
47
+ const modifyXlsx = async (template, sheets, logo) => {
48
+ const zip = await (await import("jszip")).default.loadAsync(template);
49
+ if (logo) {
50
+ zip.file("xl/media/image1.png", logo);
51
+ const contentTypesFile = zip.file("[Content_Types].xml");
52
+ if (contentTypesFile) {
53
+ let contentTypesXml = await contentTypesFile.async("string");
54
+ if (!contentTypesXml.includes(`Extension="png"`)) contentTypesXml = contentTypesXml.replace("</Types>", () => {
55
+ return `<Default Extension="png" ContentType="image/png"/></Types>`;
56
+ });
57
+ zip.file("[Content_Types].xml", contentTypesXml);
58
+ }
59
+ }
60
+ let drawingCounter = 0;
61
+ for (const sheet of sheets) {
62
+ const filename = `xl/worksheets/sheet${sheet.index}.xml`;
63
+ let existing = zip.file(filename);
64
+ if (!existing && sheet.createIfMissing) {
65
+ const name = sheet.sheetName ?? `Sheet${sheet.index}`;
66
+ const rId = `rId${sheet.index + 10}`;
67
+ const workbookFile = zip.file("xl/workbook.xml");
68
+ if (workbookFile) {
69
+ const workbookXml = await workbookFile.async("string");
70
+ zip.file("xl/workbook.xml", workbookXml.replace("</sheets>", () => {
71
+ return `<sheet name="${getEscapedXml(name)}" sheetId="${sheet.index}" r:id="${rId}"/></sheets>`;
72
+ }));
73
+ }
74
+ const relsFile = zip.file("xl/_rels/workbook.xml.rels");
75
+ if (relsFile) {
76
+ const relsXml = await relsFile.async("string");
77
+ zip.file("xl/_rels/workbook.xml.rels", relsXml.replace("</Relationships>", () => {
78
+ return `<Relationship Id="${rId}" Type="${WORKSHEET_REL_TYPE}" Target="worksheets/sheet${sheet.index}.xml"/></Relationships>`;
79
+ }));
80
+ }
81
+ zip.file(filename, EMPTY_SHEET_XML);
82
+ existing = zip.file(filename);
83
+ }
84
+ if (!existing) continue;
85
+ let xml = sheet.modify(await existing.async("string"));
86
+ if (sheet.addLogo && logo) {
87
+ drawingCounter++;
88
+ const drawingNum = drawingCounter;
89
+ const logoWidthEmu = Math.round((sheet.logoWidthPx ?? LOGO_WIDTH_PX) * PX_TO_EMU);
90
+ const logoHeightEmu = Math.round((sheet.logoHeightPx ?? LOGO_HEIGHT_PX) * PX_TO_EMU);
91
+ const drawingRId = `rIdLogo${drawingNum}`;
92
+ zip.file(`xl/drawings/drawing${drawingNum}.xml`, buildDrawingXml(logoWidthEmu, logoHeightEmu));
93
+ zip.file(`xl/drawings/_rels/drawing${drawingNum}.xml.rels`, `<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="${IMAGE_REL_TYPE}" Target="../media/image1.png"/></Relationships>`);
94
+ const contentTypesFile = zip.file("[Content_Types].xml");
95
+ if (contentTypesFile) {
96
+ let contentTypesXml = await contentTypesFile.async("string");
97
+ const drawingPart = `/xl/drawings/drawing${drawingNum}.xml`;
98
+ if (!contentTypesXml.includes(drawingPart)) contentTypesXml = contentTypesXml.replace("</Types>", () => {
99
+ return `<Override PartName="${drawingPart}" ContentType="${DRAWING_CONTENT_TYPE}"/></Types>`;
100
+ });
101
+ zip.file("[Content_Types].xml", contentTypesXml);
102
+ }
103
+ const sheetRelsPath = `xl/worksheets/_rels/sheet${sheet.index}.xml.rels`;
104
+ const sheetRelsFile = zip.file(sheetRelsPath);
105
+ if (sheetRelsFile) {
106
+ const relsXml = await sheetRelsFile.async("string");
107
+ zip.file(sheetRelsPath, relsXml.replace("</Relationships>", () => {
108
+ return `<Relationship Id="${drawingRId}" Type="${DRAWING_REL_TYPE}" Target="../drawings/drawing${drawingNum}.xml"/></Relationships>`;
109
+ }));
110
+ } else zip.file(sheetRelsPath, `<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="${drawingRId}" Type="${DRAWING_REL_TYPE}" Target="../drawings/drawing${drawingNum}.xml"/></Relationships>`);
111
+ if (!xml.includes("xmlns:r=")) xml = xml.replace("<worksheet ", `<worksheet xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" `);
112
+ xml = xml.replace("</worksheet>", () => {
113
+ return `<drawing r:id="${drawingRId}"/></worksheet>`;
114
+ });
115
+ }
116
+ zip.file(filename, xml);
117
+ }
118
+ return zip.generateAsync({
119
+ type: "uint8array",
120
+ compression: "DEFLATE"
121
+ });
122
+ };
123
+ //#endregion
124
+ export { modifyXlsx };
@@ -0,0 +1,36 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ //#region src/xlsx/sheet.ts
3
+ /** Excel refuses to open a workbook whose sheet name exceeds 31 characters. */
4
+ const SHEET_NAME_MAX_LENGTH = 31;
5
+ /**
6
+ * Coerce a sheet name into something Excel will accept: no []:*?/\ characters,
7
+ * no wrapping apostrophes, at most 31 characters, and never empty.
8
+ *
9
+ * Uniqueness is handled separately, since that needs the whole set.
10
+ */
11
+ const getSanitisedSheetName = (name) => {
12
+ const cleaned = (name || "").replace(/[[\]:*?/\\]/g, "_").replace(/^'+|'+$/g, "").trim().slice(0, SHEET_NAME_MAX_LENGTH);
13
+ return "" === cleaned ? "Sheet" : cleaned;
14
+ };
15
+ /**
16
+ * Sanitise every sheet name and break collisions with _2, _3, … while staying
17
+ * inside the 31 character limit. Excel rejects duplicate names outright, so this
18
+ * cannot be left to chance once sheets are generated from data.
19
+ */
20
+ const getUniqueSheetNames = (sheets) => {
21
+ const used = {};
22
+ return sheets.map((sheet) => {
23
+ const base = getSanitisedSheetName(sheet.name);
24
+ const key = base.toLowerCase();
25
+ if (!(key in used)) {
26
+ used[key] = 1;
27
+ return base;
28
+ }
29
+ used[key] += 1;
30
+ const suffix = `_${used[key]}`;
31
+ return base.slice(0, SHEET_NAME_MAX_LENGTH - suffix.length) + suffix;
32
+ });
33
+ };
34
+ //#endregion
35
+ exports.getSanitisedSheetName = getSanitisedSheetName;
36
+ exports.getUniqueSheetNames = getUniqueSheetNames;
@@ -0,0 +1,29 @@
1
+ import { XlsxCellValue } from "./cell.cjs";
2
+ import { XlsxColumn } from "./column.cjs";
3
+ //#region src/xlsx/sheet.d.ts
4
+ type XlsxSheet = {
5
+ name: string;
6
+ columns: XlsxColumn[];
7
+ data: Record<string, XlsxCellValue>[];
8
+ /**
9
+ * Optional lines written above the table — typically a client name and a
10
+ * reporting period. The first line is bold, the rest are plain, and a blank
11
+ * row separates them from the column headers.
12
+ */
13
+ heading?: string[];
14
+ };
15
+ /**
16
+ * Coerce a sheet name into something Excel will accept: no []:*?/\ characters,
17
+ * no wrapping apostrophes, at most 31 characters, and never empty.
18
+ *
19
+ * Uniqueness is handled separately, since that needs the whole set.
20
+ */
21
+ declare const getSanitisedSheetName: (name: string) => string;
22
+ /**
23
+ * Sanitise every sheet name and break collisions with _2, _3, … while staying
24
+ * inside the 31 character limit. Excel rejects duplicate names outright, so this
25
+ * cannot be left to chance once sheets are generated from data.
26
+ */
27
+ declare const getUniqueSheetNames: (sheets: XlsxSheet[]) => string[];
28
+ //#endregion
29
+ export { XlsxSheet, getSanitisedSheetName, getUniqueSheetNames };
@@ -0,0 +1,29 @@
1
+ import { XlsxCellValue } from "./cell.mjs";
2
+ import { XlsxColumn } from "./column.mjs";
3
+ //#region src/xlsx/sheet.d.ts
4
+ type XlsxSheet = {
5
+ name: string;
6
+ columns: XlsxColumn[];
7
+ data: Record<string, XlsxCellValue>[];
8
+ /**
9
+ * Optional lines written above the table — typically a client name and a
10
+ * reporting period. The first line is bold, the rest are plain, and a blank
11
+ * row separates them from the column headers.
12
+ */
13
+ heading?: string[];
14
+ };
15
+ /**
16
+ * Coerce a sheet name into something Excel will accept: no []:*?/\ characters,
17
+ * no wrapping apostrophes, at most 31 characters, and never empty.
18
+ *
19
+ * Uniqueness is handled separately, since that needs the whole set.
20
+ */
21
+ declare const getSanitisedSheetName: (name: string) => string;
22
+ /**
23
+ * Sanitise every sheet name and break collisions with _2, _3, … while staying
24
+ * inside the 31 character limit. Excel rejects duplicate names outright, so this
25
+ * cannot be left to chance once sheets are generated from data.
26
+ */
27
+ declare const getUniqueSheetNames: (sheets: XlsxSheet[]) => string[];
28
+ //#endregion
29
+ export { XlsxSheet, getSanitisedSheetName, getUniqueSheetNames };
@@ -0,0 +1,34 @@
1
+ //#region src/xlsx/sheet.ts
2
+ /** Excel refuses to open a workbook whose sheet name exceeds 31 characters. */
3
+ const SHEET_NAME_MAX_LENGTH = 31;
4
+ /**
5
+ * Coerce a sheet name into something Excel will accept: no []:*?/\ characters,
6
+ * no wrapping apostrophes, at most 31 characters, and never empty.
7
+ *
8
+ * Uniqueness is handled separately, since that needs the whole set.
9
+ */
10
+ const getSanitisedSheetName = (name) => {
11
+ const cleaned = (name || "").replace(/[[\]:*?/\\]/g, "_").replace(/^'+|'+$/g, "").trim().slice(0, SHEET_NAME_MAX_LENGTH);
12
+ return "" === cleaned ? "Sheet" : cleaned;
13
+ };
14
+ /**
15
+ * Sanitise every sheet name and break collisions with _2, _3, … while staying
16
+ * inside the 31 character limit. Excel rejects duplicate names outright, so this
17
+ * cannot be left to chance once sheets are generated from data.
18
+ */
19
+ const getUniqueSheetNames = (sheets) => {
20
+ const used = {};
21
+ return sheets.map((sheet) => {
22
+ const base = getSanitisedSheetName(sheet.name);
23
+ const key = base.toLowerCase();
24
+ if (!(key in used)) {
25
+ used[key] = 1;
26
+ return base;
27
+ }
28
+ used[key] += 1;
29
+ const suffix = `_${used[key]}`;
30
+ return base.slice(0, SHEET_NAME_MAX_LENGTH - suffix.length) + suffix;
31
+ });
32
+ };
33
+ //#endregion
34
+ export { getSanitisedSheetName, getUniqueSheetNames };