@justybase/spreadsheet-tasks 2.0.0 → 2.1.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/dist/cjs/index.js CHANGED
@@ -38,8 +38,10 @@ __export(index_exports, {
38
38
  ReaderFactory: () => ReaderFactory,
39
39
  StreamingSheetState: () => StreamingSheetState,
40
40
  XlsbReader: () => XlsbReader,
41
+ XlsbUpdater: () => XlsbUpdater,
41
42
  XlsbWriter: () => XlsbWriter,
42
43
  XlsxReader: () => XlsxReader,
44
+ XlsxUpdater: () => XlsxUpdater,
43
45
  XlsxWriter: () => XlsxWriter,
44
46
  applyHeaderWidths: () => applyHeaderWidths,
45
47
  defaultColWidth: () => defaultColWidth,
@@ -603,6 +605,93 @@ var XlsbReader = class extends ExcelReaderAbstract {
603
605
 
604
606
  // src/XlsxReader.ts
605
607
  var import_yauzl = __toESM(require("yauzl"));
608
+
609
+ // src/xmlUtils.ts
610
+ function hasInvalidControlChars(str) {
611
+ for (let i = 0; i < str.length; i++) {
612
+ const c = str.charCodeAt(i);
613
+ if (c < 32 && c !== 9 && c !== 10 && c !== 13) {
614
+ return true;
615
+ }
616
+ }
617
+ return false;
618
+ }
619
+ function stripInvalidControlChars(str) {
620
+ let out = "";
621
+ for (let i = 0; i < str.length; i++) {
622
+ const c = str.charCodeAt(i);
623
+ if (c === 9 || c === 10 || c === 13 || c >= 32 && c <= 55295 || c >= 57344 && c <= 65533) {
624
+ out += str[i];
625
+ }
626
+ }
627
+ return out;
628
+ }
629
+ function escapeXmlText(str) {
630
+ if (!/&|<|>|"|'/.test(str) && !hasInvalidControlChars(str)) {
631
+ return str;
632
+ }
633
+ let out = str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
634
+ if (hasInvalidControlChars(out)) {
635
+ out = stripInvalidControlChars(out);
636
+ }
637
+ return out;
638
+ }
639
+ function unescapeXml(str) {
640
+ if (!str || str.indexOf("&") === -1) return str;
641
+ return str.replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&apos;/g, "'");
642
+ }
643
+ function columnIndexToLetter(colIndex) {
644
+ let n = colIndex + 1;
645
+ let result = "";
646
+ while (n > 0) {
647
+ const rem = (n - 1) % 26;
648
+ result = String.fromCharCode(65 + rem) + result;
649
+ n = Math.floor((n - 1) / 26);
650
+ }
651
+ return result;
652
+ }
653
+ function columnLetterToIndex(letter) {
654
+ let column = 0;
655
+ const length = letter.length;
656
+ for (let i = 0; i < length; i++) {
657
+ column += (letter.charCodeAt(i) - 64) * Math.pow(26, length - i - 1);
658
+ }
659
+ return column - 1;
660
+ }
661
+ function trimTrailingEmptyRows(rows) {
662
+ let end = rows.length;
663
+ while (end > 0 && rows[end - 1].every((v) => v === null || v === void 0)) {
664
+ end--;
665
+ }
666
+ return end === rows.length ? rows : rows.slice(0, end);
667
+ }
668
+ function parseSharedStringsXml(xml) {
669
+ const result = [];
670
+ let pos = 0;
671
+ while (true) {
672
+ const siStart = xml.indexOf("<si>", pos);
673
+ if (siStart === -1) break;
674
+ const siEnd = xml.indexOf("</si>", siStart);
675
+ if (siEnd === -1) break;
676
+ const content = xml.substring(siStart, siEnd);
677
+ let val = "";
678
+ let tPos = 0;
679
+ while (true) {
680
+ const tStart = content.indexOf("<t", tPos);
681
+ if (tStart === -1) break;
682
+ const tagEnd = content.indexOf(">", tStart);
683
+ const tEnd = content.indexOf("</t>", tagEnd);
684
+ if (tEnd === -1) break;
685
+ val += content.substring(tagEnd + 1, tEnd);
686
+ tPos = tEnd + 4;
687
+ }
688
+ result.push(unescapeXml(val));
689
+ pos = siEnd + 5;
690
+ }
691
+ return result;
692
+ }
693
+
694
+ // src/XlsxReader.ts
606
695
  var XlsxReader = class extends ExcelReaderAbstract {
607
696
  constructor() {
608
697
  super();
@@ -644,7 +733,7 @@ var XlsxReader = class extends ExcelReaderAbstract {
644
733
  const sheetRegex = /<sheet[^>]*name="([^"]*)"[^>]*sheetId="([^"]*)"[^>]*r:id="([^"]*)"/g;
645
734
  let match;
646
735
  while ((match = sheetRegex.exec(wbContent)) !== null) {
647
- const name = this._unescapeXml(match[1]);
736
+ const name = unescapeXml(match[1]);
648
737
  const sheetId = match[2];
649
738
  const rId = match[3];
650
739
  const target = rIdToTarget[rId];
@@ -697,33 +786,8 @@ var XlsxReader = class extends ExcelReaderAbstract {
697
786
  });
698
787
  });
699
788
  }
700
- _unescapeXml(str) {
701
- if (!str) return "";
702
- if (str.indexOf("&") === -1) return str;
703
- return str.replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&apos;/g, "'");
704
- }
705
789
  _parseSharedStrings(xml) {
706
- let pos = 0;
707
- while (true) {
708
- const siStart = xml.indexOf("<si>", pos);
709
- if (siStart === -1) break;
710
- const siEnd = xml.indexOf("</si>", siStart);
711
- if (siEnd === -1) break;
712
- const content = xml.substring(siStart, siEnd);
713
- let val = "";
714
- let tPos = 0;
715
- while (true) {
716
- const tStart = content.indexOf("<t", tPos);
717
- if (tStart === -1) break;
718
- const tagEnd = content.indexOf(">", tStart);
719
- const tEnd = content.indexOf("</t>", tagEnd);
720
- if (tEnd === -1) break;
721
- val += content.substring(tagEnd + 1, tEnd);
722
- tPos = tEnd + 4;
723
- }
724
- this.sharedStrings.push(this._unescapeXml(val));
725
- pos = siEnd + 5;
726
- }
790
+ this.sharedStrings = parseSharedStringsXml(xml);
727
791
  }
728
792
  _parseStyles(xml) {
729
793
  const numFmtRegex = /<numFmt\s+[^>]*numFmtId="(\d+)"[^>]*formatCode="([^"]*)"/g;
@@ -814,7 +878,7 @@ var XlsxReader = class extends ExcelReaderAbstract {
814
878
  if (key === "r") {
815
879
  let letterLen = 0;
816
880
  while (letterLen < val2.length && val2.charCodeAt(letterLen) >= 65) letterLen++;
817
- colIndex = this._columnLetterToIndex(val2.substring(0, letterLen));
881
+ colIndex = columnLetterToIndex(val2.substring(0, letterLen));
818
882
  } else if (key === "t") {
819
883
  type = val2;
820
884
  } else if (key === "s") {
@@ -857,7 +921,7 @@ var XlsxReader = class extends ExcelReaderAbstract {
857
921
  } else if (type === "b") {
858
922
  finalVal = val === "1" || val === "true";
859
923
  } else if (type === "inlineStr") {
860
- finalVal = this._unescapeXml(val);
924
+ finalVal = unescapeXml(val);
861
925
  } else if (type === "n" || type === "") {
862
926
  finalVal = parseFloat(val);
863
927
  if (styleIndex > 0 && this.xfIdToNumFmtId) {
@@ -881,14 +945,6 @@ var XlsxReader = class extends ExcelReaderAbstract {
881
945
  }
882
946
  }
883
947
  }
884
- _columnLetterToIndex(letter) {
885
- let column = 0;
886
- const length = letter.length;
887
- for (let i = 0; i < length; i++) {
888
- column += (letter.charCodeAt(i) - 64) * Math.pow(26, length - i - 1);
889
- }
890
- return column - 1;
891
- }
892
948
  getValue(i) {
893
949
  if (i < 0 || i >= this._currentRow.length) return null;
894
950
  return this._currentRow[i];
@@ -3919,6 +3975,975 @@ ${xfEntries.join("\n")}
3919
3975
  this.archive.append(wbRels, { name: "xl/_rels/workbook.xml.rels" });
3920
3976
  }
3921
3977
  };
3978
+
3979
+ // src/XlsxUpdater.ts
3980
+ var fs3 = __toESM(require("fs"));
3981
+ var import_adm_zip2 = __toESM(require("adm-zip"));
3982
+ var XlsxUpdater = class {
3983
+ /**
3984
+ * @param path Path to an existing `.xlsx` file.
3985
+ */
3986
+ constructor(path2) {
3987
+ this.sheetNameToPath = /* @__PURE__ */ new Map();
3988
+ this.pivotCacheDefs = [];
3989
+ this.pivotTableDefPaths = [];
3990
+ this.sharedStringsXml = null;
3991
+ this.sharedStringsValues = [];
3992
+ this.sharedStringsOriginalLength = 0;
3993
+ this.sharedStringsCount = 0;
3994
+ this.stringIndexMap = /* @__PURE__ */ new Map();
3995
+ this.sourcePath = path2;
3996
+ this._oaEpoch = Date.UTC(1899, 11, 30);
3997
+ if (!fs3.existsSync(path2)) {
3998
+ throw new Error(`XlsxUpdater: file not found: ${path2}`);
3999
+ }
4000
+ this.zip = new import_adm_zip2.default(path2);
4001
+ if (this.zip.getEntry("xl/workbook.bin")) {
4002
+ throw new Error(
4003
+ "XlsxUpdater: XLSB files are not supported yet. Convert the workbook to XLSX first."
4004
+ );
4005
+ }
4006
+ if (!this.zip.getEntry("xl/workbook.xml")) {
4007
+ throw new Error("XlsxUpdater: not a valid XLSX workbook (xl/workbook.xml missing).");
4008
+ }
4009
+ this._loadWorkbookStructure();
4010
+ }
4011
+ /** Worksheet names in workbook order. */
4012
+ getSheetNames() {
4013
+ return [...this.sheetNameToPath.keys()];
4014
+ }
4015
+ /**
4016
+ * Clear the entire cell data of the target sheet and write new rows in its place.
4017
+ * All other parts of the workbook (pivot tables, other sheets, styles, …) are preserved.
4018
+ *
4019
+ * @param sheetName Name of the worksheet to replace.
4020
+ * @param rows New data rows (`CellValue` cells; null/undefined = blank).
4021
+ * @param options See {@link ReplaceSheetDataOptions}.
4022
+ */
4023
+ replaceSheetData(sheetName, rows, options = {}) {
4024
+ const { headers, styleFallback = "inherit" } = options;
4025
+ rows = trimTrailingEmptyRows(rows);
4026
+ const sheetPath = this.sheetNameToPath.get(sheetName);
4027
+ if (!sheetPath) {
4028
+ throw new Error(`XlsxUpdater: sheet "${sheetName}" not found in the workbook.`);
4029
+ }
4030
+ const entry = this.zip.getEntry(sheetPath);
4031
+ if (!entry) {
4032
+ throw new Error(`XlsxUpdater: worksheet part missing for sheet "${sheetName}".`);
4033
+ }
4034
+ const sheetXml = entry.getData().toString("utf8");
4035
+ this._ensureSharedStringsLoaded();
4036
+ let colStyles = /* @__PURE__ */ new Map();
4037
+ let headerStyles = /* @__PURE__ */ new Map();
4038
+ let dateStyle = null;
4039
+ if (styleFallback !== "general") {
4040
+ const collected = this._collectExistingStyles(sheetXml);
4041
+ colStyles = collected.dataStyles;
4042
+ headerStyles = collected.headerStyles;
4043
+ dateStyle = this._findDateStyleIndex();
4044
+ }
4045
+ const lastCol = Math.max(rows.reduce((m, r) => Math.max(m, r.length), 0), (headers == null ? void 0 : headers.length) ?? 0) - 1;
4046
+ const totalRows = rows.length + (headers ? 1 : 0);
4047
+ const newSheetData = this._buildSheetData(rows, headers, colStyles, headerStyles, dateStyle);
4048
+ const newXml = this._patchSheetXml(sheetXml, newSheetData, totalRows, lastCol);
4049
+ this.zip.updateFile(sheetPath, Buffer.from(newXml, "utf8"));
4050
+ if (this.sharedStringsXml !== null) {
4051
+ this._commitSharedStrings();
4052
+ }
4053
+ const dimRef = totalRows > 0 && lastCol >= 0 ? `A1:${columnIndexToLetter(lastCol)}${totalRows}` : "A1";
4054
+ this._updatePivotCaches(sheetName, dimRef, rows.length);
4055
+ this._addRefreshOnLoadToPivotTables();
4056
+ }
4057
+ /**
4058
+ * Write the updated workbook to disk.
4059
+ * @param outputPath Destination path; defaults to the source file (overwrites in place).
4060
+ */
4061
+ save(outputPath) {
4062
+ const target = outputPath ?? this.sourcePath;
4063
+ fs3.writeFileSync(target, this.zip.toBuffer());
4064
+ }
4065
+ /** The updated workbook as an in-memory ZIP buffer. */
4066
+ toBuffer() {
4067
+ return this.zip.toBuffer();
4068
+ }
4069
+ // ------------------------------------------------------------------
4070
+ // Workbook structure
4071
+ // ------------------------------------------------------------------
4072
+ _loadWorkbookStructure() {
4073
+ const relsEntry = this.zip.getEntry("xl/_rels/workbook.xml.rels");
4074
+ const rIdToTarget = {};
4075
+ if (relsEntry) {
4076
+ const rels = relsEntry.getData().toString("utf8");
4077
+ const relRegex = /<Relationship[^>]*Id="([^"]*)"[^>]*Target="([^"]*)"/g;
4078
+ let match2;
4079
+ while ((match2 = relRegex.exec(rels)) !== null) {
4080
+ rIdToTarget[match2[1]] = match2[2];
4081
+ }
4082
+ }
4083
+ const wbEntry = this.zip.getEntry("xl/workbook.xml");
4084
+ const wbXml = wbEntry ? wbEntry.getData().toString("utf8") : "";
4085
+ const sheetRe = /<sheet\b[^>]*>/g;
4086
+ let match;
4087
+ while ((match = sheetRe.exec(wbXml)) !== null) {
4088
+ const tag = match[0];
4089
+ const nameMatch = /name="([^"]*)"/.exec(tag);
4090
+ const rIdMatch = /r:id="([^"]*)"/.exec(tag);
4091
+ if (!nameMatch || !rIdMatch) continue;
4092
+ const name = nameMatch[1].replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&apos;/g, "'");
4093
+ const target = rIdToTarget[rIdMatch[1]] ?? "";
4094
+ let fullPath = target;
4095
+ if (fullPath.startsWith("/")) {
4096
+ fullPath = fullPath.substring(1);
4097
+ } else if (!fullPath.startsWith("xl/")) {
4098
+ fullPath = "xl/" + fullPath;
4099
+ }
4100
+ if (fullPath) {
4101
+ this.sheetNameToPath.set(name, fullPath);
4102
+ }
4103
+ }
4104
+ for (const entry of this.zip.getEntries()) {
4105
+ const name = entry.entryName;
4106
+ if (/^xl\/pivotCache\/pivotCacheDefinition\d*\.xml$/.test(name)) {
4107
+ this.pivotCacheDefs.push({ path: name, xml: entry.getData().toString("utf8") });
4108
+ } else if (/^xl\/pivotTables\/pivotTable\d*\.xml$/.test(name)) {
4109
+ this.pivotTableDefPaths.push(name);
4110
+ }
4111
+ }
4112
+ }
4113
+ // ------------------------------------------------------------------
4114
+ // Shared strings
4115
+ // ------------------------------------------------------------------
4116
+ _ensureSharedStringsLoaded() {
4117
+ if (this.stringIndexMap.size > 0 || this.sharedStringsXml !== null) {
4118
+ return;
4119
+ }
4120
+ const entry = this.zip.getEntry("xl/sharedStrings.xml");
4121
+ if (!entry) {
4122
+ this.sharedStringsXml = null;
4123
+ return;
4124
+ }
4125
+ this.sharedStringsXml = entry.getData().toString("utf8");
4126
+ this.sharedStringsValues = parseSharedStringsXml(this.sharedStringsXml);
4127
+ const countMatch = /<sst\b[^>]*>/.exec(this.sharedStringsXml);
4128
+ const countAttr = countMatch ? /count="(\d+)"/.exec(countMatch[0]) : null;
4129
+ this.sharedStringsCount = countAttr ? parseInt(countAttr[1], 10) : 0;
4130
+ this.sharedStringsValues.forEach((value, index) => {
4131
+ if (!this.stringIndexMap.has(value)) {
4132
+ this.stringIndexMap.set(value, index);
4133
+ }
4134
+ });
4135
+ this.sharedStringsOriginalLength = this.sharedStringsValues.length;
4136
+ }
4137
+ _commitSharedStrings() {
4138
+ if (this.sharedStringsXml === null || this.sharedStringsValues.length === this.sharedStringsOriginalLength) {
4139
+ return;
4140
+ }
4141
+ let xml = this.sharedStringsXml;
4142
+ const sstStart = xml.indexOf("<sst");
4143
+ const sstTagEnd = xml.indexOf(">", sstStart);
4144
+ if (sstStart !== -1 && sstTagEnd !== -1) {
4145
+ const tag = xml.substring(sstStart, sstTagEnd + 1);
4146
+ const newTag = tag.replace(/count="\d+"/, `count="${this.sharedStringsCount}"`).replace(/uniqueCount="\d+"/, `uniqueCount="${this.sharedStringsValues.length}"`);
4147
+ xml = xml.substring(0, sstStart) + newTag + xml.substring(sstTagEnd + 1);
4148
+ }
4149
+ const sstEnd = xml.lastIndexOf("</sst>");
4150
+ if (sstEnd === -1) {
4151
+ return;
4152
+ }
4153
+ let appended = "";
4154
+ for (let i = this.sharedStringsOriginalLength; i < this.sharedStringsValues.length; i++) {
4155
+ const txt = this.sharedStringsValues[i];
4156
+ const clean = escapeXmlText(txt);
4157
+ const preserve = clean.length > 0 && (clean[0] === " " || clean[clean.length - 1] === " " || /[\t\n\r]/.test(clean));
4158
+ appended += preserve ? `<si><t xml:space="preserve">${clean}</t></si>` : `<si><t>${clean}</t></si>`;
4159
+ }
4160
+ xml = xml.substring(0, sstEnd) + appended + xml.substring(sstEnd);
4161
+ this.zip.updateFile("xl/sharedStrings.xml", Buffer.from(xml, "utf8"));
4162
+ }
4163
+ // ------------------------------------------------------------------
4164
+ // Styles
4165
+ // ------------------------------------------------------------------
4166
+ _collectExistingStyles(sheetXml) {
4167
+ const dataCounts = /* @__PURE__ */ new Map();
4168
+ const headerStyles = /* @__PURE__ */ new Map();
4169
+ const sdStart = sheetXml.indexOf("<sheetData>");
4170
+ if (sdStart === -1) return { dataStyles: /* @__PURE__ */ new Map(), headerStyles };
4171
+ const sdEnd = sheetXml.indexOf("</sheetData>", sdStart);
4172
+ if (sdEnd === -1) return { dataStyles: /* @__PURE__ */ new Map(), headerStyles };
4173
+ const region = sheetXml.substring(sdStart, sdEnd);
4174
+ const cellRe = /<c\b[^>]*>/g;
4175
+ let m;
4176
+ while ((m = cellRe.exec(region)) !== null) {
4177
+ const tag = m[0];
4178
+ const rMatch = /r="([A-Z]+)(\d+)"/.exec(tag);
4179
+ if (!rMatch) continue;
4180
+ const col = columnLetterToIndex(rMatch[1]);
4181
+ const row = parseInt(rMatch[2], 10);
4182
+ const sMatch = /s="(\d+)"/.exec(tag);
4183
+ if (!sMatch) continue;
4184
+ const s = parseInt(sMatch[1], 10);
4185
+ if (s <= 0) continue;
4186
+ if (row === 1) {
4187
+ if (!headerStyles.has(col)) headerStyles.set(col, s);
4188
+ continue;
4189
+ }
4190
+ let colCounts = dataCounts.get(col);
4191
+ if (!colCounts) {
4192
+ colCounts = /* @__PURE__ */ new Map();
4193
+ dataCounts.set(col, colCounts);
4194
+ }
4195
+ colCounts.set(s, (colCounts.get(s) ?? 0) + 1);
4196
+ }
4197
+ const dataStyles = /* @__PURE__ */ new Map();
4198
+ for (const [col, colCounts] of dataCounts) {
4199
+ let best = 0;
4200
+ let bestCount = -1;
4201
+ for (const [s, count] of colCounts) {
4202
+ if (count > bestCount) {
4203
+ best = s;
4204
+ bestCount = count;
4205
+ }
4206
+ }
4207
+ if (bestCount > 0) dataStyles.set(col, best);
4208
+ }
4209
+ return { dataStyles, headerStyles };
4210
+ }
4211
+ _findDateStyleIndex() {
4212
+ const entry = this.zip.getEntry("xl/styles.xml");
4213
+ if (!entry) return null;
4214
+ const xml = entry.getData().toString("utf8");
4215
+ const customDateFormats = /* @__PURE__ */ new Set();
4216
+ const numFmtRe = /<numFmt\s+[^>]*numFmtId="(\d+)"[^>]*formatCode="([^"]*)"/g;
4217
+ let m;
4218
+ while ((m = numFmtRe.exec(xml)) !== null) {
4219
+ const id = parseInt(m[1], 10);
4220
+ const code = m[2].toLowerCase();
4221
+ if (code.includes("yy") || code.includes("mm") || code.includes("dd") || code.includes("h:mm")) {
4222
+ customDateFormats.add(id);
4223
+ }
4224
+ }
4225
+ const cellXfsStart = xml.indexOf("<cellXfs");
4226
+ if (cellXfsStart === -1) return null;
4227
+ const cellXfsEnd = xml.indexOf("</cellXfs>", cellXfsStart);
4228
+ if (cellXfsEnd === -1) return null;
4229
+ const cellXfsContent = xml.substring(cellXfsStart, cellXfsEnd);
4230
+ const xfRe = /<xf\b[^>]*>/g;
4231
+ let index = 0;
4232
+ while ((m = xfRe.exec(cellXfsContent)) !== null) {
4233
+ const nfMatch = /numFmtId="(\d+)"/.exec(m[0]);
4234
+ const nfId = nfMatch ? parseInt(nfMatch[1], 10) : 0;
4235
+ const isDate = nfId >= 14 && nfId <= 22 || nfId >= 45 && nfId <= 47 || customDateFormats.has(nfId);
4236
+ if (isDate) return index;
4237
+ index++;
4238
+ }
4239
+ return null;
4240
+ }
4241
+ // ------------------------------------------------------------------
4242
+ // Cell / row serialization
4243
+ // ------------------------------------------------------------------
4244
+ _buildSheetData(rows, headers, colStyles, headerStyles, dateStyle) {
4245
+ let out = "";
4246
+ let rowNum = 0;
4247
+ if (headers) {
4248
+ rowNum = 1;
4249
+ out += '<row r="1">';
4250
+ for (let c = 0; c < headers.length; c++) {
4251
+ const style = headerStyles.get(c) ?? 0;
4252
+ out += this._stringCell(headers[c], c, rowNum, style);
4253
+ }
4254
+ out += "</row>";
4255
+ }
4256
+ for (const row of rows) {
4257
+ rowNum++;
4258
+ out += `<row r="${rowNum}">`;
4259
+ for (let c = 0; c < row.length; c++) {
4260
+ const raw = row[c];
4261
+ if (raw === null || raw === void 0) continue;
4262
+ out += this._valueCell(raw, c, rowNum, colStyles, dateStyle);
4263
+ }
4264
+ out += "</row>";
4265
+ }
4266
+ return out;
4267
+ }
4268
+ _valueCell(raw, col, rowNum, colStyles, dateStyle) {
4269
+ const colRef = columnIndexToLetter(col);
4270
+ const fmtString = getFormat(raw);
4271
+ const val = fmtString !== null ? unwrapCell(raw) : raw;
4272
+ const colStyle = colStyles.get(col) ?? 0;
4273
+ if (typeof val === "number") {
4274
+ if (Number.isFinite(val)) {
4275
+ return `<c r="${colRef}${rowNum}"${colStyle > 0 ? ` s="${colStyle}"` : ""}><v>${val}</v></c>`;
4276
+ }
4277
+ return this._stringCell(val.toString(), col, rowNum, colStyle);
4278
+ }
4279
+ if (typeof val === "bigint") {
4280
+ return this._stringCell(val.toString(), col, rowNum, colStyle);
4281
+ }
4282
+ if (typeof val === "boolean") {
4283
+ return `<c r="${colRef}${rowNum}" t="b"${colStyle > 0 ? ` s="${colStyle}"` : ""}><v>${val ? 1 : 0}</v></c>`;
4284
+ }
4285
+ if (val instanceof Date) {
4286
+ const oaDate = (val.getTime() - this._oaEpoch) / 864e5;
4287
+ if (Number.isFinite(oaDate)) {
4288
+ const style = colStyle > 0 ? colStyle : dateStyle !== null ? dateStyle : 0;
4289
+ return `<c r="${colRef}${rowNum}"${style > 0 ? ` s="${style}"` : ""}><v>${oaDate}</v></c>`;
4290
+ }
4291
+ return this._stringCell(val.toString(), col, rowNum, colStyle);
4292
+ }
4293
+ if (val !== null && val !== void 0) {
4294
+ return this._stringCell(String(val), col, rowNum, colStyle);
4295
+ }
4296
+ return "";
4297
+ }
4298
+ _stringCell(text, col, rowNum, style) {
4299
+ const colRef = columnIndexToLetter(col);
4300
+ const styleAttr = style > 0 ? ` s="${style}"` : "";
4301
+ if (this.sharedStringsXml === null) {
4302
+ const clean = escapeXmlText(text);
4303
+ const preserve = clean.length > 0 && (clean[0] === " " || clean[clean.length - 1] === " " || /[\t\n\r]/.test(clean));
4304
+ const tAttr = preserve ? ' xml:space="preserve"' : "";
4305
+ return `<c r="${colRef}${rowNum}" t="inlineStr"${styleAttr}><is><t${tAttr}>${clean}</t></is></c>`;
4306
+ }
4307
+ let index = this.stringIndexMap.get(text);
4308
+ if (index === void 0) {
4309
+ index = this.sharedStringsValues.length;
4310
+ this.sharedStringsValues.push(text);
4311
+ this.stringIndexMap.set(text, index);
4312
+ }
4313
+ this.sharedStringsCount++;
4314
+ return `<c r="${colRef}${rowNum}" t="s"${styleAttr}><v>${index}</v></c>`;
4315
+ }
4316
+ // ------------------------------------------------------------------
4317
+ // Worksheet XML patching
4318
+ // ------------------------------------------------------------------
4319
+ _patchSheetXml(sheetXml, newSheetData, totalRows, lastCol) {
4320
+ let xml = sheetXml;
4321
+ const dimRef = totalRows > 0 && lastCol >= 0 ? `A1:${columnIndexToLetter(lastCol)}${totalRows}` : "A1";
4322
+ const dimRe = /<dimension\b[^>]*>/;
4323
+ const dimMatch = dimRe.exec(xml);
4324
+ if (dimMatch) {
4325
+ xml = xml.substring(0, dimMatch.index) + dimMatch[0].replace(/ref="[^"]*"/, `ref="${dimRef}"`) + xml.substring(dimMatch.index + dimMatch[0].length);
4326
+ } else {
4327
+ const rootRe = /<worksheet\b[^>]*>/;
4328
+ const rootMatch = rootRe.exec(xml);
4329
+ if (rootMatch) {
4330
+ const insertAt = rootMatch.index + rootMatch[0].length;
4331
+ xml = xml.substring(0, insertAt) + `<dimension ref="${dimRef}"/>` + xml.substring(insertAt);
4332
+ }
4333
+ }
4334
+ const sdOpen = "<sheetData>";
4335
+ const sdStart = xml.indexOf(sdOpen);
4336
+ if (sdStart === -1) {
4337
+ const selfClosing = /<sheetData\s*\/\s*>/;
4338
+ const scMatch = selfClosing.exec(xml);
4339
+ if (scMatch) {
4340
+ xml = xml.substring(0, scMatch.index) + "<sheetData>" + newSheetData + "</sheetData>" + xml.substring(scMatch.index + scMatch[0].length);
4341
+ return xml;
4342
+ }
4343
+ throw new Error("XlsxUpdater: <sheetData> element not found in worksheet XML.");
4344
+ }
4345
+ const sdEnd = xml.indexOf("</sheetData>", sdStart);
4346
+ if (sdEnd === -1) {
4347
+ throw new Error("XlsxUpdater: <sheetData> element not closed in worksheet XML.");
4348
+ }
4349
+ xml = xml.substring(0, sdStart + sdOpen.length) + newSheetData + xml.substring(sdEnd);
4350
+ const afRe = /<autoFilter\b[^>]*>/;
4351
+ const afMatch = afRe.exec(xml);
4352
+ if (afMatch && totalRows > 0 && lastCol >= 0 && afMatch[0].includes("ref=")) {
4353
+ xml = xml.substring(0, afMatch.index) + afMatch[0].replace(/ref="[^"]*"/, `ref="${dimRef}"`) + xml.substring(afMatch.index + afMatch[0].length);
4354
+ }
4355
+ return xml;
4356
+ }
4357
+ // ------------------------------------------------------------------
4358
+ // Pivot table integration
4359
+ // ------------------------------------------------------------------
4360
+ _updatePivotCaches(sheetName, dimRef, recordCount) {
4361
+ for (const cache of this.pivotCacheDefs) {
4362
+ const wsRe = /<worksheetSource\b[^>]*>/;
4363
+ const wsMatch = wsRe.exec(cache.xml);
4364
+ if (!wsMatch) continue;
4365
+ const wsTag = wsMatch[0];
4366
+ const sheetAttr = /sheet="([^"]*)"/.exec(wsTag);
4367
+ if (!sheetAttr || sheetAttr[1] !== sheetName) continue;
4368
+ let xml = cache.xml;
4369
+ xml = xml.substring(0, wsMatch.index) + wsTag.replace(/ref="[^"]*"/, `ref="${dimRef}"`) + xml.substring(wsMatch.index + wsTag.length);
4370
+ const rootRe = /<pivotCacheDefinition\b[^>]*>/;
4371
+ const rootMatch = rootRe.exec(xml);
4372
+ if (rootMatch) {
4373
+ let rootTag = rootMatch[0];
4374
+ if (/recordCount="\d+"/.test(rootTag)) {
4375
+ rootTag = rootTag.replace(/recordCount="\d+"/, `recordCount="${recordCount}"`);
4376
+ } else if (!/\/>$/.test(rootTag)) {
4377
+ rootTag = rootTag.replace(/>$/, ` recordCount="${recordCount}">`);
4378
+ }
4379
+ xml = xml.substring(0, rootMatch.index) + rootTag + xml.substring(rootMatch.index + rootMatch[0].length);
4380
+ }
4381
+ this.zip.updateFile(cache.path, Buffer.from(xml, "utf8"));
4382
+ }
4383
+ }
4384
+ _addRefreshOnLoadToPivotTables() {
4385
+ for (const path2 of this.pivotTableDefPaths) {
4386
+ const entry = this.zip.getEntry(path2);
4387
+ if (!entry) continue;
4388
+ let xml = entry.getData().toString("utf8");
4389
+ const rootRe = /<pivotTableDefinition\b[^>]*>/;
4390
+ const rootMatch = rootRe.exec(xml);
4391
+ if (!rootMatch || rootMatch[0].includes("refreshOnLoad")) continue;
4392
+ const newTag = rootMatch[0].replace(/(\/?>)$/, ' refreshOnLoad="1"$1');
4393
+ xml = xml.substring(0, rootMatch.index) + newTag + xml.substring(rootMatch.index + rootMatch[0].length);
4394
+ this.zip.updateFile(path2, Buffer.from(xml, "utf8"));
4395
+ }
4396
+ }
4397
+ };
4398
+
4399
+ // src/XlsbUpdater.ts
4400
+ var fs4 = __toESM(require("fs"));
4401
+ var import_adm_zip3 = __toESM(require("adm-zip"));
4402
+
4403
+ // src/biff12Utils.ts
4404
+ function readVlq(buf, pos) {
4405
+ let value = 0;
4406
+ let shift = 0;
4407
+ let byte;
4408
+ do {
4409
+ byte = buf[pos++];
4410
+ value |= (byte & 127) << shift;
4411
+ shift += 7;
4412
+ } while ((byte & 128) !== 0);
4413
+ return { value, nextPos: pos };
4414
+ }
4415
+ function vlqBytes(value) {
4416
+ const out = [];
4417
+ while (value >= 128) {
4418
+ out.push(value & 127 | 128);
4419
+ value >>>= 7;
4420
+ }
4421
+ out.push(value & 127);
4422
+ return out;
4423
+ }
4424
+ function readRecord(buf, pos, rec) {
4425
+ const idRes = readVlq(buf, pos);
4426
+ if (idRes.nextPos > buf.length) return false;
4427
+ const lenRes = readVlq(buf, idRes.nextPos);
4428
+ if (lenRes.nextPos + lenRes.value > buf.length) return false;
4429
+ rec.headerStart = pos;
4430
+ rec.dataStart = lenRes.nextPos;
4431
+ rec.dataEnd = lenRes.nextPos + lenRes.value;
4432
+ rec.id = idRes.value;
4433
+ rec.len = lenRes.value;
4434
+ return true;
4435
+ }
4436
+ function buildRecord(id, payload) {
4437
+ const idBytes = vlqBytes(id);
4438
+ const lenBytes = vlqBytes(payload.length);
4439
+ const header = Buffer.alloc(idBytes.length + lenBytes.length);
4440
+ idBytes.forEach((b, i) => header[i] = b);
4441
+ lenBytes.forEach((b, i) => header[idBytes.length + i] = b);
4442
+ return Buffer.concat([header, payload]);
4443
+ }
4444
+ function readUtf16(buf, start, charCount) {
4445
+ const end = start + charCount * 2;
4446
+ if (end > buf.length) return "";
4447
+ return buf.toString("utf16le", start, end);
4448
+ }
4449
+ function parseSharedStringsBin(buf) {
4450
+ const values = [];
4451
+ let total = 0;
4452
+ let unique = 0;
4453
+ let endSstOffset = buf.length;
4454
+ const rec = { headerStart: 0, dataStart: 0, dataEnd: 0, id: 0, len: 0 };
4455
+ let pos = 0;
4456
+ while (readRecord(buf, pos, rec)) {
4457
+ pos = rec.dataEnd;
4458
+ if (rec.id === 159) {
4459
+ total = buf.readUInt32LE(rec.dataStart);
4460
+ unique = buf.readUInt32LE(rec.dataStart + 4);
4461
+ } else if (rec.id === 19) {
4462
+ const cch = buf.readUInt32LE(rec.dataStart + 1);
4463
+ values.push(readUtf16(buf, rec.dataStart + 5, cch));
4464
+ } else if (rec.id === 160) {
4465
+ endSstOffset = rec.headerStart;
4466
+ }
4467
+ }
4468
+ return { values, total, unique, endSstOffset };
4469
+ }
4470
+
4471
+ // src/XlsbUpdater.ts
4472
+ var CELL_RECORDS = /* @__PURE__ */ new Set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]);
4473
+ var RK_INT_LOWER = -1 << 29;
4474
+ var RK_INT_UPPER = (1 << 29) - 1;
4475
+ var XlsbUpdater = class {
4476
+ /**
4477
+ * @param path Path to an existing `.xlsb` file.
4478
+ */
4479
+ constructor(path2) {
4480
+ this.sheetNameToPath = /* @__PURE__ */ new Map();
4481
+ this.pivotCacheDefPaths = [];
4482
+ this.sharedStringsBuf = null;
4483
+ this.sharedStringsValues = [];
4484
+ this.sharedStringsTotal = 0;
4485
+ this.sharedStringsUnique = 0;
4486
+ this.sharedStringsEndSst = 0;
4487
+ this.stringIndexMap = /* @__PURE__ */ new Map();
4488
+ // ------------------------------------------------------------------
4489
+ // Shared strings
4490
+ // ------------------------------------------------------------------
4491
+ this._appendCount = 0;
4492
+ this.sourcePath = path2;
4493
+ this._oaEpoch = Date.UTC(1899, 11, 30);
4494
+ if (!fs4.existsSync(path2)) {
4495
+ throw new Error(`XlsbUpdater: file not found: ${path2}`);
4496
+ }
4497
+ this.zip = new import_adm_zip3.default(path2);
4498
+ if (!this.zip.getEntry("xl/workbook.bin")) {
4499
+ throw new Error(
4500
+ "XlsbUpdater: not an XLSB workbook (xl/workbook.bin missing). Convert the file to XLSB first."
4501
+ );
4502
+ }
4503
+ this._loadWorkbookStructure();
4504
+ }
4505
+ /** Worksheet names in workbook order. */
4506
+ getSheetNames() {
4507
+ return [...this.sheetNameToPath.keys()];
4508
+ }
4509
+ /**
4510
+ * Clear the entire cell data of the target sheet and write new rows in its place.
4511
+ * All other parts of the workbook (pivot tables, other sheets, styles, …) are preserved.
4512
+ *
4513
+ * @param sheetName Name of the worksheet to replace.
4514
+ * @param rows New data rows (`CellValue` cells; null/undefined = blank).
4515
+ * @param options See {@link ReplaceSheetDataOptions}.
4516
+ */
4517
+ replaceSheetData(sheetName, rows, options = {}) {
4518
+ const { headers, styleFallback = "inherit" } = options;
4519
+ rows = trimTrailingEmptyRows(rows);
4520
+ const sheetPath = this.sheetNameToPath.get(sheetName);
4521
+ if (!sheetPath) {
4522
+ throw new Error(`XlsbUpdater: sheet "${sheetName}" not found in the workbook.`);
4523
+ }
4524
+ const entry = this.zip.getEntry(sheetPath);
4525
+ if (!entry) {
4526
+ throw new Error(`XlsbUpdater: worksheet part missing for sheet "${sheetName}".`);
4527
+ }
4528
+ const sheetBuf = entry.getData();
4529
+ this._ensureSharedStringsLoaded();
4530
+ let dataStyles = /* @__PURE__ */ new Map();
4531
+ let headerStyles = /* @__PURE__ */ new Map();
4532
+ let dateXf = null;
4533
+ if (styleFallback !== "general") {
4534
+ const collected = this._collectStyles(sheetBuf);
4535
+ dataStyles = collected.dataStyles;
4536
+ headerStyles = collected.headerStyles;
4537
+ dateXf = this._findDateXf();
4538
+ }
4539
+ const lastCol = Math.max(0, Math.max(
4540
+ rows.reduce((m, r) => Math.max(m, r.length), 0),
4541
+ (headers == null ? void 0 : headers.length) ?? 0
4542
+ ) - 1);
4543
+ const newRows = this._buildRows(rows, headers, dataStyles, headerStyles, dateXf);
4544
+ const { rowsStart, rowsEnd, autoFilterRanges } = this._findRowsRegion(sheetBuf);
4545
+ const newSheet = Buffer.alloc(sheetBuf.length - (rowsEnd - rowsStart) + newRows.length);
4546
+ sheetBuf.copy(newSheet, 0, 0, rowsStart);
4547
+ newRows.copy(newSheet, rowsStart);
4548
+ sheetBuf.copy(newSheet, rowsStart + newRows.length, rowsEnd);
4549
+ const lastRowIdx = rows.length + (headers ? 1 : 0) - 1;
4550
+ const delta = newRows.length - (rowsEnd - rowsStart);
4551
+ for (const af of autoFilterRanges) {
4552
+ const newAf = af + delta;
4553
+ newSheet.writeInt32LE(lastCol, newAf + 12);
4554
+ newSheet.writeInt32LE(lastRowIdx, newAf + 4);
4555
+ }
4556
+ this._patchDimension(newSheet, lastRowIdx, lastCol);
4557
+ this.zip.updateFile(sheetPath, newSheet);
4558
+ if (this.sharedStringsBuf !== null && this._appendCount > 0) {
4559
+ this._commitSharedStrings();
4560
+ }
4561
+ const rwLast = Math.max(0, rows.length + (headers ? 1 : 0) - 1);
4562
+ const colLast = lastCol;
4563
+ this._patchPivotCaches(sheetName, rwLast, colLast);
4564
+ }
4565
+ /**
4566
+ * Write the updated workbook to disk.
4567
+ * @param outputPath Destination path; defaults to the source file (overwrites in place).
4568
+ */
4569
+ save(outputPath) {
4570
+ const target = outputPath ?? this.sourcePath;
4571
+ fs4.writeFileSync(target, this.zip.toBuffer());
4572
+ }
4573
+ /** The updated workbook as an in-memory ZIP buffer. */
4574
+ toBuffer() {
4575
+ return this.zip.toBuffer();
4576
+ }
4577
+ // ------------------------------------------------------------------
4578
+ // Workbook structure
4579
+ // ------------------------------------------------------------------
4580
+ _loadWorkbookStructure() {
4581
+ const relsEntry = this.zip.getEntry("xl/_rels/workbook.bin.rels");
4582
+ const rIdToTarget = {};
4583
+ if (relsEntry) {
4584
+ const rels = relsEntry.getData().toString("utf8");
4585
+ const relRegex = /<Relationship[^>]*Id="([^"]*)"[^>]*Target="([^"]*)"/g;
4586
+ let match;
4587
+ while ((match = relRegex.exec(rels)) !== null) {
4588
+ rIdToTarget[match[1]] = match[2];
4589
+ }
4590
+ }
4591
+ const wbEntry = this.zip.getEntry("xl/workbook.bin");
4592
+ if (wbEntry) {
4593
+ const wbBuf = wbEntry.getData();
4594
+ const rec = { headerStart: 0, dataStart: 0, dataEnd: 0, id: 0, len: 0 };
4595
+ let pos = 0;
4596
+ while (readRecord(wbBuf, pos, rec)) {
4597
+ pos = rec.dataEnd;
4598
+ if (rec.id !== 156 || rec.len < 8) continue;
4599
+ let o = rec.dataStart + 8;
4600
+ const rIdLen = wbBuf.readUInt32LE(o);
4601
+ o += 4;
4602
+ const rId = readUtf16(wbBuf, o, rIdLen);
4603
+ o += rIdLen * 2;
4604
+ const nameLen = wbBuf.readUInt32LE(o);
4605
+ o += 4;
4606
+ const name = readUtf16(wbBuf, o, nameLen);
4607
+ let target = rIdToTarget[rId] ?? "";
4608
+ if (target.startsWith("/")) target = target.substring(1);
4609
+ else if (!target.startsWith("xl/")) target = "xl/" + target;
4610
+ if (target) {
4611
+ this.sheetNameToPath.set(name, target);
4612
+ }
4613
+ }
4614
+ }
4615
+ for (const e of this.zip.getEntries()) {
4616
+ if (/^xl\/pivotCache\/pivotCacheDefinition\d*\.bin$/.test(e.entryName)) {
4617
+ this.pivotCacheDefPaths.push(e.entryName);
4618
+ }
4619
+ }
4620
+ }
4621
+ _ensureSharedStringsLoaded() {
4622
+ if (this.stringIndexMap.size > 0 || this.sharedStringsBuf !== null) {
4623
+ return;
4624
+ }
4625
+ const entry = this.zip.getEntry("xl/sharedStrings.bin");
4626
+ if (!entry) {
4627
+ this.sharedStringsBuf = null;
4628
+ return;
4629
+ }
4630
+ this.sharedStringsBuf = entry.getData();
4631
+ const parsed = parseSharedStringsBin(this.sharedStringsBuf);
4632
+ this.sharedStringsValues = parsed.values;
4633
+ this.sharedStringsTotal = parsed.total;
4634
+ this.sharedStringsUnique = parsed.unique;
4635
+ this.sharedStringsEndSst = parsed.endSstOffset;
4636
+ this.sharedStringsValues.forEach((value, index) => {
4637
+ if (!this.stringIndexMap.has(value)) {
4638
+ this.stringIndexMap.set(value, index);
4639
+ }
4640
+ });
4641
+ this._appendCount = 0;
4642
+ }
4643
+ _commitSharedStrings() {
4644
+ if (this.sharedStringsBuf === null || this._appendCount === 0) return;
4645
+ const originalValuesLength = this.sharedStringsValues.length - this._appendCount;
4646
+ let newItems = Buffer.alloc(0);
4647
+ for (let i = originalValuesLength; i < this.sharedStringsValues.length; i++) {
4648
+ const text = this.sharedStringsValues[i];
4649
+ const payload = Buffer.alloc(1 + 4 + text.length * 2);
4650
+ payload[0] = 0;
4651
+ payload.writeUInt32LE(text.length, 1);
4652
+ payload.write(text, 5, text.length * 2, "utf16le");
4653
+ newItems = Buffer.concat([newItems, buildRecord(19, payload)]);
4654
+ }
4655
+ const out = Buffer.alloc(this.sharedStringsBuf.length + newItems.length);
4656
+ this.sharedStringsBuf.copy(out, 0, 0, this.sharedStringsEndSst);
4657
+ newItems.copy(out, this.sharedStringsEndSst);
4658
+ this.sharedStringsBuf.copy(out, this.sharedStringsEndSst + newItems.length, this.sharedStringsEndSst);
4659
+ const rec = { headerStart: 0, dataStart: 0, dataEnd: 0, id: 0, len: 0 };
4660
+ let pos = 0;
4661
+ while (readRecord(out, pos, rec)) {
4662
+ if (rec.id === 159) {
4663
+ out.writeUInt32LE(this.sharedStringsTotal, rec.dataStart);
4664
+ out.writeUInt32LE(this.sharedStringsUnique, rec.dataStart + 4);
4665
+ break;
4666
+ }
4667
+ pos = rec.dataEnd;
4668
+ }
4669
+ this.zip.updateFile("xl/sharedStrings.bin", out);
4670
+ }
4671
+ // ------------------------------------------------------------------
4672
+ // Styles
4673
+ // ------------------------------------------------------------------
4674
+ _collectStyles(sheetBuf) {
4675
+ const dataCounts = /* @__PURE__ */ new Map();
4676
+ const headerStyles = /* @__PURE__ */ new Map();
4677
+ const rec = { headerStart: 0, dataStart: 0, dataEnd: 0, id: 0, len: 0 };
4678
+ let pos = 0;
4679
+ let row = -1;
4680
+ while (readRecord(sheetBuf, pos, rec)) {
4681
+ pos = rec.dataEnd;
4682
+ if (rec.id === 0) {
4683
+ row = sheetBuf.readInt32LE(rec.dataStart);
4684
+ continue;
4685
+ }
4686
+ if (!CELL_RECORDS.has(rec.id) || rec.len < 8) continue;
4687
+ const col = sheetBuf.readUInt32LE(rec.dataStart);
4688
+ const xf = sheetBuf.readUInt32LE(rec.dataStart + 4) & 16777215;
4689
+ if (xf <= 0) continue;
4690
+ if (row === 0) {
4691
+ if (!headerStyles.has(col)) headerStyles.set(col, xf);
4692
+ continue;
4693
+ }
4694
+ let colCounts = dataCounts.get(col);
4695
+ if (!colCounts) {
4696
+ colCounts = /* @__PURE__ */ new Map();
4697
+ dataCounts.set(col, colCounts);
4698
+ }
4699
+ colCounts.set(xf, (colCounts.get(xf) ?? 0) + 1);
4700
+ }
4701
+ const dataStyles = /* @__PURE__ */ new Map();
4702
+ for (const [col, colCounts] of dataCounts) {
4703
+ let best = 0;
4704
+ let bestCount = -1;
4705
+ for (const [xf, count] of colCounts) {
4706
+ if (count > bestCount) {
4707
+ best = xf;
4708
+ bestCount = count;
4709
+ }
4710
+ }
4711
+ if (bestCount > 0) dataStyles.set(col, best);
4712
+ }
4713
+ return { dataStyles, headerStyles };
4714
+ }
4715
+ _findDateXf() {
4716
+ const entry = this.zip.getEntry("xl/styles.bin");
4717
+ if (!entry) return null;
4718
+ const stylesBuf = entry.getData();
4719
+ const rec = { headerStart: 0, dataStart: 0, dataEnd: 0, id: 0, len: 0 };
4720
+ let pos = 0;
4721
+ let inCellXfs = false;
4722
+ let xfIndex = 0;
4723
+ while (readRecord(stylesBuf, pos, rec)) {
4724
+ pos = rec.dataEnd;
4725
+ if (rec.id === 617) {
4726
+ inCellXfs = true;
4727
+ xfIndex = 0;
4728
+ continue;
4729
+ }
4730
+ if (rec.id === 618) {
4731
+ inCellXfs = false;
4732
+ continue;
4733
+ }
4734
+ if (inCellXfs && rec.id === 47 && rec.len >= 4) {
4735
+ const numFmtId = stylesBuf.readUInt16LE(rec.dataStart + 2);
4736
+ const isDate = numFmtId >= 14 && numFmtId <= 22 || numFmtId >= 45 && numFmtId <= 47;
4737
+ if (isDate) return xfIndex;
4738
+ xfIndex++;
4739
+ }
4740
+ }
4741
+ return null;
4742
+ }
4743
+ // ------------------------------------------------------------------
4744
+ // Row / cell serialization
4745
+ // ------------------------------------------------------------------
4746
+ _buildRows(rows, headers, dataStyles, headerStyles, dateXf) {
4747
+ const chunks = [];
4748
+ const maxCol = Math.max(rows.reduce((m, r) => Math.max(m, r.length), 0), (headers == null ? void 0 : headers.length) ?? 0, 0);
4749
+ const colLast = Math.max(0, maxCol - 1);
4750
+ const pushRow = (rowNum2, cellBytes) => {
4751
+ const header = Buffer.alloc(27);
4752
+ header[0] = 0;
4753
+ header[1] = 25;
4754
+ header.writeInt32LE(rowNum2, 2);
4755
+ header[10] = 44;
4756
+ header[11] = 1;
4757
+ header[15] = 1;
4758
+ header.writeInt32LE(0, 19);
4759
+ header.writeInt32LE(colLast, 23);
4760
+ chunks.push(header);
4761
+ for (const cell of cellBytes) {
4762
+ chunks.push(cell);
4763
+ }
4764
+ };
4765
+ if (headers) {
4766
+ const cells = [];
4767
+ for (let c = 0; c < headers.length; c++) {
4768
+ const style = headerStyles.get(c) ?? 0;
4769
+ cells.push(this._stringCellBytes(c, style, headers[c]));
4770
+ }
4771
+ pushRow(0, cells);
4772
+ }
4773
+ let rowNum = headers ? 1 : 0;
4774
+ for (const row of rows) {
4775
+ const cells = [];
4776
+ for (let c = 0; c < row.length; c++) {
4777
+ const raw = row[c];
4778
+ if (raw === null || raw === void 0) continue;
4779
+ cells.push(this._valueCellBytes(raw, c, dataStyles, dateXf));
4780
+ }
4781
+ pushRow(rowNum, cells);
4782
+ rowNum++;
4783
+ }
4784
+ return Buffer.concat(chunks);
4785
+ }
4786
+ _valueCellBytes(raw, col, dataStyles, dateXf) {
4787
+ const fmtString = getFormat(raw);
4788
+ const val = fmtString !== null ? unwrapCell(raw) : raw;
4789
+ const colStyle = dataStyles.get(col) ?? 0;
4790
+ if (typeof val === "number") {
4791
+ if (Number.isFinite(val) && Number.isInteger(val) && val >= RK_INT_LOWER && val <= RK_INT_UPPER) {
4792
+ const payload = Buffer.alloc(12);
4793
+ payload.writeUInt32LE(col, 0);
4794
+ payload.writeUInt32LE(colStyle, 4);
4795
+ payload.writeInt32LE(val << 2 | 2, 8);
4796
+ return buildRecord(2, payload);
4797
+ }
4798
+ if (Number.isFinite(val)) {
4799
+ const payload = Buffer.alloc(16);
4800
+ payload.writeUInt32LE(col, 0);
4801
+ payload.writeUInt32LE(colStyle, 4);
4802
+ payload.writeDoubleLE(val, 8);
4803
+ return buildRecord(5, payload);
4804
+ }
4805
+ return this._stringCellBytes(col, colStyle, val.toString());
4806
+ }
4807
+ if (typeof val === "bigint") {
4808
+ return this._stringCellBytes(col, colStyle, val.toString());
4809
+ }
4810
+ if (typeof val === "boolean") {
4811
+ const payload = Buffer.alloc(9);
4812
+ payload.writeUInt32LE(col, 0);
4813
+ payload.writeUInt32LE(colStyle, 4);
4814
+ payload[8] = val ? 1 : 0;
4815
+ return buildRecord(4, payload);
4816
+ }
4817
+ if (val instanceof Date) {
4818
+ const oaDate = (val.getTime() - this._oaEpoch) / 864e5;
4819
+ if (Number.isFinite(oaDate)) {
4820
+ const style = colStyle > 0 ? colStyle : dateXf !== null ? dateXf : 0;
4821
+ const payload = Buffer.alloc(16);
4822
+ payload.writeUInt32LE(col, 0);
4823
+ payload.writeUInt32LE(style, 4);
4824
+ payload.writeDoubleLE(oaDate, 8);
4825
+ return buildRecord(5, payload);
4826
+ }
4827
+ return this._stringCellBytes(col, colStyle, val.toString());
4828
+ }
4829
+ if (val !== null && val !== void 0) {
4830
+ return this._stringCellBytes(col, colStyle, String(val));
4831
+ }
4832
+ return this._stringCellBytes(col, colStyle, "");
4833
+ }
4834
+ _stringCellBytes(col, style, text) {
4835
+ if (this.sharedStringsBuf === null) {
4836
+ const payload2 = Buffer.alloc(12 + text.length * 2);
4837
+ payload2.writeUInt32LE(col, 0);
4838
+ payload2.writeUInt32LE(style, 4);
4839
+ payload2.writeUInt32LE(text.length, 8);
4840
+ payload2.write(text, 12, text.length * 2, "utf16le");
4841
+ return buildRecord(6, payload2);
4842
+ }
4843
+ let index = this.stringIndexMap.get(text);
4844
+ if (index === void 0) {
4845
+ index = this.sharedStringsValues.length;
4846
+ this.sharedStringsValues.push(text);
4847
+ this.stringIndexMap.set(text, index);
4848
+ this.sharedStringsUnique++;
4849
+ this._appendCount++;
4850
+ }
4851
+ this.sharedStringsTotal++;
4852
+ const payload = Buffer.alloc(12);
4853
+ payload.writeUInt32LE(col, 0);
4854
+ payload.writeUInt32LE(style, 4);
4855
+ payload.writeUInt32LE(index, 8);
4856
+ return buildRecord(7, payload);
4857
+ }
4858
+ // ------------------------------------------------------------------
4859
+ // Rows region detection
4860
+ // ------------------------------------------------------------------
4861
+ _findRowsRegion(sheetBuf) {
4862
+ const autoFilterRanges = [];
4863
+ let rowsStart = -1;
4864
+ let lastCellEnd = -1;
4865
+ let lastW25 = -1;
4866
+ const rec = { headerStart: 0, dataStart: 0, dataEnd: 0, id: 0, len: 0 };
4867
+ let pos = 0;
4868
+ while (readRecord(sheetBuf, pos, rec)) {
4869
+ if (rec.id === 0) {
4870
+ if (rowsStart === -1) rowsStart = rec.headerStart;
4871
+ } else if (rec.id >= 1 && rec.id <= 11) {
4872
+ lastCellEnd = rec.dataEnd;
4873
+ } else if (rec.id === 37 && rec.len === 6) {
4874
+ lastW25 = rec.headerStart;
4875
+ } else if (rec.id === 161 && rec.len >= 16) {
4876
+ autoFilterRanges.push(rec.dataStart);
4877
+ }
4878
+ pos = rec.dataEnd;
4879
+ }
4880
+ if (rowsStart === -1) {
4881
+ const insertAt = lastW25 >= 0 ? lastW25 : sheetBuf.length;
4882
+ return { rowsStart: insertAt, rowsEnd: insertAt, autoFilterRanges };
4883
+ }
4884
+ const rowsEnd = lastCellEnd >= 0 ? lastCellEnd : lastW25 >= 0 ? lastW25 : sheetBuf.length;
4885
+ return { rowsStart, rowsEnd, autoFilterRanges };
4886
+ }
4887
+ /**
4888
+ * Keep the sheet dimension record (0x98) in sync with the new data.
4889
+ * Excel uses its rwLast (payload offset 24) and colLast (payload offset 32)
4890
+ * fields to read the full row range; stale values make the last written row
4891
+ * invisible to Excel (and drop it from pivot refreshes).
4892
+ */
4893
+ _patchDimension(sheetBuf, lastRowIdx, lastCol) {
4894
+ const rec = { headerStart: 0, dataStart: 0, dataEnd: 0, id: 0, len: 0 };
4895
+ let pos = 0;
4896
+ while (readRecord(sheetBuf, pos, rec)) {
4897
+ if (rec.id === 152 && rec.len >= 36) {
4898
+ sheetBuf.writeInt32LE(lastRowIdx, rec.dataStart + 24);
4899
+ sheetBuf.writeInt32LE(lastCol, rec.dataStart + 32);
4900
+ return;
4901
+ }
4902
+ pos = rec.dataEnd;
4903
+ }
4904
+ }
4905
+ // ------------------------------------------------------------------
4906
+ // Pivot cache integration
4907
+ // ------------------------------------------------------------------
4908
+ _patchPivotCaches(sheetName, rwLast, colLast) {
4909
+ for (const path2 of this.pivotCacheDefPaths) {
4910
+ const entry = this.zip.getEntry(path2);
4911
+ if (!entry) continue;
4912
+ const buf = Buffer.from(entry.getData());
4913
+ const rec = { headerStart: 0, dataStart: 0, dataEnd: 0, id: 0, len: 0 };
4914
+ let pos = 0;
4915
+ let patched = false;
4916
+ let refreshXfPatched = false;
4917
+ while (readRecord(buf, pos, rec)) {
4918
+ pos = rec.dataEnd;
4919
+ if (rec.id === 179 && rec.len >= 4 && !refreshXfPatched) {
4920
+ if (rec.dataStart + 4 <= buf.length) {
4921
+ const v = buf[rec.dataStart + 3];
4922
+ if ((v & 4) === 0) {
4923
+ buf[rec.dataStart + 3] = v | 4;
4924
+ patched = true;
4925
+ }
4926
+ }
4927
+ refreshXfPatched = true;
4928
+ }
4929
+ if (rec.id === 187 && rec.len >= 23) {
4930
+ const cch = buf.readUInt32LE(rec.dataStart + 3);
4931
+ const nameStart = rec.dataStart + 7;
4932
+ const refStart = nameStart + cch * 2;
4933
+ const name = readUtf16(buf, nameStart, cch);
4934
+ if (name === sheetName && refStart + 16 <= buf.length) {
4935
+ buf.writeInt32LE(rwLast, refStart + 4);
4936
+ buf.writeInt32LE(colLast, refStart + 12);
4937
+ patched = true;
4938
+ }
4939
+ }
4940
+ }
4941
+ if (patched) {
4942
+ this.zip.updateFile(path2, buf);
4943
+ }
4944
+ }
4945
+ }
4946
+ };
3922
4947
  // Annotate the CommonJS export names for ESM import in node:
3923
4948
  0 && (module.exports = {
3924
4949
  BiffReaderWriter,
@@ -3929,8 +4954,10 @@ ${xfEntries.join("\n")}
3929
4954
  ReaderFactory,
3930
4955
  StreamingSheetState,
3931
4956
  XlsbReader,
4957
+ XlsbUpdater,
3932
4958
  XlsbWriter,
3933
4959
  XlsxReader,
4960
+ XlsxUpdater,
3934
4961
  XlsxWriter,
3935
4962
  applyHeaderWidths,
3936
4963
  defaultColWidth,