@evotecit/officeimo 0.1.2 → 0.1.3

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 (37) hide show
  1. package/README.md +43 -49
  2. package/bundles/officeimo-canopyx.js +966 -122
  3. package/bundles/officeimo-canopyx.mjs +929 -92
  4. package/bundles/officeimo-csv.js +18 -15
  5. package/bundles/officeimo-csv.mjs +16 -13
  6. package/bundles/officeimo-datatables.js +168 -82
  7. package/bundles/officeimo-datatables.mjs +140 -54
  8. package/bundles/officeimo-pdf.js +148 -65
  9. package/bundles/officeimo-pdf.mjs +124 -41
  10. package/bundles/officeimo.js +168 -82
  11. package/bundles/officeimo.mjs +140 -54
  12. package/dist/csv/index.js +16 -13
  13. package/dist/integrations/canopyx/diagnostics.d.ts +3 -0
  14. package/dist/integrations/canopyx/diagnostics.js +17 -0
  15. package/dist/integrations/canopyx/grouping.d.ts +6 -0
  16. package/dist/integrations/canopyx/grouping.js +188 -0
  17. package/dist/integrations/canopyx/index.d.ts +2 -2
  18. package/dist/integrations/canopyx/index.js +72 -15
  19. package/dist/integrations/canopyx/metadata.d.ts +4 -0
  20. package/dist/integrations/canopyx/metadata.js +51 -0
  21. package/dist/integrations/canopyx/presentation.d.ts +8 -0
  22. package/dist/integrations/canopyx/presentation.js +40 -0
  23. package/dist/integrations/canopyx/rule-predicates.d.ts +3 -0
  24. package/dist/integrations/canopyx/rule-predicates.js +110 -0
  25. package/dist/integrations/canopyx/rules.d.ts +6 -0
  26. package/dist/integrations/canopyx/rules.js +176 -0
  27. package/dist/integrations/canopyx/source.js +24 -22
  28. package/dist/integrations/canopyx/types.d.ts +89 -8
  29. package/dist/integrations/canopyx/workbook.d.ts +6 -0
  30. package/dist/integrations/canopyx/workbook.js +52 -0
  31. package/dist/pdf/font-resources.js +33 -14
  32. package/dist/pdf/pages.js +60 -14
  33. package/dist/pdf/table-band-flow.js +7 -2
  34. package/dist/pdf/table-band-plan.js +9 -1
  35. package/dist/pdf/table-layout.js +6 -2
  36. package/dist/pdf/table-structure.js +9 -8
  37. package/package.json +1 -1
@@ -5772,7 +5772,7 @@ _modules.set("2f5c0823847e9209017d01b2a753f36056df2a9988fae1f3a1bd5fd186545220",
5772
5772
  return _exports;
5773
5773
  })();
5774
5774
 
5775
- const _m55 = _modules.get("b6dbf755b495baef5c7d7651e6a55b2098f2ee304edca2c8b285a0bd7ec127a1") ?? (() => {
5775
+ const _m55 = _modules.get("b48bcab805d4c75294dd8d8e8dc57f96d9db3f5af31a8f0ddc6562f010f566e4") ?? (() => {
5776
5776
  const { beginTask, checkAbort, consumeRows, taskYieldDue, withAbort } = _m4;
5777
5777
 
5778
5778
  const { BlobByteSink, ChunkedTextSink, withDestination } = _m3;
@@ -5797,29 +5797,32 @@ const { captureCsvOptions } = _m16;
5797
5797
 
5798
5798
 
5799
5799
 
5800
- function csvField(value, delimiter, protect, quote, booleanText, nullValue) {
5801
- if (value == null && nullValue !== undefined)
5802
- value = nullValue;
5800
+ function csvField(value, delimiter, protect, quote, booleanText) {
5801
+ const kind = typeof value;
5803
5802
  let text;
5804
5803
  if (value == null)
5805
5804
  text = "";
5805
+ else if (kind === "string")
5806
+ text = value;
5807
+ else if (kind === "number") {
5808
+ text = Number.isFinite(value) ? String(value) : "";
5809
+ // Numeric text has no CSV delimiter, quote or line break to escape.
5810
+ return quote === "all" ? '"' + text + '"' : text;
5811
+ }
5812
+ else if (kind === "boolean")
5813
+ text = booleanText[value ? "true" : "false"];
5806
5814
  else if (isDate(value))
5807
5815
  text = Number.isFinite(value.getTime()) ? value.toISOString() : "";
5808
- else if (typeof value === "boolean")
5809
- text = booleanText[value ? "true" : "false"];
5810
- else if (typeof value === "number")
5811
- text = Number.isFinite(value) ? String(value) : "";
5812
- else if (typeof value === "string")
5813
- text = value;
5814
5816
  else {
5815
5817
  if (typeof value.then === "function")
5816
5818
  void Promise.resolve(value).catch(() => { });
5817
5819
  throw new TypeError("CSV cells and formatter results must be synchronous strings, numbers, booleans, Dates or null.");
5818
5820
  }
5819
- if (protect && (typeof value === "string" || typeof value === "boolean") && /^ *[=+\-@\t\r\n]/.test(text))
5821
+ // Only ASCII spaces, controls and markers through @ can begin the protected prefix.
5822
+ if (protect && (kind === "string" || kind === "boolean") && text.charCodeAt(0) <= 64 && /^ *[=+\-@\t\r\n]/.test(text))
5820
5823
  text = "'" + text;
5821
- return quote === "all" || (quote === "strings" && typeof value === "string") || text.includes(delimiter) || /["\r\n]/.test(text)
5822
- ? '"' + text.replace(/"/g, '""') + '"' : text;
5824
+ return quote === "all" || (quote === "strings" && kind === "string") || text.includes(delimiter) || /["\r\n]/.test(text)
5825
+ ? '"' + (text.includes('"') ? text.replace(/"/g, '""') : text) + '"' : text;
5823
5826
  }
5824
5827
  async function writeCsvTo(rows, destination, configuration) {
5825
5828
  const options = captureCsvOptions(configuration);
@@ -5871,7 +5874,7 @@ async function write(rows, sink, options) {
5871
5874
  value = options.nullValue;
5872
5875
  budget.cell(typeof value === "boolean" ? booleanText[value ? "true" : "false"] : value);
5873
5876
  checkAbort(signal);
5874
- text += (i ? delimiter : "") + csvField(value, delimiter, protect, quote, booleanText, options.nullValue);
5877
+ text += (i ? delimiter : "") + csvField(value, delimiter, protect, quote, booleanText);
5875
5878
  if (text.length >= buffer.chunkSize || (i & 127) === 127 && taskYieldDue()) {
5876
5879
  if (buffer.append(text))
5877
5880
  return buffer.flush().then(() => record(values, header, i + 1, snapshot));
@@ -5919,7 +5922,7 @@ async function writeCsv(rows, configuration) {
5919
5922
  }
5920
5923
  }
5921
5924
  const _exports = Object.freeze({ saveBlob: _m1.saveBlob, ExportCell: _m5.ExportCell, writeCsvTo: writeCsvTo, writeCsv: writeCsv });
5922
- _modules.set("b6dbf755b495baef5c7d7651e6a55b2098f2ee304edca2c8b285a0bd7ec127a1", _exports);
5925
+ _modules.set("b48bcab805d4c75294dd8d8e8dc57f96d9db3f5af31a8f0ddc6562f010f566e4", _exports);
5923
5926
  return _exports;
5924
5927
  })();
5925
5928
 
@@ -7244,7 +7247,7 @@ _modules.set("59911f0fe023545e9e97521b268551078bdc4c5f303e446a13b7d52f905e8070",
7244
7247
  return _exports;
7245
7248
  })();
7246
7249
 
7247
- const _m62 = _modules.get("7da602b40c346a3838e75963f9a3f10c95ac5ce08a7b0a23b9d96f8898a01db7") ?? (() => {
7250
+ const _m62 = _modules.get("4d4736e6b8e2aaecc6f6c1b124b7e6bc0a5e141dcc725edf0ad4847d87fca1b3") ?? (() => {
7248
7251
  const { NotSupportedError, OfficeIMOError } = _m2;
7249
7252
 
7250
7253
  const { fontProgram } = _m63;
@@ -7255,7 +7258,8 @@ const { pdfNumber, unicodeHex } = _m60;
7255
7258
 
7256
7259
  const { checkAbort, pause, taskYieldDue } = _m4;
7257
7260
 
7258
- const standardHexBytes = Object.freeze(Array.from({ length: 256 }, (_, byte) => byte.toString(16).padStart(2, "0")));
7261
+ const hexBytes = Object.freeze(Array.from({ length: 256 }, (_, byte) => byte.toString(16).padStart(2, "0")));
7262
+ function cidHex(cid) { return hexBytes[cid >>> 8] + hexBytes[cid & 255]; }
7259
7263
  class PdfFontResource {
7260
7264
  index;
7261
7265
  bold;
@@ -7286,12 +7290,16 @@ class PdfFontResource {
7286
7290
  width(scalar) {
7287
7291
  if (this.shared)
7288
7292
  return this.shared.width(scalar);
7289
- const existing = this.mappings.get(scalar);
7290
- if (existing)
7291
- return existing.width;
7292
- const standard = this.standardWidths.get(scalar);
7293
- if (standard !== undefined)
7294
- return standard;
7293
+ if (this.program) {
7294
+ const existing = this.mappings.get(scalar);
7295
+ if (existing)
7296
+ return existing.width;
7297
+ }
7298
+ else {
7299
+ const standard = this.standardWidths.get(scalar);
7300
+ if (standard !== undefined)
7301
+ return standard;
7302
+ }
7295
7303
  const resolved = resolveScalar(scalar, this.program, this.bold);
7296
7304
  if (!resolved.supported) {
7297
7305
  if (resolved.code === "unpaired-surrogate")
@@ -7304,7 +7312,8 @@ class PdfFontResource {
7304
7312
  }
7305
7313
  if (this.mappings.size >= 65535)
7306
7314
  throw new OfficeIMOError("RESOURCE_LIMIT", "A PDF font supports at most 65,535 distinct Unicode scalars.");
7307
- const mapping = { cid: this.mappings.size + 1, glyph: resolved.glyph, width: resolved.width, text: String.fromCodePoint(scalar) };
7315
+ const cid = this.mappings.size + 1;
7316
+ const mapping = { cid, hex: cidHex(cid), glyph: resolved.glyph, width: resolved.width, text: String.fromCodePoint(scalar) };
7308
7317
  this.mappings.set(scalar, mapping);
7309
7318
  return mapping.width;
7310
7319
  }
@@ -7317,8 +7326,20 @@ class PdfFontResource {
7317
7326
  let hex = "";
7318
7327
  for (const char of text) {
7319
7328
  const cp = char.codePointAt(0);
7320
- this.width(cp);
7321
- hex += this.program ? this.mappings.get(cp).cid.toString(16).padStart(4, "0") : standardHexBytes[standardCode(cp)];
7329
+ if (this.program) {
7330
+ let mapping = this.mappings.get(cp);
7331
+ // Layout normally registered the scalar already; validate only a newly painted scalar.
7332
+ if (!mapping) {
7333
+ this.width(cp);
7334
+ mapping = this.mappings.get(cp);
7335
+ }
7336
+ hex += mapping.hex;
7337
+ }
7338
+ else {
7339
+ if (!this.standardWidths.has(cp))
7340
+ this.width(cp);
7341
+ hex += hexBytes[standardCode(cp)];
7342
+ }
7322
7343
  }
7323
7344
  return "<" + hex + ">";
7324
7345
  }
@@ -7333,10 +7354,11 @@ class PdfFontResource {
7333
7354
  if (!mapping) {
7334
7355
  if (this.mappings.size >= 65535)
7335
7356
  throw new OfficeIMOError("RESOURCE_LIMIT", "A PDF font supports at most 65,535 distinct CID mappings.");
7336
- mapping = { cid: this.mappings.size + 1, glyph, width: this.program.widths[glyph], text };
7357
+ const cid = this.mappings.size + 1;
7358
+ mapping = { cid, hex: cidHex(cid), glyph, width: this.program.widths[glyph], text };
7337
7359
  this.mappings.set(key, mapping);
7338
7360
  }
7339
- return "<" + mapping.cid.toString(16).padStart(4, "0") + ">";
7361
+ return "<" + mapping.hex + ">";
7340
7362
  }
7341
7363
  async write(objects, compression) {
7342
7364
  checkAbort(this.signal);
@@ -7385,7 +7407,7 @@ class PdfFontResource {
7385
7407
  const batch = mapped.slice(i, i + 100);
7386
7408
  cmap += batch.length + " beginbfchar\n";
7387
7409
  for (const [, m] of batch)
7388
- cmap += "<" + m.cid.toString(16).padStart(4, "0") + "> <" + unicodeHex(m.text) + ">\n";
7410
+ cmap += "<" + m.hex + "> <" + unicodeHex(m.text) + ">\n";
7389
7411
  cmap += "endbfchar\n";
7390
7412
  if (taskYieldDue())
7391
7413
  await pause();
@@ -7436,7 +7458,7 @@ class PdfFontResources {
7436
7458
  if (!found)
7437
7459
  this.explicitSelections.set(explicit, selections);
7438
7460
  }
7439
- const key = String(bold) + String(italic), existing = selections.get(key);
7461
+ const key = (bold ? 2 : 0) | (italic ? 1 : 0), existing = selections.get(key);
7440
7462
  if (existing)
7441
7463
  return existing;
7442
7464
  const { font, syntheticBold, syntheticItalic } = explicit ? { font: explicit, syntheticBold: bold, syntheticItalic: italic } : selectFont(this.fonts, bold, italic);
@@ -7453,7 +7475,7 @@ class PdfFontResources {
7453
7475
  dictionary() { return "<< " + this.resources.map(f => "/" + f.name + " " + f.object + " 0 R").join(" ") + " >>"; }
7454
7476
  }
7455
7477
  const _exports = Object.freeze({ PdfFontResource: PdfFontResource, PdfFontResources: PdfFontResources });
7456
- _modules.set("7da602b40c346a3838e75963f9a3f10c95ac5ce08a7b0a23b9d96f8898a01db7", _exports);
7478
+ _modules.set("4d4736e6b8e2aaecc6f6c1b124b7e6bc0a5e141dcc725edf0ad4847d87fca1b3", _exports);
7457
7479
  return _exports;
7458
7480
  })();
7459
7481
 
@@ -7978,7 +8000,7 @@ _modules.set("0a1c79b51ac9a164b86197239117df6497f45ca2892b423b1ec77a663ccc1c47",
7978
8000
  return _exports;
7979
8001
  })();
7980
8002
 
7981
- const _m73 = _modules.get("9a88773878eacc51df9f05bb5ee90cc2b683b083ebea8fb54375092301388e96") ?? (() => {
8003
+ const _m73 = _modules.get("2f40af05ba09102fe440c1d46385b64cecdd233371771796c9ae4e8d523f2cea") ?? (() => {
7982
8004
  const { OfficeIMOError } = _m2;
7983
8005
 
7984
8006
  const { wrapPdfText } = _m71;
@@ -8026,6 +8048,14 @@ async function projectBandRows(rows, band, widths, settings, fonts) {
8026
8048
  for (const row of rows) {
8027
8049
  const cells = [];
8028
8050
  for (const cell of row.cells) {
8051
+ // Ordinary data and leaf headings keep their captured width and lines in every band.
8052
+ // Look up their physical position without allocating another per-row column index.
8053
+ if (cell.span === 1) {
8054
+ const first = band.columns.indexOf(cell.first);
8055
+ if (first >= 0)
8056
+ cells.push({ ...cell, source: cell.source ?? cell, first });
8057
+ continue;
8058
+ }
8029
8059
  for (let first = 0; first < band.columns.length;) {
8030
8060
  const source = band.columns[first];
8031
8061
  if (source < cell.first || source >= cell.first + cell.span) {
@@ -8036,7 +8066,7 @@ async function projectBandRows(rows, band, widths, settings, fonts) {
8036
8066
  while (end < band.columns.length && band.columns[end] === band.columns[end - 1] + 1 && band.columns[end] < cell.first + cell.span)
8037
8067
  end++;
8038
8068
  const width = band.columns.slice(first, end).reduce((sum, index) => sum + widths[index], 0);
8039
- const lines = cell.span === 1 ? cell.lines : await wrapPdfText(cell.captured, fonts, settings.fontSize, width - settings.padding * 2, settings, cell.style.wrapText !== false);
8069
+ const lines = await wrapPdfText(cell.captured, fonts, settings.fontSize, width - settings.padding * 2, settings, cell.style.wrapText !== false);
8040
8070
  cells.push({ ...cell, source: cell.source ?? cell, first, span: end - first, width, lines,
8041
8071
  lineHeight: lines.reduce((height, line) => Math.max(height, line.lineHeight), cell.font.lineHeight(settings.fontSize)) });
8042
8072
  first = end;
@@ -8065,11 +8095,11 @@ function alignBandBlocks(bands, settings) {
8065
8095
  cells: row.cells.map(cell => ({ ...cell, height: heights.slice(index, index + (cell.rowSpan ?? 1)).reduce((sum, value) => sum + value, 0) })) })));
8066
8096
  }
8067
8097
  const _exports = Object.freeze({ planTableBands: planTableBands, projectBandRows: projectBandRows, alignBandBlocks: alignBandBlocks });
8068
- _modules.set("9a88773878eacc51df9f05bb5ee90cc2b683b083ebea8fb54375092301388e96", _exports);
8098
+ _modules.set("2f40af05ba09102fe440c1d46385b64cecdd233371771796c9ae4e8d523f2cea", _exports);
8069
8099
  return _exports;
8070
8100
  })();
8071
8101
 
8072
- const _m69 = _modules.get("07d2da8d8b93f12f172a48b97c1807e485555cf608e2eaa5b7610aa91d4a5305") ?? (() => {
8102
+ const _m69 = _modules.get("ad81357e627d3100e1068a8ce521aa1c1cd65de5c6c6ab36f807a3e5da50d874") ?? (() => {
8073
8103
  const { ExportCell } = _m5;
8074
8104
 
8075
8105
  const { copyExportLink } = _m7;
@@ -8189,8 +8219,12 @@ class PdfTableLayout {
8189
8219
  lines };
8190
8220
  }
8191
8221
  row(cells) {
8192
- const lines = Math.max(1, ...cells.map(c => c.lines.length));
8193
- const lineHeight = Math.max(this.lineHeight, ...cells.map(c => c.lineHeight));
8222
+ let lines = 1, lineHeight = this.lineHeight;
8223
+ for (let index = 0; index < cells.length; index++) {
8224
+ const cell = cells[index];
8225
+ lines = Math.max(lines, cell.lines.length);
8226
+ lineHeight = Math.max(lineHeight, cell.lineHeight);
8227
+ }
8194
8228
  return { cells, lines, lineHeight, height: lines * lineHeight + this.settings.padding * 2 };
8195
8229
  }
8196
8230
  async headers() {
@@ -8296,11 +8330,11 @@ class PdfTableLayout {
8296
8330
  }
8297
8331
  }
8298
8332
  const _exports = Object.freeze({ PdfTableLayout: PdfTableLayout });
8299
- _modules.set("07d2da8d8b93f12f172a48b97c1807e485555cf608e2eaa5b7610aa91d4a5305", _exports);
8333
+ _modules.set("ad81357e627d3100e1068a8ce521aa1c1cd65de5c6c6ab36f807a3e5da50d874", _exports);
8300
8334
  return _exports;
8301
8335
  })();
8302
8336
 
8303
- const _m75 = _modules.get("67ad5f4adbd6bc0dddafe5cf82638d46d150237f4ff0bee15c0ace652d5095f4") ?? (() => {
8337
+ const _m75 = _modules.get("9ea74d93c18250e809a7be745444b886bcd5ec924a78e6ab004d649789db1f72") ?? (() => {
8304
8338
  const { OfficeIMOError } = _m2;
8305
8339
 
8306
8340
  const { checkAbort } = _m4;
@@ -8344,7 +8378,7 @@ class PdfTableBandFlow {
8344
8378
  await this.flush();
8345
8379
  }
8346
8380
  async row(row, allowFirstFragment = false) {
8347
- const { padding, fontSize, options } = this.layout.settings, minimumLines = this.layout.minimumRowLines(row), minimumHeight = this.layout.minimumRowHeight(row);
8381
+ const { padding, fontSize, options } = this.layout.settings, minimumLines = this.layout.minimumRowLines(row), minimumHeight = minimumLines * row.lineHeight + padding * 2;
8348
8382
  if (minimumHeight > this.painter.firstFullCapacity + .001 || minimumHeight > this.painter.continuationCapacity + .001)
8349
8383
  throw new RangeError("Repeated PDF identifiers must fit intact below the first and continued band headings/context.");
8350
8384
  // Keep ordinary rows intact when they fit fresh. A kept heading/caption can deliberately
@@ -8378,9 +8412,14 @@ class PdfTableBandFlow {
8378
8412
  let remaining = false;
8379
8413
  const cells = rows[0].cells.map(cell => {
8380
8414
  const source = this.layout.bands[index].columns[cell.first];
8381
- const repeated = this.layout.repeatedColumn(source), visible = repeated ? cell.lines : cell.lines.slice(first, first + lines);
8415
+ const repeated = this.layout.repeatedColumn(source), reusable = cell.span === 1 && (cell.source?.span ?? 1) === 1 && (cell.rowSpan ?? 1) === 1 &&
8416
+ cell.height === undefined && first === 0 && (repeated || lines >= cell.lines.length);
8417
+ const visible = repeated || reusable ? cell.lines : cell.lines.slice(first, first + lines);
8382
8418
  if (!repeated && (visible.length > 0 || cell.link !== undefined))
8383
8419
  remaining = true;
8420
+ // A complete first fragment already owns these lines and their maximum font metrics.
8421
+ if (reusable)
8422
+ return cell;
8384
8423
  const { height: _height, ...plain } = cell;
8385
8424
  return { ...plain, lines: visible,
8386
8425
  lineHeight: visible.reduce((value, line) => Math.max(value, line.lineHeight), cell.font.lineHeight(fontSize)),
@@ -8433,11 +8472,11 @@ class PdfTableBandFlow {
8433
8472
  }
8434
8473
  }
8435
8474
  const _exports = Object.freeze({ PdfTableBandFlow: PdfTableBandFlow });
8436
- _modules.set("67ad5f4adbd6bc0dddafe5cf82638d46d150237f4ff0bee15c0ace652d5095f4", _exports);
8475
+ _modules.set("9ea74d93c18250e809a7be745444b886bcd5ec924a78e6ab004d649789db1f72", _exports);
8437
8476
  return _exports;
8438
8477
  })();
8439
8478
 
8440
- const _m76 = _modules.get("b52424ed74721dce3a2621456888fe1c6af0490627063e56f690df9abcb1dfff") ?? (() => {
8479
+ const _m76 = _modules.get("9deed79565a5da5009f7a01579df8d6a3f019b78eb7b17d831c7964840e9a6bf") ?? (() => {
8441
8480
  /** @internal Source-cell identities survive page fragments and horizontal band projections.
8442
8481
  * Only column headers and still-owned row objects remain reachable from this table owner. */
8443
8482
  class PdfTableStructure {
@@ -8489,30 +8528,31 @@ class PdfTableStructure {
8489
8528
  return row.cells.map(cell => this.cells.get(cell));
8490
8529
  const rowId = this.structure.element("TR", parent);
8491
8530
  this.rows.set(row, rowId);
8492
- const headers = row.cells.map((cell, index) => rowHeaderIndex === undefined ? cell.rowHeader === true : index === rowHeaderIndex);
8493
8531
  // Allocate in source order, then resolve every row header before associating even earlier data cells.
8494
8532
  // Generated summary labels override detail roles so numeric subtotal cells never become row headers.
8495
8533
  const ids = row.cells.map((cell, index) => {
8496
- const id = this.structure.element(headers[index] ? "TH" : "TD", rowId);
8534
+ const header = rowHeaderIndex === undefined ? cell.rowHeader === true : index === rowHeaderIndex;
8535
+ const id = this.structure.element(header ? "TH" : "TD", rowId);
8497
8536
  this.cells.set(cell, id);
8498
8537
  return id;
8499
8538
  });
8500
- const rowHeaders = [];
8539
+ let rowHeaders;
8501
8540
  for (let index = 0; index < ids.length; index++)
8502
- if (headers[index])
8503
- rowHeaders.push(await this.structure.identifier(ids[index]));
8541
+ if (rowHeaderIndex === undefined ? row.cells[index].rowHeader === true : index === rowHeaderIndex)
8542
+ (rowHeaders ??= []).push(await this.structure.identifier(ids[index]));
8504
8543
  for (let index = 0; index < row.cells.length; index++) {
8505
8544
  const cell = row.cells[index];
8506
- if (!rowHeaders.length && cell.span === 1 && (cell.rowSpan ?? 1) === 1) {
8545
+ if (!rowHeaders && cell.span === 1 && (cell.rowSpan ?? 1) === 1) {
8507
8546
  const attributes = this.ordinaryAttributes[cell.first] ??=
8508
8547
  await this.structure.attributeReference(this.attributeDictionary(cell, this.associations(cell)));
8509
8548
  this.structure.setAttributes(ids[index], attributes);
8510
8549
  continue;
8511
8550
  }
8512
8551
  const associations = this.associations(cell);
8513
- if (!headers[index])
8552
+ const header = rowHeaderIndex === undefined ? cell.rowHeader === true : index === rowHeaderIndex;
8553
+ if (!header && rowHeaders)
8514
8554
  associations.push(...rowHeaders);
8515
- this.structure.setAttributes(ids[index], this.attributes(cell, associations, headers[index] ? "Row" : undefined));
8555
+ this.structure.setAttributes(ids[index], this.attributes(cell, associations, header ? "Row" : undefined));
8516
8556
  }
8517
8557
  return ids;
8518
8558
  }
@@ -8547,7 +8587,7 @@ class PdfTableStructure {
8547
8587
  }
8548
8588
  }
8549
8589
  const _exports = Object.freeze({ PdfTableStructure: PdfTableStructure });
8550
- _modules.set("b52424ed74721dce3a2621456888fe1c6af0490627063e56f690df9abcb1dfff", _exports);
8590
+ _modules.set("9deed79565a5da5009f7a01579df8d6a3f019b78eb7b17d831c7964840e9a6bf", _exports);
8551
8591
  return _exports;
8552
8592
  })();
8553
8593
 
@@ -8665,7 +8705,7 @@ _modules.set("a66257a32f03d958aa57be4de9da7f80b708cebca26b5cc6404de0ee11bfe052",
8665
8705
  return _exports;
8666
8706
  })();
8667
8707
 
8668
- const _m74 = _modules.get("a7fca40cb8c75af206111c90db36839b4648982beeb4179efda0ddd1ee366210") ?? (() => {
8708
+ const _m74 = _modules.get("3ed7114181be5a3066742336da574fef7f2fc04ee6dfc5e64211f3bedad4cab9") ?? (() => {
8669
8709
  const { OfficeIMOError } = _m2;
8670
8710
 
8671
8711
  const { checkAbort } = _m4;
@@ -8700,7 +8740,8 @@ class PdfPages {
8700
8740
  outlines;
8701
8741
  references = [];
8702
8742
  current = 0;
8703
- commands = [];
8743
+ commands = "";
8744
+ commandParts = [];
8704
8745
  commandBytes = 0;
8705
8746
  annotations = [];
8706
8747
  hyperlinks = 0;
@@ -8718,6 +8759,12 @@ class PdfPages {
8718
8759
  pendingBookmarks = [];
8719
8760
  pageNumberWidth = 0;
8720
8761
  colors = new Map();
8762
+ textFont;
8763
+ textSize = 0;
8764
+ textColor = "";
8765
+ textPrefix = "";
8766
+ rectangleLefts;
8767
+ rectangleColumns = [];
8721
8768
  externalObjects = new Map();
8722
8769
  bandFlow;
8723
8770
  bandCellBudget = false;
@@ -8784,7 +8831,7 @@ class PdfPages {
8784
8831
  }
8785
8832
  add(command) {
8786
8833
  this.retainPageBytes(command.length);
8787
- this.commands.push(command);
8834
+ this.commands += command;
8788
8835
  }
8789
8836
  retainPageBytes(length) {
8790
8837
  this.commandBytes += length;
@@ -8804,9 +8851,17 @@ class PdfPages {
8804
8851
  return this.structure ? "/Artifact << /Type /" + type + " >> BDC\n" + command + "EMC\n" : command;
8805
8852
  }
8806
8853
  text(text, font, size, x, baseline, foreground = "111827", element) {
8807
- const n = pdfNumber, shear = font.syntheticItalic ? .213 : 0;
8808
- const command = "q " + this.rgb(foreground) + " rg " + this.rgb(foreground) + " RG\nBT /" + font.name + " " + n(size) + " Tf " +
8809
- (font.syntheticBold ? n(size * .025) + " w 2 Tr " : "0 Tr ") + "1 0 " + n(shear) + " 1 " + n(x) + " " + n(baseline) + " Tm " + font.encode(text) + " Tj ET Q\n";
8854
+ const n = pdfNumber;
8855
+ if (font !== this.textFont || size !== this.textSize || foreground !== this.textColor) {
8856
+ const shear = font.syntheticItalic ? .213 : 0, rgb = this.rgb(foreground);
8857
+ // Keep one prefix, independent of report size. Resource identity includes synthetic styling.
8858
+ this.textPrefix = "q " + rgb + " rg " + rgb + " RG\nBT /" + font.name + " " + n(size) + " Tf " +
8859
+ (font.syntheticBold ? n(size * .025) + " w 2 Tr " : "0 Tr ") + "1 0 " + n(shear) + " 1 ";
8860
+ this.textFont = font;
8861
+ this.textSize = size;
8862
+ this.textColor = foreground;
8863
+ }
8864
+ const command = this.textPrefix + n(x) + " " + n(baseline) + " Tm " + font.encode(text) + " Tj ET Q\n";
8810
8865
  this.add(this.structure && element !== undefined ? this.structure.mark(element) + command + "EMC\n" : this.artifact(command, "Pagination"));
8811
8866
  }
8812
8867
  link(link, x, bottom, width, height, element) {
@@ -8836,8 +8891,8 @@ class PdfPages {
8836
8891
  for (const segment of line.segments) {
8837
8892
  const registered = marks?.get(segment), owner = registered?.owner ?? (segment.link && this.structure && element !== undefined ? this.structure.link(element, segment.link) : element);
8838
8893
  if (segment.glyphs) {
8839
- const font = segment.font, n = pdfNumber, shear = font.syntheticItalic ? .213 : 0;
8840
- let cursor = x, command = "q " + this.rgb(segment.color ?? "111827") + " rg " + this.rgb(segment.color ?? "111827") + " RG\nBT /" + font.name + " " + n(size) + " Tf " +
8894
+ const font = segment.font, n = pdfNumber, shear = font.syntheticItalic ? .213 : 0, rgb = this.rgb(segment.color ?? "111827");
8895
+ let cursor = x, command = "q " + rgb + " rg " + rgb + " RG\nBT /" + font.name + " " + n(size) + " Tf " +
8841
8896
  (font.syntheticBold ? n(size * .025) + " w 2 Tr " : "0 Tr ");
8842
8897
  for (const glyph of segment.glyphs) {
8843
8898
  command += "1 0 " + n(shear) + " 1 " + n(cursor + (glyph.xOffset + shear * glyph.yOffset) * size / 1000) + " " + n(baseline + glyph.yOffset * size / 1000) + " Tm " + font.encodeGlyph(glyph.id, glyph.logicalText) + " Tj\n";
@@ -8885,7 +8940,8 @@ class PdfPages {
8885
8940
  this.current = this.objects.reserve();
8886
8941
  this.references.push(this.current);
8887
8942
  }
8888
- this.commands = [];
8943
+ this.commands = "";
8944
+ this.commandParts = [];
8889
8945
  this.annotations = [];
8890
8946
  this.commandBytes = 0;
8891
8947
  this.bodyAdded = false;
@@ -8968,15 +9024,32 @@ class PdfPages {
8968
9024
  if (!this.layout)
8969
9025
  throw new Error("A table layout is required before drawing rows.");
8970
9026
  this.bodyAdded = true;
8971
- const { padding, fontSize } = this.settings, n = pdfNumber, height = lineCount * row.lineHeight + padding * 2;
9027
+ const { padding, fontSize } = this.settings, n = pdfNumber, height = lineCount * row.lineHeight + padding * 2, lefts = this.layout.lefts;
9028
+ // One geometry token per active physical column; table/band changes release the old tokens.
9029
+ if (this.rectangleLefts !== lefts) {
9030
+ this.rectangleLefts = lefts;
9031
+ this.rectangleColumns = [];
9032
+ }
9033
+ let rectangleHeight, rectangleBottom = "", rectangleHeightText = "";
8972
9034
  for (const [index, cell] of row.cells.entries()) {
8973
9035
  if (this.bandCellBudget)
8974
9036
  this.settings.budget.cell(this.settings.budget.limits.maxTextCharacters === undefined ? "" :
8975
9037
  (cell.height === undefined ? cell.lines.slice(firstLine, firstLine + lineCount) : cell.lines).map(line => line.text).join(""));
8976
- const x = this.layout.lefts[cell.first], cellHeight = cell.height ?? height;
9038
+ const x = lefts[cell.first], cellHeight = cell.height ?? height;
9039
+ if (cellHeight !== rectangleHeight) {
9040
+ rectangleBottom = n(this.y - cellHeight);
9041
+ rectangleHeightText = n(cellHeight);
9042
+ rectangleHeight = cellHeight;
9043
+ }
9044
+ let horizontal = this.rectangleColumns[cell.first];
9045
+ if (!horizontal || horizontal.x !== x || horizontal.width !== cell.width) {
9046
+ horizontal = { x, width: cell.width, left: n(x), widthText: n(cell.width) };
9047
+ this.rectangleColumns[cell.first] = horizontal;
9048
+ }
9049
+ const rectangle = horizontal.left + " " + rectangleBottom + " " + horizontal.widthText + " " + rectangleHeightText;
8977
9050
  if (cell.style.background)
8978
- this.add(this.artifact("q " + this.rgb(cell.style.background) + " rg " + n(x) + " " + n(this.y - cellHeight) + " " + n(cell.width) + " " + n(cellHeight) + " re f Q\n"));
8979
- this.add(this.artifact("q 0.82 0.85 0.89 RG 0.4 w " + n(x) + " " + n(this.y - cellHeight) + " " + n(cell.width) + " " + n(cellHeight) + " re S Q\n"));
9051
+ this.add(this.artifact("q " + this.rgb(cell.style.background) + " rg " + rectangle + " re f Q\n"));
9052
+ this.add(this.artifact("q 0.82 0.85 0.89 RG 0.4 w " + rectangle + " re S Q\n"));
8980
9053
  const element = elements?.[index], artifact = cell.semanticArtifact || repeated[index], owner = cell.link && this.structure && element !== undefined ? this.structure.link(element, cell.link) : element;
8981
9054
  for (let line = firstLine; line < Math.min(cell.lines.length, cell.height ? cell.lines.length : firstLine + lineCount); line++) {
8982
9055
  const text = cell.lines[line], left = cell.style.alignment === "right" ? cell.width - padding - text.width : cell.style.alignment === "center" ? (cell.width - text.width) / 2 : padding;
@@ -8986,6 +9059,7 @@ class PdfPages {
8986
9059
  this.link(cell.link, x, this.y - cellHeight, cell.width, cellHeight, owner);
8987
9060
  }
8988
9061
  this.y -= row.structured ? row.height : height;
9062
+ this.sealCommands();
8989
9063
  }
8990
9064
  async block(rows) {
8991
9065
  if (this.bandFlow)
@@ -9311,9 +9385,22 @@ class PdfPages {
9311
9385
  marker: { line: item.marker, gap: item.markerGap, ...(label === undefined ? {} : { owner: label }) } });
9312
9386
  await this.structure?.complete(li);
9313
9387
  }
9388
+ sealCommands() {
9389
+ if (this.commands) {
9390
+ this.commandParts.push(this.commands);
9391
+ this.commands = "";
9392
+ }
9393
+ }
9394
+ takeCommands() {
9395
+ this.sealCommands();
9396
+ const content = this.commandParts.join("");
9397
+ // Encoding and awaited delivery own the page value; the next page starts independently.
9398
+ this.commandParts = [];
9399
+ return content;
9400
+ }
9314
9401
  async finishPage() {
9315
9402
  const contents = this.objects.reserve(), { page, options } = this.settings;
9316
- await this.objects.stream(contents, this.commands.join(""), "", options.compression !== false);
9403
+ await this.objects.stream(contents, this.takeCommands(), "", options.compression !== false);
9317
9404
  const annotations = [];
9318
9405
  for (const annotation of this.annotations) {
9319
9406
  annotations.push(annotation.id);
@@ -9325,7 +9412,6 @@ class PdfPages {
9325
9412
  (annotations.length ? " /Annots [" + annotations.map(id => id + " 0 R").join(" ") + "]" : "") + " >>");
9326
9413
  if (this.structure)
9327
9414
  await this.structure.finishPage();
9328
- this.commands = [];
9329
9415
  this.annotations = [];
9330
9416
  this.commandBytes = 0;
9331
9417
  this.current = 0;
@@ -9357,7 +9443,7 @@ class PdfPages {
9357
9443
  }
9358
9444
  }
9359
9445
  const _exports = Object.freeze({ PdfPages: PdfPages });
9360
- _modules.set("a7fca40cb8c75af206111c90db36839b4648982beeb4179efda0ddd1ee366210", _exports);
9446
+ _modules.set("3ed7114181be5a3066742336da574fef7f2fc04ee6dfc5e64211f3bedad4cab9", _exports);
9361
9447
  return _exports;
9362
9448
  })();
9363
9449
 
@@ -9800,7 +9886,7 @@ _modules.set("52c78ca6833cee7e5a96b657e2c00172d550176daf2c95e742692f8416977bea",
9800
9886
  return _exports;
9801
9887
  })();
9802
9888
 
9803
- const _m59 = _modules.get("eb2c981b4568b33deca2137956ace31ea621b6a6287755ec234336d0a7c23cfc") ?? (() => {
9889
+ const _m59 = _modules.get("afdad27eb363e8de0c3bd69ebf358860eb76f5c6fb29f43a87635807cb7fc273") ?? (() => {
9804
9890
  const { PdfObjects, unicodeHex } = _m60;
9805
9891
 
9806
9892
  const { PdfFontResources } = _m62;
@@ -9863,11 +9949,11 @@ class PdfWriteSession {
9863
9949
  }
9864
9950
  }
9865
9951
  const _exports = Object.freeze({ PdfWriteSession: PdfWriteSession });
9866
- _modules.set("eb2c981b4568b33deca2137956ace31ea621b6a6287755ec234336d0a7c23cfc", _exports);
9952
+ _modules.set("afdad27eb363e8de0c3bd69ebf358860eb76f5c6fb29f43a87635807cb7fc273", _exports);
9867
9953
  return _exports;
9868
9954
  })();
9869
9955
 
9870
- const _m58 = _modules.get("98eb735e985f873ed0ffc628449a20d1f3bb729a87b6d6b3099b6f308438fcb5") ?? (() => {
9956
+ const _m58 = _modules.get("45cf9fd6b6293c1a83bc8554e1bcb5cf119f44701fbad7849f39a712cab5074b") ?? (() => {
9871
9957
  const { BlobByteSink, withDestination } = _m3;
9872
9958
 
9873
9959
  const { beginTask, checkAbort, consumeRows, pause, taskYieldDue } = _m4;
@@ -9932,7 +10018,7 @@ async function writePdfTo(rows, destination, configuration) {
9932
10018
  });
9933
10019
  }
9934
10020
  const _exports = Object.freeze({ writePdf: writePdf, writePdfTo: writePdfTo });
9935
- _modules.set("98eb735e985f873ed0ffc628449a20d1f3bb729a87b6d6b3099b6f308438fcb5", _exports);
10021
+ _modules.set("45cf9fd6b6293c1a83bc8554e1bcb5cf119f44701fbad7849f39a712cab5074b", _exports);
9936
10022
  return _exports;
9937
10023
  })();
9938
10024
 
@@ -10864,7 +10950,7 @@ _modules.set("d04686d2c067355dfd215333b83eb5f79f96e9e4be49f942e050f21ac0795343",
10864
10950
  return _exports;
10865
10951
  })();
10866
10952
 
10867
- const _m91 = _modules.get("d43e573fd5bad18a7ec2d71752168c422c4f8fabbc51f1cef8e3ba389f298715") ?? (() => {
10953
+ const _m91 = _modules.get("289fa3a052c7fbab2a3ca0fb91fb9974db709d24b7d850f1175810258f0409a0") ?? (() => {
10868
10954
  const { assertGroupedReportSource, groupedReportOperation } = _m8;
10869
10955
 
10870
10956
  const { consumeRows } = _m4;
@@ -11118,11 +11204,11 @@ async function renderGroupedPdfTable(block, context) {
11118
11204
  }
11119
11205
  }
11120
11206
  const _exports = Object.freeze({ renderGroupedPdfTable: renderGroupedPdfTable });
11121
- _modules.set("d43e573fd5bad18a7ec2d71752168c422c4f8fabbc51f1cef8e3ba389f298715", _exports);
11207
+ _modules.set("289fa3a052c7fbab2a3ca0fb91fb9974db709d24b7d850f1175810258f0409a0", _exports);
11122
11208
  return _exports;
11123
11209
  })();
11124
11210
 
11125
- const _m84 = _modules.get("f6c70e9a0bed09b5a1c61a662ad7d3faf731c911f574e2df285f669bd643b947") ?? (() => {
11211
+ const _m84 = _modules.get("9051bf9fc3168e24b53b16c123a42816198456846003fb49191c03a18cdab904") ?? (() => {
11126
11212
  const { BlobByteSink, withDestination } = _m3;
11127
11213
 
11128
11214
  const { OfficeIMOError } = _m2;
@@ -11412,11 +11498,11 @@ function captureTableOptions(options) {
11412
11498
  return { ...captured, ...(captured.wideTable === undefined ? {} : { wideTable: captureWideTable(captured.wideTable) }) };
11413
11499
  }
11414
11500
  const _exports = Object.freeze({ pdfTable: pdfTable, writePdfDocument: writePdfDocument, writePdfDocumentTo: writePdfDocumentTo });
11415
- _modules.set("f6c70e9a0bed09b5a1c61a662ad7d3faf731c911f574e2df285f669bd643b947", _exports);
11501
+ _modules.set("9051bf9fc3168e24b53b16c123a42816198456846003fb49191c03a18cdab904", _exports);
11416
11502
  return _exports;
11417
11503
  })();
11418
11504
 
11419
- const _m83 = _modules.get("879a0adeb3c62918085a071cbc37f221eb89a0fd73d56ebb5e9cfe0d49db8ee9") ?? (() => {
11505
+ const _m83 = _modules.get("abe76e52ffeed11ab42477c83ddde1d1d7de28b803096436b5b23cb153af58ba") ?? (() => {
11420
11506
  const { assertGroupedReportSource } = _m8;
11421
11507
 
11422
11508
  const { BlobByteSink } = _m3;
@@ -11462,7 +11548,7 @@ async function writeGroupedPdfTo(report, destination, configuration) {
11462
11548
  return writePdfDocumentTo([pdfGroupedTable(report, tableOptions)], destination, documentOptions);
11463
11549
  }
11464
11550
  const _exports = Object.freeze({ pdfGroupedTable: _m92.pdfGroupedTable, writeGroupedPdf: writeGroupedPdf, writeGroupedPdfTo: writeGroupedPdfTo });
11465
- _modules.set("879a0adeb3c62918085a071cbc37f221eb89a0fd73d56ebb5e9cfe0d49db8ee9", _exports);
11551
+ _modules.set("abe76e52ffeed11ab42477c83ddde1d1d7de28b803096436b5b23cb153af58ba", _exports);
11466
11552
  return _exports;
11467
11553
  })();
11468
11554
 
@@ -11506,10 +11592,10 @@ _modules.set("3d777096288d1be55a05a80bc015d4674212e587703f25a7e7cf99a8065feb86",
11506
11592
  return _exports;
11507
11593
  })();
11508
11594
 
11509
- const _m57 = _modules.get("2deab7b4ccb08bed297341ddb563d8fcf74277aff38c1dfc3d9edd61c0d98481") ?? (() => {
11595
+ const _m57 = _modules.get("027aafa08408056b10d7d717d63d1f7c0ee20ecfc68213aa66feacc75ec525fe") ?? (() => {
11510
11596
 
11511
11597
  const _exports = Object.freeze({ writePdf: _m58.writePdf, writePdfTo: _m58.writePdfTo, writeGroupedPdf: _m83.writeGroupedPdf, writeGroupedPdfTo: _m83.writeGroupedPdfTo, pdfGroupedTable: _m83.pdfGroupedTable, createGroupedReport: _m8.createGroupedReport, writePdfDocument: _m84.writePdfDocument, writePdfDocumentTo: _m84.writePdfDocumentTo, pdfTable: _m84.pdfTable, PdfFont: _m63.PdfFont, preflightPdfText: _m93.preflightPdfText, ExportCell: _m5.ExportCell, saveBlob: _m1.saveBlob });
11512
- _modules.set("2deab7b4ccb08bed297341ddb563d8fcf74277aff38c1dfc3d9edd61c0d98481", _exports);
11598
+ _modules.set("027aafa08408056b10d7d717d63d1f7c0ee20ecfc68213aa66feacc75ec525fe", _exports);
11513
11599
  return _exports;
11514
11600
  })();
11515
11601
 
@@ -11553,7 +11639,76 @@ _modules.set("c0aee2c5df0df3e62ca31fc685243cdd4b449f083834e8d28cf92c20dfa7b27f",
11553
11639
  return _exports;
11554
11640
  })();
11555
11641
 
11556
- const _m94 = _modules.get("91dbdf35d8f192b3c0ea92dfab6b9812872fbe3c8d85a5d2afe389bd61262ba2") ?? (() => {
11642
+ const _m96 = _modules.get("3d1862d8ab32171bca4b3ba5fe0bdcc073f67ce940aaff0ee735635893f86ee8") ?? (() => {
11643
+ /** One policy for capture diagnostics and unsupported adapter mappings; callbacks stay synchronous. */
11644
+ function canopyDiagnostics(format, options) {
11645
+ const policy = options.unsupportedPresentation ?? (format === "csv" ? "text" : "reject"), notify = options.onDiagnostic;
11646
+ if (policy !== "reject" && policy !== "text")
11647
+ throw new TypeError("unsupportedPresentation must be reject or text.");
11648
+ if (notify !== undefined && typeof notify !== "function")
11649
+ throw new TypeError("onDiagnostic must be a synchronous function.");
11650
+ return diagnostic => {
11651
+ if (policy === "reject")
11652
+ throw new TypeError("Unsupported Canopy presentation: " + diagnostic.code + (diagnostic.columnId ? " (" + diagnostic.columnId + ")" : ""));
11653
+ const result = notify?.(Object.freeze(diagnostic));
11654
+ if (result && typeof result.then === "function") {
11655
+ void Promise.resolve(result).catch(() => { });
11656
+ throw new TypeError("onDiagnostic must be synchronous.");
11657
+ }
11658
+ };
11659
+ }
11660
+ const _exports = Object.freeze({ canopyDiagnostics: canopyDiagnostics });
11661
+ _modules.set("3d1862d8ab32171bca4b3ba5fe0bdcc073f67ce940aaff0ee735635893f86ee8", _exports);
11662
+ return _exports;
11663
+ })();
11664
+
11665
+ const _m97 = _modules.get("040752afe195985e6f2e91f8c62fc13464c455fc44034b8cef4828851e05b83d") ?? (() => {
11666
+ /** Calibri 11, 96-DPI CSS pixels, seven-pixel maximum digit and five-pixel cell padding.
11667
+ * Quantize to native 1/256-character units; this is a reproducible profile, not pixel-identical rendering. */
11668
+ function canopyXlsxWidth(pixels) {
11669
+ const width = Math.floor((pixels < 12 ? pixels / 12 : (pixels - 5) / 7) * 256) / 256;
11670
+ if (!Number.isFinite(width) || width <= 0 || width > 255)
11671
+ throw new RangeError("Captured width exceeds the Calibri-11 XLSX width profile.");
11672
+ return width;
11673
+ }
11674
+ /** Escape literal prefixes/suffixes; no browser formatter or CSS becomes workbook code. */
11675
+ function canopyNumberFormat(input, report, id) {
11676
+ if (!input || typeof input !== "object" || Array.isArray(input))
11677
+ throw new TypeError("Canopy numeric format must be an object.");
11678
+ if (Object.keys(input).some(key => !["minimumFractionDigits", "maximumFractionDigits", "prefix", "suffix"].includes(key))) {
11679
+ report({ code: "UNSUPPORTED_NUMBER_FORMAT", columnId: id });
11680
+ return undefined;
11681
+ }
11682
+ const { minimumFractionDigits: minimum = 0, maximumFractionDigits: maximum = 3, prefix = "", suffix = "" } = input;
11683
+ if (!Number.isInteger(minimum) || !Number.isInteger(maximum) || minimum < 0 || maximum < minimum || maximum > 10 ||
11684
+ typeof prefix !== "string" || typeof suffix !== "string" || prefix.length > 16 || suffix.length > 16)
11685
+ throw new TypeError("Canopy numeric fraction bounds must be ordered integers from zero through ten, with literal affixes of at most sixteen characters.");
11686
+ const literal = (value) => value ? '"' + value.replace(/"/g, '"\\""') + '"' : "";
11687
+ return literal(prefix) + "0" + (maximum ? "." + "0".repeat(minimum) + "#".repeat(maximum - minimum) : "") + literal(suffix);
11688
+ }
11689
+ /** Only a contiguous leading left pin can be represented by an Excel freeze pane. */
11690
+ function canopyPins(columns, report) {
11691
+ let leading = 0, ended = false;
11692
+ for (const column of columns) {
11693
+ const pin = column.pinned;
11694
+ if (pin !== undefined && pin !== null && pin !== "left" && pin !== "right")
11695
+ throw new TypeError("Invalid Canopy pin.");
11696
+ if (!ended && pin === "left")
11697
+ leading++;
11698
+ else {
11699
+ ended = true;
11700
+ if (pin === "left" || pin === "right")
11701
+ report({ code: "UNREPRESENTABLE_PIN:" + pin, columnId: column.id });
11702
+ }
11703
+ }
11704
+ return leading;
11705
+ }
11706
+ const _exports = Object.freeze({ canopyXlsxWidth: canopyXlsxWidth, canopyNumberFormat: canopyNumberFormat, canopyPins: canopyPins });
11707
+ _modules.set("040752afe195985e6f2e91f8c62fc13464c455fc44034b8cef4828851e05b83d", _exports);
11708
+ return _exports;
11709
+ })();
11710
+
11711
+ const _m94 = _modules.get("a92d57114c08988b60d7dc46d24aeea3096cb6c695c12a7ea26761010692ef43") ?? (() => {
11557
11712
  const { ExportCell, checkAbort, inputRows } = _m1;
11558
11713
 
11559
11714
  const { datetime } = _m95;
@@ -11564,37 +11719,33 @@ const { copyColumns } = _m11;
11564
11719
 
11565
11720
  const { copyCellPresentation } = _m5;
11566
11721
 
11722
+ const { canopyDiagnostics } = _m96;
11723
+
11724
+ const { canopyNumberFormat, canopyXlsxWidth } = _m97;
11725
+
11567
11726
  const columnFields = ["width", "format", "wrapText", "alignment", "rowHeader", "groups"];
11568
11727
  /** Map an immutable CanopyX record capture to a writer without querying the grid or retaining its body. */
11569
11728
  function createCanopyExport(capture, format, options = {}) {
11729
+ return prepareCanopyExport(capture, format, options).source;
11730
+ }
11731
+ /** @internal Capture the input once before full-writer metadata mapping and asynchronous enumeration. */
11732
+ function prepareCanopyExport(capture, format, options = {}) {
11570
11733
  options = captureFields(options, ["tones", "columnOptions", "unsupportedPresentation", "datetime", "xlsx", "signal", "onDiagnostic"]);
11571
11734
  if (format !== "xlsx" && format !== "csv" && format !== "pdf")
11572
11735
  throw new TypeError("Canopy export format must be xlsx, csv or pdf.");
11573
11736
  if (!capture || typeof capture.rows !== "function" || !capture.request)
11574
11737
  throw new TypeError("A portable CanopyX capture with request and rows() is required.");
11575
- const { request } = capture, signal = options.signal, values = request.values;
11738
+ const request = captureFields(capture.request, ["columns", "recordCount", "values", "presentation", "timeZone", "revision", "scope", "total", "matched", "selection", "query", "generatedAt", "grouping", "formatRules"]);
11739
+ const signal = options.signal, values = request.values;
11576
11740
  if (!Array.isArray(request.columns) || !request.columns.length || (request.recordCount !== null && (!Number.isSafeInteger(request.recordCount) || request.recordCount < 0)) ||
11577
11741
  (values !== "raw" && values !== "display") || (request.timeZone !== "utc" && request.timeZone !== "local") || typeof request.revision !== "string")
11578
11742
  throw new TypeError("Invalid portable CanopyX capture metadata.");
11579
- const policy = options.unsupportedPresentation ?? (format === "csv" ? "text" : "reject"), dateMode = options.datetime ?? "preserve", notify = options.onDiagnostic;
11743
+ const dateMode = options.datetime ?? "preserve", report = canopyDiagnostics(format, options);
11580
11744
  const clock = options.xlsx?.dateMode ?? request.timeZone;
11581
11745
  if (clock !== "utc" && clock !== "local")
11582
11746
  throw new TypeError("XLSX dateMode must be utc or local.");
11583
- if (policy !== "reject" && policy !== "text")
11584
- throw new TypeError("unsupportedPresentation must be reject or text.");
11585
11747
  if (dateMode !== "preserve" && dateMode !== "typed" && dateMode !== "text")
11586
11748
  throw new TypeError("datetime must be preserve, typed or text.");
11587
- if (notify !== undefined && typeof notify !== "function")
11588
- throw new TypeError("onDiagnostic must be a synchronous function.");
11589
- const report = (diagnostic) => {
11590
- if (policy === "reject")
11591
- throw new TypeError("Unsupported Canopy presentation: " + diagnostic.code + (diagnostic.columnId ? " (" + diagnostic.columnId + ")" : ""));
11592
- const result = notify?.(Object.freeze(diagnostic));
11593
- if (result && typeof result.then === "function") {
11594
- void Promise.resolve(result).catch(() => { });
11595
- throw new TypeError("onDiagnostic must be synchronous.");
11596
- }
11597
- };
11598
11749
  const diagnostics = (items, rowId, columnId) => {
11599
11750
  if (items === undefined)
11600
11751
  return;
@@ -11603,9 +11754,7 @@ function createCanopyExport(capture, format, options = {}) {
11603
11754
  for (const code of items)
11604
11755
  report({ code, ...(rowId === undefined ? {} : { rowId }), ...(columnId === undefined ? {} : { columnId }) });
11605
11756
  };
11606
- if (request.presentation === "text")
11607
- report({ code: "TEXT_ONLY_CAPTURE" });
11608
- else if (request.presentation !== "semantic")
11757
+ if (request.presentation !== "text" && request.presentation !== "semantic")
11609
11758
  throw new TypeError("Canopy captures must declare text or semantic presentation.");
11610
11759
  const tones = new Map(Object.entries(options.tones ?? {}).map(([name, style]) => {
11611
11760
  if (!style || typeof style !== "object" || Array.isArray(style))
@@ -11618,12 +11767,16 @@ function createCanopyExport(capture, format, options = {}) {
11618
11767
  if (typeof name !== "string")
11619
11768
  throw new TypeError("Canopy tones must be strings.");
11620
11769
  const style = tones.get(name);
11621
- if (!style)
11770
+ if (!style && name !== "neutral")
11622
11771
  report({ code: "UNMAPPED_TONE:" + name, rowId, ...(columnId === undefined ? {} : { columnId }) });
11623
11772
  return style;
11624
11773
  };
11625
11774
  const ids = new Set();
11626
- const specs = request.columns.map(column => {
11775
+ const specs = request.columns.map(input => {
11776
+ const fields = captureFields(input, ["id", "title", "kind", "width", "pinned", "format", "wrap", "alignment", "diagnostics"]);
11777
+ const column = Object.freeze({ ...fields,
11778
+ ...(fields.width === undefined ? {} : { width: Object.freeze(captureFields(fields.width, ["unit", "preferred", "minimum", "maximum"])) }),
11779
+ ...(fields.format === undefined ? {} : { format: Object.freeze(captureFields(fields.format, ["minimumFractionDigits", "maximumFractionDigits", "prefix", "suffix"])) }) });
11627
11780
  if (!column || typeof column.id !== "string" || !column.id || ids.has(column.id) || typeof column.title !== "string" ||
11628
11781
  !["text", "number", "datetime"].includes(column.kind) ||
11629
11782
  (column.wrap !== undefined && typeof column.wrap !== "boolean") || (column.alignment !== undefined && !["left", "right"].includes(column.alignment)) ||
@@ -11639,14 +11792,19 @@ function createCanopyExport(capture, format, options = {}) {
11639
11792
  if (!columnFields.includes(key))
11640
11793
  throw new TypeError("Unsupported Canopy column option: " + key);
11641
11794
  const override = captureFields(selected, columnFields);
11795
+ const numericFormat = format === "xlsx" && values === "raw" && column.kind === "number" && column.format !== undefined && override.format === undefined
11796
+ ? canopyNumberFormat(column.format, report, column.id) : undefined;
11642
11797
  const [captured] = copyColumns([{ ...override, key: column.id, header: column.title,
11798
+ ...(format === "xlsx" && override.width === undefined && column.width !== undefined ? { width: canopyXlsxWidth(column.width.preferred) } : {}),
11799
+ ...(override.format === undefined && numericFormat !== undefined ? { format: numericFormat } : {}),
11800
+ ...(format === "xlsx" && values === "raw" && column.kind === "datetime" && override.format === undefined ? { format: "yyyy-mm-dd hh:mm:ss.000" } : {}),
11643
11801
  ...(values === "raw" && column.kind === "number" ? { type: "number" } : {}),
11644
11802
  ...(override.wrapText === undefined && column.wrap === undefined ? {} : { wrapText: override.wrapText ?? column.wrap }),
11645
11803
  ...(override.alignment === undefined && column.alignment === undefined ? {} : { alignment: override.alignment ?? column.alignment }) }]);
11646
- return Object.freeze({ id: column.id, kind: column.kind, column: Object.freeze(captured) });
11804
+ return Object.freeze({ id: column.id, kind: column.kind, input: column, column: Object.freeze(captured) });
11647
11805
  });
11648
11806
  const rowCount = request.recordCount;
11649
- return Object.freeze({ columns: Object.freeze(specs.map(spec => spec.column)), rowCount, async *rows() {
11807
+ const source = Object.freeze({ columns: Object.freeze(specs.map(spec => spec.column)), rowCount, async *rows() {
11650
11808
  checkAbort(signal);
11651
11809
  let count = 0;
11652
11810
  for await (const row of inputRows(capture.rows(signal ? { signal } : {}), signal)) {
@@ -11680,14 +11838,638 @@ function createCanopyExport(capture, format, options = {}) {
11680
11838
  if (rowCount !== null && count !== rowCount)
11681
11839
  throw new TypeError("Canopy capture did not produce its declared recordCount.");
11682
11840
  } });
11841
+ return Object.freeze({ source, request: Object.freeze({ ...request, columns: Object.freeze(specs.map(spec => spec.input)) }), report, tones });
11842
+ }
11843
+ const _exports = Object.freeze({ createCanopyExport: createCanopyExport, prepareCanopyExport: prepareCanopyExport });
11844
+ _modules.set("a92d57114c08988b60d7dc46d24aeea3096cb6c695c12a7ea26761010692ef43", _exports);
11845
+ return _exports;
11846
+ })();
11847
+
11848
+ const _m99 = _modules.get("237239bcf5fa7675f75c53d2f367d843e089051bfd9f586770330a2c504ce1f7") ?? (() => {
11849
+ const { columnName, excelDate } = _m35;
11850
+
11851
+ const { captureFields } = _m10;
11852
+
11853
+ const { datetime } = _m95;
11854
+
11855
+ /** Compile only comparisons whose raw types and native encodings have a faithful bounded mapping. */
11856
+ function canopyPredicate(request, grouped, options, root, unsupported, cellTypes) {
11857
+ let nodes = 0;
11858
+ const operations = { eq: "=", ne: "<>", gt: ">", ge: ">=", lt: "<", le: "<=" };
11859
+ const numeric = (value) => {
11860
+ const number = typeof value === "boolean" ? Number(value) : typeof value === "string" ? Number(value) : value;
11861
+ // Use platform decimal conversion; separator/culture profiles need a diagnostic, not a second parser.
11862
+ if (typeof value === "string") {
11863
+ const text = value.trim().toLowerCase();
11864
+ if (Number.parseFloat(value) !== number || ["0x", "0b", "0o"].some(prefix => text.startsWith(prefix)))
11865
+ return unsupported("UNSUPPORTED_NUMERIC_RULE_LITERAL");
11866
+ }
11867
+ if (!Number.isFinite(number) || Math.abs(number) > Number.MAX_SAFE_INTEGER)
11868
+ throw new TypeError("Canopy rule comparison values must be finite safe-range numbers.");
11869
+ return number;
11870
+ };
11871
+ const date = (value) => {
11872
+ if (options.datetime !== "typed" || (options.xlsx?.dateMode ?? request.timeZone) !== "utc")
11873
+ return unsupported("DATETIME_RULE_REQUIRES_TYPED_UTC");
11874
+ if (typeof value === "boolean")
11875
+ return unsupported("UNSUPPORTED_DATETIME_RULE_LITERAL");
11876
+ if (typeof value === "number" && !Number.isSafeInteger(value))
11877
+ return unsupported("UNSUPPORTED_DATETIME_RULE_LITERAL");
11878
+ try {
11879
+ const literal = typeof value === "number" ? new Date(value).toISOString() : value;
11880
+ const captured = datetime(literal, "typed", "utc");
11881
+ if (!(captured instanceof Date))
11882
+ return unsupported("UNSUPPORTED_DATETIME_RULE_LITERAL");
11883
+ const serial = excelDate(captured, "utc");
11884
+ if (serial === null)
11885
+ return unsupported("UNSUPPORTED_DATETIME_RULE_LITERAL");
11886
+ return serial;
11887
+ }
11888
+ catch (error) {
11889
+ if (!(error instanceof TypeError) && !(error instanceof RangeError))
11890
+ throw error;
11891
+ return unsupported("UNSUPPORTED_DATETIME_RULE_LITERAL");
11892
+ }
11893
+ };
11894
+ const leaf = (input) => {
11895
+ if (++nodes > 64)
11896
+ return unsupported("RULE_PREDICATE_LIMIT");
11897
+ const filter = captureFields(input, ["column", "operator", "values"]), operation = operations[filter.operator];
11898
+ if (Object.keys(filter).some(key => !["column", "operator", "values"].includes(key)))
11899
+ return unsupported("UNSUPPORTED_RULE_FILTER_OPTIONS");
11900
+ const index = request.columns.findIndex(column => column.id === filter.column);
11901
+ if (index < 0)
11902
+ return unsupported("RULE_COLUMN_NOT_EXPORTED:" + filter.column);
11903
+ const column = request.columns[index], letter = columnName(index + 1 + (grouped ? 1 : 0));
11904
+ const reference = "INDEX($" + letter + ":$" + letter + ",ROW())", present = "NOT(ISBLANK(" + reference + "))";
11905
+ if (column.kind === "number")
11906
+ cellTypes.set(index, "number");
11907
+ if (column.kind === "datetime") {
11908
+ if (options.datetime !== "typed" || (options.xlsx?.dateMode ?? request.timeZone) !== "utc")
11909
+ return unsupported("DATETIME_RULE_REQUIRES_TYPED_UTC");
11910
+ cellTypes.set(index, "date");
11911
+ }
11912
+ if (filter.operator === "isNull" || filter.operator === "isNotNull") {
11913
+ if (filter.values !== undefined && filter.values.length)
11914
+ return unsupported("UNSUPPORTED_NULL_RULE_OPERANDS");
11915
+ return filter.operator === "isNull" ? "ISBLANK(" + reference + ")" : present;
11916
+ }
11917
+ if (!operation || !Array.isArray(filter.values) || filter.values.length !== 1)
11918
+ return unsupported("UNSUPPORTED_RULE_FILTER:" + filter.operator);
11919
+ const value = filter.values[0];
11920
+ if (typeof value !== "string" && typeof value !== "number" && typeof value !== "boolean")
11921
+ throw new TypeError("Canopy rule values must be portable scalars.");
11922
+ if (column.kind === "number" || column.kind === "datetime") {
11923
+ const operand = column.kind === "number" ? numeric(value) : date(value);
11924
+ return "AND(" + present + ",ISNUMBER(" + reference + ")," + reference + operation + String(operand) + ")";
11925
+ }
11926
+ if (filter.operator !== "eq" && filter.operator !== "ne")
11927
+ return unsupported("UNSUPPORTED_TEXT_RULE_COMPARISON");
11928
+ // Canopy's Unicode text folding is not the native workbook's comparison contract.
11929
+ if (typeof value === "string")
11930
+ return unsupported("UNQUALIFIED_NATIVE_TEXT_COMPARISON");
11931
+ const kind = typeof value === "boolean" ? "ISLOGICAL" : "ISNUMBER";
11932
+ const literal = typeof value === "boolean" ? value ? "TRUE" : "FALSE" : String(numeric(value));
11933
+ const sameType = kind + "(" + reference + ")", comparison = reference + operation + literal;
11934
+ return filter.operator === "eq" ? "AND(" + present + "," + sameType + "," + comparison + ")"
11935
+ : "AND(" + present + ",OR(NOT(" + sameType + ")," + comparison + "))";
11936
+ };
11937
+ const visit = (input, depth) => {
11938
+ if (depth > 4 || ++nodes > 64)
11939
+ return unsupported("RULE_PREDICATE_LIMIT");
11940
+ if (!input || typeof input !== "object")
11941
+ throw new TypeError("Canopy rule predicate must be an object.");
11942
+ const captured = captureFields(input, ["operator", "filters", "groups"]);
11943
+ if (captured.operator !== "and" && captured.operator !== "or")
11944
+ return unsupported("UNSUPPORTED_RULE_BOOLEAN:" + captured.operator);
11945
+ const filters = captured.filters ?? [], groups = captured.groups ?? [];
11946
+ if (!Array.isArray(filters) || !Array.isArray(groups))
11947
+ throw new TypeError("Canopy predicate filters and groups must be arrays.");
11948
+ const terms = [];
11949
+ for (const filter of filters)
11950
+ terms.push(leaf(filter));
11951
+ for (const group of groups)
11952
+ terms.push(visit(group, depth + 1));
11953
+ if (!terms.length)
11954
+ return unsupported("EMPTY_RULE_PREDICATE");
11955
+ return captured.operator.toUpperCase() + "(" + terms.join(",") + ")";
11956
+ };
11957
+ const formula = visit(root, 1);
11958
+ if (formula.length > 8192)
11959
+ return unsupported("RULE_FORMULA_LIMIT");
11960
+ return formula;
11961
+ }
11962
+ const _exports = Object.freeze({ canopyPredicate: canopyPredicate });
11963
+ _modules.set("237239bcf5fa7675f75c53d2f367d843e089051bfd9f586770330a2c504ce1f7", _exports);
11964
+ return _exports;
11965
+ })();
11966
+
11967
+ const _m98 = _modules.get("13582dc7ba6ecf2a33722c6fee326b500408542ffdaa5cdac26ae72c310ea1ba") ?? (() => {
11968
+ const { captureFields } = _m10;
11969
+
11970
+ const { canopyPredicate } = _m99;
11971
+
11972
+ // Stable document palette. Browser CSS variables and resolved cell.format are never interpreted.
11973
+ const palette = {
11974
+ info: { color: "4472C4", background: "DDEBF7", foreground: "1F4E78" },
11975
+ success: { color: "70AD47", background: "E2F0D9", foreground: "375623" },
11976
+ warning: { color: "FFC000", background: "FFF2CC", foreground: "9C6500" },
11977
+ danger: { color: "C00000", background: "FFC7CE", foreground: "9C0006" }
11978
+ };
11979
+ class UnsupportedRule extends Error {
11980
+ }
11981
+ const unsupported = (message) => { throw new UnsupportedRule(message); };
11982
+ /** Compile declarations in source order, then emit native target/aspect priorities.
11983
+ * Data-column selectors let grouped writers exclude generated headings, subtotals and grand totals. */
11984
+ function canopyRules(request, format, grouped, tones, report, options = {}, cellTypes) {
11985
+ if (request.formatRules === undefined || format === "csv")
11986
+ return [];
11987
+ if (!Array.isArray(request.formatRules) || request.formatRules.length > 1000)
11988
+ throw new TypeError("Canopy formatRules must be a bounded array of at most 1,000 declarations.");
11989
+ const visuals = [], cells = [], rows = [], ids = new Set(), columns = request.columns;
11990
+ const inputs = request.formatRules;
11991
+ const declarations = inputs.map(input => {
11992
+ if (!input || typeof input !== "object")
11993
+ throw new TypeError("Canopy rule declarations must be objects.");
11994
+ const rule = captureFields(input, ["id", "enabled", "stopIfTrue", "column", "when", "target", "style"]);
11995
+ if (typeof rule.id !== "string" || !rule.id || ids.has(rule.id))
11996
+ throw new TypeError("Canopy rule IDs must be unique nonempty strings.");
11997
+ ids.add(rule.id);
11998
+ if (rule.enabled !== undefined && typeof rule.enabled !== "boolean" || rule.stopIfTrue !== undefined && typeof rule.stopIfTrue !== "boolean")
11999
+ throw new TypeError("Canopy rule flags must be boolean.");
12000
+ const style = rule.style && typeof rule.style === "object" ? captureFields(rule.style, ["tone", "bar", "scale"]) : rule.style;
12001
+ return { ...rule, style };
12002
+ });
12003
+ if (format === "pdf") {
12004
+ for (const rule of declarations)
12005
+ if (rule.enabled !== false)
12006
+ report({ code: "PDF_NATIVE_RULE_NOT_RENDERED:" + rule.id });
12007
+ return [];
12008
+ }
12009
+ const hasStops = declarations.some(rule => rule.enabled !== false && rule.stopIfTrue);
12010
+ if (hasStops && declarations.some(rule => rule.enabled !== false && (rule.style?.bar !== undefined || rule.style?.scale !== undefined))) {
12011
+ report({ code: "UNSUPPORTED_GLOBAL_STOP_WITH_NATIVE_VISUALS" });
12012
+ return [];
12013
+ }
12014
+ const barColumns = new Set(declarations.filter(rule => rule.enabled !== false && rule.style?.bar !== undefined).map(rule => rule.column));
12015
+ const barTone = declarations.find(rule => rule.enabled !== false && rule.target !== "row" && rule.style?.tone !== undefined && rule.column !== undefined && barColumns.has(rule.column));
12016
+ if (barTone) {
12017
+ // Canopy suppresses a cell tone's fill only where its bar resolves. A single native tone patch cannot express both cases.
12018
+ report({ code: "UNSUPPORTED_CELL_TONE_WITH_DATA_BAR", columnId: barTone.column });
12019
+ return [];
12020
+ }
12021
+ const priorStops = [];
12022
+ const priorRows = [], priorCells = new Map();
12023
+ const requiredCells = new Map();
12024
+ const column = (id) => {
12025
+ const index = columns.findIndex(column => column.id === id);
12026
+ if (index < 0)
12027
+ return unsupported("RULE_COLUMN_NOT_EXPORTED:" + id);
12028
+ return index;
12029
+ };
12030
+ const numeric = (id) => {
12031
+ if (columns[column(id)].kind !== "number")
12032
+ unsupported("RULE_COLUMN_NOT_NUMERIC:" + id);
12033
+ };
12034
+ const color = (name) => {
12035
+ const mapping = tones.get(name), value = mapping?.background ?? mapping?.color ?? palette[name]?.color;
12036
+ if (value === undefined)
12037
+ return unsupported("UNMAPPED_RULE_TONE:" + name);
12038
+ return value;
12039
+ };
12040
+ const style = (name) => {
12041
+ const defaults = palette[name];
12042
+ const mapping = tones.get(name) ?? (defaults ? { background: defaults.background, color: defaults.foreground } : undefined);
12043
+ if (!mapping)
12044
+ return unsupported("UNMAPPED_RULE_TONE:" + name);
12045
+ if ("alignment" in mapping || "wrapText" in mapping)
12046
+ return unsupported("UNSUPPORTED_RULE_TONE_STYLE:" + name);
12047
+ return {
12048
+ ...("background" in mapping && mapping.background !== undefined ? { fill: { color: mapping.background } } : {}),
12049
+ font: { ...(mapping.color === undefined ? {} : { color: mapping.color }),
12050
+ ...("bold" in mapping && mapping.bold !== undefined ? { bold: mapping.bold } : {}),
12051
+ ...("italic" in mapping && mapping.italic !== undefined ? { italic: mapping.italic } : {}) },
12052
+ ...("numberFormat" in mapping && mapping.numberFormat !== undefined ? { numberFormat: mapping.numberFormat } : {})
12053
+ };
12054
+ };
12055
+ for (const rule of declarations) {
12056
+ if (rule.enabled === false)
12057
+ continue;
12058
+ try {
12059
+ if (request.values !== "raw")
12060
+ unsupported("NATIVE_RULE_REQUIRES_RAW_VALUES");
12061
+ if (rule.target === "columns" || "columns" in rule && rule.columns !== undefined)
12062
+ unsupported("UNSUPPORTED_RULE_COLUMNS_TARGET");
12063
+ if (!rule.style || typeof rule.style !== "object" || Array.isArray(rule.style))
12064
+ throw new TypeError("Canopy rule style must be an object.");
12065
+ const styleInput = captureFields(rule.style, ["tone", "bar", "scale"]);
12066
+ if (Object.keys(styleInput).some(key => !["tone", "bar", "scale"].includes(key)))
12067
+ unsupported("UNSUPPORTED_RULE_STYLE");
12068
+ const supplied = [styleInput.bar, styleInput.scale, styleInput.tone].filter(value => value !== undefined);
12069
+ if (supplied.length !== 1)
12070
+ unsupported("UNSUPPORTED_RULE_STYLE_COMBINATION");
12071
+ if (styleInput.bar !== undefined) {
12072
+ if (rule.column === undefined || rule.when !== undefined || rule.target === "row")
12073
+ unsupported("UNSUPPORTED_BAR_TARGET");
12074
+ numeric(rule.column);
12075
+ if (rule.stopIfTrue)
12076
+ unsupported("UNSUPPORTED_BAR_STOP");
12077
+ const { minimum, maximum, tone = "info", showValue } = captureFields(styleInput.bar, ["minimum", "maximum", "tone", "showValue"]);
12078
+ if (minimum === undefined || maximum === undefined)
12079
+ return unsupported("UNBOUNDED_CANOPY_BAR");
12080
+ if (!Number.isFinite(minimum) || !Number.isFinite(maximum) || maximum <= minimum)
12081
+ throw new TypeError("Canopy bar bounds must be finite and increasing.");
12082
+ visuals.push({ type: "dataBar", range: { column: rule.column }, color: color(tone),
12083
+ minimum: { type: "number", value: minimum }, maximum: { type: "number", value: maximum }, ...(showValue === undefined ? {} : { showValue }) });
12084
+ requiredCells.set(column(rule.column), "number");
12085
+ }
12086
+ else if (styleInput.scale !== undefined) {
12087
+ if (rule.stopIfTrue)
12088
+ unsupported("UNSUPPORTED_SCALE_STOP");
12089
+ if (rule.column === undefined || rule.when !== undefined || rule.target === "row")
12090
+ unsupported("UNSUPPORTED_SCALE_TARGET");
12091
+ numeric(rule.column);
12092
+ const { stops } = captureFields(styleInput.scale, ["stops"]);
12093
+ if (!Array.isArray(stops) || stops.length < 2 || stops.length > 3)
12094
+ unsupported("UNSUPPORTED_SCALE_STOPS");
12095
+ const mapped = stops.map((input) => {
12096
+ const stop = captureFields(input, ["type", "value", "tone"]);
12097
+ if (!["min", "max", "number", "percent", "percentile"].includes(stop.type))
12098
+ unsupported("UNSUPPORTED_SCALE_THRESHOLD:" + stop.type);
12099
+ const threshold = stop.type === "min" || stop.type === "max" ? { type: stop.type }
12100
+ : { type: stop.type, value: stop.value };
12101
+ return { threshold, color: color(stop.tone) };
12102
+ });
12103
+ visuals.push({ type: "colorScale", range: { column: rule.column },
12104
+ stops: mapped });
12105
+ requiredCells.set(column(rule.column), "number");
12106
+ }
12107
+ else {
12108
+ if (rule.when === undefined || styleInput.tone === undefined || rule.target !== "row" && rule.column === undefined)
12109
+ unsupported("UNSUPPORTED_HIGHLIGHT_TARGET");
12110
+ if (rule.target !== undefined && rule.target !== "row" && rule.target !== "cell")
12111
+ unsupported("UNSUPPORTED_RULE_TARGET");
12112
+ const range = rule.target === "row" ? { column: columns[0].id, through: columns.at(-1).id } : { column: rule.column };
12113
+ if (rule.column !== undefined)
12114
+ column(rule.column);
12115
+ const ruleCells = new Map();
12116
+ const ownPredicate = canopyPredicate(request, grouped, options, rule.when, unsupported, ruleCells);
12117
+ const reachable = priorStops.length ? "AND(" + ownPredicate + ",NOT(OR(" + priorStops.join(",") + ")))" : ownPredicate;
12118
+ const previous = rule.target === "row" ? priorRows : priorCells.get(rule.column) ?? [];
12119
+ const formula = previous.length ? "AND(" + reachable + ",NOT(OR(" + previous.join(",") + ")))" : reachable;
12120
+ if (formula.length > 8192)
12121
+ unsupported("RULE_FORMULA_LIMIT");
12122
+ (rule.target === "row" ? rows : cells).push({ type: "expression", range, formula, style: style(styleInput.tone) });
12123
+ previous.push(ownPredicate);
12124
+ if (rule.target !== "row")
12125
+ priorCells.set(rule.column, previous);
12126
+ for (const [column, type] of ruleCells)
12127
+ requiredCells.set(column, type);
12128
+ // A matched declaration still stops the row when an earlier tone on that target already won.
12129
+ if (rule.stopIfTrue)
12130
+ priorStops.push(ownPredicate);
12131
+ }
12132
+ }
12133
+ catch (error) {
12134
+ if (!(error instanceof UnsupportedRule))
12135
+ throw error;
12136
+ report({ code: error.message + ":" + rule.id, ...(rule.column === undefined ? {} : { columnId: rule.column }) });
12137
+ if (hasStops)
12138
+ return []; // A partial sequence cannot claim to preserve its row-global stopping behavior.
12139
+ }
12140
+ }
12141
+ for (const [column, type] of requiredCells)
12142
+ cellTypes?.set(column, type);
12143
+ // Canopy paints cell visuals/tones over the row tint. Build masks before changing native priority order.
12144
+ return Object.freeze([...visuals, ...cells, ...rows]);
11683
12145
  }
11684
- const _exports = Object.freeze({ createCanopyExport: createCanopyExport });
11685
- _modules.set("91dbdf35d8f192b3c0ea92dfab6b9812872fbe3c8d85a5d2afe389bd61262ba2", _exports);
12146
+ const _exports = Object.freeze({ canopyRules: canopyRules });
12147
+ _modules.set("13582dc7ba6ecf2a33722c6fee326b500408542ffdaa5cdac26ae72c310ea1ba", _exports);
11686
12148
  return _exports;
11687
12149
  })();
11688
12150
 
11689
- const _m0 = _modules.get("3e66cc3ead243255e3903dfabd767d39c2507193c6631b6a40caad66216c13ed") ?? (() => {
11690
- const { BlobByteSink } = _m1;
12151
+ const _m100 = _modules.get("0f2b50bd606bf0a3273e7a3bec7ed6255f23cfee522a7cfeb2cb676c062ad40e") ?? (() => {
12152
+ const { createGroupedReport } = _m8;
12153
+
12154
+ const { ExportCell } = _m5;
12155
+
12156
+ const { checkAbort } = _m4;
12157
+
12158
+ const { createTotals } = _m12;
12159
+
12160
+ const { captureFields } = _m10;
12161
+
12162
+ const { datetime } = _m95;
12163
+
12164
+ const identity = (value) => value instanceof Date ? "date:" + value.getTime() : typeof value + ":" + String(value);
12165
+ const scalar = (value) => value instanceof ExportCell ? value.value : value;
12166
+ /** Validate captured ranges, then use the owned grouping factory and its existing writers.
12167
+ * Only ranges, labels and at most four active aggregate vectors are retained; no detail body is buffered. */
12168
+ function canopyGrouped(source, request, options, limits, report, format) {
12169
+ const input = request.grouping;
12170
+ if (input === undefined)
12171
+ return undefined; // query.groupBy never manufactures a group snapshot.
12172
+ if (request.values !== "raw") {
12173
+ report({ code: "GROUPING_REQUIRES_RAW_VALUES" });
12174
+ return undefined;
12175
+ }
12176
+ if (source.rowCount === null)
12177
+ throw new TypeError("Captured grouping requires its exact scope recordCount.");
12178
+ const grouping = captureFields(input, ["levels", "aggregates", "totals", "groups"]);
12179
+ if (!Array.isArray(grouping.levels) || grouping.levels.length < 1 || grouping.levels.length > 4 || !Array.isArray(grouping.aggregates) || !Array.isArray(grouping.groups))
12180
+ throw new TypeError("Canopy grouping needs one through four levels, aggregates and ordered groups.");
12181
+ const levels = grouping.levels.map(level => Object.freeze(captureFields(level, ["column", "direction", "title"])));
12182
+ if (levels.some(level => typeof level.column !== "string" || !level.column || level.direction !== "asc" && level.direction !== "desc") ||
12183
+ new Set(levels.map(level => level.column)).size !== levels.length)
12184
+ throw new TypeError("Canopy grouping levels need unique stable columns and directions.");
12185
+ const declarations = grouping.aggregates.map(aggregate => Object.freeze(captureFields(aggregate, ["id", "column", "operation", "label"])));
12186
+ const ids = new Set(), totals = Object.create(null);
12187
+ const operations = { sum: "sum", count: "count", average: "average", minimum: "min", maximum: "max" };
12188
+ for (const aggregate of declarations) {
12189
+ if (typeof aggregate.id !== "string" || !aggregate.id || ids.has(aggregate.id))
12190
+ throw new TypeError("Canopy aggregate IDs must be unique nonempty strings.");
12191
+ ids.add(aggregate.id);
12192
+ const column = source.columns.find(column => column.key === aggregate.column);
12193
+ if (!column || column.type !== "number")
12194
+ throw new TypeError("Canopy aggregate declarations require an exported raw numeric column.");
12195
+ if (Object.hasOwn(totals, aggregate.column))
12196
+ throw new TypeError("The grouped report supports one aggregate operation per column.");
12197
+ const operation = operations[aggregate.operation];
12198
+ if (operation === undefined) {
12199
+ report({ code: "UNSUPPORTED_GROUP_AGGREGATE:" + aggregate.operation, columnId: aggregate.column });
12200
+ return undefined;
12201
+ }
12202
+ totals[aggregate.column] = operation;
12203
+ }
12204
+ // Reuse the canonical operation validator rather than implementing aggregate semantics here.
12205
+ createTotals(source.columns, totals);
12206
+ const expected = (input) => {
12207
+ if (!input || typeof input !== "object" || Array.isArray(input))
12208
+ throw new TypeError("Canopy aggregate values must be an ID-keyed object.");
12209
+ const snapshot = { ...input };
12210
+ if (Object.keys(snapshot).some(key => !ids.has(key)) || declarations.some(aggregate => !Object.hasOwn(snapshot, aggregate.id)))
12211
+ throw new TypeError("Canopy aggregate values must reference exactly the captured declarations.");
12212
+ for (const value of Object.values(snapshot))
12213
+ if (value !== null && (typeof value !== "number" || !Number.isFinite(value)))
12214
+ throw new TypeError("Canopy aggregate values must be finite numbers or null.");
12215
+ return Object.freeze(snapshot);
12216
+ };
12217
+ const grandExpected = expected(grouping.totals), byDepth = levels.map(() => []), labels = levels.map(() => new Map());
12218
+ let groups = 0, characters = 0;
12219
+ const ranges = (inputs, offset, end, depth) => {
12220
+ if (!Array.isArray(inputs))
12221
+ throw new TypeError("Canopy groups must be ordered arrays.");
12222
+ let cursor = offset;
12223
+ const keys = new Set(), values = new Set();
12224
+ for (const input of inputs) {
12225
+ const group = captureFields(input, ["key", "value", "text", "offset", "count", "aggregates", "groups"]);
12226
+ if (!group || typeof group.key !== "string" || keys.has(group.key) || !Number.isSafeInteger(group.offset) || !Number.isSafeInteger(group.count) ||
12227
+ group.count <= 0 || group.offset !== cursor || group.count > end - group.offset)
12228
+ throw new TypeError("Canopy group ranges must be nonempty contiguous half-open partitions within their parent.");
12229
+ if (group.value !== null && !["string", "number", "boolean"].includes(typeof group.value) ||
12230
+ typeof group.value === "number" && !Number.isFinite(group.value))
12231
+ throw new TypeError("Canopy group values must be portable finite scalars.");
12232
+ const dateColumn = request.columns.find(column => column.id === levels[depth].column)?.kind === "datetime";
12233
+ const value = format === "xlsx" && dateColumn && typeof group.value === "string"
12234
+ ? datetime(group.value, options.datetime ?? "preserve", options.xlsx?.dateMode ?? request.timeZone) : group.value;
12235
+ const key = identity(value), text = group.text ?? String(group.value ?? "");
12236
+ if (typeof text !== "string" || values.has(key))
12237
+ throw new TypeError("A Canopy group key cannot recur within the same parent.");
12238
+ const previousLabel = labels[depth].get(key);
12239
+ if (previousLabel !== undefined && previousLabel !== text)
12240
+ throw new TypeError("The same grouping value needs consistent captured text at one level.");
12241
+ labels[depth].set(key, text);
12242
+ keys.add(group.key);
12243
+ values.add(key);
12244
+ if (++groups > 1000 || (characters += group.key.length + key.length + text.length) > 1000000)
12245
+ throw new RangeError("Canopy group metadata exceeds the existing bounded report profile.");
12246
+ const next = group.offset + group.count;
12247
+ byDepth[depth].push(Object.freeze({ offset: group.offset, end: next, value, text, expected: expected(group.aggregates) }));
12248
+ if (depth + 1 < levels.length)
12249
+ ranges(group.groups ?? [], group.offset, next, depth + 1);
12250
+ else if (group.groups !== undefined && group.groups.length)
12251
+ throw new TypeError("Canopy nested groups exceed their declared levels.");
12252
+ cursor = next;
12253
+ }
12254
+ if (cursor !== end)
12255
+ throw new TypeError("Canopy grouping does not cover its complete exported detail range.");
12256
+ };
12257
+ ranges(grouping.groups, 0, source.rowCount, 0);
12258
+ // Validate the producer's wire arithmetic separately from the grouped writer's native formula caches.
12259
+ // Canopy sum/average use compensated accumulation and return null without numeric inputs.
12260
+ const wireTotals = () => {
12261
+ const ordinary = createTotals(source.columns, totals), sums = source.columns.map(() => 0), corrections = source.columns.map(() => 0), counts = source.columns.map(() => 0);
12262
+ return {
12263
+ accept(values) {
12264
+ for (let index = 0; index < values.length; index++) {
12265
+ const value = scalar(values[index]), operation = totals[source.columns[index].key];
12266
+ if (operation !== "sum" && operation !== "average") {
12267
+ ordinary[index].accept(value);
12268
+ continue;
12269
+ }
12270
+ if (typeof value !== "number" || !Number.isFinite(value))
12271
+ continue;
12272
+ counts[index] = counts[index] + 1;
12273
+ const next = value - corrections[index], total = sums[index] + next;
12274
+ corrections[index] = total - sums[index] - next;
12275
+ sums[index] = total;
12276
+ }
12277
+ },
12278
+ value(index) {
12279
+ const operation = totals[source.columns[index].key];
12280
+ return operation === "sum" || operation === "average" ? !counts[index] ? null
12281
+ : operation === "sum" ? sums[index] : sums[index] / counts[index] : ordinary[index].value();
12282
+ }
12283
+ };
12284
+ };
12285
+ const indexes = levels.map(() => 0), active = levels.map(() => undefined);
12286
+ const at = (depth, row) => {
12287
+ const list = byDepth[depth];
12288
+ while (list[indexes[depth]] && list[indexes[depth]].end <= row)
12289
+ indexes[depth] = indexes[depth] + 1;
12290
+ const range = list[indexes[depth]];
12291
+ if (!range || row < range.offset || row >= range.end)
12292
+ throw new TypeError("A detail row is outside its captured Canopy grouping.");
12293
+ return range;
12294
+ };
12295
+ const verify = (actual, expected) => {
12296
+ for (const declaration of declarations) {
12297
+ const position = source.columns.findIndex(column => column.key === declaration.column), observed = actual.value(position), declared = expected[declaration.id];
12298
+ // Exact producer-wire comparison retains wrong-scope rejection without rounding native caches or applying an epsilon.
12299
+ if (observed !== declared)
12300
+ throw new TypeError("Canopy captured aggregate differs from its consumed rows: " + declaration.id + ".");
12301
+ }
12302
+ };
12303
+ const same = (actual, expected) => actual instanceof Date && expected instanceof Date
12304
+ ? actual.getTime() === expected.getTime() : actual === expected;
12305
+ async function* rows() {
12306
+ let index = 0;
12307
+ const grand = wireTotals();
12308
+ for await (const values of source.rows()) {
12309
+ checkAbort(options.signal);
12310
+ for (let depth = 0; depth < levels.length; depth++) {
12311
+ const range = at(depth, index), column = source.columns.findIndex(column => column.key === levels[depth].column);
12312
+ if (column >= 0 && !same(scalar(values[column]), range.value))
12313
+ throw new TypeError("Canopy detail value disagrees with its captured group range.");
12314
+ if (range.offset === index)
12315
+ active[depth] = { range, aggregates: wireTotals() };
12316
+ }
12317
+ grand.accept(values);
12318
+ for (const group of active)
12319
+ group.aggregates.accept(values);
12320
+ yield values;
12321
+ index++;
12322
+ for (let depth = levels.length - 1; depth >= 0; depth--) {
12323
+ const group = active[depth];
12324
+ if (group.range.end === index) {
12325
+ verify(group.aggregates, group.range.expected);
12326
+ active[depth] = undefined;
12327
+ }
12328
+ }
12329
+ }
12330
+ verify(grand, grandExpected);
12331
+ }
12332
+ const groupBy = levels.map((level, depth) => {
12333
+ const visible = source.columns.some(column => column.key === level.column);
12334
+ return { key: level.column,
12335
+ ...(visible ? {} : { value: (_row, context) => at(depth, context.rowIndex).value }),
12336
+ label: (value) => labels[depth].get(identity(value)) ?? String(value ?? "") };
12337
+ });
12338
+ const sourceLimits = limits === undefined ? undefined : {
12339
+ ...(limits.maxRows === undefined ? {} : { maxRows: limits.maxRows }),
12340
+ ...(limits.maxCells === undefined ? {} : { maxCells: limits.maxCells }),
12341
+ ...(limits.maxTextCharacters === undefined ? {} : { maxTextCharacters: limits.maxTextCharacters })
12342
+ };
12343
+ return createGroupedReport(rows(), { columns: source.columns, groupBy, totals,
12344
+ ...(options.signal === undefined ? {} : { signal: options.signal }), ...(sourceLimits === undefined ? {} : { limits: sourceLimits }) });
12345
+ }
12346
+ const _exports = Object.freeze({ canopyGrouped: canopyGrouped });
12347
+ _modules.set("0f2b50bd606bf0a3273e7a3bec7ed6255f23cfee522a7cfeb2cb676c062ad40e", _exports);
12348
+ return _exports;
12349
+ })();
12350
+
12351
+ const _m101 = _modules.get("c3e14cc7c7a8367d216ab1ca0b2a41751cc8775866d730cb941d062509dd4886") ?? (() => {
12352
+ const { cellText } = _m35;
12353
+
12354
+ const { cleanXml } = _m28;
12355
+
12356
+ /** Snapshot optional About metadata before enumeration. The accepted query is serialized, never evaluated. */
12357
+ function canopyAbout(request, options) {
12358
+ const result = [["revision", request.revision], ["recordCount", request.recordCount === null ? "unknown" : request.recordCount]];
12359
+ if (request.scope !== undefined) {
12360
+ if (!["filtered", "selected", "all"].includes(request.scope))
12361
+ throw new TypeError("Invalid Canopy export scope.");
12362
+ result.push(["scope", request.scope]);
12363
+ }
12364
+ for (const key of ["total", "matched"])
12365
+ if (request[key] !== undefined) {
12366
+ const value = request[key];
12367
+ if (value === null) {
12368
+ result.push([key, "unknown"]);
12369
+ continue;
12370
+ }
12371
+ if (!Number.isSafeInteger(value) || value < 0)
12372
+ throw new TypeError("Canopy metadata counts must be nonnegative safe integers.");
12373
+ result.push([key, value]);
12374
+ }
12375
+ if (request.generatedAt !== undefined) {
12376
+ if (typeof request.generatedAt !== "string" || !/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d{1,9})?Z$/.test(request.generatedAt) || !Number.isFinite(new Date(request.generatedAt).getTime()))
12377
+ throw new TypeError("Canopy generatedAt must be a captured UTC ISO instant.");
12378
+ result.push(["generatedAt", request.generatedAt]);
12379
+ }
12380
+ if (request.selection !== undefined) {
12381
+ if (!Array.isArray(request.selection) || request.selection.some(id => typeof id !== "string"))
12382
+ throw new TypeError("Canopy selection metadata must contain stable string IDs.");
12383
+ result.push(["selection", JSON.stringify(request.selection)]);
12384
+ }
12385
+ if (request.query !== undefined) {
12386
+ if (!request.query || typeof request.query !== "object" || Array.isArray(request.query))
12387
+ throw new TypeError("Canopy accepted query must be a captured object.");
12388
+ const query = JSON.stringify(request.query);
12389
+ if (typeof query !== "string")
12390
+ throw new TypeError("Canopy accepted query must serialize as JSON metadata.");
12391
+ result.push(["query", query]);
12392
+ }
12393
+ if (result.reduce((sum, row) => sum + row[0].length + String(row[1]).length, 0) > 65536)
12394
+ throw new RangeError("Canopy About metadata exceeds 65,536 captured characters.");
12395
+ // Validate known cell text before consuming details; overflow preservation and XML policy stay workbook-owned.
12396
+ for (const [field, value] of result) {
12397
+ cellText(field, options.invalidCharacterPolicy);
12398
+ if (options.oversizedText === "preserve")
12399
+ cleanXml(value, options.invalidCharacterPolicy);
12400
+ else
12401
+ cellText(value, options.invalidCharacterPolicy);
12402
+ }
12403
+ return Object.freeze(result.map(row => Object.freeze(row)));
12404
+ }
12405
+ const _exports = Object.freeze({ canopyAbout: canopyAbout });
12406
+ _modules.set("c3e14cc7c7a8367d216ab1ca0b2a41751cc8775866d730cb941d062509dd4886", _exports);
12407
+ return _exports;
12408
+ })();
12409
+
12410
+ const _m102 = _modules.get("e9bef8c7399cd0b119a8802014687efc2004572db8fa3045f2dbfe3c37ab6fb9") ?? (() => {
12411
+ const { Workbook, addGroupedXlsx } = _m23;
12412
+
12413
+ const { portableWorkbook } = _m52;
12414
+
12415
+ const { withDestination } = _m3;
12416
+
12417
+ /** Compose only the adapter's data/grouped sheet and optional metadata sheet in the existing workbook owner. */
12418
+ async function writeCanopyWorkbook(source, grouped, destination, options, labels, about) {
12419
+ const { sheet: sheetSettings = {}, columns: _columns, ...settings } = options;
12420
+ const { name = "Data", ...sheet } = sheetSettings;
12421
+ if (about && name.toLowerCase() === "about")
12422
+ throw new TypeError("The optional About worksheet needs a distinct data-sheet name.");
12423
+ if (grouped && settings.cellValueWriters !== undefined)
12424
+ throw new TypeError("Grouped Canopy exports use resolved source values rather than custom cellValueWriters.");
12425
+ return withDestination(destination, async (sink) => {
12426
+ const workbookOptions = { ...portableWorkbook(settings), sink };
12427
+ // Grouped worksheets generate native FormulaCells; flat tables keep the portable-value boundary.
12428
+ const book = grouped ? new Workbook(workbookOptions) : Workbook.forTable(workbookOptions);
12429
+ try {
12430
+ let rows, columns;
12431
+ if (grouped) {
12432
+ const { conditionalFormats, ...groupedSheet } = sheet;
12433
+ const written = await addGroupedXlsx(book, grouped, {
12434
+ labelColumn: { header: labels?.labelColumn?.header ?? "Group", width: 18 },
12435
+ subtotalLabel: labels?.subtotalLabel ?? (group => group.label + " total"),
12436
+ grandTotalLabel: labels?.grandTotalLabel ?? (() => "Grand total"),
12437
+ ...(labels?.includeGrandTotal === undefined ? {} : { includeGrandTotal: labels.includeGrandTotal }),
12438
+ sheet: { ...groupedSheet, name }, ...(conditionalFormats === undefined ? {} : { conditionalFormats })
12439
+ });
12440
+ rows = written.rows;
12441
+ columns = written.columns;
12442
+ }
12443
+ else {
12444
+ const data = book.addWorksheet(name, { boldHeader: true, autoFilter: sheet.includeHeader !== false,
12445
+ autoSize: { minWidth: 6, maxWidth: 54 }, ...sheet, columns: source.columns });
12446
+ await data.addRows(source.rows());
12447
+ await data.close();
12448
+ rows = data.rowCount;
12449
+ columns = source.columns.length;
12450
+ }
12451
+ if (about) {
12452
+ const metadata = book.addWorksheet("About", { columns: [{ header: "Field", width: 18 }, { header: "Value", width: 72, wrapText: true }],
12453
+ boldHeader: true, freezeHeader: true });
12454
+ await metadata.addRows(about);
12455
+ await metadata.close();
12456
+ }
12457
+ const result = await book.finish();
12458
+ return { rows, columns, bytes: result.bytes };
12459
+ }
12460
+ catch (error) {
12461
+ await book.discard(error);
12462
+ throw error;
12463
+ }
12464
+ });
12465
+ }
12466
+ const _exports = Object.freeze({ writeCanopyWorkbook: writeCanopyWorkbook });
12467
+ _modules.set("e9bef8c7399cd0b119a8802014687efc2004572db8fa3045f2dbfe3c37ab6fb9", _exports);
12468
+ return _exports;
12469
+ })();
12470
+
12471
+ const _m0 = _modules.get("06222f91ea59fdd2aff673ab351a19c8b3372e05c612adf6136ffa05ee8bf037") ?? (() => {
12472
+ const { BlobByteSink, ExportCell } = _m1;
11691
12473
 
11692
12474
  const { notifyProgress } = _m14;
11693
12475
 
@@ -11699,36 +12481,98 @@ const { writeXlsxTo } = _m23;
11699
12481
 
11700
12482
  const { writeCsvTo } = _m55;
11701
12483
 
11702
- const { writePdfTo } = _m57;
12484
+ const { writePdfTo, writeGroupedPdfTo } = _m57;
12485
+
12486
+ const { prepareCanopyExport } = _m94;
12487
+
12488
+ const { canopyPins } = _m97;
12489
+
12490
+ const { canopyRules } = _m98;
11703
12491
 
11704
- const { createCanopyExport } = _m94;
12492
+ const { canopyGrouped } = _m100;
11705
12493
 
12494
+ const { canopyAbout } = _m101;
11706
12495
 
12496
+ const { writeCanopyWorkbook } = _m102;
11707
12497
 
11708
12498
 
11709
12499
 
11710
12500
 
11711
12501
 
11712
- /** Write a captured CanopyX grid to a caller-owned destination; its partial bytes remain caller-owned on failure. */
12502
+
12503
+
12504
+ /** Write a captured CanopyX grid to a caller-owned destination; partial bytes remain caller-owned on failure. */
11713
12505
  async function writeCanopyTo(capture, format, destination, options = {}) {
11714
- const selected = captureFields(options, ["tones", "columnOptions", "unsupportedPresentation", "datetime", "xlsx", "csv", "pdf", "signal", "onDiagnostic", "limits", "onProgress"]);
12506
+ const selected = captureFields(options, ["tones", "columnOptions", "unsupportedPresentation", "datetime", "xlsx", "csv", "pdf", "signal", "onDiagnostic", "limits", "onProgress", "grouped", "about"]);
11715
12507
  const { signal, onProgress } = selected, limits = captureCommonLimits(selected.limits);
11716
12508
  const xlsx = captureXlsxOptions(format === "xlsx" ? selected.xlsx : undefined);
11717
12509
  const csv = captureCsvOptions(format === "csv" ? selected.csv : undefined);
11718
12510
  const pdf = capturePdfOptions(format === "pdf" ? selected.pdf : undefined);
11719
- const source = createCanopyExport(capture, format, { ...selected, xlsx });
12511
+ const prepared = prepareCanopyExport(capture, format, { ...selected, xlsx }), { request, report, tones } = prepared;
12512
+ if (selected.about !== undefined && typeof selected.about !== "boolean")
12513
+ throw new TypeError("Canopy about must be boolean.");
12514
+ const labels = selected.grouped === undefined ? undefined : captureFields(selected.grouped, ["labelColumn", "subtotalLabel", "grandTotalLabel", "includeGrandTotal", "continuationLabel", "groupHeadingLevel"]);
12515
+ const capturedLabels = labels && { ...labels, ...(labels.labelColumn === undefined ? {} : { labelColumn: Object.freeze({ header: labels.labelColumn.header }) }) };
12516
+ const about = format === "xlsx" && selected.about ? canopyAbout(request, xlsx) : undefined;
12517
+ const ruleCellTypes = new Map();
12518
+ let consumed = 0;
12519
+ const source = Object.freeze({ ...prepared.source, async *rows() {
12520
+ for await (const row of prepared.source.rows()) {
12521
+ for (const [column, type] of ruleCellTypes) {
12522
+ const cell = row[column], raw = cell instanceof ExportCell ? cell.value : cell;
12523
+ if (raw == null || type === "number" && typeof raw === "number" && Number.isFinite(raw) || type === "date" && raw instanceof Date && Number.isFinite(raw.getTime()))
12524
+ continue;
12525
+ const code = "UNSUPPORTED_NATIVE_RULE_CELL_TYPE:" + type;
12526
+ report({ code, columnId: source.columns[column].key });
12527
+ // Text fallback cannot retract an already captured native declaration after streaming starts.
12528
+ throw new TypeError("Unsupported Canopy presentation: " + code + " (" + source.columns[column].key + ")");
12529
+ }
12530
+ consumed++;
12531
+ yield row;
12532
+ }
12533
+ } });
11720
12534
  const progress = onProgress ? { onProgress: (event) => {
11721
- notifyProgress(onProgress, { ...event, ...(source.rowCount === null ? {} : { totalRows: source.rowCount }) });
12535
+ // About and generated group rows consume output budgets, but never become exported source details.
12536
+ notifyProgress(onProgress, { ...event, rows: consumed,
12537
+ ...(event.sheetRows === undefined ? {} : { sheetRows: about !== undefined && event.sheetName === "About" ? 0 : consumed }),
12538
+ ...(source.rowCount === null ? {} : { totalRows: source.rowCount }) });
11722
12539
  } } : {};
11723
12540
  const stream = { ...(signal ? { signal } : {}), ...progress };
11724
- if (format === "xlsx")
11725
- return writeXlsxTo(source.rows(), destination, { ...xlsx, ...stream, columns: source.columns,
11726
- dateMode: xlsx.dateMode ?? capture.request.timeZone,
11727
- limits: mergeAdapterLimits(xlsx.limits, limits) });
11728
- if (format === "pdf")
11729
- return writePdfTo(source.rows(), destination, { ...pdf, ...stream, columns: source.columns,
11730
- limits: mergeAdapterLimits(pdf.limits, limits) });
11731
- return writeCsvTo(source.rows(), destination, { ...csv, ...stream, columns: source.columns, valueMode: capture.request.values,
12541
+ if (format === "xlsx") {
12542
+ const formatLimits = mergeAdapterLimits(xlsx.limits, limits), grouped = canopyGrouped(source, request, { ...selected, xlsx }, formatLimits, report, format);
12543
+ const pinned = canopyPins(request.columns, report), rules = canopyRules(request, format, grouped !== undefined, tones, report, { ...selected, xlsx }, ruleCellTypes);
12544
+ const sheet = { ...xlsx.sheet,
12545
+ freezeHeader: xlsx.sheet?.freezeHeader ?? (xlsx.sheet?.includeHeader !== false),
12546
+ freezeColumns: xlsx.sheet?.freezeColumns ?? (pinned ? pinned + (grouped ? 1 : 0) : 0),
12547
+ conditionalFormats: [...rules, ...(xlsx.sheet?.conditionalFormats ?? [])] };
12548
+ const settings = { ...xlsx, ...stream, columns: source.columns, sheet, dateMode: xlsx.dateMode ?? request.timeZone, limits: formatLimits };
12549
+ if (grouped || about)
12550
+ return writeCanopyWorkbook(source, grouped, destination, settings, capturedLabels, about);
12551
+ return writeXlsxTo(source.rows(), destination, settings);
12552
+ }
12553
+ if (format === "pdf") {
12554
+ const formatLimits = mergeAdapterLimits(pdf.limits, limits), grouped = canopyGrouped(source, request, selected, formatLimits, report, format);
12555
+ canopyRules(request, format, grouped !== undefined, tones, report, selected);
12556
+ // CSS pixels become points before the existing fit/band policy. Explicit PDF point widths win.
12557
+ const fitted = request.columns.every(column => column.width !== undefined) ? request.columns.map(column => column.width.preferred * 72 / 96) : undefined;
12558
+ const widths = pdf.columnWidths ?? fitted;
12559
+ const settings = { ...(fitted === undefined ? {} : { orientation: "landscape", wideTable: "fit" }), ...pdf, ...stream, limits: formatLimits };
12560
+ if (grouped) {
12561
+ if (pdf.headerRows !== undefined || pdf.footer !== undefined)
12562
+ throw new TypeError("Grouped Canopy PDF owns heading and summary rows.");
12563
+ const { headerRows: _headers, footer: _footer, ...groupedSettings } = settings;
12564
+ return writeGroupedPdfTo(grouped, destination, { ...groupedSettings,
12565
+ ...(widths === undefined ? {} : { columnWidths: [72, ...widths] }),
12566
+ labelColumn: { header: capturedLabels?.labelColumn?.header ?? "Group", width: 12 },
12567
+ subtotalLabel: capturedLabels?.subtotalLabel ?? (group => group.label + " total"),
12568
+ grandTotalLabel: capturedLabels?.grandTotalLabel ?? (() => "Grand total"),
12569
+ ...(capturedLabels?.includeGrandTotal === undefined ? {} : { includeGrandTotal: capturedLabels.includeGrandTotal }),
12570
+ ...(capturedLabels?.continuationLabel === undefined ? {} : { continuationLabel: capturedLabels.continuationLabel }),
12571
+ ...(capturedLabels?.groupHeadingLevel === undefined ? {} : { groupHeadingLevel: capturedLabels.groupHeadingLevel }) });
12572
+ }
12573
+ return writePdfTo(source.rows(), destination, { ...settings, columns: source.columns, ...(widths === undefined ? {} : { columnWidths: widths }) });
12574
+ }
12575
+ return writeCsvTo(source.rows(), destination, { ...csv, ...stream, columns: source.columns, valueMode: request.values,
11732
12576
  limits: mergeAdapterLimits(csv.limits, limits) });
11733
12577
  }
11734
12578
  /** Export an immutable native capture as a Blob without loading or registering CanopyX. */
@@ -11744,7 +12588,7 @@ async function exportCanopy(capture, format, options = {}) {
11744
12588
  }
11745
12589
  }
11746
12590
  const _exports = Object.freeze({ createCanopyExport: _m94.createCanopyExport, ExportCell: _m5.ExportCell, PdfFont: _m63.PdfFont, writeCanopyTo: writeCanopyTo, exportCanopy: exportCanopy });
11747
- _modules.set("3e66cc3ead243255e3903dfabd767d39c2507193c6631b6a40caad66216c13ed", _exports);
12591
+ _modules.set("06222f91ea59fdd2aff673ab351a19c8b3372e05c612adf6136ffa05ee8bf037", _exports);
11748
12592
  return _exports;
11749
12593
  })();
11750
12594
  Object.assign(officeimo, _m0);