ooxml-core 1.14.0 → 1.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (143) hide show
  1. package/dist/PptxHandler-3A7VEXVK.cjs +13 -0
  2. package/dist/PptxHandler-7POULDRL.mjs +4 -0
  3. package/dist/{PptxHandler-KNBFECUE.mjs → PptxHandler-M35YFCUC.mjs} +2 -2
  4. package/dist/PresentationBuilder-C7NPM7OQ.mjs +4 -0
  5. package/dist/{PresentationBuilder-II7C4A3R.cjs → PresentationBuilder-XVRTITYR.cjs} +6 -5
  6. package/dist/{PresentationBuilder-5DCCFHWJ.mjs → PresentationBuilder-Y6DJK6H2.mjs} +2 -2
  7. package/dist/automation/index.cjs +1198 -1095
  8. package/dist/automation/index.mjs +1198 -1095
  9. package/dist/chunk-5W2QL4SB.cjs +244 -0
  10. package/dist/{chunk-TQE7FFNT.cjs → chunk-AHRFBMLK.cjs} +4070 -2015
  11. package/dist/{chunk-2D4IFQ5M.mjs → chunk-B37EVUMG.mjs} +1 -1
  12. package/dist/{chunk-4WZLFUUA.mjs → chunk-C2Y6SZDN.mjs} +934 -200
  13. package/dist/chunk-CA7KCNL3.mjs +236 -0
  14. package/dist/{chunk-BSUIDT6K.cjs → chunk-DWRJ62KP.cjs} +1 -0
  15. package/dist/{chunk-TNNXOW2O.mjs → chunk-KOX5Y5E5.mjs} +1 -1
  16. package/dist/{chunk-54ASP65T.mjs → chunk-LM6VBPQJ.mjs} +416 -15
  17. package/dist/{chunk-PC4MTLG4.cjs → chunk-OA5V3JJC.cjs} +8 -8
  18. package/dist/{chunk-ORH32TO3.mjs → chunk-OKGQ2X7D.mjs} +3092 -1037
  19. package/dist/{chunk-X7MGZQ6C.cjs → chunk-UGWY72WC.cjs} +396 -254
  20. package/dist/{chunk-XGXIS4PN.mjs → chunk-WBCV52YV.mjs} +3077 -1027
  21. package/dist/{chunk-2EBMHIGJ.mjs → chunk-WEFFRYXN.mjs} +379 -242
  22. package/dist/{chunk-AXF2FC4D.mjs → chunk-WSRCLCMB.mjs} +1 -0
  23. package/dist/{chunk-LMMP67YN.mjs → chunk-XCJRUBGJ.mjs} +1 -1
  24. package/dist/geometry/index.cjs +259 -0
  25. package/dist/geometry/index.d.ts +1 -0
  26. package/dist/geometry/index.d.ts.map +1 -1
  27. package/dist/geometry/index.mjs +255 -1
  28. package/dist/geometry/shape-gallery-catalog.d.ts +32 -0
  29. package/dist/geometry/shape-gallery-catalog.d.ts.map +1 -0
  30. package/dist/index.cjs +371 -112
  31. package/dist/index.mjs +371 -112
  32. package/dist/pptx/automation/index.cjs +4523 -1957
  33. package/dist/pptx/automation/index.d.ts +4 -4
  34. package/dist/pptx/automation/index.mjs +5 -5
  35. package/dist/pptx/chunks/{elements-tK7xnWeS.d.ts → elements-iUzpAeqR.d.ts} +232 -2
  36. package/dist/pptx/chunks/elements-iUzpAeqR.d.ts.map +1 -0
  37. package/dist/pptx/chunks/{index-DS9Y4Ne3.d.ts → index-BWHNCVNC.d.ts} +1673 -1534
  38. package/dist/pptx/chunks/index-BWHNCVNC.d.ts.map +1 -0
  39. package/dist/pptx/chunks/{index-BSpNQuvz.d.ts → index-CiyTR6mm.d.ts} +201 -5
  40. package/dist/pptx/chunks/index-CiyTR6mm.d.ts.map +1 -0
  41. package/dist/pptx/chunks/{text-operations-BdD_UQ11.d.ts → text-operations-CfLVZ7DK.d.ts} +81 -3
  42. package/dist/pptx/chunks/text-operations-CfLVZ7DK.d.ts.map +1 -0
  43. package/dist/pptx/cli/index.cjs +4465 -1899
  44. package/dist/pptx/cli/index.d.ts +1 -1
  45. package/dist/pptx/cli/index.mjs +4 -4
  46. package/dist/pptx/converter/index.cjs +52 -1
  47. package/dist/pptx/converter/index.d.ts +1 -1
  48. package/dist/pptx/converter/index.mjs +2 -2
  49. package/dist/pptx/editor/render/collaboration-live-patch-target.cjs +4 -4
  50. package/dist/pptx/editor/render/collaboration-live-patch-target.mjs +2 -2
  51. package/dist/pptx/editor/render/collaboration-reconcile.cjs +7 -7
  52. package/dist/pptx/editor/render/collaboration-reconcile.mjs +2 -2
  53. package/dist/pptx/editor/render/collaboration-sync.cjs +14 -14
  54. package/dist/pptx/editor/render/collaboration-sync.d.ts.map +1 -1
  55. package/dist/pptx/editor/render/collaboration-sync.mjs +1 -1
  56. package/dist/pptx/editor/render/find-replace.cjs +15 -14
  57. package/dist/pptx/editor/render/find-replace.d.ts +2 -2
  58. package/dist/pptx/editor/render/find-replace.mjs +2 -1
  59. package/dist/pptx/editor/render/slide-operations.cjs +9 -8
  60. package/dist/pptx/editor/render/slide-operations.mjs +3 -2
  61. package/dist/pptx/editor/render/slide-size-rescale.cjs +3 -3
  62. package/dist/pptx/editor/render/slide-size-rescale.d.ts +1 -1
  63. package/dist/pptx/editor/render/slide-size-rescale.d.ts.map +1 -1
  64. package/dist/pptx/editor/render/slide-size-rescale.mjs +3 -3
  65. package/dist/pptx/editor/render/text-runs-style-patch.d.ts +1 -1
  66. package/dist/pptx/editor/render/text-style-scope.d.ts +1 -1
  67. package/dist/pptx/index.cjs +5656 -2290
  68. package/dist/pptx/index.d.ts +5 -5
  69. package/dist/pptx/index.mjs +5 -5
  70. package/dist/teams/ics.d.ts.map +1 -1
  71. package/dist/teams/index.cjs +631 -635
  72. package/dist/teams/index.d.ts +1 -0
  73. package/dist/teams/index.d.ts.map +1 -1
  74. package/dist/teams/index.mjs +616 -636
  75. package/dist/teams/meetings.d.ts +11 -1
  76. package/dist/teams/meetings.d.ts.map +1 -1
  77. package/dist/teams/recurrence-calendar.d.ts +41 -0
  78. package/dist/teams/recurrence-calendar.d.ts.map +1 -0
  79. package/dist/teams/recurrence.d.ts +1 -1
  80. package/dist/teams/recurrence.d.ts.map +1 -1
  81. package/dist/teams/server-session.d.ts +19 -0
  82. package/dist/teams/server-session.d.ts.map +1 -1
  83. package/dist/xlsx/edit/pivots.d.ts.map +1 -1
  84. package/dist/xlsx/index.cjs +1137 -1027
  85. package/dist/xlsx/index.mjs +1136 -1028
  86. package/dist/xlsx/load/index.cjs +593 -652
  87. package/dist/xlsx/load/index.mjs +593 -652
  88. package/dist/xlsx/model-pivots.d.ts +64 -4
  89. package/dist/xlsx/model-pivots.d.ts.map +1 -1
  90. package/dist/xlsx/pivot/aggregate.d.ts +6 -3
  91. package/dist/xlsx/pivot/aggregate.d.ts.map +1 -1
  92. package/dist/xlsx/pivot/axes.d.ts +5 -0
  93. package/dist/xlsx/pivot/axes.d.ts.map +1 -1
  94. package/dist/xlsx/pivot/captions-locales.d.ts +3 -0
  95. package/dist/xlsx/pivot/captions-locales.d.ts.map +1 -0
  96. package/dist/xlsx/pivot/captions-read.d.ts +14 -0
  97. package/dist/xlsx/pivot/captions-read.d.ts.map +1 -0
  98. package/dist/xlsx/pivot/captions.d.ts +26 -0
  99. package/dist/xlsx/pivot/captions.d.ts.map +1 -0
  100. package/dist/xlsx/pivot/columns.d.ts +9 -3
  101. package/dist/xlsx/pivot/columns.d.ts.map +1 -1
  102. package/dist/xlsx/pivot/data.d.ts +3 -2
  103. package/dist/xlsx/pivot/data.d.ts.map +1 -1
  104. package/dist/xlsx/pivot/date-axes.d.ts +1 -1
  105. package/dist/xlsx/pivot/date-axes.d.ts.map +1 -1
  106. package/dist/xlsx/pivot/date-group-read.d.ts.map +1 -1
  107. package/dist/xlsx/pivot/date-groups.d.ts +8 -3
  108. package/dist/xlsx/pivot/date-groups.d.ts.map +1 -1
  109. package/dist/xlsx/pivot/index.d.ts +2 -1
  110. package/dist/xlsx/pivot/index.d.ts.map +1 -1
  111. package/dist/xlsx/pivot/item-labels.d.ts +12 -0
  112. package/dist/xlsx/pivot/item-labels.d.ts.map +1 -0
  113. package/dist/xlsx/pivot/item-names-read.d.ts +8 -0
  114. package/dist/xlsx/pivot/item-names-read.d.ts.map +1 -0
  115. package/dist/xlsx/pivot/measures.d.ts +2 -8
  116. package/dist/xlsx/pivot/measures.d.ts.map +1 -1
  117. package/dist/xlsx/pivot/nested.d.ts +4 -2
  118. package/dist/xlsx/pivot/nested.d.ts.map +1 -1
  119. package/dist/xlsx/pivot/page-filter-admission.d.ts.map +1 -1
  120. package/dist/xlsx/pivot/page-filter.d.ts +1 -1
  121. package/dist/xlsx/pivot/page-filter.d.ts.map +1 -1
  122. package/dist/xlsx/pivot/read.d.ts.map +1 -1
  123. package/dist/xlsx/pivot/subtotals.d.ts +6 -1
  124. package/dist/xlsx/pivot/subtotals.d.ts.map +1 -1
  125. package/dist/xlsx/pivot/table-xml.d.ts.map +1 -1
  126. package/dist/xlsx/pivot/values-axis.d.ts +7 -4
  127. package/dist/xlsx/pivot/values-axis.d.ts.map +1 -1
  128. package/dist/xlsx/ui/commands/i18n/navigation.d.ts.map +1 -1
  129. package/dist/xlsx/ui/commands/i18n/pivots.d.ts.map +1 -1
  130. package/dist/xlsx/ui/index.cjs +1002 -1136
  131. package/dist/xlsx/ui/index.mjs +1002 -1136
  132. package/package.json +1 -1
  133. package/dist/PptxHandler-5YP75BPO.cjs +0 -12
  134. package/dist/PptxHandler-GT5Q66TG.mjs +0 -3
  135. package/dist/PresentationBuilder-CVM6LJ7L.mjs +0 -3
  136. package/dist/pptx/chunks/elements-tK7xnWeS.d.ts.map +0 -1
  137. package/dist/pptx/chunks/index-BSpNQuvz.d.ts.map +0 -1
  138. package/dist/pptx/chunks/index-DS9Y4Ne3.d.ts.map +0 -1
  139. package/dist/pptx/chunks/text-operations-BdD_UQ11.d.ts.map +0 -1
  140. package/dist/xlsx/pivot/hierarchy-first.d.ts +0 -21
  141. package/dist/xlsx/pivot/hierarchy-first.d.ts.map +0 -1
  142. package/dist/xlsx/pivot/hierarchy.d.ts +0 -8
  143. package/dist/xlsx/pivot/hierarchy.d.ts.map +0 -1
@@ -81,7 +81,7 @@ var DEFAULT_XML_LIMITS = {
81
81
  maxNodes: 5e6
82
82
  };
83
83
  var MARKUP_RE = /<!--[\s\S]*?-->|<!\[CDATA\[[\s\S]*?\]\]>|<\?[\s\S]*?\?>|<(\/?)([^\s\/>]+)(?:\s+[^\s=\/>]+\s*=\s*(?:"[^"]*"|'[^']*'))*\s*(\/?)>/g;
84
- function checkXmlLimits(xml, label5, limits = {}) {
84
+ function checkXmlLimits(xml, label2, limits = {}) {
85
85
  const maxDepth = limits.maxDepth ?? DEFAULT_XML_LIMITS.maxDepth;
86
86
  const maxNodes = limits.maxNodes ?? DEFAULT_XML_LIMITS.maxNodes;
87
87
  let depth = 0;
@@ -94,16 +94,16 @@ function checkXmlLimits(xml, label5, limits = {}) {
94
94
  continue;
95
95
  }
96
96
  nodes++;
97
- if (nodes > maxNodes) throw new Error(`${label5} XML exceeds the limit of ${maxNodes} elements`);
97
+ if (nodes > maxNodes) throw new Error(`${label2} XML exceeds the limit of ${maxNodes} elements`);
98
98
  if (!selfClosing && ++depth > maxDepth)
99
- throw new Error(`${label5} XML exceeds the nesting depth limit of ${maxDepth}`);
99
+ throw new Error(`${label2} XML exceeds the nesting depth limit of ${maxDepth}`);
100
100
  }
101
101
  }
102
102
  function parseXml(xml, options = {}) {
103
- const label5 = options.label ?? "OOXML";
103
+ const label2 = options.label ?? "OOXML";
104
104
  if (/<!DOCTYPE|<!ENTITY/i.test(xml))
105
- throw new Error(`${label5} XML with DTD or entity declarations is not supported`);
106
- checkXmlLimits(xml, label5, options.limits);
105
+ throw new Error(`${label2} XML with DTD or entity declarations is not supported`);
106
+ checkXmlLimits(xml, label2, options.limits);
107
107
  let parseError = "";
108
108
  let parsed;
109
109
  try {
@@ -114,12 +114,12 @@ function parseXml(xml, options = {}) {
114
114
  }).parseFromString(xml, "application/xml");
115
115
  } catch (error) {
116
116
  throw new Error(
117
- `Invalid ${label5} XML: ${error instanceof Error ? error.message : String(error)}`,
117
+ `Invalid ${label2} XML: ${error instanceof Error ? error.message : String(error)}`,
118
118
  { cause: error }
119
119
  );
120
120
  }
121
121
  if (parseError || !parsed.documentElement)
122
- throw new Error(`Invalid ${label5} XML: ${parseError || "missing root element"}`);
122
+ throw new Error(`Invalid ${label2} XML: ${parseError || "missing root element"}`);
123
123
  return parsed;
124
124
  }
125
125
  var buildXml = (node3) => new xmldom.XMLSerializer().serializeToString(node3);
@@ -406,10 +406,10 @@ function withParseWarnings(warnings, fn) {
406
406
  function reportParseWarning(message) {
407
407
  if (sink && !sink.includes(message)) sink.push(message);
408
408
  }
409
- function enumValue(guard2, raw2, label5) {
409
+ function enumValue(guard2, raw2, label2) {
410
410
  if (raw2 === null || raw2 === void 0 || raw2 === "") return void 0;
411
411
  if (guard2(raw2)) return raw2;
412
- reportParseWarning(`Ignored invalid ${label5} value \u201C${raw2}\u201D; it is not allowed by the schema.`);
412
+ reportParseWarning(`Ignored invalid ${label2} value \u201C${raw2}\u201D; it is not allowed by the schema.`);
413
413
  return void 0;
414
414
  }
415
415
 
@@ -2298,7 +2298,7 @@ function flatChildren(parent, names, level = "block", enclosing, controls3 = /*
2298
2298
  return found;
2299
2299
  }
2300
2300
  var flatBlocks = (container) => flatChildren(container, ["p", "tbl"]);
2301
- var flatRows = (table3) => flatChildren(table3, ["tr"], "row");
2301
+ var flatRows = (table4) => flatChildren(table4, ["tr"], "row");
2302
2302
  var flatCells = (row3) => flatChildren(row3, ["tc"], "cell");
2303
2303
  var flatCellParagraphs = (cell) => flatChildren(cell, ["p"]);
2304
2304
 
@@ -3011,42 +3011,42 @@ function buildMargins(doc, margins, tag) {
3011
3011
  }
3012
3012
  return element2.childNodes.length ? element2 : void 0;
3013
3013
  }
3014
- function tableJustification(table3) {
3015
- const { alignment, justification } = table3;
3014
+ function tableJustification(table4) {
3015
+ const { alignment, justification } = table4;
3016
3016
  const implied = justification === "start" ? "left" : justification === "end" ? "right" : justification;
3017
3017
  return justification && implied === alignment ? justification : alignment;
3018
3018
  }
3019
- function tableColumnCount(table3) {
3019
+ function tableColumnCount(table4) {
3020
3020
  return Math.max(
3021
3021
  1,
3022
- ...table3.rows.map((row3) => row3.reduce((sum3, cell) => sum3 + (cell.gridSpan ?? 1), 0))
3022
+ ...table4.rows.map((row3) => row3.reduce((sum3, cell) => sum3 + (cell.gridSpan ?? 1), 0))
3023
3023
  );
3024
3024
  }
3025
- function buildNewTableProperties(doc, table3, contentWidthTwips) {
3025
+ function buildNewTableProperties(doc, table4, contentWidthTwips) {
3026
3026
  const tblPr = makeW(doc, "tblPr");
3027
- if (table3.style) {
3027
+ if (table4.style) {
3028
3028
  const style3 = makeW(doc, "tblStyle");
3029
- setW2(style3, "val", table3.style);
3029
+ setW2(style3, "val", table4.style);
3030
3030
  tblPr.appendChild(style3);
3031
3031
  }
3032
3032
  const width = makeW(doc, "tblW");
3033
- setW2(width, "w", String(table3.widthTwips ?? 0));
3034
- setW2(width, "type", table3.widthTwips ? "dxa" : "auto");
3033
+ setW2(width, "w", String(table4.widthTwips ?? 0));
3034
+ setW2(width, "type", table4.widthTwips ? "dxa" : "auto");
3035
3035
  tblPr.appendChild(width);
3036
- const jcValue = tableJustification(table3);
3036
+ const jcValue = tableJustification(table4);
3037
3037
  if (jcValue) {
3038
3038
  const jc = makeW(doc, "jc");
3039
3039
  setW2(jc, "val", jcValue);
3040
3040
  tblPr.appendChild(jc);
3041
3041
  }
3042
- if (table3.indentTwips !== void 0) {
3042
+ if (table4.indentTwips !== void 0) {
3043
3043
  const indent = makeW(doc, "tblInd");
3044
- setW2(indent, "w", String(table3.indentTwips));
3044
+ setW2(indent, "w", String(table4.indentTwips));
3045
3045
  setW2(indent, "type", "dxa");
3046
3046
  tblPr.appendChild(indent);
3047
3047
  }
3048
- if (table3.borders) tblPr.appendChild(buildBorders(doc, table3.borders, "tblBorders"));
3049
- const margins = table3.cellMargins && buildMargins(doc, table3.cellMargins, "tblCellMar");
3048
+ if (table4.borders) tblPr.appendChild(buildBorders(doc, table4.borders, "tblBorders"));
3049
+ const margins = table4.cellMargins && buildMargins(doc, table4.cellMargins, "tblCellMar");
3050
3050
  if (margins) tblPr.appendChild(margins);
3051
3051
  const look = makeW(doc, "tblLook");
3052
3052
  const lookAttributes = [
@@ -3061,8 +3061,8 @@ function buildNewTableProperties(doc, table3, contentWidthTwips) {
3061
3061
  for (const [name3, value2] of lookAttributes) setW2(look, name3, value2);
3062
3062
  tblPr.appendChild(look);
3063
3063
  const tblGrid = makeW(doc, "tblGrid");
3064
- const columns = tableColumnCount(table3);
3065
- const widths = table3.grid?.length === columns ? table3.grid : Array.from({ length: columns }, () => Math.max(1, Math.floor(contentWidthTwips / columns)));
3064
+ const columns = tableColumnCount(table4);
3065
+ const widths = table4.grid?.length === columns ? table4.grid : Array.from({ length: columns }, () => Math.max(1, Math.floor(contentWidthTwips / columns)));
3066
3066
  for (const value2 of widths) {
3067
3067
  const column2 = makeW(doc, "gridCol");
3068
3068
  setW2(column2, "w", String(value2));
@@ -3310,14 +3310,14 @@ function patchRowProperties(doc, tr, next, base2) {
3310
3310
  }
3311
3311
  orderChildren(props, ROW_ORDER);
3312
3312
  }
3313
- function patchTableMargins(doc, table3, node3, base2) {
3313
+ function patchTableMargins(doc, table4, node3, base2) {
3314
3314
  patchMarginProperties(
3315
3315
  doc,
3316
3316
  node3,
3317
3317
  "tblPr",
3318
3318
  "tblCellMar",
3319
3319
  TABLE_ORDER,
3320
- table3.cellMargins,
3320
+ table4.cellMargins,
3321
3321
  base2?.cellMargins
3322
3322
  );
3323
3323
  }
@@ -3412,12 +3412,12 @@ function patchCellShading(doc, tc, next, base2) {
3412
3412
  }
3413
3413
 
3414
3414
  // docx/write-table.ts
3415
- function canEditTableStructure(table3) {
3415
+ function canEditTableStructure(table4) {
3416
3416
  const only = (parent, allowed) => Array.from(parent.childNodes).filter(isElement).every((node3) => allowed.some((name3) => named2(node3, name3)));
3417
- if (!only(table3, ["tblPr", "tblGrid", "tr"])) return false;
3418
- const grid = first2(table3, "tblGrid");
3417
+ if (!only(table4, ["tblPr", "tblGrid", "tr"])) return false;
3418
+ const grid = first2(table4, "tblGrid");
3419
3419
  if (grid && !only(grid, ["gridCol"])) return false;
3420
- const rows = children2(table3, "tr");
3420
+ const rows = children2(table4, "tr");
3421
3421
  if (!rows.length) return false;
3422
3422
  const [firstRow] = rows;
3423
3423
  if (!firstRow) return false;
@@ -3443,7 +3443,7 @@ function canEditTableStructure(table3) {
3443
3443
  }
3444
3444
  return true;
3445
3445
  }
3446
- var layout = (table3) => table3.rows.map((row3) => row3.map((cell) => cell.paragraphs.map((p) => p.id)));
3446
+ var layout = (table4) => table4.rows.map((row3) => row3.map((cell) => cell.paragraphs.map((p) => p.id)));
3447
3447
  var TABLE_DESCRIPTOR_KEYS = [
3448
3448
  "grid",
3449
3449
  "widthTwips",
@@ -3460,9 +3460,9 @@ function pick(source2, keys) {
3460
3460
  for (const key2 of keys) if (record2[key2] !== void 0) result2[key2] = record2[key2];
3461
3461
  return result2;
3462
3462
  }
3463
- function assertNoDescriptorEdits(table3, base2) {
3463
+ function assertNoDescriptorEdits(table4, base2) {
3464
3464
  if (!base2) return;
3465
- if (JSON.stringify(pick(table3, TABLE_DESCRIPTOR_KEYS)) !== JSON.stringify(pick(base2, TABLE_DESCRIPTOR_KEYS)))
3465
+ if (JSON.stringify(pick(table4, TABLE_DESCRIPTOR_KEYS)) !== JSON.stringify(pick(base2, TABLE_DESCRIPTOR_KEYS)))
3466
3466
  throw new Error(
3467
3467
  "Cannot edit table grid widths, width, alignment, indent, borders, or style; only cell text and row/column structure changes are supported. The original DOCX package remains unchanged."
3468
3468
  );
@@ -3472,7 +3472,7 @@ function assertNoDescriptorEdits(table3, base2) {
3472
3472
  const id3 = cell.paragraphs[0]?.id;
3473
3473
  if (id3) baseCellById.set(id3, cell);
3474
3474
  }
3475
- for (const row3 of table3.rows)
3475
+ for (const row3 of table4.rows)
3476
3476
  for (const cell of row3) {
3477
3477
  const id3 = cell.paragraphs[0]?.id;
3478
3478
  const source2 = id3 ? baseCellById.get(id3) : void 0;
@@ -3488,23 +3488,23 @@ function writeNestedTables(doc, tc, cell, base2, writeParagraph, replaceSlots2)
3488
3488
  const next = tables(cell.sourceBlocks);
3489
3489
  const before = tables(base2?.sourceBlocks);
3490
3490
  const nodes = children2(tc, "tbl");
3491
- next.forEach((table3, index3) => {
3491
+ next.forEach((table4, index3) => {
3492
3492
  const node3 = nodes[index3];
3493
3493
  if (node3 && before[index3])
3494
- writeTable(doc, table3, node3, before[index3], writeParagraph, replaceSlots2);
3494
+ writeTable(doc, table4, node3, before[index3], writeParagraph, replaceSlots2);
3495
3495
  });
3496
3496
  }
3497
- function writeTable(doc, table3, node3, base2, writeParagraph, replaceSlots2) {
3498
- if (base2 && JSON.stringify(table3) === JSON.stringify(base2)) return node3;
3499
- assertNoDescriptorEdits(table3, base2);
3500
- patchTableMargins(doc, table3, node3, base2);
3501
- const structural = base2 && JSON.stringify(layout(table3)) !== JSON.stringify(layout(base2));
3497
+ function writeTable(doc, table4, node3, base2, writeParagraph, replaceSlots2) {
3498
+ if (base2 && JSON.stringify(table4) === JSON.stringify(base2)) return node3;
3499
+ assertNoDescriptorEdits(table4, base2);
3500
+ patchTableMargins(doc, table4, node3, base2);
3501
+ const structural = base2 && JSON.stringify(layout(table4)) !== JSON.stringify(layout(base2));
3502
3502
  if (structural && !canEditTableStructure(node3))
3503
3503
  throw new Error(
3504
3504
  "Cannot change the structure of a merged, nested, or complex table. The original DOCX package remains unchanged."
3505
3505
  );
3506
- const width = table3.rows[0]?.length ?? 0;
3507
- if (!width || table3.rows.some((row3) => row3.length !== width || row3.some((cell) => !cell.paragraphs.length)))
3506
+ const width = table4.rows[0]?.length ?? 0;
3507
+ if (!width || table4.rows.some((row3) => row3.length !== width || row3.some((cell) => !cell.paragraphs.length)))
3508
3508
  throw new Error("Tables must contain rectangular rows and at least one paragraph per cell.");
3509
3509
  const oldRows = flatRows(node3).map((entry3) => entry3.element);
3510
3510
  const sourceById = /* @__PURE__ */ new Map();
@@ -3525,7 +3525,7 @@ function writeTable(doc, table3, node3, base2, writeParagraph, replaceSlots2) {
3525
3525
  const usedCells = /* @__PURE__ */ new Set();
3526
3526
  const usedRows = /* @__PURE__ */ new Set();
3527
3527
  const columns = /* @__PURE__ */ new Map();
3528
- const nextRows = table3.rows.map((row3, rowIndex2) => {
3528
+ const nextRows = table4.rows.map((row3, rowIndex2) => {
3529
3529
  const sources = row3.map(
3530
3530
  (cell) => cell.paragraphs.map((p) => sourceById.get(p.id)).find(Boolean)
3531
3531
  );
@@ -3540,7 +3540,7 @@ function writeTable(doc, table3, node3, base2, writeParagraph, replaceSlots2) {
3540
3540
  patchRowProperties(
3541
3541
  doc,
3542
3542
  tr,
3543
- table3.rowProperties?.[rowIndex2],
3543
+ table4.rowProperties?.[rowIndex2],
3544
3544
  sourceRow === void 0 ? void 0 : base2?.rowProperties?.[sourceRow]
3545
3545
  );
3546
3546
  const nextCells = row3.map((cell, ci) => {
@@ -11566,8 +11566,8 @@ function gd14(name3, formula) {
11566
11566
  const parts = formula.trim().split(/\s+/);
11567
11567
  return { name: name3, formula, args: parts.slice(1) };
11568
11568
  }
11569
- function parseGdTable(table3) {
11570
- return table3.trim().split(/[\n;]/).filter((entry3) => entry3.length > 0).map((entry3) => {
11569
+ function parseGdTable(table4) {
11570
+ return table4.trim().split(/[\n;]/).filter((entry3) => entry3.length > 0).map((entry3) => {
11571
11571
  const sep = entry3.indexOf("|");
11572
11572
  return gd14(entry3.slice(0, sep), entry3.slice(sep + 1));
11573
11573
  });
@@ -13460,8 +13460,8 @@ function parseDiagramDataModel(source2, part) {
13460
13460
  "CONNECTION_ENDPOINT_MISSING",
13461
13461
  `dgm:cxn ${attribute4} references missing point: ${id3}.`
13462
13462
  );
13463
- const label5 = connectionLabel(connection, transitionText);
13464
- connections2.push(label5 ? { ...connection, label: label5 } : connection);
13463
+ const label2 = connectionLabel(connection, transitionText);
13464
+ connections2.push(label2 ? { ...connection, label: label2 } : connection);
13465
13465
  if ((!connection.type || connection.type === "parOf") && !parentById.has(connection.destId))
13466
13466
  parentById.set(connection.destId, connection.sourceId);
13467
13467
  }
@@ -13500,14 +13500,14 @@ function colorList(container) {
13500
13500
  }
13501
13501
  function parseDiagramColors(source2) {
13502
13502
  const root = rootOf2(source2);
13503
- const labels = children(root, "styleLbl", NS.dgm).map((label5) => ({
13504
- name: stringAttribute(label5, "name") ?? "",
13505
- fill: colorList(first(label5, "fillClrLst", NS.dgm)),
13506
- line: colorList(first(label5, "linClrLst", NS.dgm)),
13507
- effect: colorList(first(label5, "effectClrLst", NS.dgm)),
13508
- textLine: colorList(first(label5, "txLinClrLst", NS.dgm)),
13509
- textFill: colorList(first(label5, "txFillClrLst", NS.dgm)),
13510
- textEffect: colorList(first(label5, "txEffectClrLst", NS.dgm))
13503
+ const labels = children(root, "styleLbl", NS.dgm).map((label2) => ({
13504
+ name: stringAttribute(label2, "name") ?? "",
13505
+ fill: colorList(first(label2, "fillClrLst", NS.dgm)),
13506
+ line: colorList(first(label2, "linClrLst", NS.dgm)),
13507
+ effect: colorList(first(label2, "effectClrLst", NS.dgm)),
13508
+ textLine: colorList(first(label2, "txLinClrLst", NS.dgm)),
13509
+ textFill: colorList(first(label2, "txFillClrLst", NS.dgm)),
13510
+ textEffect: colorList(first(label2, "txEffectClrLst", NS.dgm))
13511
13511
  }));
13512
13512
  return { ...parseDefinitionHeader(root), labels };
13513
13513
  }
@@ -13540,16 +13540,16 @@ function parseStyleReferences(style3) {
13540
13540
  var hasContent = (element2) => Boolean(element2 && (element2.attributes.length > 0 || elements(element2).length > 0));
13541
13541
  function parseDiagramQuickStyle(source2) {
13542
13542
  const root = rootOf2(source2);
13543
- const labels = children(root, "styleLbl", NS.dgm).map((label5) => ({
13544
- name: stringAttribute(label5, "name") ?? "",
13545
- ...parseStyleReferences(first(label5, "style", NS.dgm)),
13546
- hasScene3d: Boolean(first(label5, "scene3d", NS.dgm)),
13547
- hasShape3d: hasContent(first(label5, "sp3d", NS.dgm))
13543
+ const labels = children(root, "styleLbl", NS.dgm).map((label2) => ({
13544
+ name: stringAttribute(label2, "name") ?? "",
13545
+ ...parseStyleReferences(first(label2, "style", NS.dgm)),
13546
+ hasScene3d: Boolean(first(label2, "scene3d", NS.dgm)),
13547
+ hasShape3d: hasContent(first(label2, "sp3d", NS.dgm))
13548
13548
  }));
13549
13549
  return {
13550
13550
  ...parseDefinitionHeader(root),
13551
13551
  labels,
13552
- has3d: labels.some((label5) => label5.hasShape3d)
13552
+ has3d: labels.some((label2) => label2.hasShape3d)
13553
13553
  };
13554
13554
  }
13555
13555
  function parseDiagramLayoutSummary(source2) {
@@ -14719,10 +14719,10 @@ function parseDisplayUnits(context, element2) {
14719
14719
  if (!element2) return void 0;
14720
14720
  reportUnmodelled(context, element2, DISPLAY_UNITS);
14721
14721
  const labelElement = cChild(element2, "dispUnitsLbl");
14722
- let label5;
14722
+ let label2;
14723
14723
  if (labelElement) {
14724
14724
  reportUnmodelled(context, labelElement, DISPLAY_UNITS_LABEL);
14725
- label5 = assignDefined(
14725
+ label2 = assignDefined(
14726
14726
  {},
14727
14727
  {
14728
14728
  layout: manualLayout(labelElement),
@@ -14737,7 +14737,7 @@ function parseDisplayUnits(context, element2) {
14737
14737
  {
14738
14738
  builtInUnit: cVal(element2, "builtInUnit"),
14739
14739
  customUnit: cNumber(context, element2, "custUnit"),
14740
- label: label5,
14740
+ label: label2,
14741
14741
  extLst: extensionList2(element2)
14742
14742
  }
14743
14743
  );
@@ -15591,10 +15591,10 @@ function titleXml(context, title) {
15591
15591
  function labelOptionsXml(context, options) {
15592
15592
  return numberFormatXml(options.numberFormat) + shapePropertiesXml(context, options.spPr) + textBodyXml(context, options.txPr) + valXml("dLblPos", options.position) + valXml("showLegendKey", options.showLegendKey) + valXml("showVal", options.showValue) + valXml("showCatName", options.showCategoryName) + valXml("showSerName", options.showSeriesName) + valXml("showPercent", options.showPercent) + valXml("showBubbleSize", options.showBubbleSize) + (options.separator === void 0 ? "" : textElement("separator", options.separator));
15593
15593
  }
15594
- function labelXml(context, label5) {
15594
+ function labelXml(context, label2) {
15595
15595
  return elementXml(
15596
15596
  "dLbl",
15597
- valXml("idx", label5.index) + valXml("delete", label5.deleted) + layoutXml(context, label5.layout) + chartTextXml(context, label5.tx, false) + labelOptionsXml(context, label5) + raw(context, label5.extLst)
15597
+ valXml("idx", label2.index) + valXml("delete", label2.deleted) + layoutXml(context, label2.layout) + chartTextXml(context, label2.tx, false) + labelOptionsXml(context, label2) + raw(context, label2.extLst)
15598
15598
  );
15599
15599
  }
15600
15600
  function dataLabelsXml(context, labels) {
@@ -15602,7 +15602,7 @@ function dataLabelsXml(context, labels) {
15602
15602
  const leaderLines = labels.leaderLines ? elementXml("leaderLines", shapePropertiesXml(context, labels.leaderLines.spPr)) : "";
15603
15603
  return elementXml(
15604
15604
  "dLbls",
15605
- labels.labels.map((label5) => labelXml(context, label5)).join("") + valXml("delete", labels.deleted) + labelOptionsXml(context, labels) + valXml("showLeaderLines", labels.showLeaderLines) + leaderLines + raw(context, labels.extLst)
15605
+ labels.labels.map((label2) => labelXml(context, label2)).join("") + valXml("delete", labels.deleted) + labelOptionsXml(context, labels) + valXml("showLeaderLines", labels.showLeaderLines) + leaderLines + raw(context, labels.extLst)
15606
15606
  );
15607
15607
  }
15608
15608
 
@@ -15614,21 +15614,21 @@ function surfaceXml(context, local, surface) {
15614
15614
  valXml("thickness", surface.thickness) + shapePropertiesXml(context, surface.spPr) + raw(context, surface.pictureOptionsXml) + raw(context, surface.extLst)
15615
15615
  );
15616
15616
  }
15617
- function dataTableXml(context, table3) {
15618
- if (!table3) return "";
15617
+ function dataTableXml(context, table4) {
15618
+ if (!table4) return "";
15619
15619
  return elementXml(
15620
15620
  "dTable",
15621
- valXml("showHorzBorder", table3.showHorizontalBorder) + valXml("showVertBorder", table3.showVerticalBorder) + valXml("showOutline", table3.showOutline) + valXml("showKeys", table3.showKeys) + shapePropertiesXml(context, table3.spPr) + textBodyXml(context, table3.txPr) + raw(context, table3.extLst)
15621
+ valXml("showHorzBorder", table4.showHorizontalBorder) + valXml("showVertBorder", table4.showVerticalBorder) + valXml("showOutline", table4.showOutline) + valXml("showKeys", table4.showKeys) + shapePropertiesXml(context, table4.spPr) + textBodyXml(context, table4.txPr) + raw(context, table4.extLst)
15622
15622
  );
15623
15623
  }
15624
15624
  function displayUnitsXml(context, units2) {
15625
15625
  if (!units2) return "";
15626
- const label5 = units2.label;
15626
+ const label2 = units2.label;
15627
15627
  return elementXml(
15628
15628
  "dispUnits",
15629
- valXml("custUnit", units2.customUnit) + (units2.customUnit === void 0 ? valXml("builtInUnit", units2.builtInUnit) : "") + (label5 ? elementXml(
15629
+ valXml("custUnit", units2.customUnit) + (units2.customUnit === void 0 ? valXml("builtInUnit", units2.builtInUnit) : "") + (label2 ? elementXml(
15630
15630
  "dispUnitsLbl",
15631
- layoutXml(context, label5.layout) + chartTextXml(context, label5.tx, false) + shapePropertiesXml(context, label5.spPr) + textBodyXml(context, label5.txPr)
15631
+ layoutXml(context, label2.layout) + chartTextXml(context, label2.tx, false) + shapePropertiesXml(context, label2.spPr) + textBodyXml(context, label2.txPr)
15632
15632
  ) : "") + raw(context, units2.extLst)
15633
15633
  );
15634
15634
  }
@@ -15653,11 +15653,11 @@ function axisXml(context, axis) {
15653
15653
  }
15654
15654
 
15655
15655
  // chart/write-analysis.ts
15656
- function trendlineLabelXml(context, label5) {
15657
- if (!label5) return "";
15656
+ function trendlineLabelXml(context, label2) {
15657
+ if (!label2) return "";
15658
15658
  return elementXml(
15659
15659
  "trendlineLbl",
15660
- layoutXml(context, label5.layout) + chartTextXml(context, label5.tx, false) + numberFormatXml(label5.numberFormat) + shapePropertiesXml(context, label5.spPr) + textBodyXml(context, label5.txPr) + raw(context, label5.extLst)
15660
+ layoutXml(context, label2.layout) + chartTextXml(context, label2.tx, false) + numberFormatXml(label2.numberFormat) + shapePropertiesXml(context, label2.spPr) + textBodyXml(context, label2.txPr) + raw(context, label2.extLst)
15661
15661
  );
15662
15662
  }
15663
15663
  function trendlineXml(context, trendline) {
@@ -17908,16 +17908,16 @@ var RelationshipAllocator = class {
17908
17908
 
17909
17909
  // docx/write.ts
17910
17910
  var twips2 = (pixels) => String(Math.round(pixels * 15));
17911
- function createTable(doc, table3, allocator, contentWidthTwips, spans2) {
17911
+ function createTable(doc, table4, allocator, contentWidthTwips, spans2) {
17912
17912
  const node3 = makeW(doc, "tbl");
17913
- const { tblPr, tblGrid } = buildNewTableProperties(doc, table3, contentWidthTwips);
17913
+ const { tblPr, tblGrid } = buildNewTableProperties(doc, table4, contentWidthTwips);
17914
17914
  node3.appendChild(tblPr);
17915
17915
  node3.appendChild(tblGrid);
17916
- const columns = tableColumnCount(table3);
17917
- table3.rows.forEach((row3, rowIndex2) => {
17916
+ const columns = tableColumnCount(table4);
17917
+ table4.rows.forEach((row3, rowIndex2) => {
17918
17918
  const tr = makeW(doc, "tr");
17919
17919
  const spanned = row3.reduce((sum3, cell) => sum3 + (cell.gridSpan ?? 1), 0);
17920
- const trPr = buildRowProperties(doc, table3.rowProperties?.[rowIndex2], columns - spanned);
17920
+ const trPr = buildRowProperties(doc, table4.rowProperties?.[rowIndex2], columns - spanned);
17921
17921
  if (trPr) tr.appendChild(trPr);
17922
17922
  for (const cell of row3) {
17923
17923
  const tc = makeW(doc, "tc");
@@ -18320,28 +18320,28 @@ function validateCell(c2, cell) {
18320
18320
  for (const side2 of ["top", "bottom", "left", "right"])
18321
18321
  c2.at(".margins").signed(side2, cell.margins[side2], "ST_SignedTwipsMeasure");
18322
18322
  }
18323
- function validateTable(c2, table3) {
18324
- c2.unsigned("widthTwips", table3.widthTwips, "ST_TwipsMeasure");
18325
- c2.signed("indentTwips", table3.indentTwips, "ST_SignedTwipsMeasure");
18323
+ function validateTable(c2, table4) {
18324
+ c2.unsigned("widthTwips", table4.widthTwips, "ST_TwipsMeasure");
18325
+ c2.signed("indentTwips", table4.indentTwips, "ST_SignedTwipsMeasure");
18326
18326
  c2.check(
18327
18327
  "alignment",
18328
- table3.alignment,
18328
+ table4.alignment,
18329
18329
  (v) => v === "left" || v === "center" || v === "right",
18330
18330
  'must be "left", "center" or "right"'
18331
18331
  );
18332
- c2.enum("justification", table3.justification, isStJcTable, "ST_JcTable");
18333
- table3.grid?.forEach(
18332
+ c2.enum("justification", table4.justification, isStJcTable, "ST_JcTable");
18333
+ table4.grid?.forEach(
18334
18334
  (width, index3) => c2.at(`.grid[${index3}]`).unsigned("width", width, "ST_TwipsMeasure")
18335
18335
  );
18336
- validateBorders(c2.at(".borders"), table3.borders);
18337
- if (table3.cellMargins)
18336
+ validateBorders(c2.at(".borders"), table4.borders);
18337
+ if (table4.cellMargins)
18338
18338
  for (const side2 of ["top", "bottom", "left", "right"])
18339
- c2.at(".cellMargins").signed(side2, table3.cellMargins[side2], "ST_SignedTwipsMeasure");
18340
- table3.rowProperties?.forEach((row3, index3) => {
18339
+ c2.at(".cellMargins").signed(side2, table4.cellMargins[side2], "ST_SignedTwipsMeasure");
18340
+ table4.rowProperties?.forEach((row3, index3) => {
18341
18341
  if (row3)
18342
18342
  c2.at(`.rowProperties[${index3}]`).unsigned("heightTwips", row3.heightTwips, "ST_TwipsMeasure");
18343
18343
  });
18344
- table3.rows.forEach(
18344
+ table4.rows.forEach(
18345
18345
  (row3, r) => row3.forEach((cell, k) => validateCell(c2.at(`.rows[${r}][${k}]`), cell))
18346
18346
  );
18347
18347
  }
@@ -19773,40 +19773,40 @@ function parseTable(node3, id3, parseParagraph3) {
19773
19773
  (cell, ci) => parseCell(cell.element, parseParagraph3, `${id3}-r${ri}c${ci}`, cell.control)
19774
19774
  )
19775
19775
  );
19776
- const table3 = { type: "table", id: id3, rows, structureEditable: canEditTableStructure(node3) };
19776
+ const table4 = { type: "table", id: id3, rows, structureEditable: canEditTableStructure(node3) };
19777
19777
  const gridElement = first2(node3, "tblGrid");
19778
19778
  const grid = gridElement ? children2(gridElement, "gridCol").flatMap((column2) => {
19779
19779
  const width2 = dxa(getW(column2, "w"));
19780
19780
  return width2 === void 0 ? [] : [width2];
19781
19781
  }) : [];
19782
- if (grid.length) table3.grid = grid;
19782
+ if (grid.length) table4.grid = grid;
19783
19783
  const tblPr = first2(node3, "tblPr");
19784
19784
  const tableWidth = first2(tblPr, "tblW");
19785
19785
  const width = (getW(tableWidth, "type") ?? "dxa") === "dxa" ? dxa(getW(tableWidth, "w")) : void 0;
19786
- if (width !== void 0) table3.widthTwips = width;
19786
+ if (width !== void 0) table4.widthTwips = width;
19787
19787
  const justification = enumValue(isStJcTable, getW(first2(tblPr, "jc"), "val"), "w:tblPr/w:jc");
19788
19788
  if (justification) {
19789
- table3.justification = justification;
19789
+ table4.justification = justification;
19790
19790
  const rtl = onOffElement(first2(tblPr, "bidiVisual")) === true;
19791
- table3.alignment = justification === "start" ? rtl ? "right" : "left" : justification === "end" ? rtl ? "left" : "right" : justification;
19791
+ table4.alignment = justification === "start" ? rtl ? "right" : "left" : justification === "end" ? rtl ? "left" : "right" : justification;
19792
19792
  }
19793
19793
  const indent = parseSignedTwips(getW(first2(tblPr, "tblInd"), "w"));
19794
- if (indent !== void 0) table3.indentTwips = indent;
19794
+ if (indent !== void 0) table4.indentTwips = indent;
19795
19795
  const borders = parseTableBorders(first2(tblPr, "tblBorders"));
19796
- if (borders) table3.borders = borders;
19796
+ if (borders) table4.borders = borders;
19797
19797
  const styleId = getW(first2(tblPr, "tblStyle"), "val");
19798
- if (styleId) table3.style = styleId;
19798
+ if (styleId) table4.style = styleId;
19799
19799
  const look = parseLook(first2(tblPr, "tblLook"));
19800
- if (look) table3.look = look;
19800
+ if (look) table4.look = look;
19801
19801
  const cellMargins = parseMargins(first2(tblPr, "tblCellMar"));
19802
- if (cellMargins) table3.cellMargins = cellMargins;
19802
+ if (cellMargins) table4.cellMargins = cellMargins;
19803
19803
  const rowProperties = rowEntries.map(({ element: element2, control }) => {
19804
19804
  const properties = parseRowProperties(element2);
19805
19805
  if (control) properties.contentControl = control;
19806
19806
  return properties;
19807
19807
  });
19808
- if (rowProperties.some((row3) => Object.keys(row3).length)) table3.rowProperties = rowProperties;
19809
- return table3;
19808
+ if (rowProperties.some((row3) => Object.keys(row3).length)) table4.rowProperties = rowProperties;
19809
+ return table4;
19810
19810
  }
19811
19811
 
19812
19812
  // docx/hyperlink.ts
@@ -20860,19 +20860,19 @@ var nextSheetId = (workbook) => workbook.sheets.reduce((max, sheet) => Math.max(
20860
20860
  var MAX_ROW = 1048575;
20861
20861
  var MAX_COL = 16383;
20862
20862
  function columnLabel(col) {
20863
- let label5 = "";
20863
+ let label2 = "";
20864
20864
  let n = col + 1;
20865
20865
  while (n > 0) {
20866
20866
  const rem = (n - 1) % 26;
20867
- label5 = String.fromCharCode(65 + rem) + label5;
20867
+ label2 = String.fromCharCode(65 + rem) + label2;
20868
20868
  n = Math.floor((n - 1) / 26);
20869
20869
  }
20870
- return label5;
20870
+ return label2;
20871
20871
  }
20872
- function columnIndex(label5) {
20873
- if (!/^[A-Za-z]{1,3}$/.test(label5)) return -1;
20872
+ function columnIndex(label2) {
20873
+ if (!/^[A-Za-z]{1,3}$/.test(label2)) return -1;
20874
20874
  let n = 0;
20875
- for (const ch of label5.toUpperCase()) n = n * 26 + (ch.charCodeAt(0) - 64);
20875
+ for (const ch of label2.toUpperCase()) n = n * 26 + (ch.charCodeAt(0) - 64);
20876
20876
  return n - 1;
20877
20877
  }
20878
20878
  var formatAddress = (address2) => `${columnLabel(address2.col)}${address2.row + 1}`;
@@ -23231,11 +23231,235 @@ var pivotRowFields = (pivot) => [
23231
23231
  ...pivot.secondRowField ? [pivot.secondRowField] : [],
23232
23232
  ...pivot.secondRowField ? pivot.moreRowFields ?? [] : []
23233
23233
  ];
23234
+ function pivotValuesIndex(pivot) {
23235
+ if (pivot.valuesAxis !== "rows") return -1;
23236
+ const count2 = pivotRowFields(pivot).length;
23237
+ const at2 = pivot.valuesPosition;
23238
+ if (typeof at2 === "number") return Math.min(Math.max(Math.trunc(at2), 0), count2);
23239
+ return at2 === "first" ? 0 : at2 === "between" ? Math.min(1, count2) : count2;
23240
+ }
23234
23241
  var pivotColumnFields = (pivot) => [
23235
23242
  ...pivot.columnField ? [pivot.columnField] : [],
23236
23243
  ...pivot.columnField ? pivot.moreColumnFields ?? [] : []
23237
23244
  ];
23238
23245
 
23246
+ // i18n/locale.ts
23247
+ var SUPPORTED_OFFICE_LOCALES = ["en", "fr", "de", "es", "zh-CN"];
23248
+ var DEFAULT_REJECTED_SUBTAGS = ["hant", "tw", "hk", "mo"];
23249
+ function normalizeLocale(input, supported2, fallback, options = {}) {
23250
+ const parts = (input ?? "").trim().toLowerCase().split(/[-_]/).filter(Boolean);
23251
+ const language = parts[0];
23252
+ if (!language) return fallback;
23253
+ const find3 = (tag) => supported2.find((item) => item.toLowerCase() === tag);
23254
+ const exact = find3(parts.join("-"));
23255
+ if (exact) return exact;
23256
+ const base2 = find3(language);
23257
+ if (base2) return base2;
23258
+ const rejected = options.rejectedSubtags ?? DEFAULT_REJECTED_SUBTAGS;
23259
+ if (parts.slice(1).some((part) => rejected.includes(part))) return fallback;
23260
+ return supported2.find((item) => item.toLowerCase().split("-")[0] === language && item.includes("-")) ?? fallback;
23261
+ }
23262
+ function normalizeOfficeLocale(input) {
23263
+ return normalizeLocale(input, SUPPORTED_OFFICE_LOCALES, "en");
23264
+ }
23265
+
23266
+ // xlsx/pivot/captions-locales.ts
23267
+ var table = (words2, prefix3, rest, functions) => ({
23268
+ ...rest,
23269
+ functions,
23270
+ aggregates: Object.fromEntries(
23271
+ Object.keys(words2).map((fn) => [fn, prefix3(words2[fn])])
23272
+ )
23273
+ });
23274
+ var GERMAN = {
23275
+ sum: "Summe",
23276
+ count: "Anzahl",
23277
+ average: "Mittelwert",
23278
+ max: "Max",
23279
+ min: "Min",
23280
+ product: "Produkt",
23281
+ countNums: "Anzahl (Zahlen)",
23282
+ stdDev: "Standardabweichung",
23283
+ stdDevp: "Standardabweichung (Grundgesamtheit)",
23284
+ var: "Varianz",
23285
+ varp: "Varianz (Grundgesamtheit)"
23286
+ };
23287
+ var SPANISH = {
23288
+ sum: "Suma",
23289
+ count: "Cuenta",
23290
+ average: "Promedio",
23291
+ max: "M\xE1x",
23292
+ min: "M\xEDn",
23293
+ product: "Producto",
23294
+ countNums: "Cuenta de n\xFAmeros",
23295
+ stdDev: "Desvest",
23296
+ stdDevp: "Desvestp",
23297
+ var: "Var",
23298
+ varp: "Varp"
23299
+ };
23300
+ var FRENCH = {
23301
+ sum: "Somme",
23302
+ count: "Nombre",
23303
+ average: "Moyenne",
23304
+ max: "Max",
23305
+ min: "Min",
23306
+ product: "Produit",
23307
+ countNums: "Nombre (nombres)",
23308
+ stdDev: "\xC9cartype",
23309
+ stdDevp: "\xC9cartypep",
23310
+ var: "Var",
23311
+ varp: "Varp"
23312
+ };
23313
+ var CHINESE = {
23314
+ sum: "\u6C42\u548C",
23315
+ count: "\u8BA1\u6570",
23316
+ average: "\u5E73\u5747\u503C",
23317
+ max: "\u6700\u5927\u503C",
23318
+ min: "\u6700\u5C0F\u503C",
23319
+ product: "\u4E58\u79EF",
23320
+ countNums: "\u6570\u503C\u8BA1\u6570",
23321
+ stdDev: "\u6807\u51C6\u504F\u5DEE",
23322
+ stdDevp: "\u603B\u4F53\u6807\u51C6\u504F\u5DEE",
23323
+ var: "\u65B9\u5DEE",
23324
+ varp: "\u603B\u4F53\u65B9\u5DEE"
23325
+ };
23326
+ var LOCALIZED_PIVOT_CAPTIONS = {
23327
+ de: table(
23328
+ GERMAN,
23329
+ (word) => `${word} von {0}`,
23330
+ {
23331
+ rowLabels: "Zeilenbeschriftungen",
23332
+ columnLabels: "Spaltenbeschriftungen",
23333
+ grandTotal: "Gesamtergebnis",
23334
+ values: "Werte",
23335
+ all: "(Alle)",
23336
+ blank: "(leer)",
23337
+ subtotal: "{0} Ergebnis",
23338
+ measureTotal: "Gesamt {0}"
23339
+ },
23340
+ GERMAN
23341
+ ),
23342
+ es: table(
23343
+ SPANISH,
23344
+ (word) => `${word} de {0}`,
23345
+ {
23346
+ rowLabels: "Etiquetas de fila",
23347
+ columnLabels: "Etiquetas de columna",
23348
+ grandTotal: "Total general",
23349
+ values: "Valores",
23350
+ all: "(Todas)",
23351
+ blank: "(en blanco)",
23352
+ subtotal: "{0} Total",
23353
+ measureTotal: "Total {0}"
23354
+ },
23355
+ SPANISH
23356
+ ),
23357
+ fr: table(
23358
+ FRENCH,
23359
+ (word) => `${word} de {0}`,
23360
+ {
23361
+ rowLabels: "\xC9tiquettes de lignes",
23362
+ columnLabels: "\xC9tiquettes de colonnes",
23363
+ grandTotal: "Total g\xE9n\xE9ral",
23364
+ values: "Valeurs",
23365
+ all: "(Tous)",
23366
+ blank: "(vide)",
23367
+ subtotal: "{0} Total",
23368
+ measureTotal: "Total {0}"
23369
+ },
23370
+ FRENCH
23371
+ ),
23372
+ "zh-CN": table(
23373
+ CHINESE,
23374
+ (word) => `${word}\u9879:{0}`,
23375
+ {
23376
+ rowLabels: "\u884C\u6807\u7B7E",
23377
+ columnLabels: "\u5217\u6807\u7B7E",
23378
+ grandTotal: "\u603B\u8BA1",
23379
+ values: "\u6570\u503C",
23380
+ all: "(\u5168\u90E8)",
23381
+ blank: "(\u7A7A\u767D)",
23382
+ subtotal: "{0} \u6C47\u603B",
23383
+ measureTotal: "\u603B\u8BA1 {0}"
23384
+ },
23385
+ CHINESE
23386
+ )
23387
+ };
23388
+
23389
+ // xlsx/pivot/captions.ts
23390
+ var FUNCTIONS = {
23391
+ sum: "Sum",
23392
+ count: "Count",
23393
+ average: "Average",
23394
+ max: "Max",
23395
+ min: "Min",
23396
+ product: "Product",
23397
+ countNums: "Count",
23398
+ stdDev: "StdDev",
23399
+ stdDevp: "StdDevp",
23400
+ var: "Var",
23401
+ varp: "Varp"
23402
+ };
23403
+ var aggregateNames = () => Object.fromEntries(
23404
+ Object.keys(FUNCTIONS).map((fn) => [
23405
+ fn,
23406
+ `${fn[0].toUpperCase()}${fn.slice(1)} of {0}`
23407
+ ])
23408
+ );
23409
+ var ENGLISH_PIVOT_CAPTIONS = {
23410
+ rowLabels: "Row Labels",
23411
+ columnLabels: "Column Labels",
23412
+ grandTotal: "Grand Total",
23413
+ values: "Values",
23414
+ all: "(All)",
23415
+ blank: "(blank)",
23416
+ subtotal: "{0} Total",
23417
+ measureTotal: "Total {0}",
23418
+ functions: FUNCTIONS,
23419
+ aggregates: aggregateNames()
23420
+ };
23421
+ var fillCaption = (template, ...args) => template.replace(/\{(\d)\}/g, (_match, at2) => args[Number(at2)] ?? "");
23422
+ function pivotCaptions(pivot) {
23423
+ const own2 = pivot.captions;
23424
+ if (!own2) return ENGLISH_PIVOT_CAPTIONS;
23425
+ return {
23426
+ ...ENGLISH_PIVOT_CAPTIONS,
23427
+ ...Object.fromEntries(Object.entries(own2).filter(([, value2]) => typeof value2 === "string")),
23428
+ functions: { ...ENGLISH_PIVOT_CAPTIONS.functions, ...own2.functions },
23429
+ aggregates: { ...ENGLISH_PIVOT_CAPTIONS.aggregates, ...own2.aggregates }
23430
+ };
23431
+ }
23432
+ var pivotMeasureName = (aggregate2, field2, pivot = {}) => fillCaption(pivotCaptions(pivot).aggregates[aggregate2], field2);
23433
+ function localizedPivotCaptions(locale) {
23434
+ const caps = LOCALIZED_PIVOT_CAPTIONS[normalizeOfficeLocale(locale)];
23435
+ return caps ? structuredClone(caps) : void 0;
23436
+ }
23437
+ function trimmedCaptions(caps) {
23438
+ const out = {};
23439
+ for (const key2 of [
23440
+ "rowLabels",
23441
+ "columnLabels",
23442
+ "grandTotal",
23443
+ "values",
23444
+ "all",
23445
+ "blank",
23446
+ "subtotal",
23447
+ "measureTotal"
23448
+ ])
23449
+ if (caps[key2] !== ENGLISH_PIVOT_CAPTIONS[key2]) out[key2] = caps[key2];
23450
+ for (const key2 of ["functions", "aggregates"]) {
23451
+ const changed = Object.keys(caps[key2]).filter(
23452
+ (fn) => caps[key2][fn] !== ENGLISH_PIVOT_CAPTIONS[key2][fn]
23453
+ );
23454
+ if (changed.length) out[key2] = Object.fromEntries(changed.map((fn) => [fn, caps[key2][fn]]));
23455
+ }
23456
+ return Object.keys(out).length ? out : void 0;
23457
+ }
23458
+ function authoredCaptions(options) {
23459
+ const own2 = options.captions ?? localizedPivotCaptions(options.locale);
23460
+ return own2 && Object.keys(own2).length ? structuredClone(own2) : void 0;
23461
+ }
23462
+
23239
23463
  // xlsx/formula/date-serial.ts
23240
23464
  var DAY_MS = 864e5;
23241
23465
  var EPOCH_19002 = Date.UTC(1899, 11, 30);
@@ -23332,7 +23556,7 @@ var LEAP_MONTHS = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
23332
23556
  var MAX_ITEMS = 1e4;
23333
23557
  var pad3 = (value2, width = 2) => String(value2).padStart(width, "0");
23334
23558
  var dateGroupUnits = (group) => PIVOT_DATE_UNITS.filter((unit3) => group.by.includes(unit3));
23335
- var dateGroupFieldName = (unit3, field2) => `${UNIT_TITLES[unit3]} (${field2})`;
23559
+ var dateGroupFieldName = (unit3, field2, group) => group?.localized?.[unit3]?.name ?? `${UNIT_TITLES[unit3]} (${field2})`;
23336
23560
  var dateGroupDays = (group) => group.by.length === 1 && group.by[0] === "days" ? group.days ?? 1 : 1;
23337
23561
  function dateGroupRange(group, serials) {
23338
23562
  let min = Infinity;
@@ -23355,7 +23579,7 @@ var secondsOfDay = (serial) => Math.round((serial - Math.floor(serial)) * 86400)
23355
23579
  function dayBuckets(range2, days) {
23356
23580
  return Math.max(1, Math.ceil((Math.floor(range2.end) - Math.floor(range2.start) + 1) / days));
23357
23581
  }
23358
- function dateUnitLabels(unit3, range2, days, date1904) {
23582
+ function englishDateUnitLabels(unit3, range2, days, date1904) {
23359
23583
  const labels = [`<${isoDay(range2.start, date1904)}`];
23360
23584
  if (unit3 === "seconds" || unit3 === "minutes")
23361
23585
  for (let i2 = 0; i2 < 60; i2++) labels.push(`:${pad3(i2)}`);
@@ -23384,6 +23608,11 @@ function dateUnitLabels(unit3, range2, days, date1904) {
23384
23608
  labels.push(`>${isoDay(range2.end, date1904)}`);
23385
23609
  return labels;
23386
23610
  }
23611
+ function dateUnitLabels(unit3, range2, days, date1904, group) {
23612
+ const english = englishDateUnitLabels(unit3, range2, days, date1904);
23613
+ const localized = group?.localized?.[unit3]?.labels;
23614
+ return localized?.length === english.length ? localized : english;
23615
+ }
23387
23616
  function dateUnitIndex(unit3, range2, days, date1904, serial, count2) {
23388
23617
  if (serial < range2.start) return 0;
23389
23618
  if (serial > range2.end) return count2 - 1;
@@ -23407,7 +23636,7 @@ function derivedDateFields(pivot) {
23407
23636
  for (const group of pivot.dateGroups ?? [])
23408
23637
  for (const unit3 of dateGroupUnits(group))
23409
23638
  derived.push({
23410
- name: dateGroupFieldName(unit3, group.field),
23639
+ name: dateGroupFieldName(unit3, group.field, group),
23411
23640
  unit: unit3,
23412
23641
  group,
23413
23642
  index: databaseFields + derived.length
@@ -23418,7 +23647,7 @@ function countDerived(pivot) {
23418
23647
  let count2 = 0;
23419
23648
  for (const group of pivot.dateGroups ?? [])
23420
23649
  for (const unit3 of dateGroupUnits(group))
23421
- if (pivot.fields.includes(dateGroupFieldName(unit3, group.field))) count2++;
23650
+ if (pivot.fields.includes(dateGroupFieldName(unit3, group.field, group))) count2++;
23422
23651
  return count2;
23423
23652
  }
23424
23653
  var pivotAxisFieldNames = (pivot) => [
@@ -23438,7 +23667,7 @@ function derivedDateLabels(pivot, name3) {
23438
23667
  if (!entry3) return void 0;
23439
23668
  const [group] = resolveDateGroups({ ...pivot, dateGroups: [entry3.group] });
23440
23669
  const range2 = { start: group.start, end: group.end };
23441
- return dateUnitLabels(entry3.unit, range2, dateGroupDays(group), pivot.date1904 ?? false);
23670
+ return dateUnitLabels(entry3.unit, range2, dateGroupDays(group), pivot.date1904 ?? false, group);
23442
23671
  }
23443
23672
  function validateDateGroups(pivot) {
23444
23673
  const groups = pivot.dateGroups;
@@ -23454,18 +23683,16 @@ function validateDateGroups(pivot) {
23454
23683
  seen.add(group.field);
23455
23684
  if (!(pivot.dateFields ?? []).includes(group.field))
23456
23685
  throw new Error("Only fields that contain dates can be grouped by date.");
23457
- if (pivot.pageFilter || pivot.dateFilter)
23458
- throw new Error("Date groups cannot be combined with report filters or timelines.");
23459
23686
  const serials = pivot.records.map((record2) => record2[index3]);
23460
23687
  if (!serials.length || serials.some((v) => typeof v !== "number" || !Number.isFinite(v)))
23461
23688
  throw new Error("Only fields that contain dates can be grouped by date.");
23462
23689
  const range2 = dateGroupRange(group, serials);
23463
23690
  if (range2.start >= range2.end) throw new Error("The date group must end after it starts.");
23464
23691
  for (const unit3 of dateGroupUnits(group)) {
23465
- const name3 = dateGroupFieldName(unit3, group.field);
23692
+ const name3 = dateGroupFieldName(unit3, group.field, group);
23466
23693
  if (pivot.fields.includes(name3))
23467
23694
  throw new Error("A source field already has the name of a date group field.");
23468
- if (dateUnitLabels(unit3, range2, dateGroupDays(group), pivot.date1904 ?? false).length > MAX_ITEMS)
23695
+ if (dateUnitLabels(unit3, range2, dateGroupDays(group), pivot.date1904 ?? false, group).length > MAX_ITEMS)
23469
23696
  throw new Error("The date group has too many items.");
23470
23697
  }
23471
23698
  }
@@ -23479,7 +23706,7 @@ function expandDateGroups(pivot) {
23479
23706
  const tables = derived.map((entry3) => {
23480
23707
  const range2 = { start: entry3.group.start, end: entry3.group.end };
23481
23708
  const days = dateGroupDays(entry3.group);
23482
- const labels = dateUnitLabels(entry3.unit, range2, days, date1904);
23709
+ const labels = dateUnitLabels(entry3.unit, range2, days, date1904, entry3.group);
23483
23710
  return {
23484
23711
  base: pivot.fields.indexOf(entry3.group.field),
23485
23712
  labels,
@@ -23491,9 +23718,9 @@ function expandDateGroups(pivot) {
23491
23718
  fields: [...pivot.fields, ...derived.map((entry3) => entry3.name)],
23492
23719
  records: pivot.records.map((record2) => [
23493
23720
  ...record2,
23494
- ...tables.map((table3) => {
23495
- const value2 = record2[table3.base];
23496
- return typeof value2 === "number" ? table3.labels[table3.index(value2)] : null;
23721
+ ...tables.map((table4) => {
23722
+ const value2 = record2[table4.base];
23723
+ return typeof value2 === "number" ? table4.labels[table4.index(value2)] : null;
23497
23724
  })
23498
23725
  ])
23499
23726
  };
@@ -23612,15 +23839,13 @@ function normalizedFieldSubtotals(entries) {
23612
23839
  };
23613
23840
  });
23614
23841
  }
23615
- function validateFieldSubtotals(pivot, rowFields) {
23842
+ function validateFieldSubtotals(pivot, axisFields) {
23616
23843
  const entries = pivot.fieldSubtotals;
23617
23844
  if (entries === void 0) return;
23618
23845
  if (!Array.isArray(entries)) throw new Error("Choose valid field subtotals.");
23619
- if (entries.length && pivot.valuesAxis === "rows")
23620
- throw new Error("Field subtotals require Values on columns.");
23621
23846
  const seen = /* @__PURE__ */ new Set();
23622
23847
  for (const entry3 of entries) {
23623
- if (!entry3 || typeof entry3 !== "object" || !rowFields.includes(entry3.field) || seen.has(entry3.field) || !Array.isArray(entry3.functions) || entry3.functions.some((fn) => !PIVOT_AGGREGATES.includes(fn)) || new Set(entry3.functions).size !== entry3.functions.length)
23848
+ if (!entry3 || typeof entry3 !== "object" || !axisFields.includes(entry3.field) || seen.has(entry3.field) || !Array.isArray(entry3.functions) || entry3.functions.some((fn) => !PIVOT_AGGREGATES.includes(fn)) || new Set(entry3.functions).size !== entry3.functions.length)
23624
23849
  throw new Error("Choose valid field subtotals.");
23625
23850
  seen.add(entry3.field);
23626
23851
  }
@@ -23699,6 +23924,17 @@ function pruneItemFilters(pivot) {
23699
23924
  return next.length ? next : void 0;
23700
23925
  }
23701
23926
 
23927
+ // xlsx/pivot/item-labels.ts
23928
+ var keyOf = (field2, item) => `${field2}\0${pivotValueKey(item)}`;
23929
+ function pivotItemLabeler(pivot) {
23930
+ const blank = pivotCaptions(pivot).blank;
23931
+ const names = pivot.itemNames?.length ? new Map(pivot.itemNames.map((entry3) => [keyOf(entry3.field, entry3.item), entry3.name])) : void 0;
23932
+ return (field2, value2) => names?.get(keyOf(field2, value2)) ?? (value2 === null || value2 === "" ? blank : pivotItemLabel(value2));
23933
+ }
23934
+ var pivotItemName = (pivot, field2, item) => pivot.itemNames?.find(
23935
+ (entry3) => entry3.field === field2 && pivotValueKey(entry3.item) === pivotValueKey(item)
23936
+ )?.name;
23937
+
23702
23938
  // xlsx/pivot/page-filter.ts
23703
23939
  function validatePivotPageFilter(pivot) {
23704
23940
  const filter2 = pivot.pageFilter;
@@ -23710,23 +23946,24 @@ function validatePivotPageFilter(pivot) {
23710
23946
  pivot.columnField,
23711
23947
  pivot.valueField,
23712
23948
  ...extras.map((v) => v?.field)
23713
- ].includes(filter2.field) || pivot.valuesAxis === "rows")
23714
- throw new Error("Report filters require Values on columns and a separate source field.");
23949
+ ].includes(filter2.field))
23950
+ throw new Error("Report filters require a separate source field.");
23715
23951
  if (filter2.item !== void 0 && !(filter2.item === null || typeof filter2.item === "string" || typeof filter2.item === "boolean" || typeof filter2.item === "number" && Number.isFinite(filter2.item) || isCellError(filter2.item) && isErrorCode(filter2.item.error) && Object.keys(filter2.item).length === 1))
23716
23952
  throw new Error("Choose a cached literal report filter item.");
23717
23953
  }
23718
23954
  function pivotPageProjection(pivot) {
23719
- return applyPivotGroups(applyPivotItemFilters(pagedProjection(pivot)));
23955
+ const groups = pivot.dateGroups?.length ? { ...pivot, dateGroups: resolveDateGroups(pivot) } : pivot;
23956
+ return applyPivotGroups(applyPivotItemFilters(pagedProjection(groups)));
23720
23957
  }
23721
23958
  function pagedProjection(pivot) {
23722
23959
  const filter2 = pivot.pageFilter;
23723
23960
  if (!filter2) return pivot;
23724
23961
  const labels = /* @__PURE__ */ new Map();
23725
23962
  for (const item of pivotItems(pivot, filter2.field)) {
23726
- const label5 = String(pivotItemLabel(item)).toLowerCase(), key3 = pivotValueKey(item);
23727
- if (label5 === "(all)" || labels.has(label5) && labels.get(label5) !== key3)
23963
+ const label2 = String(pivotItemLabel(item)).toLowerCase(), key3 = pivotValueKey(item);
23964
+ if (label2 === "(all)" || labels.has(label2) && labels.get(label2) !== key3)
23728
23965
  throw new Error("Ambiguous report filter item captions are preserved.");
23729
- labels.set(label5, key3);
23966
+ labels.set(label2, key3);
23730
23967
  }
23731
23968
  if (filter2.item === void 0) return pivot;
23732
23969
  const index3 = pivot.fields.indexOf(filter2.field), key2 = pivotValueKey(filter2.item);
@@ -23744,7 +23981,7 @@ function prependPivotPage(grid, pivot) {
23744
23981
  values: [
23745
23982
  [
23746
23983
  pivot.pageFilter.field,
23747
- pivot.pageFilter.item === void 0 ? "(All)" : pivotItemLabel(pivot.pageFilter.item),
23984
+ pivot.pageFilter.item === void 0 ? pivotCaptions(pivot).all : pivotItemLabeler(pivot)(pivot.pageFilter.field, pivot.pageFilter.item),
23748
23985
  ...Array(width - 2).fill(null)
23749
23986
  ],
23750
23987
  Array(width).fill(null),
@@ -23865,13 +24102,9 @@ function validatePivotFields(pivot) {
23865
24102
  const columns = pivotColumnFields(pivot);
23866
24103
  if (pivot.moreColumnFields !== void 0 && (!Array.isArray(pivot.moreColumnFields) || pivot.moreColumnFields.length > 0 && !pivot.columnField || pivot.moreColumnFields.length > 62 || pivot.moreColumnFields.some((name3) => typeof name3 !== "string")))
23867
24104
  throw new Error("Choose valid PivotTable column fields.");
23868
- if (pivot.valuesAxis === "rows" && rows.length > 2)
23869
- throw new Error("Values on rows support at most two row fields.");
23870
- if (pivot.valuesAxis === "rows" && columns.length > 1)
23871
- throw new Error("Values on rows support one column field.");
23872
24105
  if (pivot.pageFilter && columns.length > 1)
23873
24106
  throw new Error("Report filters support one column field.");
23874
- validateFieldSubtotals(pivot, rows);
24107
+ validateFieldSubtotals(pivot, [...rows, ...columns]);
23875
24108
  const axisNames = pivotAxisFieldNames(pivot);
23876
24109
  if ((pivot.dateGroups ?? []).some(
23877
24110
  (group) => [...rows, ...columns].some((name3) => name3 === group.field)
@@ -23880,13 +24113,14 @@ function validatePivotFields(pivot) {
23880
24113
  const extras = pivot.additionalValues ?? [];
23881
24114
  if (pivot.valuesAxis !== void 0 && !["columns", "rows"].includes(pivot.valuesAxis))
23882
24115
  throw new Error("Choose a valid Values axis.");
23883
- if (pivot.valuesPosition !== void 0 && !["last", "between", "first"].includes(pivot.valuesPosition))
24116
+ const position2 = pivot.valuesPosition;
24117
+ if (position2 !== void 0 && !["last", "between", "first"].includes(position2) && !(typeof position2 === "number" && Number.isInteger(position2) && position2 >= 0))
23884
24118
  throw new Error("Choose a valid Values position.");
23885
- if ((pivot.valuesPosition === "between" || pivot.valuesPosition === "first") && (pivot.valuesAxis !== "rows" || !pivot.secondRowField))
24119
+ if (position2 !== void 0 && position2 !== "last" && (pivot.valuesAxis !== "rows" || position2 === "between" && !pivot.secondRowField || typeof position2 === "number" && position2 > rows.length))
23886
24120
  throw new Error("Values before or between fields require two row fields and Values on rows.");
23887
24121
  if (pivot.valuesAxis === "rows" && (!Array.isArray(extras) || !extras.length))
23888
24122
  throw new Error("Values on rows require multiple measures.");
23889
- if (extras.length > 0 && pivot.sourceXml && parseXml(pivot.sourceXml).documentElement.getAttribute("dataCaption") !== "Values")
24123
+ if (extras.length > 0 && pivot.sourceXml && parseXml(pivot.sourceXml).documentElement.getAttribute("dataCaption") !== pivotCaptions(pivot).values)
23890
24124
  throw new Error("This PivotTable uses unsupported Values header captions.");
23891
24125
  if (!Array.isArray(extras) || extras.length > 15 || extras.some(
23892
24126
  (measure2) => !measure2 || !pivot.fields.includes(measure2.field) || !PIVOT_AGGREGATES.includes(measure2.aggregate) || typeof measure2.caption !== "string" || !measure2.caption.trim() || measure2.caption.length > 255 || pivot.fields.some((field2) => field2.toLowerCase() === measure2.caption.toLowerCase())
@@ -23899,8 +24133,47 @@ function validatePivotFields(pivot) {
23899
24133
  if (pivot.layout !== void 0 && !["tabular", "compact", "outline"].includes(pivot.layout) || pivot.subtotalPosition !== void 0 && !["top", "bottom"].includes(pivot.subtotalPosition) || !PIVOT_AGGREGATES.includes(pivot.aggregate) || !pivot.fields.includes(pivot.valueField) || [...rows, ...columns].some((field2) => !axisNames.includes(field2)) || (/* @__PURE__ */ new Set([...rows, ...columns])).size !== rows.length + columns.length || pivot.subtotals !== void 0 && typeof pivot.subtotals !== "boolean" || pivot.repeatLabels !== void 0 && typeof pivot.repeatLabels !== "boolean")
23900
24134
  throw new Error("Choose valid PivotTable fields; row and column fields must differ.");
23901
24135
  }
23902
- function pivotCaption(aggregate2, field2) {
23903
- return `${aggregate2[0].toUpperCase()}${aggregate2.slice(1)} of ${field2}`;
24136
+ function pivotCaption(aggregate2, field2, pivot) {
24137
+ return pivotMeasureName(aggregate2, field2, pivot);
24138
+ }
24139
+
24140
+ // xlsx/write/xml-out.ts
24141
+ var XML_HEADER = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n';
24142
+ var CONTROL2 = "\0-\b\v\f-" + String.fromCharCode(65534, 65535);
24143
+ var NEEDS_ESCAPE = new RegExp(`[${CONTROL2}\r]|_x[0-9A-Fa-f]{4}_`);
24144
+ var ESCAPABLE = new RegExp(`[${CONTROL2}\r]|_(?=x[0-9A-Fa-f]{4}_)`, "g");
24145
+ function encodeEscapes(text8) {
24146
+ if (!NEEDS_ESCAPE.test(text8)) return text8;
24147
+ return text8.replace(
24148
+ ESCAPABLE,
24149
+ (ch) => `_x${ch.charCodeAt(0).toString(16).toUpperCase().padStart(4, "0")}_`
24150
+ );
24151
+ }
24152
+ var INVALID_XML2 = new RegExp(`[${CONTROL2}]`, "g");
24153
+ var escapeText3 = (text8) => text8.replace(INVALID_XML2, "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
24154
+ var escapeAttr3 = (text8) => text8.replace(INVALID_XML2, "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/\r/g, "&#13;").replace(/\n/g, "&#10;").replace(/\t/g, "&#9;");
24155
+ function attrs2(values2) {
24156
+ let out = "";
24157
+ for (const [name3, value2] of Object.entries(values2)) {
24158
+ if (value2 === void 0) continue;
24159
+ const text8 = typeof value2 === "boolean" ? value2 ? "1" : "0" : typeof value2 === "number" ? num(value2) : value2;
24160
+ out += ` ${name3}="${escapeAttr3(text8)}"`;
24161
+ }
24162
+ return out;
24163
+ }
24164
+ var el4 = (name3, values2 = {}, content2 = "") => content2 ? `<${name3}${attrs2(values2)}>${content2}</${name3}>` : `<${name3}${attrs2(values2)}/>`;
24165
+ var num = (value2) => Object.is(value2, -0) ? "0" : String(value2);
24166
+ function tElement(text8, name3 = "t") {
24167
+ const encoded = escapeText3(encodeEscapes(text8));
24168
+ const preserve = /^\s|\s$|\n|\t/.test(text8) ? ' xml:space="preserve"' : "";
24169
+ return `<${name3}${preserve}>${encoded}</${name3}>`;
24170
+ }
24171
+ var MAIN_NS = ' xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"';
24172
+ function inlineFragment(xml) {
24173
+ const end = xml.indexOf(">");
24174
+ if (end < 0) return xml;
24175
+ const head = xml.slice(0, end);
24176
+ return head.includes(MAIN_NS) ? head.replace(MAIN_NS, "") + xml.slice(end) : xml;
23904
24177
  }
23905
24178
 
23906
24179
  // xlsx/pivot/measures.ts
@@ -23908,7 +24181,7 @@ var pivotMeasures = (pivot) => [
23908
24181
  { field: pivot.valueField, aggregate: pivot.aggregate, caption: pivot.valueCaption },
23909
24182
  ...pivot.additionalValues ?? []
23910
24183
  ];
23911
- function normalizedPivotMeasures(values2) {
24184
+ function normalizedPivotMeasures(values2, pivot) {
23912
24185
  if (!Array.isArray(values2) || values2.length > 15)
23913
24186
  throw new Error("Choose between one and sixteen PivotTable value fields.");
23914
24187
  return values2.map((value2) => {
@@ -23920,7 +24193,7 @@ function normalizedPivotMeasures(values2) {
23920
24193
  return {
23921
24194
  field: value2.field,
23922
24195
  aggregate: aggregate2,
23923
- caption: value2.caption ?? `${aggregate2[0].toUpperCase()}${aggregate2.slice(1)} of ${value2.field}`
24196
+ caption: value2.caption ?? pivotMeasureName(aggregate2, value2.field, pivot)
23924
24197
  };
23925
24198
  });
23926
24199
  }
@@ -23952,329 +24225,16 @@ function aggregateValues(records, field2, type) {
23952
24225
  return type === "average" ? sum3 / numbers3.length : sum3;
23953
24226
  }
23954
24227
  var pivotMeasureNumber = (pivot, records, measure2) => aggregateValues(records, pivot.fields.indexOf(measure2.field), measure2.aggregate);
23955
- var pivotNumbers = (pivot, records) => pivotMeasures(pivot).map((measure2) => pivotMeasureNumber(pivot, records, measure2));
23956
- function pivotHeaderDimensions(pivot, columnItems, rowLabels) {
23957
- return {
23958
- rows: (pivot.columnField ? 2 : 1) + (pivot.pageFilter ? 2 : 0),
23959
- width: rowLabels + (pivot.columnField ? columnItems + 1 : 1)
23960
- };
23961
- }
23962
- function pivotHeaders(pivot, columns, labels, label5) {
23963
- const rowLabels = pivot.layout === "compact" ? ["Row Labels"] : pivot.valuesPosition === "first" ? ["Values", ...labels] : pivot.valuesPosition === "between" ? [labels[0], "Values", labels[1]] : [...labels, "Values"];
23964
- return pivot.columnField ? [
23965
- [
23966
- ...rowLabels.map(() => null),
23967
- pivot.layout === "compact" ? "Column Labels" : pivot.columnField,
23968
- ...columns.map(() => null)
23969
- ],
23970
- [...rowLabels, ...columns.map(label5), "Grand Total"]
23971
- ] : [[...rowLabels, null]];
23972
- }
23973
-
23974
- // xlsx/pivot/hierarchy-first.ts
23975
- function appendFirstPivotValues(pivot, context) {
23976
- const {
23977
- rowItems,
23978
- secondRowItems,
23979
- columnItems,
23980
- children: children4,
23981
- innerIndices,
23982
- groups,
23983
- details,
23984
- buckets,
23985
- width,
23986
- rowLabels,
23987
- top,
23988
- bottom,
23989
- append
23990
- } = context;
23991
- const compact3 = pivot.layout === "compact";
23992
- const tabular = !pivot.layout || pivot.layout === "tabular";
23993
- const blank = () => Array(width - rowLabels).fill(null);
23994
- pivotMeasures(pivot).forEach((measure2, m) => {
23995
- const numbers3 = (keys, records) => [
23996
- ...columnItems.map(
23997
- (column2) => pivotMeasureNumber(
23998
- pivot,
23999
- buckets.get(JSON.stringify([...keys, pivotValueKey(column2)])) ?? [],
24000
- measure2
24001
- )
24002
- ),
24003
- pivotMeasureNumber(pivot, records, measure2)
24004
- ];
24005
- if (!tabular)
24006
- append([measure2.caption, ...Array(rowLabels - 1).fill(null)], blank(), {
24007
- indices: [m],
24008
- measure: m
24009
- });
24010
- let first3 = true;
24011
- rowItems.forEach((outer, outerIndex) => {
24012
- const key2 = pivotValueKey(outer);
24013
- const group = groups.get(key2) ?? [];
24014
- if (!tabular)
24015
- append(
24016
- compact3 ? [pivotItemLabel(outer)] : [null, pivotItemLabel(outer), null],
24017
- top ? numbers3([key2], group) : blank(),
24018
- { indices: [m, outerIndex], measure: m },
24019
- compact3 ? 1 : 0
24020
- );
24021
- const innerKeys = [...children4.get(key2)].sort(
24022
- (a2, b) => innerIndices.get(a2) - innerIndices.get(b)
24023
- );
24024
- innerKeys.forEach((innerKey, child7) => {
24025
- const innerIndex = innerIndices.get(innerKey);
24026
- append(
24027
- compact3 ? [pivotItemLabel(secondRowItems[innerIndex])] : [
24028
- tabular && first3 ? measure2.caption : null,
24029
- pivot.repeatLabels || tabular && child7 === 0 ? pivotItemLabel(outer) : null,
24030
- pivotItemLabel(secondRowItems[innerIndex])
24031
- ],
24032
- numbers3([key2, innerKey], details.get(JSON.stringify([key2, innerKey]))),
24033
- { indices: [m, outerIndex, innerIndex], measure: m },
24034
- compact3 ? 2 : 0
24035
- );
24036
- first3 = false;
24037
- });
24038
- if (bottom)
24039
- append(
24040
- compact3 ? [`${String(pivotItemLabel(outer))} Total`] : [null, `${String(pivotItemLabel(outer))} Total`, null],
24041
- numbers3([key2], group),
24042
- { indices: [m, outerIndex], measure: m, type: "default" },
24043
- compact3 ? 1 : 0
24044
- );
24045
- });
24046
- });
24047
- }
24048
-
24049
- // xlsx/pivot/hierarchy.ts
24050
- var label = pivotItemLabel;
24051
- function hierarchicalPivotGrid(pivot) {
24052
- const rowItems = pivotItems(pivot, pivot.rowField);
24053
- const secondRowItems = pivotItems(pivot, pivot.secondRowField);
24054
- const columnItems = pivot.columnField ? pivotItems(pivot, pivot.columnField) : [];
24055
- const outerField = pivot.fields.indexOf(pivot.rowField);
24056
- const innerField = pivot.fields.indexOf(pivot.secondRowField);
24057
- const columnField = pivot.columnField ? pivot.fields.indexOf(pivot.columnField) : -1;
24058
- const layout3 = pivot.layout ?? "tabular";
24059
- const compact3 = layout3 === "compact";
24060
- const firstValues = pivot.valuesPosition === "first";
24061
- const between = pivot.valuesPosition === "between";
24062
- const measures2 = pivotMeasures(pivot);
24063
- const top = firstValues && layout3 !== "tabular" && pivot.subtotals !== false && (pivot.subtotalPosition ?? "top") === "top";
24064
- const bottom = pivot.subtotals !== false && !top;
24065
- const rowLabelColumns = compact3 ? 1 : 3;
24066
- const groups = /* @__PURE__ */ new Map();
24067
- const details = /* @__PURE__ */ new Map();
24068
- const children4 = /* @__PURE__ */ new Map();
24069
- const innerIndices = new Map(secondRowItems.map((item, index3) => [pivotValueKey(item), index3]));
24070
- const buckets = /* @__PURE__ */ new Map();
24071
- const collect = (map, key2, record2) => {
24072
- const list2 = map.get(key2);
24073
- if (list2) list2.push(record2);
24074
- else map.set(key2, [record2]);
24075
- };
24076
- for (const record2 of pivot.records) {
24077
- const outer = pivotValueKey(record2[outerField] ?? null);
24078
- const inner2 = pivotValueKey(record2[innerField] ?? null);
24079
- collect(groups, outer, record2);
24080
- collect(details, JSON.stringify([outer, inner2]), record2);
24081
- if (!children4.has(outer)) children4.set(outer, /* @__PURE__ */ new Set());
24082
- children4.get(outer).add(inner2);
24083
- if (pivot.columnField) {
24084
- const column2 = pivotValueKey(record2[columnField] ?? null);
24085
- for (const key2 of [[], [outer], [outer, inner2]])
24086
- collect(buckets, JSON.stringify([...key2, column2]), record2);
24087
- }
24088
- }
24089
- const dimensions3 = pivotHeaderDimensions(pivot, columnItems.length, rowLabelColumns);
24090
- const rows = (details.size + rowItems.length * Number(bottom) + 1) * measures2.length + rowItems.length * Number(layout3 !== "tabular") * (firstValues ? measures2.length : 1) + (firstValues ? measures2.length : between ? rowItems.length * measures2.length : details.size) * Number(layout3 !== "tabular") + dimensions3.rows;
24091
- if (rows * dimensions3.width > 1e6) throw new Error("The PivotTable result is too large.");
24092
- const labels = compact3 ? ["Row Labels"] : [pivot.rowField, pivot.secondRowField];
24093
- const values2 = pivotHeaders(pivot, columnItems, labels, label);
24094
- const firstDataRow = values2.length;
24095
- const indents = values2.map(() => 0);
24096
- const rowEntries = [];
24097
- const append = (labels2, numbers4, entry3, indent = 0) => {
24098
- values2.push([...labels2, ...numbers4]);
24099
- rowEntries.push(entry3);
24100
- indents.push(indent);
24101
- };
24102
- const bands = (keys, records) => [
24103
- ...columnItems.map(
24104
- (column2) => pivotNumbers(pivot, buckets.get(JSON.stringify([...keys, pivotValueKey(column2)])) ?? [])
24105
- ),
24106
- pivotNumbers(pivot, records)
24107
- ];
24108
- const numbers3 = (keys, records) => bands(keys, records).flat();
24109
- const appendMeasures = (labels2, keys, records, indices, type) => {
24110
- const values3 = bands(keys, records);
24111
- measures2.forEach(
24112
- (measure2, m) => append(
24113
- type ? [
24114
- `${type === "grand" ? "Total" : String(labels2[0])} ${measure2.caption}`,
24115
- ...Array(rowLabelColumns - 1).fill(null)
24116
- ] : compact3 ? [measure2.caption] : [
24117
- ...labels2.map(
24118
- (label5) => layout3 === "tabular" && m === 0 || pivot.repeatLabels ? label5 : null
24119
- ),
24120
- measure2.caption
24121
- ],
24122
- values3.map((band2) => band2[m] ?? null),
24123
- { indices: type ? indices : [...indices, m], measure: m, ...type ? { type } : {} },
24124
- compact3 && !type ? 2 : 0
24125
- )
24126
- );
24127
- };
24128
- if (firstValues)
24129
- appendFirstPivotValues(pivot, {
24130
- rowItems,
24131
- secondRowItems,
24132
- columnItems,
24133
- children: children4,
24134
- innerIndices,
24135
- groups,
24136
- details,
24137
- buckets,
24138
- width: dimensions3.width,
24139
- rowLabels: rowLabelColumns,
24140
- top,
24141
- bottom,
24142
- append
24143
- });
24144
- else
24145
- rowItems.forEach((outer, outerIndex) => {
24146
- const key2 = pivotValueKey(outer);
24147
- if (layout3 !== "tabular")
24148
- append(
24149
- [label(outer), ...Array(rowLabelColumns - 1).fill(null)],
24150
- top ? numbers3([key2], groups.get(key2) ?? []) : Array(dimensions3.width - rowLabelColumns).fill(null),
24151
- { indices: [outerIndex] }
24152
- );
24153
- let first3 = true;
24154
- const innerKeys = [...children4.get(key2)].sort(
24155
- (a2, b) => innerIndices.get(a2) - innerIndices.get(b)
24156
- );
24157
- if (between)
24158
- measures2.forEach((measure2, m) => {
24159
- if (layout3 !== "tabular")
24160
- append(
24161
- compact3 ? [measure2.caption] : [pivot.repeatLabels ? label(outer) : null, measure2.caption, null],
24162
- Array(dimensions3.width - rowLabelColumns).fill(null),
24163
- { indices: [outerIndex, m], measure: m },
24164
- compact3 ? 1 : 0
24165
- );
24166
- innerKeys.forEach((innerKey, child7) => {
24167
- const innerIndex = innerIndices.get(innerKey);
24168
- const keys = [key2, innerKey];
24169
- const records = details.get(JSON.stringify(keys));
24170
- append(
24171
- compact3 ? [label(secondRowItems[innerIndex])] : [
24172
- pivot.repeatLabels || layout3 === "tabular" && m === 0 && child7 === 0 ? label(outer) : null,
24173
- layout3 === "tabular" && child7 === 0 ? measure2.caption : null,
24174
- label(secondRowItems[innerIndex])
24175
- ],
24176
- [
24177
- ...columnItems.map(
24178
- (column2) => pivotMeasureNumber(
24179
- pivot,
24180
- buckets.get(JSON.stringify([...keys, pivotValueKey(column2)])) ?? [],
24181
- measure2
24182
- )
24183
- ),
24184
- pivotMeasureNumber(pivot, records, measure2)
24185
- ],
24186
- { indices: [outerIndex, m, innerIndex], measure: m },
24187
- compact3 ? 2 : 0
24188
- );
24189
- });
24190
- });
24191
- else
24192
- innerKeys.forEach((innerKey) => {
24193
- const innerIndex = innerIndices.get(innerKey);
24194
- const inner2 = secondRowItems[innerIndex];
24195
- const keys = [key2, innerKey];
24196
- const records = details.get(JSON.stringify(keys));
24197
- if (!records) return;
24198
- if (layout3 !== "tabular")
24199
- append(
24200
- compact3 ? [label(inner2)] : [pivot.repeatLabels ? label(outer) : null, label(inner2), null],
24201
- Array(dimensions3.width - rowLabelColumns).fill(null),
24202
- { indices: [outerIndex, innerIndex] },
24203
- compact3 ? 1 : 0
24204
- );
24205
- appendMeasures(
24206
- [pivot.repeatLabels || first3 ? label(outer) : null, label(inner2)],
24207
- keys,
24208
- records,
24209
- [outerIndex, innerIndex]
24210
- );
24211
- first3 = false;
24212
- });
24213
- if (bottom)
24214
- appendMeasures([label(outer)], [key2], groups.get(key2) ?? [], [outerIndex], "default");
24215
- });
24216
- appendMeasures([], [], pivot.records, [0], "grand");
24217
- return {
24218
- values: values2,
24219
- rowItems,
24220
- secondRowItems,
24221
- columnItems,
24222
- rowEntries,
24223
- firstDataRow,
24224
- rowLabelColumns,
24225
- indents,
24226
- firstHeaderRow: 1
24227
- };
24228
- }
24229
-
24230
- // xlsx/write/xml-out.ts
24231
- var XML_HEADER = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n';
24232
- var CONTROL2 = "\0-\b\v\f-" + String.fromCharCode(65534, 65535);
24233
- var NEEDS_ESCAPE = new RegExp(`[${CONTROL2}\r]|_x[0-9A-Fa-f]{4}_`);
24234
- var ESCAPABLE = new RegExp(`[${CONTROL2}\r]|_(?=x[0-9A-Fa-f]{4}_)`, "g");
24235
- function encodeEscapes(text8) {
24236
- if (!NEEDS_ESCAPE.test(text8)) return text8;
24237
- return text8.replace(
24238
- ESCAPABLE,
24239
- (ch) => `_x${ch.charCodeAt(0).toString(16).toUpperCase().padStart(4, "0")}_`
24240
- );
24241
- }
24242
- var INVALID_XML2 = new RegExp(`[${CONTROL2}]`, "g");
24243
- var escapeText3 = (text8) => text8.replace(INVALID_XML2, "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
24244
- var escapeAttr3 = (text8) => text8.replace(INVALID_XML2, "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/\r/g, "&#13;").replace(/\n/g, "&#10;").replace(/\t/g, "&#9;");
24245
- function attrs2(values2) {
24246
- let out = "";
24247
- for (const [name3, value2] of Object.entries(values2)) {
24248
- if (value2 === void 0) continue;
24249
- const text8 = typeof value2 === "boolean" ? value2 ? "1" : "0" : typeof value2 === "number" ? num(value2) : value2;
24250
- out += ` ${name3}="${escapeAttr3(text8)}"`;
24251
- }
24252
- return out;
24253
- }
24254
- var el4 = (name3, values2 = {}, content2 = "") => content2 ? `<${name3}${attrs2(values2)}>${content2}</${name3}>` : `<${name3}${attrs2(values2)}/>`;
24255
- var num = (value2) => Object.is(value2, -0) ? "0" : String(value2);
24256
- function tElement(text8, name3 = "t") {
24257
- const encoded = escapeText3(encodeEscapes(text8));
24258
- const preserve = /^\s|\s$|\n|\t/.test(text8) ? ' xml:space="preserve"' : "";
24259
- return `<${name3}${preserve}>${encoded}</${name3}>`;
24260
- }
24261
- var MAIN_NS = ' xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"';
24262
- function inlineFragment(xml) {
24263
- const end = xml.indexOf(">");
24264
- if (end < 0) return xml;
24265
- const head = xml.slice(0, end);
24266
- return head.includes(MAIN_NS) ? head.replace(MAIN_NS, "") + xml.slice(end) : xml;
24267
- }
24268
24228
 
24269
24229
  // xlsx/pivot/columns.ts
24270
24230
  var SEPARATOR = "";
24271
- var label2 = pivotItemLabel;
24272
24231
  var columnKey = (keys, depth) => keys.slice(0, depth).join(SEPARATOR);
24273
24232
  var recordColumnKeys = (record2, indices) => indices.map((index3) => pivotValueKey(record2[index3] ?? null));
24274
24233
  function pivotColumnEntries(pivot) {
24275
24234
  const names = pivotColumnFields(pivot);
24276
24235
  const items = names.map((name3) => pivotItems(pivot, name3));
24277
24236
  const entries = [];
24237
+ const functions = names.map((name3) => fieldSubtotalFunctions(pivot, name3));
24278
24238
  if (names.length) {
24279
24239
  const order = items.map(
24280
24240
  (list2) => new Map(list2.map((item, index3) => [pivotValueKey(item), index3]))
@@ -24309,7 +24269,9 @@ function pivotColumnEntries(pivot) {
24309
24269
  if (level === names.length - 1) entries.push({ kind: "leaf", ...entry3 });
24310
24270
  else {
24311
24271
  visit2(child7[1], level + 1, here.path, here.values, here.keys);
24312
- entries.push({ kind: "subtotal", ...entry3 });
24272
+ const own2 = functions[level];
24273
+ if (own2 === "auto") entries.push({ kind: "subtotal", ...entry3 });
24274
+ else for (const fn of own2) entries.push({ kind: "subtotal", ...entry3, fn });
24313
24275
  }
24314
24276
  }
24315
24277
  };
@@ -24318,26 +24280,31 @@ function pivotColumnEntries(pivot) {
24318
24280
  entries.push({ kind: "grand", path: [], key: "", values: [] });
24319
24281
  return { names, items, entries };
24320
24282
  }
24321
- function pivotColumnDimensions(pivot, columns, labelColumns) {
24322
- const measures2 = 1 + (pivot.additionalValues?.length ?? 0);
24283
+ function pivotColumnDimensions(pivot, columns, labelColumns, valuesOnRows = false) {
24284
+ const measures2 = valuesOnRows ? 1 : 1 + (pivot.additionalValues?.length ?? 0);
24323
24285
  const levels = columns.names.length;
24324
24286
  return {
24325
24287
  rows: (levels ? levels + 1 + Number(measures2 > 1) : 1) + (pivot.pageFilter ? 2 : 0),
24326
24288
  width: labelColumns + (levels ? columns.entries.length : 1) * measures2
24327
24289
  };
24328
24290
  }
24329
- function pivotColumnHeaders(pivot, columns, rowLabels) {
24330
- const measures2 = pivotMeasures(pivot);
24291
+ function pivotColumnHeaders(pivot, columns, rowLabels, valuesOnRows = false) {
24292
+ const measures2 = valuesOnRows ? pivotMeasures(pivot).slice(0, 1) : pivotMeasures(pivot);
24331
24293
  const count2 = measures2.length;
24332
24294
  const levels = columns.names.length;
24333
- if (!levels) return [[...rowLabels, ...measures2.map((measure2) => measure2.caption)]];
24295
+ if (!levels)
24296
+ return [
24297
+ [...rowLabels, ...valuesOnRows ? [null] : measures2.map((measure2) => measure2.caption)]
24298
+ ];
24334
24299
  const compact3 = pivot.layout === "compact";
24335
24300
  const labelColumns = rowLabels.length;
24336
24301
  const width = labelColumns + columns.entries.length * count2;
24337
24302
  const rows = levels + 1 + Number(count2 > 1);
24338
24303
  const grid = Array.from({ length: rows }, () => Array(width).fill(null));
24339
- if (count2 === 1) grid[0][0] = pivot.valueCaption;
24340
- const titles = compact3 ? ["Column Labels"] : [...columns.names, ...count2 > 1 ? ["Values"] : []];
24304
+ if (count2 === 1 && !valuesOnRows) grid[0][0] = pivot.valueCaption;
24305
+ const caps = pivotCaptions(pivot);
24306
+ const labelOf = pivotItemLabeler(pivot);
24307
+ const titles = compact3 ? [caps.columnLabels] : [...columns.names, ...count2 > 1 ? [caps.values] : []];
24341
24308
  titles.forEach((title, i2) => {
24342
24309
  grid[0][labelColumns + i2] = title;
24343
24310
  });
@@ -24350,16 +24317,17 @@ function pivotColumnHeaders(pivot, columns, rowLabels) {
24350
24317
  if (entry3.kind === "leaf") {
24351
24318
  entry3.path.forEach((_index, level) => {
24352
24319
  const continued = entry3.path.slice(0, level + 1).every((p, i2) => p === previous[i2]);
24353
- if (!continued) grid[1 + level][at2] = label2(entry3.values[level]);
24320
+ if (!continued) grid[1 + level][at2] = labelOf(columns.names[level], entry3.values[level]);
24354
24321
  });
24355
24322
  previous = entry3.path;
24356
24323
  if (count2 > 1) measures2.forEach((measure2, m) => grid[rows - 1][at2 + m] = measure2.caption);
24357
24324
  return;
24358
24325
  }
24359
24326
  const row3 = entry3.kind === "grand" ? 1 : entry3.path.length;
24360
- const name3 = entry3.kind === "grand" ? "" : String(label2(entry3.values.at(-1)));
24327
+ const name3 = entry3.kind === "grand" ? "" : String(labelOf(columns.names[entry3.path.length - 1], entry3.values.at(-1)));
24361
24328
  measures2.forEach((measure2, m) => {
24362
- grid[row3][at2 + m] = count2 === 1 ? entry3.kind === "grand" ? "Grand Total" : `${name3} Total` : entry3.kind === "grand" ? `Total ${measure2.caption}` : `${name3} ${measure2.caption}`;
24329
+ const custom = entry3.fn ? caps.functions[entry3.fn] : void 0;
24330
+ grid[row3][at2 + m] = custom ? count2 === 1 ? `${name3} ${custom}` : `${name3} ${custom} of ${measure2.field}` : count2 === 1 ? entry3.kind === "grand" ? caps.grandTotal : fillCaption(caps.subtotal, name3) : entry3.kind === "grand" ? fillCaption(caps.measureTotal, measure2.caption) : `${name3} ${measure2.caption}`;
24363
24331
  });
24364
24332
  });
24365
24333
  return grid;
@@ -24384,7 +24352,7 @@ function pivotColumnItemsXml(entries, measures2, remap) {
24384
24352
  const prefix3 = sharedPrefix(path2, previous);
24385
24353
  const xs = path2.slice(prefix3).map((index3) => `<x${attrs2({ v: index3 || void 0 })}/>`);
24386
24354
  out.push(
24387
- `<i${attrs2({ t: entry3.kind === "subtotal" ? "default" : void 0, r: prefix3 || void 0, i: m || void 0 })}>${xs.join("")}</i>`
24355
+ `<i${attrs2({ t: entry3.kind === "subtotal" ? entry3.fn ? PIVOT_SUBTOTALS[entry3.fn].item : "default" : void 0, r: prefix3 || void 0, i: m || void 0 })}>${xs.join("")}</i>`
24388
24356
  );
24389
24357
  previous = path2;
24390
24358
  }
@@ -24392,7 +24360,6 @@ function pivotColumnItemsXml(entries, measures2, remap) {
24392
24360
  }
24393
24361
 
24394
24362
  // xlsx/pivot/nested.ts
24395
- var label3 = pivotItemLabel;
24396
24363
  var MAX_CELLS = 1e6;
24397
24364
  var node = (index3, value2) => ({
24398
24365
  index: index3,
@@ -24404,6 +24371,10 @@ var node = (index3, value2) => ({
24404
24371
  function nestedPivotGrid(pivot) {
24405
24372
  const names = pivotRowFields(pivot);
24406
24373
  const depth = names.length;
24374
+ const valuesAt = pivotValuesIndex(pivot);
24375
+ const onRows = valuesAt >= 0;
24376
+ const levels = depth + (onRows ? 1 : 0);
24377
+ const fieldOf = (level) => !onRows || level < valuesAt ? level : level === valuesAt ? -1 : level - 1;
24407
24378
  const axisItems = names.map((name3) => pivotItems(pivot, name3));
24408
24379
  const itemIndices = axisItems.map(
24409
24380
  (items) => new Map(items.map((item, index3) => [pivotValueKey(item), index3]))
@@ -24415,125 +24386,170 @@ function nestedPivotGrid(pivot) {
24415
24386
  const compact3 = layout3 === "compact";
24416
24387
  const tabular = layout3 === "tabular";
24417
24388
  const above = !tabular && (pivot.subtotalPosition ?? "top") === "top";
24418
- const labelColumns = compact3 ? 1 : depth;
24389
+ const labelColumns = compact3 ? 1 : levels;
24419
24390
  const measures2 = pivotMeasures(pivot);
24391
+ const functions = names.map((name3) => fieldSubtotalFunctions(pivot, name3));
24392
+ const caps = pivotCaptions(pivot);
24393
+ const labelOf = pivotItemLabeler(pivot);
24420
24394
  const root = node(0, null);
24421
24395
  for (const record2 of pivot.records) {
24422
24396
  const keys = recordColumnKeys(record2, columnFields);
24423
24397
  let current = root;
24424
- for (let level = -1; level < depth; level++) {
24425
- if (level >= 0) {
24426
- const value2 = record2[fieldIndices[level]] ?? null;
24398
+ for (let field2 = -1; field2 < depth; field2++) {
24399
+ if (field2 >= 0) {
24400
+ const value2 = record2[fieldIndices[field2]] ?? null;
24427
24401
  const key2 = pivotValueKey(value2);
24428
24402
  let child7 = current.children.get(key2);
24429
24403
  if (!child7) {
24430
- child7 = node(itemIndices[level].get(key2), value2);
24404
+ child7 = node(itemIndices[field2].get(key2), value2);
24431
24405
  current.children.set(key2, child7);
24432
24406
  }
24433
24407
  current = child7;
24434
24408
  }
24435
24409
  current.records.push(record2);
24436
- for (let width = 1; width <= keys.length; width++) {
24437
- const key2 = columnKey(keys, width);
24410
+ for (let width2 = 1; width2 <= keys.length; width2++) {
24411
+ const key2 = columnKey(keys, width2);
24438
24412
  const list2 = current.columns.get(key2);
24439
24413
  if (list2) list2.push(record2);
24440
24414
  else current.columns.set(key2, [record2]);
24441
24415
  }
24442
24416
  }
24443
24417
  }
24444
- const dimensions3 = pivotColumnDimensions(pivot, columns, labelColumns);
24445
- const functions = names.map((name3) => fieldSubtotalFunctions(pivot, name3));
24446
- let rows = 1;
24447
- const count2 = (parent, level) => {
24448
- for (const child7 of parent.children.values()) {
24449
- rows++;
24450
- if (level < depth - 1) {
24451
- const f6 = functions[level];
24452
- rows += f6 === "auto" ? 1 : f6.length;
24453
- count2(child7, level + 1);
24454
- }
24455
- }
24456
- };
24457
- count2(root, 0);
24458
- if ((rows + dimensions3.rows) * dimensions3.width > MAX_CELLS)
24459
- throw new Error("The PivotTable result is too large.");
24460
- const values2 = pivotColumnHeaders(pivot, columns, compact3 ? ["Row Labels"] : names);
24461
- const firstDataRow = values2.length;
24462
- const indents = values2.map(() => 0);
24418
+ const dimensions3 = pivotColumnDimensions(pivot, columns, labelColumns, onRows);
24419
+ const rowTitles = names.map((name3) => name3);
24420
+ if (onRows) rowTitles.splice(valuesAt, 0, caps.values);
24421
+ let values2 = [];
24422
+ let indents = [];
24463
24423
  const rowEntries = [];
24464
- const blanks = () => Array(dimensions3.width - labelColumns).fill(null);
24465
- const bands = (group, run2) => columns.entries.flatMap(
24466
- (entry3) => run2(entry3.kind === "grand" ? group.records : group.columns.get(entry3.key) ?? [])
24467
- );
24468
- const numbers3 = (group) => bands(group, (records) => pivotNumbers(pivot, records));
24469
- const subtotalNumbers = (group, fn) => bands(
24470
- group,
24471
- (records) => measures2.map((measure2) => aggregateValues(records, pivot.fields.indexOf(measure2.field), fn))
24472
- );
24473
- const labelCells = (path2, shown, text8) => {
24424
+ let counting = true;
24425
+ let rowCount = 0;
24426
+ const width = dimensions3.width - labelColumns;
24427
+ const blanks = () => Array(width).fill(null);
24428
+ const cells3 = (group, rowFn, measure2) => columns.entries.flatMap((entry3) => {
24429
+ const records = entry3.kind === "grand" ? group.records : group.columns.get(entry3.key) ?? [];
24430
+ const picked = measure2 === void 0 ? measures2 : [measures2[measure2]];
24431
+ if (rowFn && entry3.fn && rowFn !== entry3.fn) return picked.map(() => null);
24432
+ const fn = rowFn ?? entry3.fn;
24433
+ return picked.map(
24434
+ (one2) => fn ? aggregateValues(records, pivot.fields.indexOf(one2.field), fn) : pivotMeasureNumber(pivot, records, one2)
24435
+ );
24436
+ });
24437
+ const labelCells = (path2, shown, level, text8) => {
24474
24438
  if (compact3) return [text8];
24475
- const cells3 = Array(depth).fill(null);
24476
- path2.forEach((value2, level) => {
24477
- if (shown[level]) cells3[level] = label3(value2);
24439
+ const row3 = Array(levels).fill(null);
24440
+ path2.labels.forEach((value2, at2) => {
24441
+ if (shown[at2]) row3[at2] = value2;
24478
24442
  });
24479
- cells3[path2.length] = text8;
24480
- return cells3;
24443
+ row3[level] = text8;
24444
+ return row3;
24481
24445
  };
24482
- const push3 = (cells3, numbersOnRow, entry3, indent) => {
24483
- values2.push([...cells3, ...numbersOnRow]);
24446
+ const push3 = (indent, build3) => {
24447
+ if (counting) {
24448
+ if ((++rowCount + dimensions3.rows) * dimensions3.width > MAX_CELLS)
24449
+ throw new Error("The PivotTable result is too large.");
24450
+ return;
24451
+ }
24452
+ const [cells4, numbers3, entry3] = build3();
24453
+ values2.push([...cells4, ...numbers3]);
24484
24454
  rowEntries.push(entry3);
24485
24455
  indents.push(compact3 ? indent : 0);
24486
24456
  };
24487
- const emit = (parent, level, path2, indices, firsts) => {
24488
- const last = level === depth - 1;
24489
- const own2 = functions[level];
24490
- const children4 = [...parent.children.values()].sort((a2, b) => a2.index - b.index);
24457
+ const entryOf = (indices, measure2, type) => ({
24458
+ indices,
24459
+ ...measure2 !== void 0 ? { measure: measure2 } : {},
24460
+ ...type ? { type } : {}
24461
+ });
24462
+ const walk2 = (level, group, measure2, path2) => {
24463
+ const field2 = fieldOf(level);
24464
+ const last = level === levels - 1;
24465
+ const repeated = Array.from(
24466
+ { length: level },
24467
+ (_v, k) => !!pivot.repeatLabels && fieldOf(k) >= 0
24468
+ );
24469
+ const leafShown = (firsts) => repeated.map((repeat, k) => repeat || tabular && firsts.slice(k + 1).every(Boolean));
24470
+ if (field2 < 0) {
24471
+ measures2.forEach((one2, m) => {
24472
+ const here = {
24473
+ labels: [...path2.labels, one2.caption],
24474
+ indices: [...path2.indices, m],
24475
+ firsts: [...path2.firsts, m === 0]
24476
+ };
24477
+ if (last)
24478
+ return push3(level, () => [
24479
+ labelCells(path2, leafShown(here.firsts), level, one2.caption),
24480
+ cells3(group, void 0, m),
24481
+ entryOf(here.indices, m)
24482
+ ]);
24483
+ if (!tabular)
24484
+ push3(level, () => [
24485
+ labelCells(path2, repeated, level, one2.caption),
24486
+ blanks(),
24487
+ entryOf(here.indices, m)
24488
+ ]);
24489
+ walk2(level + 1, group, m, here);
24490
+ });
24491
+ return;
24492
+ }
24493
+ const own2 = functions[field2];
24494
+ const valuesAbove = !onRows || valuesAt < level;
24495
+ const showsValue = above && own2 === "auto" && valuesAbove;
24496
+ const children4 = [...group.children.values()].sort((a2, b) => a2.index - b.index);
24491
24497
  children4.forEach((child7, position2) => {
24492
- const here = [...path2, child7.value];
24493
- const at2 = [...indices, child7.index];
24494
- const firstHere = [...firsts, position2 === 0];
24495
- const repeated = Array(level).fill(!!pivot.repeatLabels);
24496
- if (last) {
24497
- const shown = repeated.map(
24498
- (repeat, k) => repeat || tabular && firstHere.slice(k + 1).every(Boolean)
24499
- );
24500
- push3(labelCells(path2, shown, label3(child7.value)), numbers3(child7), { indices: at2 }, level);
24501
- return;
24502
- }
24498
+ const here = {
24499
+ labels: [...path2.labels, labelOf(names[field2], child7.value)],
24500
+ indices: [...path2.indices, child7.index],
24501
+ firsts: [...path2.firsts, position2 === 0]
24502
+ };
24503
+ const text8 = labelOf(names[field2], child7.value);
24504
+ if (last)
24505
+ return push3(level, () => [
24506
+ labelCells(path2, leafShown(here.firsts), level, text8),
24507
+ cells3(child7, void 0, measure2),
24508
+ entryOf(here.indices, measure2)
24509
+ ]);
24503
24510
  if (!tabular)
24504
- push3(
24505
- labelCells(path2, repeated, label3(child7.value)),
24506
- own2 === "auto" && above ? numbers3(child7) : blanks(),
24507
- { indices: at2 },
24508
- level
24509
- );
24510
- emit(child7, level + 1, here, at2, firstHere);
24511
- const caption = String(label3(child7.value));
24511
+ push3(level, () => [
24512
+ labelCells(path2, repeated, level, text8),
24513
+ showsValue ? cells3(child7, void 0, measure2) : blanks(),
24514
+ entryOf(here.indices, measure2)
24515
+ ]);
24516
+ walk2(level + 1, child7, measure2, here);
24517
+ if (field2 === depth - 1) return;
24518
+ const caption = String(text8);
24519
+ const subtotal = (title, fn, one2) => push3(level, () => [
24520
+ labelCells(path2, repeated, level, title),
24521
+ cells3(child7, fn, one2),
24522
+ entryOf(here.indices, one2, fn ?? "default")
24523
+ ]);
24512
24524
  if (own2 === "auto") {
24513
- if (!above)
24514
- push3(
24515
- labelCells(path2, repeated, `${caption} Total`),
24516
- numbers3(child7),
24517
- { indices: at2, type: "default" },
24518
- level
24519
- );
24525
+ if (showsValue) return;
24526
+ if (valuesAbove) subtotal(fillCaption(caps.subtotal, caption), void 0, measure2);
24527
+ else measures2.forEach((one2, m) => subtotal(`${caption} ${one2.caption}`, void 0, m));
24520
24528
  } else
24521
24529
  for (const fn of own2)
24522
- push3(
24523
- labelCells(path2, repeated, `${caption} ${PIVOT_SUBTOTALS[fn].label}`),
24524
- subtotalNumbers(child7, fn),
24525
- { indices: at2, type: fn },
24526
- level
24527
- );
24530
+ if (valuesAbove) subtotal(`${caption} ${caps.functions[fn]}`, fn, measure2);
24531
+ else
24532
+ measures2.forEach(
24533
+ (one2, m) => subtotal(`${caption} ${caps.functions[fn]} of ${one2.field}`, fn, m)
24534
+ );
24528
24535
  });
24529
24536
  };
24530
- emit(root, 0, [], [], []);
24531
- push3(
24532
- compact3 ? ["Grand Total"] : ["Grand Total", ...Array(depth - 1).fill(null)],
24533
- numbers3(root),
24534
- { indices: [0], type: "grand" },
24535
- 0
24536
- );
24537
+ const grand = (text8, measure2) => push3(0, () => [
24538
+ compact3 ? [text8] : [text8, ...Array(levels - 1).fill(null)],
24539
+ cells3(root, void 0, measure2),
24540
+ entryOf([0], measure2, "grand")
24541
+ ]);
24542
+ const build2 = () => {
24543
+ walk2(0, root, void 0, { labels: [], indices: [], firsts: [] });
24544
+ if (onRows) measures2.forEach((one2, m) => grand(fillCaption(caps.measureTotal, one2.caption), m));
24545
+ else grand(caps.grandTotal);
24546
+ };
24547
+ build2();
24548
+ counting = false;
24549
+ values2 = pivotColumnHeaders(pivot, columns, compact3 ? [caps.rowLabels] : rowTitles, onRows);
24550
+ const firstDataRow = values2.length;
24551
+ indents = values2.map(() => 0);
24552
+ build2();
24537
24553
  return {
24538
24554
  values: values2,
24539
24555
  rowItems: axisItems[0],
@@ -24545,105 +24561,15 @@ function nestedPivotGrid(pivot) {
24545
24561
  rowEntries,
24546
24562
  firstDataRow,
24547
24563
  rowLabelColumns: labelColumns,
24548
- indents
24564
+ indents,
24565
+ ...onRows ? { firstHeaderRow: 1 } : {}
24549
24566
  };
24550
24567
  }
24551
24568
 
24552
24569
  // xlsx/pivot/aggregate.ts
24553
24570
  function pivotGrid(pivot) {
24554
24571
  validatePivotFields(pivot);
24555
- return prependPivotPage(pivotDataGrid(pivotPageProjection(pivot)), pivot);
24556
- }
24557
- function pivotDataGrid(pivot) {
24558
- if (pivot.valuesAxis !== "rows") return nestedPivotGrid(pivot);
24559
- if (pivot.secondRowField) return hierarchicalPivotGrid(pivot);
24560
- const rowItems = pivotItems(pivot, pivot.rowField);
24561
- const columnItems = pivot.columnField ? pivotItems(pivot, pivot.columnField) : [];
24562
- const compact3 = pivot.layout === "compact";
24563
- const headings = pivot.layout !== void 0 && pivot.layout !== "tabular";
24564
- const dimensions3 = pivotHeaderDimensions(pivot, columnItems.length, compact3 ? 1 : 2);
24565
- const dataRows = (rowItems.length + 1) * (1 + (pivot.additionalValues?.length ?? 0)) + (headings ? rowItems.length : 0);
24566
- if ((dataRows + dimensions3.rows) * dimensions3.width > 1e6)
24567
- throw new Error("The PivotTable result is too large.");
24568
- const label5 = pivotItemLabel;
24569
- const values2 = pivotHeaders(pivot, columnItems, [compact3 ? "Row Labels" : pivot.rowField], label5);
24570
- const rowField = pivot.fields.indexOf(pivot.rowField);
24571
- const colField = pivot.columnField ? pivot.fields.indexOf(pivot.columnField) : -1;
24572
- const groups = /* @__PURE__ */ new Map();
24573
- const cells3 = /* @__PURE__ */ new Map();
24574
- const columns = /* @__PURE__ */ new Map();
24575
- const collect = (map, key2, record2) => {
24576
- const found = map.get(key2);
24577
- if (found) found.push(record2);
24578
- else map.set(key2, [record2]);
24579
- };
24580
- for (const record2 of pivot.records) {
24581
- const key2 = pivotValueKey(record2[rowField] ?? null);
24582
- collect(groups, key2, record2);
24583
- if (pivot.columnField) {
24584
- const col = pivotValueKey(record2[colField] ?? null);
24585
- collect(columns, col, record2);
24586
- collect(cells3, JSON.stringify([key2, col]), record2);
24587
- }
24588
- }
24589
- const firstDataRow = values2.length;
24590
- const measures2 = pivotMeasures(pivot);
24591
- const rowEntries = [];
24592
- const indents = values2.map(() => 0);
24593
- const append = (caption, bands, index3, grand = false) => {
24594
- measures2.forEach((measure2, m) => {
24595
- values2.push([
24596
- ...compact3 ? [grand ? `Total ${measure2.caption}` : measure2.caption] : [
24597
- grand ? `Total ${measure2.caption}` : pivot.repeatLabels || !headings && m === 0 ? caption : null,
24598
- grand ? null : measure2.caption
24599
- ],
24600
- ...bands.map((band2) => band2[m] ?? null)
24601
- ]);
24602
- indents.push(compact3 && !grand ? 1 : 0);
24603
- rowEntries.push({
24604
- indices: grand ? [0] : [index3, m],
24605
- measure: m,
24606
- ...grand ? { type: "grand" } : {}
24607
- });
24608
- });
24609
- };
24610
- rowItems.forEach((item, index3) => {
24611
- const key2 = pivotValueKey(item);
24612
- if (headings) {
24613
- values2.push([label5(item), ...Array(dimensions3.width - 1).fill(null)]);
24614
- rowEntries.push({ indices: [index3] });
24615
- indents.push(0);
24616
- }
24617
- append(
24618
- label5(item),
24619
- [
24620
- ...columnItems.map(
24621
- (col) => pivotNumbers(pivot, cells3.get(JSON.stringify([key2, pivotValueKey(col)])) ?? [])
24622
- ),
24623
- pivotNumbers(pivot, groups.get(key2) ?? [])
24624
- ],
24625
- index3
24626
- );
24627
- });
24628
- append(
24629
- "Grand Total",
24630
- [
24631
- ...columnItems.map((col) => pivotNumbers(pivot, columns.get(pivotValueKey(col)) ?? [])),
24632
- pivotNumbers(pivot, pivot.records)
24633
- ],
24634
- 0,
24635
- true
24636
- );
24637
- return {
24638
- values: values2,
24639
- rowItems,
24640
- columnItems,
24641
- firstDataRow,
24642
- rowLabelColumns: compact3 ? 1 : 2,
24643
- indents,
24644
- firstHeaderRow: 1,
24645
- rowEntries
24646
- };
24572
+ return prependPivotPage(nestedPivotGrid(pivotPageProjection(pivot)), pivot);
24647
24573
  }
24648
24574
  function pivotTableAt(sheet, at2) {
24649
24575
  return sheet.pivotTables?.find((pivot) => rangeContains(pivot.location, at2));
@@ -24653,14 +24579,14 @@ function pivotTableAt(sheet, at2) {
24653
24579
  var X14 = "http://schemas.microsoft.com/office/spreadsheetml/2009/9/main";
24654
24580
  var LAYOUT = "http://schemas.microsoft.com/office/spreadsheetml/2016/pivotdefaultlayout";
24655
24581
  var TABLE = {
24656
- pivotTableDefinition: "name cacheId dataCaption dataOnRows dataPosition updatedVersion minRefreshableVersion createdVersion applyNumberFormats applyBorderFormats applyFontFormats applyPatternFormats applyAlignmentFormats applyWidthHeightFormats useAutoFormatting itemPrintTitles indent compact compactData outline outlineData multipleFieldFilters rowGrandTotals colGrandTotals",
24582
+ pivotTableDefinition: "name cacheId dataCaption grandTotalCaption rowHeaderCaption colHeaderCaption dataOnRows dataPosition updatedVersion minRefreshableVersion createdVersion applyNumberFormats applyBorderFormats applyFontFormats applyPatternFormats applyAlignmentFormats applyWidthHeightFormats useAutoFormatting itemPrintTitles indent compact compactData outline outlineData multipleFieldFilters rowGrandTotals colGrandTotals",
24657
24583
  location: "ref firstHeaderRow firstDataRow firstDataCol rowPageCount colPageCount",
24658
24584
  pageFields: "count",
24659
24585
  pageField: "fld item hier",
24660
24586
  pivotFields: "count",
24661
24587
  pivotField: "axis dataField compact outline showAll subtotalTop defaultSubtotal numFmtId sumSubtotal countASubtotal avgSubtotal maxSubtotal minSubtotal productSubtotal countSubtotal stdDevSubtotal stdDevPSubtotal varSubtotal varPSubtotal",
24662
24588
  items: "count",
24663
- item: "x t h",
24589
+ item: "x t h n",
24664
24590
  rowFields: "count",
24665
24591
  colFields: "count",
24666
24592
  field: "x",
@@ -24761,8 +24687,8 @@ function inspect(node3, profile, cache3) {
24761
24687
  }
24762
24688
  for (const child7 of elements(node3)) inspect(child7, profile, cache3);
24763
24689
  }
24764
- function assertPivotAdmission(table3, cache3) {
24765
- inspect(table3, TABLE, false);
24690
+ function assertPivotAdmission(table4, cache3) {
24691
+ inspect(table4, TABLE, false);
24766
24692
  inspect(cache3, CACHE, true);
24767
24693
  }
24768
24694
  function assertPivotRecords(records) {
@@ -24773,6 +24699,121 @@ function assertPivotRecords(records) {
24773
24699
  );
24774
24700
  }
24775
24701
 
24702
+ // xlsx/pivot/captions-read.ts
24703
+ var ATTRIBUTES2 = {
24704
+ rowHeaderCaption: "rowLabels",
24705
+ colHeaderCaption: "columnLabels",
24706
+ grandTotalCaption: "grandTotal",
24707
+ dataCaption: "values"
24708
+ };
24709
+ function readPivotCaptionAttributes(root) {
24710
+ const out = {};
24711
+ for (const [attribute4, key2] of Object.entries(ATTRIBUTES2)) {
24712
+ const text8 = att(root, attribute4);
24713
+ if (text8 !== void 0)
24714
+ out[key2] = decodeEscapes(text8);
24715
+ }
24716
+ return out;
24717
+ }
24718
+ function aggregateCaptionsOf(pivot) {
24719
+ const out = {};
24720
+ for (const measure2 of [
24721
+ { field: pivot.valueField, aggregate: pivot.aggregate, caption: pivot.valueCaption },
24722
+ ...pivot.additionalValues ?? []
24723
+ ]) {
24724
+ const at2 = measure2.caption.indexOf(measure2.field);
24725
+ if (at2 < 0 || measure2.caption === measure2.field) continue;
24726
+ const template = `${measure2.caption.slice(0, at2)}{0}${measure2.caption.slice(at2 + measure2.field.length)}`;
24727
+ if (template !== ENGLISH_PIVOT_CAPTIONS.aggregates[measure2.aggregate])
24728
+ out[measure2.aggregate] = template;
24729
+ }
24730
+ return Object.keys(out).length ? out : void 0;
24731
+ }
24732
+ var MARK = "";
24733
+ var SENTINELS = {
24734
+ rowLabels: `${MARK}R`,
24735
+ columnLabels: `${MARK}C`,
24736
+ grandTotal: `${MARK}G`,
24737
+ values: `${MARK}V`,
24738
+ all: `${MARK}A`,
24739
+ blank: `${MARK}B`,
24740
+ subtotal: `{0}${MARK}S`,
24741
+ measureTotal: `${MARK}M{0}`,
24742
+ functions: Object.fromEntries(
24743
+ Object.keys(ENGLISH_PIVOT_CAPTIONS.functions).map((fn) => [fn, `${MARK}F${fn}`])
24744
+ ),
24745
+ aggregates: ENGLISH_PIVOT_CAPTIONS.aggregates
24746
+ };
24747
+ function templateOf(cached6, arg) {
24748
+ if (!arg || !cached6.includes(arg)) return void 0;
24749
+ if (cached6.startsWith(arg)) return `{0}${cached6.slice(arg.length)}`;
24750
+ if (cached6.endsWith(arg)) return `${cached6.slice(0, -arg.length)}{0}`;
24751
+ const at2 = cached6.indexOf(arg);
24752
+ return `${cached6.slice(0, at2)}{0}${cached6.slice(at2 + arg.length)}`;
24753
+ }
24754
+ function inferPivotCaptions(pivot, sheet, named3) {
24755
+ const known = pivotCaptions({ captions: named3 });
24756
+ const probe = { ...SENTINELS };
24757
+ for (const key2 of Object.keys(named3))
24758
+ if (typeof named3[key2] === "string")
24759
+ probe[key2] = known[key2];
24760
+ const grid = pivotGrid({ ...pivot, captions: probe });
24761
+ const found = /* @__PURE__ */ new Map();
24762
+ const set = (key2, value2) => {
24763
+ if (value2 === void 0) return;
24764
+ const before = found.get(key2);
24765
+ found.set(key2, before === void 0 || before === value2 ? value2 : null);
24766
+ };
24767
+ grid.values.forEach(
24768
+ (line3, r) => line3.forEach((expected, c2) => {
24769
+ if (typeof expected !== "string" || !expected.includes(MARK)) return;
24770
+ const cached6 = getCell(
24771
+ sheet,
24772
+ pivot.location.start.row + r,
24773
+ pivot.location.start.col + c2
24774
+ )?.value;
24775
+ if (typeof cached6 !== "string") return;
24776
+ const kind = /\u0001([RCGVASMFB])(\w*)/.exec(expected);
24777
+ if (!kind) return;
24778
+ const at2 = kind.index;
24779
+ switch (kind[1]) {
24780
+ case "R":
24781
+ return set("rowLabels", cached6);
24782
+ case "C":
24783
+ return set("columnLabels", cached6);
24784
+ case "G":
24785
+ return set("grandTotal", cached6);
24786
+ case "V":
24787
+ return set("values", cached6);
24788
+ case "A":
24789
+ return set("all", cached6);
24790
+ case "B":
24791
+ return set("blank", cached6);
24792
+ case "S":
24793
+ return set("subtotal", templateOf(cached6, expected.slice(0, at2)));
24794
+ case "M":
24795
+ return set("measureTotal", templateOf(cached6, expected.slice(at2 + 2)));
24796
+ case "F": {
24797
+ const item = expected.slice(0, at2 - 1);
24798
+ const of = / of (.*)$/.exec(expected.slice(at2));
24799
+ const word = cached6.slice(item.length + 1, of ? cached6.length - of[0].length : void 0);
24800
+ if (cached6.startsWith(`${item} `) && (!of || cached6.endsWith(of[0])))
24801
+ set(`function:${kind[2]}`, word);
24802
+ }
24803
+ }
24804
+ })
24805
+ );
24806
+ const out = pivotCaptions({ captions: named3 });
24807
+ const functions = { ...out.functions };
24808
+ for (const [key2, value2] of found) {
24809
+ if (value2 === null) continue;
24810
+ if (key2.startsWith("function:")) functions[key2.slice(9)] = value2;
24811
+ else out[key2] = value2;
24812
+ }
24813
+ out.functions = functions;
24814
+ return trimmedCaptions(out);
24815
+ }
24816
+
24776
24817
  // xlsx/slicer/read-slicers.ts
24777
24818
  var TABLE_SLICER_URI = "{2F2917AC-EB37-4324-AD4E-5DD8C200BD13}";
24778
24819
  var X152 = "http://schemas.microsoft.com/office/spreadsheetml/2010/11/main";
@@ -24848,12 +24889,12 @@ function parseSlicerCache(xml, partName) {
24848
24889
  if (data) return void 0;
24849
24890
  const list2 = byLocal(root, "extLst");
24850
24891
  const ext = list2 ? elements(list2).find((node3) => node3.getAttribute("uri") === TABLE_SLICER_URI) : void 0;
24851
- const table3 = ext ? first(ext, "tableSlicerCache", X152) : void 0;
24852
- const tableId = numAttr(table3, "tableId");
24853
- const column2 = numAttr(table3, "column");
24854
- if (!table3 || tableId === void 0 || column2 === void 0) return void 0;
24892
+ const table4 = ext ? first(ext, "tableSlicerCache", X152) : void 0;
24893
+ const tableId = numAttr(table4, "tableId");
24894
+ const column2 = numAttr(table4, "column");
24895
+ if (!table4 || tableId === void 0 || column2 === void 0) return void 0;
24855
24896
  const cache3 = { ...common, source: { kind: "table", tableId, column: column2 } };
24856
- if (att(table3, "sortOrder") === "descending") cache3.sortOrder = "descending";
24897
+ if (att(table4, "sortOrder") === "descending") cache3.sortOrder = "descending";
24857
24898
  if (elements(root).some((node3) => node3.localName === "pivotTables")) return void 0;
24858
24899
  return cache3;
24859
24900
  }
@@ -24938,14 +24979,14 @@ function parseTimelineCache(xml, partName) {
24938
24979
  }
24939
24980
 
24940
24981
  // xlsx/slicer/table-filter.ts
24941
- function tableFilterBounds(table3) {
24982
+ function tableFilterBounds(table4) {
24942
24983
  return {
24943
- start: table3.range.start,
24944
- end: { ...table3.range.end, row: table3.range.end.row - (table3.totalsRow ? 1 : 0) }
24984
+ start: table4.range.start,
24985
+ end: { ...table4.range.end, row: table4.range.end.row - (table4.totalsRow ? 1 : 0) }
24945
24986
  };
24946
24987
  }
24947
- function tableAutoFilter(table3) {
24948
- const columns = table3.columns.flatMap(
24988
+ function tableAutoFilter(table4) {
24989
+ const columns = table4.columns.flatMap(
24949
24990
  (column2, offset2) => column2.filter ? [
24950
24991
  {
24951
24992
  offset: offset2,
@@ -24955,12 +24996,12 @@ function tableAutoFilter(table3) {
24955
24996
  ] : []
24956
24997
  );
24957
24998
  if (!columns.length) return void 0;
24958
- return { range: tableFilterBounds(table3), columns };
24999
+ return { range: tableFilterBounds(table4), columns };
24959
25000
  }
24960
- function applyTableFilter(workbook, sheet, table3) {
24961
- if (!table3.headerRow) return;
24962
- const bounds2 = tableFilterBounds(table3);
24963
- const filter2 = tableAutoFilter(table3);
25001
+ function applyTableFilter(workbook, sheet, table4) {
25002
+ if (!table4.headerRow) return;
25003
+ const bounds2 = tableFilterBounds(table4);
25004
+ const filter2 = tableAutoFilter(table4);
24964
25005
  for (let row3 = bounds2.start.row + 1; row3 <= bounds2.end.row; row3++) {
24965
25006
  const visible = !filter2 || rowMatchesFilter(workbook, sheet, row3, filter2);
24966
25007
  setRowFiltered(sheet, row3, !visible, !!filter2);
@@ -24968,8 +25009,8 @@ function applyTableFilter(workbook, sheet, table3) {
24968
25009
  }
24969
25010
  function readTableFilteredRows(workbook) {
24970
25011
  for (const sheet of workbook.sheets)
24971
- for (const table3 of sheet.tables) {
24972
- const filter2 = tableAutoFilter(table3);
25012
+ for (const table4 of sheet.tables) {
25013
+ const filter2 = tableAutoFilter(table4);
24973
25014
  if (!filter2) continue;
24974
25015
  for (let row3 = filter2.range.start.row + 1; row3 <= filter2.range.end.row; row3++) {
24975
25016
  const info = sheet.rowInfo.get(row3);
@@ -25088,9 +25129,9 @@ function settleSlicers(workbook, warn) {
25088
25129
  if (cache3.source.kind === "table") {
25089
25130
  const { tableId, column: column2 } = cache3.source;
25090
25131
  for (const sheet of workbook.sheets) {
25091
- const table3 = sheet.tables.find((entry3) => entry3.id === tableId);
25092
- if (table3)
25093
- return table3.headerRow && !table3.filterNotModeled && table3.columns.some((entry3) => entry3.sourceId === column2);
25132
+ const table4 = sheet.tables.find((entry3) => entry3.id === tableId);
25133
+ if (table4)
25134
+ return table4.headerRow && !table4.filterNotModeled && table4.columns.some((entry3) => entry3.sourceId === column2);
25094
25135
  }
25095
25136
  return false;
25096
25137
  }
@@ -25268,7 +25309,7 @@ function readFieldGroups(fields, names) {
25268
25309
  throw new Error("Unsupported pivot field group");
25269
25310
  const labels = children(list2, "s", NS.x).map((node3) => decodeEscapes(att(node3, "v") ?? ""));
25270
25311
  const expected = numberGroupLabels({ start, end, by });
25271
- if (elements(list2).length !== labels.length || labels.length !== expected.length || labels.some((label5, i2) => label5 !== expected[i2]))
25312
+ if (elements(list2).length !== labels.length || labels.length !== expected.length || labels.some((label2, i2) => label2 !== expected[i2]))
25272
25313
  throw new Error("Unsupported pivot group items");
25273
25314
  groups.push({ field: names[index3] ?? "", start, end, by });
25274
25315
  });
@@ -25346,14 +25387,18 @@ function readDateGroups(fields, count2, names, dateFields, records, date1904) {
25346
25387
  const expected = dateGroupRange(group, serials);
25347
25388
  if (!close(expected.start, start) || !close(expected.end, end))
25348
25389
  throw unsupported("stale range");
25390
+ const localized = {};
25349
25391
  for (const entry3 of list2) {
25350
- const labels = dateUnitLabels(entry3.unit, expected, dateGroupDays(group), date1904);
25392
+ const labels = englishDateUnitLabels(entry3.unit, expected, dateGroupDays(group), date1904);
25351
25393
  const node3 = first(first(entry3.node, "fieldGroup", NS.x), "groupItems", NS.x);
25352
25394
  const actual = children(node3, "s", NS.x).map((item) => decodeEscapes(att(item, "v") ?? ""));
25353
- if (att(entry3.node, "name") === void 0 || decodeEscapes(att(entry3.node, "name")) !== dateGroupFieldName(entry3.unit, field2) || elements(node3).length !== actual.length || actual.length !== labels.length || actual.some((label5, i2) => label5 !== labels[i2]))
25395
+ const name3 = decodeEscapes(att(entry3.node, "name") ?? "");
25396
+ if (!name3 || elements(node3).length !== actual.length || actual.length !== labels.length || actual.some((label2) => !label2) || new Set(actual).size !== actual.length)
25354
25397
  throw unsupported("group items");
25398
+ if (name3 !== dateGroupFieldName(entry3.unit, field2) || actual.some((l, i2) => l !== labels[i2]))
25399
+ localized[entry3.unit] = { name: name3, labels: actual };
25355
25400
  }
25356
- groups.push(group);
25401
+ groups.push(Object.keys(localized).length ? { ...group, localized } : group);
25357
25402
  }
25358
25403
  return groups;
25359
25404
  }
@@ -25406,12 +25451,32 @@ function readItemFilters(fields, names, shared) {
25406
25451
  return filters.length ? filters : void 0;
25407
25452
  }
25408
25453
 
25454
+ // xlsx/pivot/item-names-read.ts
25455
+ function readItemNames(tableFields, names, shared) {
25456
+ const out = [];
25457
+ tableFields.forEach((field2, index3) => {
25458
+ const list2 = first(field2, "items", NS.x);
25459
+ if (!list2 || index3 >= names.length) return;
25460
+ for (const item of children(list2, "item", NS.x)) {
25461
+ const name3 = att(item, "n");
25462
+ if (name3 === void 0) continue;
25463
+ const at2 = Number(att(item, "x"));
25464
+ const value2 = shared[index3]?.[at2];
25465
+ if (att(item, "t") !== void 0 || !Number.isInteger(at2) || value2 === void 0)
25466
+ throw new Error("Unsupported pivot item name");
25467
+ out.push({ field: names[index3], item: value2, name: decodeEscapes(name3) });
25468
+ }
25469
+ });
25470
+ return out;
25471
+ }
25472
+
25409
25473
  // xlsx/pivot/values-axis.ts
25410
25474
  function remapPivotRowEntries(entries, axes2) {
25411
25475
  return entries.map(
25412
25476
  (entry3) => entry3.type === "grand" ? entry3 : {
25413
25477
  ...entry3,
25414
25478
  indices: entry3.indices.map((item, axis) => {
25479
+ if (axes2[axis] === null) return item;
25415
25480
  const index3 = axes2[axis]?.[item];
25416
25481
  if (index3 === void 0) throw new Error("Invalid report row axis item");
25417
25482
  return index3;
@@ -25430,7 +25495,7 @@ function pivotValueIndex(root, axis) {
25430
25495
  const position2 = root.getAttribute("dataPosition");
25431
25496
  if (position2 !== null && (!/^\d+$/.test(position2.trim()) || Number(position2) !== index3))
25432
25497
  throw new Error("Inconsistent Values axis position");
25433
- if (axis.length === 3 && index3 >= 0 && index3 < 2 && position2 === null)
25498
+ if (index3 >= 0 && index3 < axis.length - 1 && position2 === null)
25434
25499
  throw new Error("Missing leading or between-field Values position");
25435
25500
  return index3;
25436
25501
  }
@@ -25445,7 +25510,7 @@ function pivotValueAxisItems(measures2) {
25445
25510
  function supportedPivotAxes(rows, columns, measures2, valuesOnRows) {
25446
25511
  const index3 = pivotFieldIndex;
25447
25512
  if (valuesOnRows)
25448
- return measures2 > 1 && (rows.length === 2 || rows.length === 3) && (index3(rows[0]) >= 0 || rows.length === 3) && rows.filter((field2) => index3(field2) === -2).length === 1 && rows.filter((field2) => index3(field2) !== -2).every((field2) => index3(field2) >= 0) && columns.length <= 1 && (!columns.length || index3(columns[0]) >= 0);
25513
+ return measures2 > 1 && rows.length > 1 && rows.filter((field2) => index3(field2) === -2).length === 1 && rows.filter((field2) => index3(field2) !== -2).every((field2) => index3(field2) >= 0) && columns.every((field2) => index3(field2) >= 0);
25449
25514
  if (rows.some((field2) => !Number.isInteger(index3(field2)) || index3(field2) < 0)) return false;
25450
25515
  if (measures2 > 1 && (!columns.length || index3(columns.at(-1)) !== -2)) return false;
25451
25516
  return (measures2 > 1 ? columns.slice(0, -1) : columns).every(
@@ -25466,6 +25531,9 @@ function assertPageAxisItems(root, pivot, shared, cache3, recordRoot) {
25466
25531
  literals(cache3);
25467
25532
  literals(recordRoot);
25468
25533
  const cacheFields = children(first(cache3, "cacheFields", NS.x), "cacheField", NS.x);
25534
+ const all2 = expandDateGroups(pivot).fields;
25535
+ const derived = all2.slice(pivot.fields.length).map((name3) => groupLabelsOf(pivot, name3) ?? []);
25536
+ const sharedAll = [...shared, ...derived];
25469
25537
  if (pivot.columnField) {
25470
25538
  const column2 = children(first(root, "pivotFields", NS.x), "pivotField", NS.x)[pivot.fields.indexOf(pivot.columnField)];
25471
25539
  const list2 = first(column2, "extLst", NS.x);
@@ -25484,13 +25552,13 @@ function assertPageAxisItems(root, pivot, shared, cache3, recordRoot) {
25484
25552
  ))
25485
25553
  throw new Error("Repeated report column labels are preserved");
25486
25554
  }
25487
- if (integer3(first(cache3, "cacheFields", NS.x)?.getAttribute("count") ?? null) !== pivot.fields.length || integer3(cache3.getAttribute("recordCount")) !== pivot.records.length || integer3(recordRoot.getAttribute("count")) !== pivot.records.length)
25555
+ if (integer3(first(cache3, "cacheFields", NS.x)?.getAttribute("count") ?? null) !== all2.length || integer3(cache3.getAttribute("recordCount")) !== pivot.records.length || integer3(recordRoot.getAttribute("count")) !== pivot.records.length)
25488
25556
  throw new Error("Inconsistent report cache counts");
25489
25557
  for (const name3 of [...pivotRowFields(pivot), pivot.columnField, pivot.pageFilter.field].filter(
25490
25558
  Boolean
25491
25559
  )) {
25492
- const field2 = pivot.fields.indexOf(name3);
25493
- if (integer3(first(cacheFields[field2], "sharedItems", NS.x)?.getAttribute("count") ?? null) !== shared[field2].length)
25560
+ const field2 = all2.indexOf(name3);
25561
+ if (field2 < pivot.fields.length && integer3(first(cacheFields[field2], "sharedItems", NS.x)?.getAttribute("count") ?? null) !== shared[field2].length)
25494
25562
  throw new Error("Inconsistent report shared-item counts");
25495
25563
  }
25496
25564
  for (const name3 of ["rowFields", "colFields"]) {
@@ -25500,7 +25568,7 @@ function assertPageAxisItems(root, pivot, shared, cache3, recordRoot) {
25500
25568
  }
25501
25569
  const projected = pivotPageProjection(pivot), fields = children(first(root, "pivotFields", NS.x), "pivotField", NS.x);
25502
25570
  const axisValues = (name3, axis) => {
25503
- const f6 = pivot.fields.indexOf(name3), node3 = fields[f6], list2 = first(node3, "items", NS.x), items = children(list2, "item", NS.x), count2 = shared[f6].length;
25571
+ const f6 = all2.indexOf(name3), node3 = fields[f6], list2 = first(node3, "items", NS.x), items = children(list2, "item", NS.x), count2 = sharedAll[f6].length;
25504
25572
  if (node3.getAttribute("axis") !== axis) throw new Error("Inconsistent report axis field");
25505
25573
  const defaults = node3.getAttribute("defaultSubtotal") !== "0";
25506
25574
  if (!list2 || integer3(list2.getAttribute("count")) !== items.length || items.length !== count2 + Number(defaults))
@@ -25509,7 +25577,7 @@ function assertPageAxisItems(root, pivot, shared, cache3, recordRoot) {
25509
25577
  const i2 = integer3(item.getAttribute("x"));
25510
25578
  if (item.hasAttribute("t") || !Number.isInteger(i2) || i2 >= count2)
25511
25579
  throw new Error("Invalid page-axis cache item");
25512
- return shared[f6][i2];
25580
+ return sharedAll[f6][i2];
25513
25581
  });
25514
25582
  if (new Set(data.map(pivotValueKey)).size !== count2 || defaults && (items.at(-1)?.getAttribute("t") !== "default" || items.at(-1)?.hasAttribute("x")))
25515
25583
  throw new Error("Invalid page-axis default item");
@@ -25524,7 +25592,10 @@ function assertPageAxisItems(root, pivot, shared, cache3, recordRoot) {
25524
25592
  };
25525
25593
  const rowAxes = pivotRowFields(pivot).map((name3) => axisValues(name3, "axisRow")), rowItems = read("rowItems");
25526
25594
  const grid = pivotGrid(pivot);
25527
- const entries = grid.rowEntries ? remapPivotRowEntries(grid.rowEntries, rowAxes) : [
25595
+ const valuesAt = pivotValuesIndex(pivot);
25596
+ const levelAxes = [...rowAxes];
25597
+ if (valuesAt >= 0) levelAxes.splice(valuesAt, 0, null);
25598
+ const entries = grid.rowEntries ? remapPivotRowEntries(grid.rowEntries, levelAxes) : [
25528
25599
  ...rowAxes[0].map((index3) => ({ indices: [index3] })),
25529
25600
  { indices: [0], type: "grand" }
25530
25601
  ];
@@ -25534,11 +25605,11 @@ function assertPageAxisItems(root, pivot, shared, cache3, recordRoot) {
25534
25605
  const expected2 = entries[i2];
25535
25606
  const xs = children(item, "x", NS.x).map((x) => integer3(x.getAttribute("v"), 0)), prefix3 = integer3(item.getAttribute("r"), 0);
25536
25607
  const type = expected2.type === void 0 || expected2.type === "default" || expected2.type === "grand" ? expected2.type : PIVOT_SUBTOTALS[expected2.type].item;
25537
- if (item.getAttribute("t") !== (type ?? null) || !Number.isInteger(prefix3) || prefix3 < 0 || prefix3 > previousRow.length || prefix3 >= expected2.indices.length || expected2.type === "grand" && prefix3 !== 0 || integer3(item.getAttribute("i"), 0) !== 0 || JSON.stringify([...previousRow.slice(0, prefix3), ...xs]) !== JSON.stringify(expected2.indices))
25608
+ if (item.getAttribute("t") !== (type ?? null) || !Number.isInteger(prefix3) || prefix3 < 0 || prefix3 > previousRow.length || prefix3 >= expected2.indices.length || expected2.type === "grand" && prefix3 !== 0 || integer3(item.getAttribute("i"), 0) !== (expected2.measure ?? 0) || JSON.stringify([...previousRow.slice(0, prefix3), ...xs]) !== JSON.stringify(expected2.indices))
25538
25609
  throw new Error("Unmodeled page row item");
25539
25610
  previousRow = expected2.type === "grand" ? [] : expected2.indices;
25540
25611
  });
25541
- const measures2 = 1 + (pivot.additionalValues?.length ?? 0), columns = pivot.columnField ? axisValues(pivot.columnField, "axisCol") : void 0, expected = [];
25612
+ const measures2 = valuesAt >= 0 ? 1 : 1 + (pivot.additionalValues?.length ?? 0), columns = pivot.columnField ? axisValues(pivot.columnField, "axisCol") : void 0, expected = [];
25542
25613
  if (columns)
25543
25614
  for (const col of columns)
25544
25615
  for (let m = 0; m < measures2; m++) expected.push(measures2 > 1 ? [col, m] : [col]);
@@ -25580,6 +25651,10 @@ function value(node3, date1904 = false) {
25580
25651
  if (node3.localName === "e" && isErrorCode(v)) return { error: v };
25581
25652
  throw new Error("Unsupported pivot cache item");
25582
25653
  }
25654
+ var namedAggregates = (pivot) => {
25655
+ const aggregates = aggregateCaptionsOf(pivot);
25656
+ return aggregates ? { aggregates } : {};
25657
+ };
25583
25658
  function readOne(workbook, source2, part) {
25584
25659
  const xml = source2.text(part);
25585
25660
  const root = parseXml(xml).documentElement;
@@ -25645,7 +25720,7 @@ function readOne(workbook, source2, part) {
25645
25720
  "dataField",
25646
25721
  NS.x
25647
25722
  );
25648
- if (rowFields.length < 1 || rowsAxis && rowFields.length > 3 || dataFields.length < 1 || dataFields.length > 16 || !supportedPivotAxes(rowFields, colFields, dataFields.length, rowsAxis) || root.getAttribute("rowGrandTotals") === "0" || root.getAttribute("colGrandTotals") === "0")
25723
+ if (rowFields.length < 1 || dataFields.length < 1 || dataFields.length > 16 || !supportedPivotAxes(rowFields, colFields, dataFields.length, rowsAxis) || root.getAttribute("rowGrandTotals") === "0" || root.getAttribute("colGrandTotals") === "0")
25649
25724
  throw new Error("Unsupported pivot layout");
25650
25725
  const valueIndex = pivotValueIndex(root, rowsAxis ? rowFields : colFields);
25651
25726
  const measure2 = dataFields[0];
@@ -25715,8 +25790,8 @@ function readOne(workbook, source2, part) {
25715
25790
  const col = columnNames[0];
25716
25791
  const moreColumns = columnNames.slice(1);
25717
25792
  const columnDefinitions = columnDefs.map((field2) => tableFields[Number(att(field2, "x"))]);
25718
- if (fieldSubtotalsOf(columnDefinitions.slice(0, -1), columnNames.slice(0, -1)).length || columnNames.some((name3) => !name3))
25719
- throw new Error("Column subtotal settings are preserved");
25793
+ if (columnNames.some((name3) => !name3)) throw new Error("Invalid pivot column fields");
25794
+ const columnSubtotals = fieldSubtotalsOf(columnDefinitions, columnNames);
25720
25795
  const data = names[Number(att(measure2, "fld"))];
25721
25796
  const location = parseRange(att(first(root, "location", NS.x), "ref") ?? "");
25722
25797
  if (!row3 || !data || !location || hasColumn && !col || realRows.length === 2 && !second)
@@ -25726,6 +25801,7 @@ function readOne(workbook, source2, part) {
25726
25801
  location.start.row -= 2;
25727
25802
  }
25728
25803
  const itemFilters = readItemFilters(tableFields, names, shared);
25804
+ const itemNames = readItemNames(tableFields, names, shared);
25729
25805
  const slicerCacheId = readSlicerCacheId(cache3);
25730
25806
  const fieldGroups = readFieldGroups(fields, names);
25731
25807
  const dateFields = readDateFields(fields, names);
@@ -25757,11 +25833,14 @@ function readOne(workbook, source2, part) {
25757
25833
  ]);
25758
25834
  if (dateFields.some((field2) => onAxis.has(field2)))
25759
25835
  throw new Error("Date fields used as rows, columns or values are preserved");
25760
- if ([...realRows, ...columnDefs].some((field2) => pivotFieldIndex(field2) >= databaseCount) && (pageFilter || dateFilter || itemFilters || slicerCacheId !== void 0))
25761
- throw new Error("Date groups with filters are preserved");
25836
+ const fieldSubtotals = [
25837
+ ...subtotalSettings.filter((entry4) => entry4.field !== row3 || entry4.functions.length),
25838
+ ...columnSubtotals
25839
+ ];
25762
25840
  const pivot = {
25763
25841
  ...pageFilter ? { pageFilter } : {},
25764
25842
  ...itemFilters ? { itemFilters } : {},
25843
+ ...itemNames.length ? { itemNames } : {},
25765
25844
  ...fieldGroups.length ? { fieldGroups } : {},
25766
25845
  ...dateFields.length ? { dateFields } : {},
25767
25846
  ...dateGroups.length ? { dateGroups } : {},
@@ -25773,13 +25852,11 @@ function readOne(workbook, source2, part) {
25773
25852
  rowField: row3,
25774
25853
  layout: layout3,
25775
25854
  ...rowsAxis ? { valuesAxis: "rows" } : {},
25776
- ...rowsAxis && realRows.length === 2 && valueIndex < 2 ? { valuesPosition: valueIndex === 0 ? "first" : "between" } : {},
25777
- subtotalPosition: att(outer, "subtotalTop") === "0" ? "bottom" : "top",
25778
- ...subtotalSettings.some((entry4) => entry4.field !== row3 || entry4.functions.length) ? {
25779
- fieldSubtotals: subtotalSettings.filter(
25780
- (entry4) => entry4.field !== row3 || entry4.functions.length
25781
- )
25855
+ ...rowsAxis && valueIndex < realRows.length ? {
25856
+ valuesPosition: valueIndex === 0 ? "first" : valueIndex === 1 && realRows.length === 2 ? "between" : valueIndex
25782
25857
  } : {},
25858
+ subtotalPosition: att(outer, "subtotalTop") === "0" ? "bottom" : "top",
25859
+ ...fieldSubtotals.length ? { fieldSubtotals } : {},
25783
25860
  ...more.length ? { moreRowFields: more } : {},
25784
25861
  ...second ? { secondRowField: second, subtotals: subtotal, repeatLabels: repeat[0] ?? false } : {
25785
25862
  ...subtotal ? {} : { subtotals: false },
@@ -25806,6 +25883,12 @@ function readOne(workbook, source2, part) {
25806
25883
  ...col ? { columnField: col } : {},
25807
25884
  ...moreColumns.length ? { moreColumnFields: moreColumns } : {}
25808
25885
  };
25886
+ const captions = trimmedCaptions(
25887
+ pivotCaptions({
25888
+ captions: { ...readPivotCaptionAttributes(root), ...namedAggregates(pivot) }
25889
+ })
25890
+ );
25891
+ if (captions) pivot.captions = captions;
25809
25892
  if (pageFilter && moreColumns.length) throw new Error("Report filters support one column field");
25810
25893
  assertPageAxisItems(root, pivot, shared, cache3, recordRoot);
25811
25894
  return pivot;
@@ -25833,6 +25916,12 @@ function readPivotTables(workbook, source2, warn, slicers) {
25833
25916
  if (slicers.blocked.has(pivotKey(sheet.sheetId, name3)) || cache3 && (caches2.get(cache3) ?? 0) > 1)
25834
25917
  throw new Error("Shared pivot cache or unsupported slicer connection");
25835
25918
  const pivot = readOne(workbook, source2, part);
25919
+ const inferred = inferPivotCaptions(pivot, sheet, {
25920
+ ...readPivotCaptionAttributes(parseXml(pivot.sourceXml).documentElement),
25921
+ ...namedAggregates(pivot)
25922
+ });
25923
+ if (inferred) pivot.captions = inferred;
25924
+ else delete pivot.captions;
25836
25925
  const grid = pivotGrid(pivot);
25837
25926
  if (grid.values.length !== pivot.location.end.row - pivot.location.start.row + 1 || grid.values[0].length !== pivot.location.end.col - pivot.location.start.col + 1 || grid.values.some(
25838
25927
  (line3, r) => line3.some(
@@ -26472,7 +26561,7 @@ function mergeSpacedAreas(tokens3) {
26472
26561
  }
26473
26562
  return out;
26474
26563
  }
26475
- function templateOf(formula) {
26564
+ function templateOf2(formula) {
26476
26565
  const cached6 = templates.get(formula);
26477
26566
  if (cached6 !== void 0) return cached6;
26478
26567
  const raw2 = safeTokens(formula);
@@ -26502,7 +26591,7 @@ function templateOf(formula) {
26502
26591
  return template;
26503
26592
  }
26504
26593
  function rewriteTemplate(formula, rewrite2) {
26505
- const template = templateOf(formula);
26594
+ const template = templateOf2(formula);
26506
26595
  if (!template) return formula;
26507
26596
  let next;
26508
26597
  for (let i2 = 0; i2 < template.length; i2++) {
@@ -27803,14 +27892,14 @@ function readDataTable(f6) {
27803
27892
  const ref = parseRange(att(f6, "ref") ?? "");
27804
27893
  const r1 = att(f6, "r1");
27805
27894
  if (!ref || !r1) return void 0;
27806
- const table3 = { ref, r1 };
27895
+ const table4 = { ref, r1 };
27807
27896
  const r2 = att(f6, "r2");
27808
- if (r2) table3.r2 = r2;
27809
- if (boolAttr(f6, "dt2D")) table3.dt2D = true;
27810
- if (boolAttr(f6, "dtr")) table3.dtr = true;
27811
- if (boolAttr(f6, "del1")) table3.del1 = true;
27812
- if (boolAttr(f6, "del2")) table3.del2 = true;
27813
- return table3;
27897
+ if (r2) table4.r2 = r2;
27898
+ if (boolAttr(f6, "dt2D")) table4.dt2D = true;
27899
+ if (boolAttr(f6, "dtr")) table4.dtr = true;
27900
+ if (boolAttr(f6, "del1")) table4.del1 = true;
27901
+ if (boolAttr(f6, "del2")) table4.del2 = true;
27902
+ return table4;
27814
27903
  }
27815
27904
  function readFormula(ctx, f6, row3, col, cell, masters, dynamic2, anchors, sheet) {
27816
27905
  const kind = att(f6, "t") ?? "normal";
@@ -27834,8 +27923,8 @@ function readFormula(ctx, f6, row3, col, cell, masters, dynamic2, anchors, sheet
27834
27923
  }
27835
27924
  if (kind === "dataTable") {
27836
27925
  delete cell.legacyFormula;
27837
- const table3 = readDataTable(f6);
27838
- if (table3) (sheet.dataTables ??= []).push(table3);
27926
+ const table4 = readDataTable(f6);
27927
+ if (table4) (sheet.dataTables ??= []).push(table4);
27839
27928
  else ctx.warn("A what-if data table formula could not be read; its cached values were kept.");
27840
27929
  return;
27841
27930
  }
@@ -28027,14 +28116,14 @@ function parseTable3(xml, partName) {
28027
28116
  if (id3 !== void 0 && Number.isInteger(id3) && id3 >= 0) column2.sourceId = id3;
28028
28117
  const fn = att(node3, "totalsRowFunction");
28029
28118
  if (fn && fn !== "none") column2.totalsRowFunction = fn;
28030
- const label5 = att(node3, "totalsRowLabel");
28031
- if (label5 !== void 0) column2.totalsRowLabel = label5;
28119
+ const label2 = att(node3, "totalsRowLabel");
28120
+ if (label2 !== void 0) column2.totalsRowLabel = label2;
28032
28121
  const calculated = xFirst(node3, "calculatedColumnFormula");
28033
28122
  if (calculated) column2.calculatedColumnFormula = stripFuturePrefixes(xText(calculated));
28034
28123
  return column2;
28035
28124
  }
28036
28125
  );
28037
- const table3 = {
28126
+ const table4 = {
28038
28127
  id: numAttr(root, "id") ?? 1,
28039
28128
  name: name3,
28040
28129
  displayName: att(root, "displayName") ?? name3,
@@ -28044,26 +28133,26 @@ function parseTable3(xml, partName) {
28044
28133
  columns,
28045
28134
  partName
28046
28135
  };
28047
- readColumnFilters(root, table3);
28136
+ readColumnFilters(root, table4);
28048
28137
  const info = xFirst(root, "tableStyleInfo");
28049
28138
  if (info) {
28050
28139
  const style3 = att(info, "name");
28051
- if (style3) table3.styleName = style3;
28052
- table3.showRowStripes = boolAttr(info, "showRowStripes", false);
28053
- table3.showColumnStripes = boolAttr(info, "showColumnStripes", false);
28054
- table3.showFirstColumn = boolAttr(info, "showFirstColumn", false);
28055
- table3.showLastColumn = boolAttr(info, "showLastColumn", false);
28140
+ if (style3) table4.styleName = style3;
28141
+ table4.showRowStripes = boolAttr(info, "showRowStripes", false);
28142
+ table4.showColumnStripes = boolAttr(info, "showColumnStripes", false);
28143
+ table4.showFirstColumn = boolAttr(info, "showFirstColumn", false);
28144
+ table4.showLastColumn = boolAttr(info, "showLastColumn", false);
28056
28145
  }
28057
- return table3;
28146
+ return table4;
28058
28147
  }
28059
- function readColumnFilters(root, table3) {
28148
+ function readColumnFilters(root, table4) {
28060
28149
  const filter2 = xFirst(root, "autoFilter");
28061
28150
  for (const node3 of filter2 ? xChildren(filter2, "filterColumn") : []) {
28062
- const column2 = table3.columns[numAttr(node3, "colId") ?? -1];
28151
+ const column2 = table4.columns[numAttr(node3, "colId") ?? -1];
28063
28152
  const filters = xChildren(node3, "filters");
28064
28153
  const simple = column2 && isValueListFilterColumn(node3);
28065
28154
  if (!simple) {
28066
- table3.filterNotModeled = true;
28155
+ table4.filterNotModeled = true;
28067
28156
  continue;
28068
28157
  }
28069
28158
  const values2 = xChildren(filters[0], "filter").map((child7) => att(child7, "val") ?? "");
@@ -28142,8 +28231,8 @@ function readTables(ctx, partName, node3, sheet) {
28142
28231
  const rel = rels.get(relAttr(part, "id") ?? "");
28143
28232
  const target2 = rel ? ctx.source.target(partName, rel) : void 0;
28144
28233
  const xml = target2 ? ctx.source.text(target2) : void 0;
28145
- const table3 = target2 && xml ? parseTable3(xml, target2) : void 0;
28146
- if (table3) sheet.tables.push(table3);
28234
+ const table4 = target2 && xml ? parseTable3(xml, target2) : void 0;
28235
+ if (table4) sheet.tables.push(table4);
28147
28236
  else ctx.warn("A table part could not be read and was dropped.");
28148
28237
  }
28149
28238
  }
@@ -30613,14 +30702,14 @@ function unique(args, ctx) {
30613
30702
  const byCol = args.length > 1 && args[1] !== null && toBool(ctx.toScalar(args[1] ?? null));
30614
30703
  const once = args.length > 2 && args[2] !== null && toBool(ctx.toScalar(args[2] ?? null));
30615
30704
  if (byCol) m = transpose(m);
30616
- const keyOf2 = (row3) => JSON.stringify(
30705
+ const keyOf3 = (row3) => JSON.stringify(
30617
30706
  row3.map(
30618
30707
  (v) => isError(v) ? `#${v.error}` : typeof v === "string" ? `s${v.toLowerCase()}` : v
30619
30708
  )
30620
30709
  );
30621
30710
  const counts = /* @__PURE__ */ new Map();
30622
30711
  for (const row3 of m.data) {
30623
- const key2 = keyOf2(row3);
30712
+ const key2 = keyOf3(row3);
30624
30713
  const entry3 = counts.get(key2);
30625
30714
  if (entry3) entry3.count++;
30626
30715
  else counts.set(key2, { row: row3, count: 1 });
@@ -30905,30 +30994,30 @@ function gammaLn(z) {
30905
30994
 
30906
30995
  // xlsx/formula/functions/database.ts
30907
30996
  var C3 = "Database";
30908
- var label4 = (value2) => value2 === null ? "" : typeof value2 === "string" ? value2 : String(value2);
30997
+ var label = (value2) => value2 === null ? "" : typeof value2 === "string" ? value2 : String(value2);
30909
30998
  function tableOf(ctx, value2) {
30910
30999
  const [head, ...records] = ctx.toMatrix(value2 ?? null).data;
30911
31000
  if (!head || records.length === 0) fail(ERR.VALUE);
30912
- return { headers: head.map((v) => label4(v).toLowerCase()), records };
31001
+ return { headers: head.map((v) => label(v).toLowerCase()), records };
30913
31002
  }
30914
- function fieldIndex(table3, field2) {
31003
+ function fieldIndex(table4, field2) {
30915
31004
  const value2 = scalar2(field2);
30916
31005
  if (isError(value2)) fail(value2);
30917
31006
  if (typeof value2 === "number") {
30918
31007
  const index4 = Math.trunc(value2) - 1;
30919
- if (index4 < 0 || index4 >= table3.headers.length) fail(ERR.VALUE);
31008
+ if (index4 < 0 || index4 >= table4.headers.length) fail(ERR.VALUE);
30920
31009
  return index4;
30921
31010
  }
30922
- const index3 = table3.headers.indexOf(label4(value2).toLowerCase());
31011
+ const index3 = table4.headers.indexOf(label(value2).toLowerCase());
30923
31012
  if (index3 < 0) fail(ERR.VALUE);
30924
31013
  return index3;
30925
31014
  }
30926
- function recordFilter(table3, criteria) {
31015
+ function recordFilter(table4, criteria) {
30927
31016
  const [head, ...rows] = criteria;
30928
31017
  if (!head || rows.length === 0) fail(ERR.VALUE);
30929
31018
  const columns = head.map((name3) => {
30930
31019
  if (name3 === null || name3 === "") return -1;
30931
- return table3.headers.indexOf(label4(name3).toLowerCase());
31020
+ return table4.headers.indexOf(label(name3).toLowerCase());
30932
31021
  });
30933
31022
  const alternatives = rows.map(
30934
31023
  (row3) => row3.flatMap((cell, c2) => {
@@ -30942,10 +31031,10 @@ function recordFilter(table3, criteria) {
30942
31031
  return (record2) => alternatives.some((tests) => tests.every((test) => test(record2)));
30943
31032
  }
30944
31033
  function selected(ctx, args) {
30945
- const table3 = tableOf(ctx, args[0]);
30946
- const column2 = fieldIndex(table3, args[1]);
30947
- const matches2 = recordFilter(table3, ctx.toMatrix(args[2] ?? null).data);
30948
- return table3.records.filter(matches2).map((record2) => record2[column2] ?? null);
31034
+ const table4 = tableOf(ctx, args[0]);
31035
+ const column2 = fieldIndex(table4, args[1]);
31036
+ const matches2 = recordFilter(table4, ctx.toMatrix(args[2] ?? null).data);
31037
+ return table4.records.filter(matches2).map((record2) => record2[column2] ?? null);
30949
31038
  }
30950
31039
  var numbers = (values2) => {
30951
31040
  for (const v of values2) if (isError(v)) fail(v);
@@ -31773,9 +31862,9 @@ var BESSEL_FUNCTIONS = [
31773
31862
  ];
31774
31863
 
31775
31864
  // xlsx/formula/functions/convert.ts
31776
- var table = /* @__PURE__ */ new Map();
31865
+ var table2 = /* @__PURE__ */ new Map();
31777
31866
  var add3 = (dimension3, names, factor, extra = {}) => {
31778
- for (const name3 of names) table.set(name3, { dimension: dimension3, factor, ...extra });
31867
+ for (const name3 of names) table2.set(name3, { dimension: dimension3, factor, ...extra });
31779
31868
  };
31780
31869
  add3("mass", ["g"], 1, { prefix: "metric" });
31781
31870
  add3("mass", ["sg"], 14593.9029372064);
@@ -31906,10 +31995,10 @@ var BINARY2 = {
31906
31995
  ki: 2 ** 10
31907
31996
  };
31908
31997
  function resolve(name3) {
31909
- const direct = table.get(name3);
31998
+ const direct = table2.get(name3);
31910
31999
  if (direct) return { dimension: direct.dimension, factor: direct.factor };
31911
32000
  for (const length of [2, 1]) {
31912
- const unit3 = table.get(name3.slice(length));
32001
+ const unit3 = table2.get(name3.slice(length));
31913
32002
  const prefix3 = name3.slice(0, length);
31914
32003
  if (!unit3?.prefix) continue;
31915
32004
  const scale2 = (unit3.prefix === "binary" ? BINARY2[prefix3] : void 0) ?? METRIC[prefix3];
@@ -33244,30 +33333,30 @@ function findTable(host, name3, sheet, row3, col) {
33244
33333
  if (name3) {
33245
33334
  const lower3 = name3.toLowerCase();
33246
33335
  for (let s = 0; s < sheets.length; s++) {
33247
- const table4 = sheets[s]?.tables.find(
33336
+ const table5 = sheets[s]?.tables.find(
33248
33337
  (t) => t.displayName.toLowerCase() === lower3 || t.name.toLowerCase() === lower3
33249
33338
  );
33250
- if (table4) return { table: table4, sheet: s };
33339
+ if (table5) return { table: table5, sheet: s };
33251
33340
  }
33252
33341
  return void 0;
33253
33342
  }
33254
- const table3 = sheets[sheet]?.tables.find(
33343
+ const table4 = sheets[sheet]?.tables.find(
33255
33344
  (t) => row3 >= t.range.start.row && row3 <= t.range.end.row && col >= t.range.start.col && col <= t.range.end.col
33256
33345
  );
33257
- return table3 ? { table: table3, sheet } : void 0;
33346
+ return table4 ? { table: table4, sheet } : void 0;
33258
33347
  }
33259
33348
  function resolveStructured(ref, frame2) {
33260
33349
  const found = findTable(frame2.host, ref.table, frame2.sheet, frame2.row, frame2.col);
33261
33350
  if (!found) return ref.table ? ERR.NAME : ERR.REF;
33262
- const { table: table3, sheet } = found;
33263
- const range2 = normalizeRange(table3.range);
33264
- const headerRow = table3.headerRow ? range2.start.row : -1;
33265
- const dataStart = range2.start.row + (table3.headerRow ? 1 : 0);
33266
- const dataEnd = range2.end.row - (table3.totalsRow ? 1 : 0);
33267
- const totalsRow = table3.totalsRow ? range2.end.row : -1;
33351
+ const { table: table4, sheet } = found;
33352
+ const range2 = normalizeRange(table4.range);
33353
+ const headerRow = table4.headerRow ? range2.start.row : -1;
33354
+ const dataStart = range2.start.row + (table4.headerRow ? 1 : 0);
33355
+ const dataEnd = range2.end.row - (table4.totalsRow ? 1 : 0);
33356
+ const totalsRow = table4.totalsRow ? range2.end.row : -1;
33268
33357
  const columnOf = (name3) => {
33269
33358
  const lower3 = name3.toLowerCase();
33270
- const index3 = table3.columns.findIndex((c3) => c3.name.toLowerCase() === lower3);
33359
+ const index3 = table4.columns.findIndex((c3) => c3.name.toLowerCase() === lower3);
33271
33360
  return index3 < 0 ? -1 : range2.start.col + index3;
33272
33361
  };
33273
33362
  let c1 = range2.start.col;
@@ -34579,16 +34668,16 @@ function lookupArray(value2) {
34579
34668
  }
34580
34669
  function vhlookup(args, ctx, vertical2) {
34581
34670
  const lookup2 = blankAsZero(args);
34582
- const table3 = lookupArray(args[1] ?? null);
34671
+ const table4 = lookupArray(args[1] ?? null);
34583
34672
  const index3 = int3(args[2]);
34584
34673
  const approximate2 = args.length < 4 ? true : bool(args[3]);
34585
- const { rows, cols } = shape(table3);
34674
+ const { rows, cols } = shape(table4);
34586
34675
  if (index3 < 1) fail(ERR.VALUE);
34587
34676
  if (index3 > (vertical2 ? cols : rows)) fail(ERR.REF);
34588
- const keys = line2(ctx, table3, vertical2 ? "col" : "row", 0);
34677
+ const keys = line2(ctx, table4, vertical2 ? "col" : "row", 0);
34589
34678
  const at2 = approximate2 ? findAscending(keys, lookup2) : findExact(keys, lookup2, true);
34590
34679
  if (at2 < 0) fail(ERR.NA);
34591
- return vertical2 ? cellOf(table3, at2, index3 - 1) : cellOf(table3, index3 - 1, at2);
34680
+ return vertical2 ? cellOf(table4, at2, index3 - 1) : cellOf(table4, index3 - 1, at2);
34592
34681
  }
34593
34682
  function match(args, ctx) {
34594
34683
  const lookup2 = blankAsZero(args);
@@ -36032,10 +36121,10 @@ var REGRESSION_FUNCTIONS = [
36032
36121
  const lay = logs(layout2(ctx, args));
36033
36122
  const fit3 = fitLeastSquares(lay.x, lay.y, withConst(args, 2));
36034
36123
  const stats = !omitted(args, 3) && bool(args[3]);
36035
- const table3 = coefficientTable(fit3, stats, Math.exp);
36036
- if (!stats) return table3;
36124
+ const table4 = coefficientTable(fit3, stats, Math.exp);
36125
+ if (!stats) return table4;
36037
36126
  const plain5 = coefficientTable(fit3, true, (v) => v).data;
36038
- return new Matrix([table3.data[0] ?? [], ...plain5.slice(1)]);
36127
+ return new Matrix([table4.data[0] ?? [], ...plain5.slice(1)]);
36039
36128
  },
36040
36129
  ARGS
36041
36130
  ),
@@ -38421,7 +38510,7 @@ function headerMode(args, i2, ctx, firstRow) {
38421
38510
  if (mode === 1 || mode === 3) return true;
38422
38511
  return fail(ERR.VALUE);
38423
38512
  }
38424
- var keyOf = (values2) => JSON.stringify(values2);
38513
+ var keyOf2 = (values2) => JSON.stringify(values2);
38425
38514
  var plain2 = (v) => v === void 0 || isError(v) ? null : v;
38426
38515
  function compareBy(keys, rows) {
38427
38516
  return (a2, b) => {
@@ -38461,12 +38550,12 @@ function groupby(args, ctx) {
38461
38550
  if (rows.length === 0) fail(ERR.CALC);
38462
38551
  const groups = /* @__PURE__ */ new Map();
38463
38552
  for (const r of rows) {
38464
- const key2 = keyOf(keysM.data[r]);
38553
+ const key2 = keyOf2(keysM.data[r]);
38465
38554
  const found = groups.get(key2);
38466
38555
  if (found) found.push(r);
38467
38556
  else groups.set(key2, [r]);
38468
38557
  }
38469
- const table3 = [...groups.values()].map((members3) => {
38558
+ const table4 = [...groups.values()].map((members3) => {
38470
38559
  const key2 = keysM.data[members3[0]];
38471
38560
  const cells3 = Array.from(
38472
38561
  { length: vCols },
@@ -38478,8 +38567,8 @@ function groupby(args, ctx) {
38478
38567
  return [...key2, ...cells3];
38479
38568
  });
38480
38569
  for (const key2 of sort2) if (Math.abs(key2) > kCols + vCols) fail(ERR.VALUE);
38481
- const order = table3.map((_, i2) => i2).sort(compareBy(sort2, table3));
38482
- const out = order.map((i2) => table3[i2]);
38570
+ const order = table4.map((_, i2) => i2).sort(compareBy(sort2, table4));
38571
+ const out = order.map((i2) => table4[i2]);
38483
38572
  if (depth !== 0) {
38484
38573
  const total2 = [
38485
38574
  "Total",
@@ -38528,8 +38617,8 @@ function pivotby(args, ctx) {
38528
38617
  const colKeys = /* @__PURE__ */ new Map();
38529
38618
  for (const r of used) {
38530
38619
  for (const [map, key2] of [
38531
- [rowKeys, keyOf(rowsM.data[r])],
38532
- [colKeys, keyOf(colsM.data[r])]
38620
+ [rowKeys, keyOf2(rowsM.data[r])],
38621
+ [colKeys, keyOf2(colsM.data[r])]
38533
38622
  ]) {
38534
38623
  const found = map.get(key2);
38535
38624
  if (found) found.push(r);
@@ -39262,8 +39351,8 @@ function resolveName(node3, frame2) {
39262
39351
  const value2 = evaluateDefinedName(node3.name, sheet, node3.prefix !== void 0, frame2);
39263
39352
  if (value2 !== void 0) return value2;
39264
39353
  if (!node3.prefix) {
39265
- const table3 = resolveStructured({ table: node3.name, specials: [] }, frame2);
39266
- if (!(isError(table3) && table3.error === "#NAME?")) return table3;
39354
+ const table4 = resolveStructured({ table: node3.name, specials: [] }, frame2);
39355
+ if (!(isError(table4) && table4.error === "#NAME?")) return table4;
39267
39356
  }
39268
39357
  return ERR.NAME;
39269
39358
  }
@@ -40913,8 +41002,8 @@ function deleteSheetInFormula(formula, sheetName, tableNames = []) {
40913
41002
  for (const token of tokens3) {
40914
41003
  const prefix3 = token.prefix;
40915
41004
  const onSheet = prefix3 !== void 0 && prefix3.book === void 0 && prefix3.sheet2 === void 0 && same5(prefix3.sheet, sheetName);
40916
- const table3 = typeof token.value === "string" && tables.has(token.value.toLowerCase()) && (token.kind === "structured" || token.kind === "name" && !prefix3);
40917
- if ((token.kind === "ref" || token.kind === "name") && onSheet || table3) {
41005
+ const table4 = typeof token.value === "string" && tables.has(token.value.toLowerCase()) && (token.kind === "structured" || token.kind === "name" && !prefix3);
41006
+ if ((token.kind === "ref" || token.kind === "name") && onSheet || table4) {
40918
41007
  token.text = "#REF!";
40919
41008
  changed = true;
40920
41009
  }
@@ -40977,11 +41066,11 @@ function renameTableColumnInFormula(formula, tableName, oldName, newName, inside
40977
41066
  // xlsx/formula/structured-to-a1.ts
40978
41067
  var abs = (row3, col, rowAbs = true) => `$${columnLabel(col)}${rowAbs ? "$" : ""}${row3 + 1}`;
40979
41068
  function a1For(ref, t) {
40980
- const { table: table3 } = t;
40981
- const { start, end } = table3.range;
41069
+ const { table: table4 } = t;
41070
+ const { start, end } = table4.range;
40982
41071
  const index3 = (name3) => {
40983
41072
  if (name3 === void 0) return void 0;
40984
- const i2 = table3.columns.findIndex((c3) => c3.name.toLowerCase() === name3.toLowerCase());
41073
+ const i2 = table4.columns.findIndex((c3) => c3.name.toLowerCase() === name3.toLowerCase());
40985
41074
  return i2 < 0 ? -1 : start.col + i2;
40986
41075
  };
40987
41076
  const c1 = index3(ref.column);
@@ -40989,10 +41078,10 @@ function a1For(ref, t) {
40989
41078
  if (c1 === -1 || c2 === -1) return "#REF!";
40990
41079
  const colLo = c1 ?? start.col;
40991
41080
  const colHi = c2 ?? end.col;
40992
- const headerRow = table3.headerRow ? start.row : void 0;
40993
- const totalsRow = table3.totalsRow ? end.row : void 0;
40994
- const dataLo = start.row + (table3.headerRow ? 1 : 0);
40995
- const dataHi = end.row - (table3.totalsRow ? 1 : 0);
41081
+ const headerRow = table4.headerRow ? start.row : void 0;
41082
+ const totalsRow = table4.totalsRow ? end.row : void 0;
41083
+ const dataLo = start.row + (table4.headerRow ? 1 : 0);
41084
+ const dataHi = end.row - (table4.totalsRow ? 1 : 0);
40996
41085
  const specials = new Set(ref.specials);
40997
41086
  let rowLo;
40998
41087
  let rowHi;
@@ -42425,8 +42514,8 @@ function sheetDataXml(ctx, sheet) {
42425
42514
  ].sort((a2, b) => a2 - b);
42426
42515
  const spills = new SpillPlan(sheet);
42427
42516
  const tables = /* @__PURE__ */ new Map();
42428
- for (const table3 of sheet.dataTables ?? [])
42429
- tables.set(`${table3.ref.start.row}:${table3.ref.start.col}`, table3);
42517
+ for (const table4 of sheet.dataTables ?? [])
42518
+ tables.set(`${table4.ref.start.row}:${table4.ref.start.col}`, table4);
42430
42519
  let out = "";
42431
42520
  for (const row3 of rows) {
42432
42521
  const cells3 = sheet.rows.get(row3);
@@ -42908,29 +42997,29 @@ function setChildText(doc, parent, local, text8, before) {
42908
42997
  node3.textContent = text8;
42909
42998
  if (!existing) insertBefore(parent, node3, before);
42910
42999
  }
42911
- function tableFilterRange(table3) {
43000
+ function tableFilterRange(table4) {
42912
43001
  return {
42913
- start: table3.range.start,
42914
- end: { ...table3.range.end, row: table3.range.end.row - (table3.totalsRow ? 1 : 0) }
43002
+ start: table4.range.start,
43003
+ end: { ...table4.range.end, row: table4.range.end.row - (table4.totalsRow ? 1 : 0) }
42915
43004
  };
42916
43005
  }
42917
- function sourceColumnsForPatch(root, table3, names) {
43006
+ function sourceColumnsForPatch(root, table4, names) {
42918
43007
  const list2 = xKid(root, "tableColumns");
42919
43008
  const source2 = list2 ? xKids(list2, "tableColumn") : [];
42920
43009
  const byId2 = new Map(source2.map((c2) => [Number(c2.getAttribute("id")), c2]));
42921
43010
  const byName2 = new Map(source2.map((c2) => [(c2.getAttribute("name") ?? "").toLowerCase(), c2]));
42922
- const tracked = table3.partName !== void 0 || table3.columns.some((c2) => c2.sourceId !== void 0);
43011
+ const tracked = table4.partName !== void 0 || table4.columns.some((c2) => c2.sourceId !== void 0);
42923
43012
  const used = /* @__PURE__ */ new Set();
42924
43013
  return names.map((name3, index3) => {
42925
- const id3 = table3.columns[index3]?.sourceId;
43014
+ const id3 = table4.columns[index3]?.sourceId;
42926
43015
  const match2 = id3 !== void 0 ? byId2.get(id3) : tracked ? void 0 : source2.length === names.length ? source2[index3] : byName2.get(name3.toLowerCase());
42927
43016
  if (!match2 || used.has(match2)) return void 0;
42928
43017
  used.add(match2);
42929
43018
  return match2;
42930
43019
  });
42931
43020
  }
42932
- function syncColumnFilters(doc, filter2, table3) {
42933
- table3.columns.forEach((column2, index3) => {
43021
+ function syncColumnFilters(doc, filter2, table4) {
43022
+ table4.columns.forEach((column2, index3) => {
42934
43023
  const node3 = xKids(filter2, "filterColumn").find(
42935
43024
  (n) => Number(n.getAttribute("colId")) === index3
42936
43025
  );
@@ -42952,29 +43041,29 @@ function syncColumnFilters(doc, filter2, table3) {
42952
43041
  }
42953
43042
  });
42954
43043
  }
42955
- function patchAutoFilter(doc, root, table3, before, names) {
43044
+ function patchAutoFilter(doc, root, table4, before, names) {
42956
43045
  const existing = xKid(root, "autoFilter");
42957
- if (!table3.headerRow) {
43046
+ if (!table4.headerRow) {
42958
43047
  if (existing) root.removeChild(existing);
42959
43048
  return;
42960
43049
  }
42961
43050
  const filter2 = existing ?? doc.createElementNS(NS.x, "autoFilter");
42962
- const range2 = tableFilterRange(table3);
43051
+ const range2 = tableFilterRange(table4);
42963
43052
  filter2.setAttribute("ref", formatRange(range2));
42964
43053
  const list2 = xKid(root, "tableColumns");
42965
43054
  const original = list2 ? xKids(list2, "tableColumn") : [];
42966
- const current = new Map(sourceColumnsForPatch(root, table3, names).map((c2, index3) => [c2, index3]));
43055
+ const current = new Map(sourceColumnsForPatch(root, table4, names).map((c2, index3) => [c2, index3]));
42967
43056
  for (const column2 of xKids(filter2, "filterColumn")) {
42968
43057
  const old = original[Number(column2.getAttribute("colId") ?? "0")];
42969
43058
  const index3 = old ? current.get(old) : void 0;
42970
43059
  if (index3 === void 0) filter2.removeChild(column2);
42971
43060
  else column2.setAttribute("colId", num(index3));
42972
43061
  }
42973
- syncColumnFilters(doc, filter2, table3);
43062
+ syncColumnFilters(doc, filter2, table4);
42974
43063
  if (!existing) insertBefore(root, filter2, ["sortState", "tableColumns"]);
42975
43064
  const sort2 = xKid(filter2, "sortState") ?? xKid(root, "sortState");
42976
43065
  if (!sort2) return;
42977
- const moved = before.start.row !== table3.range.start.row || before.start.col !== table3.range.start.col || before.end.col !== table3.range.end.col;
43066
+ const moved = before.start.row !== table4.range.start.row || before.start.col !== table4.range.start.col || before.end.col !== table4.range.end.col;
42978
43067
  if (moved) {
42979
43068
  sort2.parentNode?.removeChild(sort2);
42980
43069
  return;
@@ -42996,7 +43085,7 @@ function patchAutoFilter(doc, root, table3, before, names) {
42996
43085
  }
42997
43086
  }
42998
43087
  var COLUMN_CHILD_ORDER = ["calculatedColumnFormula", "totalsRowFormula", "xmlColumnPr", "extLst"];
42999
- function patchColumns(doc, root, sheet, table3, names) {
43088
+ function patchColumns(doc, root, sheet, table4, names) {
43000
43089
  let list2 = xKid(root, "tableColumns");
43001
43090
  if (!list2) {
43002
43091
  list2 = doc.createElementNS(NS.x, "tableColumns");
@@ -43004,7 +43093,7 @@ function patchColumns(doc, root, sheet, table3, names) {
43004
43093
  }
43005
43094
  const sourceColumns = xKids(list2, "tableColumn");
43006
43095
  const ids = /* @__PURE__ */ new Set();
43007
- const picked = sourceColumnsForPatch(root, table3, names).map((match2) => {
43096
+ const picked = sourceColumnsForPatch(root, table4, names).map((match2) => {
43008
43097
  if (!match2) return void 0;
43009
43098
  const id3 = Number(match2.getAttribute("id"));
43010
43099
  if (Number.isInteger(id3) && id3 >= 0 && !ids.has(id3)) ids.add(id3);
@@ -43013,15 +43102,15 @@ function patchColumns(doc, root, sheet, table3, names) {
43013
43102
  });
43014
43103
  for (const column2 of sourceColumns) list2.removeChild(column2);
43015
43104
  let nextId3 = Math.max(0, ...ids) + 1;
43016
- const totalsRow = table3.range.end.row;
43105
+ const totalsRow = table4.range.end.row;
43017
43106
  names.forEach((name3, index3) => {
43018
43107
  const column2 = picked[index3] ?? doc.createElementNS(NS.x, "tableColumn");
43019
43108
  if (!column2.getAttribute("id")) column2.setAttribute("id", num(nextId3++));
43020
43109
  column2.setAttribute("name", name3);
43021
- const model = table3.columns[index3];
43022
- const fn = table3.totalsRow ? model?.totalsRowFunction : void 0;
43110
+ const model = table4.columns[index3];
43111
+ const fn = table4.totalsRow ? model?.totalsRowFunction : void 0;
43023
43112
  setOrRemove(column2, "totalsRowFunction", fn);
43024
- setOrRemove(column2, "totalsRowLabel", table3.totalsRow ? model?.totalsRowLabel : void 0);
43113
+ setOrRemove(column2, "totalsRowLabel", table4.totalsRow ? model?.totalsRowLabel : void 0);
43025
43114
  const calculated = model?.calculatedColumnFormula;
43026
43115
  setChildText(
43027
43116
  doc,
@@ -43032,7 +43121,7 @@ function patchColumns(doc, root, sheet, table3, names) {
43032
43121
  );
43033
43122
  if (fn !== "custom") setChildText(doc, column2, "totalsRowFormula", void 0, []);
43034
43123
  else {
43035
- const cellFormula = sheet.rows.get(totalsRow)?.get(table3.range.start.col + index3)?.formula;
43124
+ const cellFormula = sheet.rows.get(totalsRow)?.get(table4.range.start.col + index3)?.formula;
43036
43125
  if (cellFormula)
43037
43126
  setChildText(
43038
43127
  doc,
@@ -43046,19 +43135,19 @@ function patchColumns(doc, root, sheet, table3, names) {
43046
43135
  });
43047
43136
  list2.setAttribute("count", num(names.length));
43048
43137
  }
43049
- function patchStyleInfo(doc, root, table3) {
43138
+ function patchStyleInfo(doc, root, table4) {
43050
43139
  let info = xKid(root, "tableStyleInfo");
43051
43140
  if (!info) {
43052
43141
  info = doc.createElementNS(NS.x, "tableStyleInfo");
43053
43142
  insertBefore(root, info, ["extLst"]);
43054
43143
  }
43055
- setOrRemove(info, "name", table3.styleName);
43056
- info.setAttribute("showFirstColumn", flag2(table3.showFirstColumn, false));
43057
- info.setAttribute("showLastColumn", flag2(table3.showLastColumn, false));
43058
- info.setAttribute("showRowStripes", flag2(table3.showRowStripes, true));
43059
- info.setAttribute("showColumnStripes", flag2(table3.showColumnStripes, false));
43144
+ setOrRemove(info, "name", table4.styleName);
43145
+ info.setAttribute("showFirstColumn", flag2(table4.showFirstColumn, false));
43146
+ info.setAttribute("showLastColumn", flag2(table4.showLastColumn, false));
43147
+ info.setAttribute("showRowStripes", flag2(table4.showRowStripes, true));
43148
+ info.setAttribute("showColumnStripes", flag2(table4.showColumnStripes, false));
43060
43149
  }
43061
- function patchTableXml(sourceXml, sheet, table3, id3, names) {
43150
+ function patchTableXml(sourceXml, sheet, table4, id3, names) {
43062
43151
  let doc;
43063
43152
  try {
43064
43153
  doc = parseXml(sourceXml, { label: "XLSX table" });
@@ -43067,80 +43156,80 @@ function patchTableXml(sourceXml, sheet, table3, id3, names) {
43067
43156
  }
43068
43157
  const root = doc.documentElement;
43069
43158
  if (root.localName !== "table") return void 0;
43070
- const before = parseRange(root.getAttribute("ref") ?? "") ?? table3.range;
43159
+ const before = parseRange(root.getAttribute("ref") ?? "") ?? table4.range;
43071
43160
  root.setAttribute("id", num(id3));
43072
- root.setAttribute("name", table3.name);
43073
- root.setAttribute("displayName", table3.displayName || table3.name);
43074
- root.setAttribute("ref", formatRange(table3.range));
43075
- setOrRemove(root, "headerRowCount", table3.headerRow ? void 0 : "0");
43076
- if (table3.totalsRow) {
43161
+ root.setAttribute("name", table4.name);
43162
+ root.setAttribute("displayName", table4.displayName || table4.name);
43163
+ root.setAttribute("ref", formatRange(table4.range));
43164
+ setOrRemove(root, "headerRowCount", table4.headerRow ? void 0 : "0");
43165
+ if (table4.totalsRow) {
43077
43166
  root.setAttribute("totalsRowCount", "1");
43078
43167
  root.removeAttribute("totalsRowShown");
43079
43168
  } else {
43080
43169
  root.removeAttribute("totalsRowCount");
43081
43170
  if (!root.hasAttribute("totalsRowShown")) root.setAttribute("totalsRowShown", "0");
43082
43171
  }
43083
- patchAutoFilter(doc, root, table3, before, names);
43084
- patchColumns(doc, root, sheet, table3, names);
43085
- patchStyleInfo(doc, root, table3);
43172
+ patchAutoFilter(doc, root, table4, before, names);
43173
+ patchColumns(doc, root, sheet, table4, names);
43174
+ patchStyleInfo(doc, root, table4);
43086
43175
  return buildXml(doc);
43087
43176
  }
43088
43177
 
43089
43178
  // xlsx/write/tables.ts
43090
43179
  var headerTextOf = (value2) => typeof value2 === "string" ? value2 : typeof value2 === "number" || typeof value2 === "boolean" ? String(value2).toUpperCase() : void 0;
43091
- function resolveTableColumns(sheet, table3) {
43180
+ function resolveTableColumns(sheet, table4) {
43092
43181
  const headerText = /* @__PURE__ */ new Map();
43093
43182
  const used = /* @__PURE__ */ new Set();
43094
- const width = table3.range.end.col - table3.range.start.col + 1;
43183
+ const width = table4.range.end.col - table4.range.start.col + 1;
43095
43184
  const names = [];
43096
43185
  for (let i2 = 0; i2 < width; i2++) {
43097
- const col = table3.range.start.col + i2;
43098
- const row3 = table3.range.start.row;
43099
- const fromCell = table3.headerRow ? headerTextOf(sheet.rows.get(row3)?.get(col)?.value) : void 0;
43100
- let name3 = (fromCell?.trim() ? fromCell : void 0) ?? table3.columns[i2]?.name ?? `Column${i2 + 1}`;
43186
+ const col = table4.range.start.col + i2;
43187
+ const row3 = table4.range.start.row;
43188
+ const fromCell = table4.headerRow ? headerTextOf(sheet.rows.get(row3)?.get(col)?.value) : void 0;
43189
+ let name3 = (fromCell?.trim() ? fromCell : void 0) ?? table4.columns[i2]?.name ?? `Column${i2 + 1}`;
43101
43190
  if (!name3.trim()) name3 = `Column${i2 + 1}`;
43102
43191
  let unique4 = name3;
43103
43192
  for (let n = 2; used.has(unique4.toLowerCase()); n++) unique4 = `${name3}${n}`;
43104
43193
  used.add(unique4.toLowerCase());
43105
43194
  names.push(unique4);
43106
43195
  const cell = sheet.rows.get(row3)?.get(col);
43107
- if (table3.headerRow && (typeof cell?.value !== "string" || cell.value !== unique4))
43196
+ if (table4.headerRow && (typeof cell?.value !== "string" || cell.value !== unique4))
43108
43197
  headerText.set(`${row3}:${col}`, unique4);
43109
43198
  }
43110
43199
  return { names, headerText };
43111
43200
  }
43112
- function tableXml(table3, id3, names) {
43113
- const range2 = formatRange(table3.range);
43114
- const filterEnd = { ...table3.range.end, row: table3.range.end.row - (table3.totalsRow ? 1 : 0) };
43115
- const criteria = table3.columns.map((column2, index3) => column2.filter ? filterColumnXml(index3, column2.filter) : "").join("");
43116
- const filterRef = formatRange({ start: table3.range.start, end: filterEnd });
43117
- const filter2 = table3.headerRow ? criteria ? `<autoFilter ref="${filterRef}">${criteria}</autoFilter>` : `<autoFilter ref="${filterRef}"/>` : "";
43201
+ function tableXml(table4, id3, names) {
43202
+ const range2 = formatRange(table4.range);
43203
+ const filterEnd = { ...table4.range.end, row: table4.range.end.row - (table4.totalsRow ? 1 : 0) };
43204
+ const criteria = table4.columns.map((column2, index3) => column2.filter ? filterColumnXml(index3, column2.filter) : "").join("");
43205
+ const filterRef = formatRange({ start: table4.range.start, end: filterEnd });
43206
+ const filter2 = table4.headerRow ? criteria ? `<autoFilter ref="${filterRef}">${criteria}</autoFilter>` : `<autoFilter ref="${filterRef}"/>` : "";
43118
43207
  const columns = names.map((name3, index3) => {
43119
- const column2 = table3.columns[index3];
43208
+ const column2 = table4.columns[index3];
43120
43209
  const calculated = column2?.calculatedColumnFormula ? `<calculatedColumnFormula>${escapeText3(addFuturePrefixes(column2.calculatedColumnFormula))}</calculatedColumnFormula>` : "";
43121
43210
  const values2 = attrs2({
43122
43211
  id: index3 + 1,
43123
43212
  name: name3,
43124
- totalsRowFunction: table3.totalsRow ? column2?.totalsRowFunction : void 0,
43125
- totalsRowLabel: table3.totalsRow ? column2?.totalsRowLabel : void 0
43213
+ totalsRowFunction: table4.totalsRow ? column2?.totalsRowFunction : void 0,
43214
+ totalsRowLabel: table4.totalsRow ? column2?.totalsRowLabel : void 0
43126
43215
  });
43127
43216
  return calculated ? `<tableColumn${values2}>${calculated}</tableColumn>` : `<tableColumn${values2}/>`;
43128
43217
  }).join("");
43129
43218
  const style3 = attrs2({
43130
- name: table3.styleName,
43131
- showFirstColumn: table3.showFirstColumn ?? false,
43132
- showLastColumn: table3.showLastColumn ?? false,
43133
- showRowStripes: table3.showRowStripes ?? true,
43134
- showColumnStripes: table3.showColumnStripes ?? false
43219
+ name: table4.styleName,
43220
+ showFirstColumn: table4.showFirstColumn ?? false,
43221
+ showLastColumn: table4.showLastColumn ?? false,
43222
+ showRowStripes: table4.showRowStripes ?? true,
43223
+ showColumnStripes: table4.showColumnStripes ?? false
43135
43224
  });
43136
43225
  const head = attrs2({
43137
43226
  id: id3,
43138
- name: table3.name,
43139
- displayName: table3.displayName || table3.name,
43227
+ name: table4.name,
43228
+ displayName: table4.displayName || table4.name,
43140
43229
  ref: range2,
43141
- headerRowCount: table3.headerRow ? void 0 : 0,
43142
- totalsRowCount: table3.totalsRow ? 1 : void 0,
43143
- totalsRowShown: table3.totalsRow ? void 0 : false
43230
+ headerRowCount: table4.headerRow ? void 0 : 0,
43231
+ totalsRowCount: table4.totalsRow ? 1 : void 0,
43232
+ totalsRowShown: table4.totalsRow ? void 0 : false
43144
43233
  });
43145
43234
  return `${XML_HEADER}<table xmlns="${NS.x}"${head}>${filter2}<tableColumns count="${names.length}">${columns}</tableColumns><tableStyleInfo${style3}/></table>`;
43146
43235
  }
@@ -43154,24 +43243,24 @@ var SUBTOTAL_CODES = {
43154
43243
  sum: 109,
43155
43244
  var: 110
43156
43245
  };
43157
- function totalsRowFormulas(sheet, table3, names) {
43246
+ function totalsRowFormulas(sheet, table4, names) {
43158
43247
  const out = /* @__PURE__ */ new Map();
43159
- if (!table3.totalsRow) return out;
43160
- const row3 = table3.range.end.row;
43248
+ if (!table4.totalsRow) return out;
43249
+ const row3 = table4.range.end.row;
43161
43250
  names.forEach((name3, index3) => {
43162
- const code = SUBTOTAL_CODES[table3.columns[index3]?.totalsRowFunction ?? ""];
43251
+ const code = SUBTOTAL_CODES[table4.columns[index3]?.totalsRowFunction ?? ""];
43163
43252
  if (code === void 0) return;
43164
- const col = table3.range.start.col + index3;
43253
+ const col = table4.range.start.col + index3;
43165
43254
  const escaped = name3.replace(/['#[\]]/g, "'$&");
43166
- const formula = `SUBTOTAL(${code},${table3.displayName || table3.name}[${escaped}])`;
43255
+ const formula = `SUBTOTAL(${code},${table4.displayName || table4.name}[${escaped}])`;
43167
43256
  if (sheet.rows.get(row3)?.get(col)?.formula !== formula) out.set(`${row3}:${col}`, formula);
43168
43257
  });
43169
43258
  return out;
43170
43259
  }
43171
- function resolveTableNames(table3, before, index3) {
43172
- const display = table3.displayName || table3.name;
43260
+ function resolveTableNames(table4, before, index3) {
43261
+ const display = table4.displayName || table4.name;
43173
43262
  const displayName = before && before.displayName === display ? display : safeTableName(display, index3);
43174
- const name3 = before && before.name === table3.name ? table3.name : table3.name === display ? displayName : safeTableName(table3.name, index3);
43263
+ const name3 = before && before.name === table4.name ? table4.name : table4.name === display ? displayName : safeTableName(table4.name, index3);
43175
43264
  return { name: name3, displayName };
43176
43265
  }
43177
43266
  function safeTableName(name3, index3) {
@@ -43264,21 +43353,21 @@ function writeTables(ctx, sheet, partName, rels, headerText, formulas) {
43264
43353
  const sourceXml = original.partName ? source2?.text(original.partName) : void 0;
43265
43354
  const before = sourceXml && original.partName ? parseTable3(sourceXml, original.partName) : void 0;
43266
43355
  const { name: name3, displayName } = resolveTableNames(original, before, index3 + 1);
43267
- const table3 = name3 === original.name && displayName === original.displayName ? original : { ...original, name: name3, displayName };
43268
- const { names, headerText: forced } = resolveTableColumns(sheet, table3);
43356
+ const table4 = name3 === original.name && displayName === original.displayName ? original : { ...original, name: name3, displayName };
43357
+ const { names, headerText: forced } = resolveTableColumns(sheet, table4);
43269
43358
  for (const [key2, text8] of forced) headerText.set(key2, text8);
43270
- const totals = totalsRowFormulas(sheet, table3, names);
43359
+ const totals = totalsRowFormulas(sheet, table4, names);
43271
43360
  for (const [key2, formula] of totals) formulas.set(key2, formula);
43272
- let id3 = table3.id;
43273
- const unchanged = table3.partName && sourceXml && !writer.has(table3.partName) && !ctx.tableIds.has(id3) && forced.size === 0 && totals.size === 0 && table3 === original && sameModel(before, table3);
43361
+ let id3 = table4.id;
43362
+ const unchanged = table4.partName && sourceXml && !writer.has(table4.partName) && !ctx.tableIds.has(id3) && forced.size === 0 && totals.size === 0 && table4 === original && sameModel(before, table4);
43274
43363
  let part;
43275
- if (unchanged && table3.partName) {
43276
- part = table3.partName;
43364
+ if (unchanged && table4.partName) {
43365
+ part = table4.partName;
43277
43366
  writer.carry(part);
43278
43367
  } else {
43279
43368
  while (ctx.tableIds.has(id3) || id3 < 1) id3++;
43280
- part = table3.partName && !writer.has(table3.partName) ? table3.partName : writer.uniqueName((n) => `xl/tables/table${n}.xml`, ctx.reserved);
43281
- const xml = (sourceXml && patchTableXml(sourceXml, sheet, table3, id3, names)) ?? tableXml(table3, id3, names);
43369
+ part = table4.partName && !writer.has(table4.partName) ? table4.partName : writer.uniqueName((n) => `xl/tables/table${n}.xml`, ctx.reserved);
43370
+ const xml = (sourceXml && patchTableXml(sourceXml, sheet, table4, id3, names)) ?? tableXml(table4, id3, names);
43282
43371
  writer.add(part, xml, CONTENT_TYPES.table);
43283
43372
  }
43284
43373
  ctx.tableIds.add(id3);
@@ -43721,15 +43810,15 @@ function derivedFields(pivot, date1904) {
43721
43810
  function derivedFieldXml(pivot, entry3, date1904) {
43722
43811
  const range2 = { start: entry3.group.start, end: entry3.group.end };
43723
43812
  const days = dateGroupDays(entry3.group);
43724
- const labels = dateUnitLabels(entry3.unit, range2, days, date1904);
43813
+ const labels = dateUnitLabels(entry3.unit, range2, days, date1904, entry3.group);
43725
43814
  const base2 = pivot.fields.indexOf(entry3.group.field);
43726
- return `<cacheField${attrs2({ name: encodeEscapes(entry3.name), numFmtId: 0, databaseField: false })}><fieldGroup base="${base2}"><rangePr${attrs2({ autoStart: entry3.autoStart ? void 0 : false, autoEnd: entry3.autoEnd ? void 0 : false, groupBy: entry3.unit, startDate: serialToIso(range2.start, date1904), endDate: serialToIso(range2.end, date1904), groupInterval: days > 1 ? days : void 0 })}/><groupItems count="${labels.length}">${labels.map((label5) => `<s v="${escapeAttr3(label5)}"/>`).join("")}</groupItems></fieldGroup></cacheField>`;
43815
+ return `<cacheField${attrs2({ name: encodeEscapes(entry3.name), numFmtId: 0, databaseField: false })}><fieldGroup base="${base2}"><rangePr${attrs2({ autoStart: entry3.autoStart ? void 0 : false, autoEnd: entry3.autoEnd ? void 0 : false, groupBy: entry3.unit, startDate: serialToIso(range2.start, date1904), endDate: serialToIso(range2.end, date1904), groupInterval: days > 1 ? days : void 0 })}/><groupItems count="${labels.length}">${labels.map((label2) => `<s v="${escapeAttr3(label2)}"/>`).join("")}</groupItems></fieldGroup></cacheField>`;
43727
43816
  }
43728
43817
  function groupXml2(pivot, name3, index3) {
43729
43818
  const group = groupOf(pivot, name3);
43730
43819
  if (!group) return "";
43731
43820
  const labels = numberGroupLabels(group);
43732
- return `<fieldGroup base="${index3}"><rangePr autoStart="0" autoEnd="0" startNum="${group.start}" endNum="${group.end}" groupInterval="${group.by}"/><groupItems count="${labels.length}">${labels.map((label5) => `<s v="${escapeAttr3(label5)}"/>`).join("")}</groupItems></fieldGroup>`;
43821
+ return `<fieldGroup base="${index3}"><rangePr autoStart="0" autoEnd="0" startNum="${group.start}" endNum="${group.end}" groupInterval="${group.by}"/><groupItems count="${labels.length}">${labels.map((label2) => `<s v="${escapeAttr3(label2)}"/>`).join("")}</groupItems></fieldGroup>`;
43733
43822
  }
43734
43823
  function slicerExt(pivot) {
43735
43824
  if (pivot.slicerCacheId === void 0) return "";
@@ -43750,8 +43839,6 @@ function pivotTableXml(source2, cacheId, cache3) {
43750
43839
  const pivot = expandDateGroups(source2);
43751
43840
  const rowNames = pivotRowFields(pivot);
43752
43841
  const rowIdx = rowNames.map((name3) => pivot.fields.indexOf(name3));
43753
- const row3 = rowIdx[0];
43754
- const second = rowIdx[1] ?? -1;
43755
43842
  const page = pivot.pageFilter ? pivot.fields.indexOf(pivot.pageFilter.field) : -1;
43756
43843
  const pageItems = page >= 0 ? pivotItems(pivot, pivot.pageFilter.field) : [];
43757
43844
  const filtered2 = filteredFields(pivot);
@@ -43779,7 +43866,10 @@ function pivotTableXml(source2, cacheId, cache3) {
43779
43866
  const columnIndicesFull = columnNames.map(
43780
43867
  (_name, k) => itemIndices(visibleColumns[k], columnItemsFull[k])
43781
43868
  );
43782
- const rowEntries = anyFull && grid.rowEntries ? remapPivotRowEntries(grid.rowEntries, rowIndicesFull) : grid.rowEntries;
43869
+ const valuesAt = pivotValuesIndex(pivot);
43870
+ const levelAxes = [...rowIndicesFull];
43871
+ if (valuesAt >= 0) levelAxes.splice(valuesAt, 0, null);
43872
+ const rowEntries = anyFull && grid.rowEntries ? remapPivotRowEntries(grid.rowEntries, levelAxes) : grid.rowEntries;
43783
43873
  const pageOffset = page >= 0 ? 2 : 0;
43784
43874
  const col = columnIdx[0] ?? -1;
43785
43875
  const measures2 = pivotMeasures(pivot);
@@ -43788,13 +43878,17 @@ function pivotTableXml(source2, cacheId, cache3) {
43788
43878
  const compact3 = pivot.layout === "compact";
43789
43879
  const outline2 = pivot.layout === "compact" || pivot.layout === "outline";
43790
43880
  const top = (pivot.subtotalPosition ?? (outline2 ? "top" : "bottom")) === "top";
43881
+ const named3 = (field2, item) => {
43882
+ const text8 = pivotItemName(pivot, field2, item);
43883
+ return text8 === void 0 ? "" : attrs2({ n: encodeEscapes(text8) });
43884
+ };
43791
43885
  const fields = pivot.fields.map((name3, index3) => {
43792
43886
  const isDate = pivot.dateFields?.includes(name3) ?? false;
43793
43887
  const at2 = rowIdx.indexOf(index3);
43794
43888
  const colAt = columnIdx.indexOf(index3);
43795
43889
  const items2 = index3 === page ? pageItems : at2 >= 0 ? rowItemsFull[at2] : colAt >= 0 ? columnItemsFull[colAt] : groupLabelsOf(pivot, name3) ?? (filtered2.has(name3) || isDate ? pivotItems(pivot, name3) : void 0);
43796
43890
  const hidden = hiddenItemKeys(pivot, name3);
43797
- const functions = at2 >= 0 ? fieldSubtotalFunctions(pivot, name3) : "auto";
43891
+ const functions = at2 >= 0 || colAt >= 0 ? fieldSubtotalFunctions(pivot, name3) : "auto";
43798
43892
  const automatic = functions === "auto";
43799
43893
  const custom = automatic ? [] : functions;
43800
43894
  const repeated = pivot.repeatLabels && at2 >= 0 ? `<extLst><ext uri="{2946ED86-A175-432a-8AC1-64E0C546D7DE}"><x14:pivotField xmlns:x14="${X143}" fillDownLabels="1"/></ext></extLst>` : "";
@@ -43802,37 +43896,27 @@ function pivotTableXml(source2, cacheId, cache3) {
43802
43896
  custom.map((fn) => [PIVOT_SUBTOTALS[fn].attr, true])
43803
43897
  );
43804
43898
  const entries = automatic ? '<item t="default"/>' : custom.map((fn) => `<item t="${PIVOT_SUBTOTALS[fn].item}"/>`).join("");
43805
- return `<pivotField${attrs2({ axis: index3 === page ? "axisPage" : at2 >= 0 ? "axisRow" : colAt >= 0 ? "axisCol" : void 0, dataField: measures2.some((measure2) => pivot.fields.indexOf(measure2.field) === index3) ? true : void 0, compact: compact3, outline: outline2, showAll: false, subtotalTop: at2 >= 0 ? top : void 0, numFmtId: isDate ? 14 : void 0, defaultSubtotal: automatic ? void 0 : false, ...flags })}>${items2 ? `<items count="${items2.length + (automatic ? 1 : custom.length)}">${items2.map((item) => `<item${hidden.has(pivotValueKey(item)) ? ' h="1"' : ""} x="${itemX(index3, item)}"/>`).join("")}${entries}</items>` : ""}${repeated}</pivotField>`;
43899
+ return `<pivotField${attrs2({ axis: index3 === page ? "axisPage" : at2 >= 0 ? "axisRow" : colAt >= 0 ? "axisCol" : void 0, dataField: measures2.some((measure2) => pivot.fields.indexOf(measure2.field) === index3) ? true : void 0, compact: compact3, outline: outline2, showAll: false, subtotalTop: at2 >= 0 ? top : void 0, numFmtId: isDate ? 14 : void 0, defaultSubtotal: automatic ? void 0 : false, ...flags })}>${items2 ? `<items count="${items2.length + (automatic ? 1 : custom.length)}">${items2.map((item) => `<item${hidden.has(pivotValueKey(item)) ? ' h="1"' : ""}${named3(name3, item)} x="${itemX(index3, item)}"/>`).join("")}${entries}</items>` : ""}${repeated}</pivotField>`;
43806
43900
  }).join("");
43807
43901
  const items = (count2, indices) => Array.from({ length: count2 }, (_v, i2) => `<i><x v="${indices?.[i2] ?? i2}"/></i>`).join("") + '<i t="grand"><x/></i>';
43808
43902
  const header = grid.firstHeaderRow !== void 0 ? grid.firstHeaderRow - pageOffset : col >= 0 ? 1 : grid.firstDataRow - pageOffset - 1;
43809
- const rowIndices = rowsAxis && pivot.valuesPosition === "first" ? [-2, row3, second] : rowsAxis && pivot.valuesPosition === "between" ? [row3, -2, second] : [...rowIdx, ...rowsAxis ? [-2] : []];
43903
+ const rowIndices = [...rowIdx];
43904
+ if (valuesAt >= 0) rowIndices.splice(valuesAt, 0, -2);
43810
43905
  let previous = [];
43811
43906
  const rowItems = rowEntries?.map((entry3) => {
43812
43907
  let prefix3 = 0;
43813
43908
  const type = entry3.type === void 0 || entry3.type === "default" || entry3.type === "grand" ? entry3.type : PIVOT_SUBTOTALS[entry3.type].item;
43814
- if (rowsAxis) {
43815
- if (entry3.type === "default" && pivot.valuesPosition === "first") prefix3 = 1;
43816
- else if (!entry3.type)
43817
- while (prefix3 < entry3.indices.length - 1 && entry3.indices[prefix3] === previous[prefix3])
43818
- prefix3++;
43819
- previous = entry3.type && !(entry3.type === "default" && pivot.valuesPosition === "first") ? [] : entry3.indices;
43820
- } else {
43821
- if (entry3.type !== "grand") prefix3 = sharedPrefix(entry3.indices, previous);
43822
- previous = entry3.type === "grand" ? [] : entry3.indices;
43823
- }
43909
+ if (entry3.type !== "grand") prefix3 = sharedPrefix(entry3.indices, previous);
43910
+ previous = entry3.type === "grand" ? [] : entry3.indices;
43824
43911
  return `<i${attrs2({ t: type, r: prefix3 || void 0, i: entry3.measure || void 0 })}>${entry3.indices.slice(prefix3).map((index3) => `<x${attrs2({ v: index3 || void 0 })}/>`).join("")}</i>`;
43825
43912
  }).join("") ?? items(grid.rowItems.length, rowIndicesFull[0]);
43826
43913
  let body = `<location${attrs2({ ref: formatRange({ ...pivot.location, start: { ...pivot.location.start, row: pivot.location.start.row + pageOffset } }), firstHeaderRow: header, firstDataRow: grid.firstDataRow - pageOffset, rowPageCount: page >= 0 ? 1 : void 0, colPageCount: page >= 0 ? 1 : void 0, firstDataCol: grid.rowLabelColumns ?? 1 })}/><pivotFields count="${pivot.fields.length}">${fields}</pivotFields><rowFields count="${rowIndices.length}">${rowIndices.map((index3) => `<field x="${index3}"/>`).join("")}</rowFields><rowItems count="${grid.rowEntries?.length ?? grid.rowItems.length + 1}">${rowItems}</rowItems>`;
43827
- if (!rowsAxis && col >= 0 && grid.columnEntries) {
43828
- const fieldsOnColumns = [...columnIdx, ...multiple ? [-2] : []];
43829
- body += `<colFields count="${fieldsOnColumns.length}">${fieldsOnColumns.map((index3) => `<field x="${index3}"/>`).join("")}</colFields>${pivotColumnItemsXml(grid.columnEntries, measures2.length, (level, index3) => columnIndicesFull[level][index3])}`;
43914
+ if (col >= 0 && grid.columnEntries) {
43915
+ const fieldsOnColumns = [...columnIdx, ...multiple && !rowsAxis ? [-2] : []];
43916
+ body += `<colFields count="${fieldsOnColumns.length}">${fieldsOnColumns.map((index3) => `<field x="${index3}"/>`).join("")}</colFields>${pivotColumnItemsXml(grid.columnEntries, rowsAxis ? 1 : measures2.length, (level, index3) => columnIndicesFull[level][index3])}`;
43830
43917
  } else if (multiple && !rowsAxis)
43831
43918
  body += `<colFields count="1"><field x="-2"/></colFields>${pivotValueAxisItems(measures2.length)}`;
43832
- else if (col >= 0)
43833
- body += `<colFields count="1"><field x="${col}"/></colFields><colItems count="${grid.columnItems.length + 1}">${items(grid.columnItems.length, columnIndicesFull[0])}</colItems>`;
43834
- else
43835
- body += rowsAxis ? '<colItems count="1"><i/></colItems>' : page >= 0 ? '<colItems count="1"><i/></colItems>' : '<colItems count="1"><i><x/></i></colItems>';
43919
+ else body += '<colItems count="1"><i/></colItems>';
43836
43920
  if (page >= 0)
43837
43921
  body += `<pageFields count="1"><pageField${attrs2({ fld: page, hier: -1, item: pivot.pageFilter.item !== void 0 ? pageItems.findIndex((item) => pivotValueKey(item) === pivotValueKey(pivot.pageFilter.item)) : void 0 })}/></pageFields>`;
43838
43922
  body += `<dataFields count="${measures2.length}">${measures2.map((measure2) => `<dataField${attrs2({ name: encodeEscapes(measure2.caption), fld: pivot.fields.indexOf(measure2.field), subtotal: measure2.aggregate, baseField: 0, baseItem: 0 })}/>`).join("")}</dataFields>`;
@@ -43842,9 +43926,17 @@ function pivotTableXml(source2, cacheId, cache3) {
43842
43926
  const root = doc.documentElement;
43843
43927
  root.setAttribute("name", pivot.name);
43844
43928
  root.setAttribute("cacheId", String(cacheId));
43929
+ const caps = pivotCaptions(pivot);
43930
+ root.setAttribute("dataCaption", caps.values);
43931
+ for (const [attribute4, key2] of [
43932
+ ["rowHeaderCaption", "rowLabels"],
43933
+ ["colHeaderCaption", "columnLabels"],
43934
+ ["grandTotalCaption", "grandTotal"]
43935
+ ])
43936
+ if (caps[key2] !== ENGLISH_PIVOT_CAPTIONS[key2] || root.hasAttribute(attribute4))
43937
+ root.setAttribute(attribute4, caps[key2]);
43845
43938
  root.setAttribute("dataOnRows", rowsAxis ? "1" : "0");
43846
- if (rowsAxis && (pivot.valuesPosition === "between" || pivot.valuesPosition === "first"))
43847
- root.setAttribute("dataPosition", pivot.valuesPosition === "first" ? "0" : "1");
43939
+ if (rowsAxis && valuesAt < rowIdx.length) root.setAttribute("dataPosition", String(valuesAt));
43848
43940
  else root.removeAttribute("dataPosition");
43849
43941
  root.setAttribute("compact", compact3 ? "1" : "0");
43850
43942
  root.setAttribute("compactData", compact3 ? "1" : "0");
@@ -43910,7 +44002,8 @@ function pivotTableXml(source2, cacheId, cache3) {
43910
44002
  }
43911
44003
  function dateFilterXml(pivot, filter2) {
43912
44004
  const x15 = "http://schemas.microsoft.com/office/spreadsheetml/2010/11/main";
43913
- return `<filters count="1"><filter${attrs2({ fld: pivot.fields.indexOf(filter2.field), type: "dateBetween", evalOrder: -1, id: 1, name: filter2.field })}><autoFilter ref="A1"><filterColumn colId="0"><customFilters and="1"><customFilter operator="greaterThanOrEqual" val="${Math.floor(filter2.start)}"/><customFilter operator="lessThanOrEqual" val="${Math.floor(filter2.end)}"/></customFilters></filterColumn></autoFilter><extLst><ext uri="{0605FD5F-26C8-4aeb-8148-2DB25E43C511}" xmlns:x15="${x15}"><x15:pivotFilter useWholeDay="1"/></ext></extLst></filter></filters>`;
44005
+ const id3 = Number(/<filter [^>]*\bid="(\d+)"/.exec(pivot.sourceXml ?? "")?.[1] ?? 1);
44006
+ return `<filters count="1"><filter${attrs2({ fld: pivot.fields.indexOf(filter2.field), type: "dateBetween", evalOrder: -1, id: id3, name: filter2.field })}><autoFilter ref="A1"><filterColumn colId="0"><customFilters and="1"><customFilter operator="greaterThanOrEqual" val="${Math.floor(filter2.start)}"/><customFilter operator="lessThanOrEqual" val="${Math.floor(filter2.end)}"/></customFilters></filterColumn></autoFilter><extLst><ext uri="{0605FD5F-26C8-4aeb-8148-2DB25E43C511}" xmlns:x15="${x15}"><x15:pivotFilter useWholeDay="1"/></ext></extLst></filter></filters>`;
43914
44007
  }
43915
44008
 
43916
44009
  // xlsx/pivot/write.ts
@@ -43965,7 +44058,7 @@ var PivotWritePlan = class {
43965
44058
  this.tableParts.set(pivot, pivot.partName);
43966
44059
  continue;
43967
44060
  }
43968
- const table3 = pivot.partName ?? writer.uniqueName((n) => `xl/pivotTables/pivotTable${n}.xml`, reserved);
44061
+ const table4 = pivot.partName ?? writer.uniqueName((n) => `xl/pivotTables/pivotTable${n}.xml`, reserved);
43969
44062
  const definition = writer.uniqueName(
43970
44063
  (n) => `xl/pivotCache/pivotCacheDefinition${n}.xml`,
43971
44064
  reserved
@@ -43987,24 +44080,24 @@ var PivotWritePlan = class {
43987
44080
  TYPES2.definition
43988
44081
  );
43989
44082
  writer.rels(definition, cacheRels);
43990
- writer.add(table3, pivotTableXml(pivot, cacheId, cache3), TYPES2.table);
44083
+ writer.add(table4, pivotTableXml(pivot, cacheId, cache3), TYPES2.table);
43991
44084
  const tableRels = new RelationshipSet();
43992
- tableRels.add(RELATIONSHIP_TYPES.pivotCacheDefinition, relativeTarget(table3, definition));
43993
- writer.rels(table3, tableRels);
44085
+ tableRels.add(RELATIONSHIP_TYPES.pivotCacheDefinition, relativeTarget(table4, definition));
44086
+ writer.rels(table4, tableRels);
43994
44087
  const rid2 = bookRels.add(
43995
44088
  RELATIONSHIP_TYPES.pivotCacheDefinition,
43996
44089
  relativeTarget(bookPart, definition)
43997
44090
  );
43998
44091
  entries.push(`<pivotCache cacheId="${cacheId++}" r:id="${rid2}"/>`);
43999
- this.tableParts.set(pivot, table3);
44092
+ this.tableParts.set(pivot, table4);
44000
44093
  }
44001
44094
  this.cachesXml = owns ? entries.length ? `<pivotCaches>${entries.join("")}</pivotCaches>` : "" : void 0;
44002
44095
  }
44003
44096
  writeSheet(writer, sheet, part, rels) {
44004
44097
  for (const pivot of sheet.pivotTables ?? []) {
44005
- const table3 = this.tableParts.get(pivot);
44006
- writer.carry(table3);
44007
- rels.add(RELATIONSHIP_TYPES.pivotTable, relativeTarget(part, table3));
44098
+ const table4 = this.tableParts.get(pivot);
44099
+ writer.carry(table4);
44100
+ rels.add(RELATIONSHIP_TYPES.pivotTable, relativeTarget(part, table4));
44008
44101
  }
44009
44102
  }
44010
44103
  };
@@ -44174,9 +44267,9 @@ function slicerTarget(workbook, cache3) {
44174
44267
  const source2 = cache3.source;
44175
44268
  for (const [sheetIndex2, sheet] of workbook.sheets.entries()) {
44176
44269
  if (source2.kind === "table") {
44177
- const table3 = sheet.tables.find((entry3) => entry3.id === source2.tableId);
44178
- const offset2 = table3?.columns.findIndex((column2) => column2.sourceId === source2.column) ?? -1;
44179
- if (table3 && offset2 >= 0) return { kind: "table", sheet, sheetIndex: sheetIndex2, table: table3, offset: offset2 };
44270
+ const table4 = sheet.tables.find((entry3) => entry3.id === source2.tableId);
44271
+ const offset2 = table4?.columns.findIndex((column2) => column2.sourceId === source2.column) ?? -1;
44272
+ if (table4 && offset2 >= 0) return { kind: "table", sheet, sheetIndex: sheetIndex2, table: table4, offset: offset2 };
44180
44273
  } else {
44181
44274
  const first3 = source2.pivots[0];
44182
44275
  const pivot = first3 && sheet.sheetId === first3.tabId ? sheet.pivotTables?.find((entry3) => entry3.name === first3.name) : void 0;
@@ -44365,12 +44458,12 @@ function slicerCacheXml(cache3, facts) {
44365
44458
  ext.setAttribute("xmlns:x15", X153);
44366
44459
  list2.appendChild(ext);
44367
44460
  }
44368
- let table3 = first(ext, "tableSlicerCache", X153);
44369
- if (!table3) table3 = ext.appendChild(make2(X153, "x15:tableSlicerCache"));
44370
- table3.setAttribute("tableId", String(source2.tableId));
44371
- table3.setAttribute("column", String(source2.column));
44372
- if (cache3.sortOrder === "descending") table3.setAttribute("sortOrder", "descending");
44373
- else table3.removeAttribute("sortOrder");
44461
+ let table4 = first(ext, "tableSlicerCache", X153);
44462
+ if (!table4) table4 = ext.appendChild(make2(X153, "x15:tableSlicerCache"));
44463
+ table4.setAttribute("tableId", String(source2.tableId));
44464
+ table4.setAttribute("column", String(source2.column));
44465
+ if (cache3.sortOrder === "descending") table4.setAttribute("sortOrder", "descending");
44466
+ else table4.removeAttribute("sortOrder");
44374
44467
  return XML_HEADER + buildXml(root);
44375
44468
  }
44376
44469
 
@@ -44923,12 +45016,12 @@ function rewriteSheetFormulas(sheet, rewrite2, formulaCells) {
44923
45016
  }
44924
45017
  {
44925
45018
  const name3 = sheet.name;
44926
- for (const table3 of sheet.tables)
44927
- for (const [index3, column2] of table3.columns.entries())
45019
+ for (const table4 of sheet.tables)
45020
+ for (const [index3, column2] of table4.columns.entries())
44928
45021
  if (column2.calculatedColumnFormula !== void 0)
44929
45022
  column2.calculatedColumnFormula = safe(rewrite2, column2.calculatedColumnFormula, name3, {
44930
- row: table3.range.start.row + (table3.headerRow ? 1 : 0),
44931
- col: table3.range.start.col + index3
45023
+ row: table4.range.start.row + (table4.headerRow ? 1 : 0),
45024
+ col: table4.range.start.col + index3
44932
45025
  });
44933
45026
  if (formulaCells) {
44934
45027
  for (const at2 of formulaCells) {
@@ -44993,14 +45086,14 @@ function tableHeaderAt(sheet, row3, col) {
44993
45086
  );
44994
45087
  }
44995
45088
  function syncTableHeader(ctx, sheet, row3, col, formulaCells) {
44996
- const table3 = tableHeaderAt(sheet, row3, col);
44997
- if (!table3) return;
44998
- const column2 = table3.columns[col - table3.range.start.col];
45089
+ const table4 = tableHeaderAt(sheet, row3, col);
45090
+ if (!table4) return;
45091
+ const column2 = table4.columns[col - table4.range.start.col];
44999
45092
  if (!column2) return;
45000
45093
  const text8 = displayText(ctx.workbook, getCell(sheet, row3, col)).trim();
45001
45094
  if (!text8 || column2.name === text8) return;
45002
45095
  const oldName = column2.name;
45003
- const others = table3.columns.filter((entry3) => entry3 !== column2).map((entry3) => entry3.name);
45096
+ const others = table4.columns.filter((entry3) => entry3 !== column2).map((entry3) => entry3.name);
45004
45097
  const newName = uniqueHeaders([...others, text8]).at(-1);
45005
45098
  column2.name = newName;
45006
45099
  if (newName !== text8) writeValue(sheet, row3, col, newName);
@@ -45010,10 +45103,10 @@ function syncTableHeader(ctx, sheet, row3, col, formulaCells) {
45010
45103
  ctx.workbook,
45011
45104
  (formula, formulaSheet, at2) => renameTableColumnInFormula(
45012
45105
  formula,
45013
- table3.name,
45106
+ table4.name,
45014
45107
  oldName,
45015
45108
  newName,
45016
- formulaSheet === sheet.name && !!at2 && rangeContains(table3.range, at2)
45109
+ formulaSheet === sheet.name && !!at2 && rangeContains(table4.range, at2)
45017
45110
  ),
45018
45111
  cells3
45019
45112
  );
@@ -46137,11 +46230,11 @@ function uniqueColumnName(columns) {
46137
46230
  const taken = new Set(columns.map((c2) => c2.name.toLowerCase()));
46138
46231
  for (let n = 1; ; n++) if (!taken.has(`column${n}`)) return `Column${n}`;
46139
46232
  }
46140
- function shiftTable(sheet, table3, shift2, moveRange) {
46141
- const old = table3.range;
46233
+ function shiftTable(sheet, table4, shift2, moveRange) {
46234
+ const old = table4.range;
46142
46235
  const range2 = moveRange(old);
46143
46236
  if (!range2) return [];
46144
- const next = { ...table3, range: range2, columns: [...table3.columns] };
46237
+ const next = { ...table4, range: range2, columns: [...table4.columns] };
46145
46238
  const widened = range2.end.col - range2.start.col !== old.end.col - old.start.col;
46146
46239
  if (shift2.axis === "col" && widened) {
46147
46240
  if (shift2.count > 0) {
@@ -46617,8 +46710,8 @@ function cellText(inner2) {
46617
46710
  ).replace(/ /g, " ").trim();
46618
46711
  }
46619
46712
  function parseHtmlTable(html, base2) {
46620
- const table3 = /<table\b[^>]*>([\s\S]*?)<\/table>/i.exec(html)?.[1];
46621
- if (table3 === void 0) return void 0;
46713
+ const table4 = /<table\b[^>]*>([\s\S]*?)<\/table>/i.exec(html)?.[1];
46714
+ if (table4 === void 0) return void 0;
46622
46715
  const classes = /* @__PURE__ */ new Map();
46623
46716
  for (const block of html.matchAll(/<style\b[^>]*>([\s\S]*?)<\/style>/gi))
46624
46717
  for (const rule2 of removeAll(block[1] ?? "", ["<!--", "-->"]).matchAll(
@@ -46631,7 +46724,7 @@ function parseHtmlTable(html, base2) {
46631
46724
  const hyperlinks = [];
46632
46725
  let r = 0;
46633
46726
  let spanned = 0;
46634
- for (const tr of table3.matchAll(/<tr\b[^>]*>([\s\S]*?)(?=<tr\b|<\/tbody|<\/table|$)/gi)) {
46727
+ for (const tr of table4.matchAll(/<tr\b[^>]*>([\s\S]*?)(?=<tr\b|<\/tbody|<\/table|$)/gi)) {
46635
46728
  const row3 = grid[r] ??= [];
46636
46729
  let c2 = 0;
46637
46730
  for (const td of (tr[1] ?? "").matchAll(
@@ -47483,9 +47576,9 @@ function filterColumn(ctx, s, col, values2) {
47483
47576
  }
47484
47577
  function sortByColumn(ctx, s, col, descending) {
47485
47578
  const sheet = sheetAt(ctx.workbook, s);
47486
- const table3 = sheet.tables.find((t) => col >= t.range.start.col && col <= t.range.end.col);
47579
+ const table4 = sheet.tables.find((t) => col >= t.range.start.col && col <= t.range.end.col);
47487
47580
  const filter2 = sheet.autoFilter;
47488
- const target2 = table3 ? { range: table3.range, header: table3.headerRow, totals: table3.totalsRow } : filter2 && rangeContains(filter2.range, { row: filter2.range.start.row, col }) ? { range: filter2.range, header: true, totals: false } : void 0;
47581
+ const target2 = table4 ? { range: table4.range, header: table4.headerRow, totals: table4.totalsRow } : filter2 && rangeContains(filter2.range, { row: filter2.range.start.row, col }) ? { range: filter2.range, header: true, totals: false } : void 0;
47489
47582
  if (!target2) throw new Error("The column is not inside a table or an auto-filter range.");
47490
47583
  const range2 = target2.totals ? { start: target2.range.start, end: { ...target2.range.end, row: target2.range.end.row - 1 } } : target2.range;
47491
47584
  ctx.run(
@@ -47545,12 +47638,12 @@ function restore(sheet, saved) {
47545
47638
  Object.assign(cell, saved.fields);
47546
47639
  }
47547
47640
  var valueAt = (sheet, row3, col) => getCell(sheet, row3, col)?.value ?? null;
47548
- function computeDataTable(workbook, calc, sheetIndex2, table3) {
47641
+ function computeDataTable(workbook, calc, sheetIndex2, table4) {
47549
47642
  const sheet = sheetAt(workbook, sheetIndex2);
47550
- const { ref } = table3;
47551
- const first3 = parseInputCell(sheet, table3.r1);
47552
- const second = table3.dt2D && table3.r2 ? parseInputCell(sheet, table3.r2) : void 0;
47553
- if (!first3 || table3.dt2D && !second || table3.del1 || table3.del2) return [];
47643
+ const { ref } = table4;
47644
+ const first3 = parseInputCell(sheet, table4.r1);
47645
+ const second = table4.dt2D && table4.r2 ? parseInputCell(sheet, table4.r2) : void 0;
47646
+ if (!first3 || table4.dt2D && !second || table4.del1 || table4.del2) return [];
47554
47647
  const inputs = [first3, ...second ? [second] : []];
47555
47648
  const saved = inputs.map((p) => save(sheet, p.row, p.col));
47556
47649
  const top = ref.start.row - 1;
@@ -47569,11 +47662,11 @@ function computeDataTable(workbook, calc, sheetIndex2, table3) {
47569
47662
  for (let row3 = ref.start.row; row3 <= ref.end.row; row3++) {
47570
47663
  for (let col = ref.start.col; col <= ref.end.col; col++) {
47571
47664
  let formulaAt;
47572
- if (table3.dt2D) {
47665
+ if (table4.dt2D) {
47573
47666
  set(first3, valueAt(sheet, top, col));
47574
47667
  if (second) set(second, valueAt(sheet, row3, left2));
47575
47668
  formulaAt = { row: top, col: left2 };
47576
- } else if (table3.dtr) {
47669
+ } else if (table4.dtr) {
47577
47670
  set(first3, valueAt(sheet, top, col));
47578
47671
  formulaAt = { row: row3, col: left2 };
47579
47672
  } else {
@@ -47598,8 +47691,8 @@ function computeDataTable(workbook, calc, sheetIndex2, table3) {
47598
47691
  function refreshDataTables(workbook, calc) {
47599
47692
  const changed = [];
47600
47693
  workbook.sheets.forEach((sheet, index3) => {
47601
- for (const table3 of sheet.dataTables ?? [])
47602
- changed.push(...computeDataTable(workbook, calc, index3, table3));
47694
+ for (const table4 of sheet.dataTables ?? [])
47695
+ changed.push(...computeDataTable(workbook, calc, index3, table4));
47603
47696
  });
47604
47697
  if (changed.length) calc.recalculateFrom(changed);
47605
47698
  }
@@ -47622,23 +47715,23 @@ function resolve2(sheet, request) {
47622
47715
  const ref = cellRange(range2.start.row + 1, range2.start.col + 1, range2.end.row, range2.end.col);
47623
47716
  if ([row3, col].some((p) => p && rangeContains(ref, p))) return { problem: "input-inside" };
47624
47717
  const name3 = (p) => formatAddress(p);
47625
- const table3 = { ref, r1: "" };
47718
+ const table4 = { ref, r1: "" };
47626
47719
  if (row3 && col) {
47627
- table3.dt2D = true;
47628
- table3.dtr = true;
47629
- table3.r1 = name3(row3);
47630
- table3.r2 = name3(col);
47720
+ table4.dt2D = true;
47721
+ table4.dtr = true;
47722
+ table4.r1 = name3(row3);
47723
+ table4.r2 = name3(col);
47631
47724
  } else if (row3) {
47632
- table3.dtr = true;
47633
- table3.r1 = name3(row3);
47634
- } else if (col) table3.r1 = name3(col);
47635
- return { table: table3 };
47725
+ table4.dtr = true;
47726
+ table4.r1 = name3(row3);
47727
+ } else if (col) table4.r1 = name3(col);
47728
+ return { table: table4 };
47636
47729
  }
47637
47730
  function createDataTable(ctx, s, request) {
47638
47731
  const sheet = sheetAt(ctx.workbook, s);
47639
47732
  const result2 = resolve2(sheet, request);
47640
47733
  if ("problem" in result2) throw new Error(MESSAGES[result2.problem]);
47641
- const { table: table3 } = result2;
47734
+ const { table: table4 } = result2;
47642
47735
  const range2 = normalizeRange(request.range);
47643
47736
  ctx.run(
47644
47737
  "Data Table",
@@ -47649,16 +47742,16 @@ function createDataTable(ctx, s, request) {
47649
47742
  ],
47650
47743
  () => {
47651
47744
  sheet.dataTables = (sheet.dataTables ?? []).filter((t) => !rangesIntersect(t.ref, range2));
47652
- sheet.dataTables.push(table3);
47653
- for (let row3 = table3.ref.start.row; row3 <= table3.ref.end.row; row3++)
47654
- for (let col = table3.ref.start.col; col <= table3.ref.end.col; col++) {
47745
+ sheet.dataTables.push(table4);
47746
+ for (let row3 = table4.ref.start.row; row3 <= table4.ref.end.row; row3++)
47747
+ for (let col = table4.ref.start.col; col <= table4.ref.end.col; col++) {
47655
47748
  const cell = ensureCell(sheet, row3, col);
47656
47749
  delete cell.formula;
47657
47750
  delete cell.arrayRange;
47658
47751
  delete cell.legacyFormula;
47659
47752
  delete cell.dynamicArray;
47660
47753
  }
47661
- computeDataTable(ctx.workbook, ctx.calc, s, table3);
47754
+ computeDataTable(ctx.workbook, ctx.calc, s, table4);
47662
47755
  },
47663
47756
  { sheet: s, ranges: [range2] }
47664
47757
  );
@@ -48895,7 +48988,7 @@ function pixelSizeToExtent(width, height) {
48895
48988
  }
48896
48989
 
48897
48990
  // xlsx/pivot/date-axes.ts
48898
- var dateGroupAxisNames = (group) => dateGroupUnits(group).reverse().map((unit3) => dateGroupFieldName(unit3, group.field));
48991
+ var dateGroupAxisNames = (group) => dateGroupUnits(group).reverse().map((unit3) => dateGroupFieldName(unit3, group.field, group));
48899
48992
  function replace(list2, names, replacement) {
48900
48993
  const at2 = list2.findIndex((name3) => names.includes(name3));
48901
48994
  if (at2 < 0) return list2;
@@ -48931,7 +49024,9 @@ function reconcileDateAxes(next, previous) {
48931
49024
  if (columns.length > 1) next.moreColumnFields = columns.slice(1);
48932
49025
  else delete next.moreColumnFields;
48933
49026
  if (next.fieldSubtotals) {
48934
- const kept = next.fieldSubtotals.filter((entry3) => rows.includes(entry3.field));
49027
+ const kept = next.fieldSubtotals.filter(
49028
+ (entry3) => rows.includes(entry3.field) || columns.includes(entry3.field)
49029
+ );
48935
49030
  if (kept.length) next.fieldSubtotals = kept;
48936
49031
  else delete next.fieldSubtotals;
48937
49032
  }
@@ -48973,7 +49068,7 @@ function plan(ctx, s, pivot, old) {
48973
49068
  if (![start.row, start.col].every(Number.isInteger) || start.row < 0 || start.col < 0 || location.end.row > MAX_ROW || location.end.col > MAX_COL)
48974
49069
  throw new Error("The PivotTable result does not fit on the worksheet.");
48975
49070
  const source2 = sparklineDataRange(ctx.workbook, s, pivot.source);
48976
- if (source2.sheet === s && rangesIntersect(source2.range, location) || sheet.merges.some((range2) => rangesIntersect(range2, location)) || sheet.tables.some((table3) => rangesIntersect(table3.range, location)) || sheet.pivotTables?.some((other) => other !== old && rangesIntersect(other.location, location)))
49071
+ if (source2.sheet === s && rangesIntersect(source2.range, location) || sheet.merges.some((range2) => rangesIntersect(range2, location)) || sheet.tables.some((table4) => rangesIntersect(table4.range, location)) || sheet.pivotTables?.some((other) => other !== old && rangesIntersect(other.location, location)))
48977
49072
  throw new Error("The PivotTable would overlap source data, another table or merged cells.");
48978
49073
  let occupied = false;
48979
49074
  forEachCellInRange(sheet, location, (cell, row3, col) => {
@@ -48983,12 +49078,12 @@ function plan(ctx, s, pivot, old) {
48983
49078
  if (occupied) throw new Error("The PivotTable would overwrite existing cell content.");
48984
49079
  return { grid, location };
48985
49080
  }
48986
- function writePivot(ctx, s, pivot, old, label5, inside2) {
49081
+ function writePivot(ctx, s, pivot, old, label2, inside2) {
48987
49082
  const sheet = sheetAt(ctx.workbook, s);
48988
49083
  const { grid, location } = plan(ctx, s, pivot, old);
48989
49084
  const ranges = [...old ? [old.location] : [], location];
48990
49085
  ctx.run(
48991
- label5 ?? (old ? "Refresh PivotTable" : "Create PivotTable"),
49086
+ label2 ?? (old ? "Refresh PivotTable" : "Create PivotTable"),
48992
49087
  "annotations",
48993
49088
  [
48994
49089
  { kind: "parts", sheet: s, parts: ["pivotTables"] },
@@ -49045,8 +49140,10 @@ function createPivotTable(ctx, s, destination, options) {
49045
49140
  const name3 = options.name ?? uniqueName(ctx);
49046
49141
  checkName2(ctx, name3);
49047
49142
  const aggregate2 = options.aggregate ?? "sum";
49143
+ const captions = authoredCaptions(options);
49048
49144
  const pivot = {
49049
49145
  ...data,
49146
+ ...captions ? { captions } : {},
49050
49147
  name: name3,
49051
49148
  rowField: options.rowField,
49052
49149
  layout: options.layout ?? "tabular",
@@ -49060,12 +49157,12 @@ function createPivotTable(ctx, s, destination, options) {
49060
49157
  ...options.repeatLabels !== void 0 ? { repeatLabels: options.repeatLabels } : {},
49061
49158
  valueField: options.valueField,
49062
49159
  aggregate: aggregate2,
49063
- valueCaption: pivotCaption(aggregate2, options.valueField),
49160
+ valueCaption: pivotCaption(aggregate2, options.valueField, { captions }),
49064
49161
  ...options.pageFilter !== void 0 ? { pageFilter: structuredClone(options.pageFilter) } : {},
49065
49162
  ...options.fieldGroups?.length ? { fieldGroups: structuredClone(options.fieldGroups) } : {},
49066
49163
  ...options.valuesAxis !== void 0 ? { valuesAxis: options.valuesAxis } : {},
49067
49164
  ...options.valuesPosition !== void 0 ? { valuesPosition: options.valuesPosition } : {},
49068
- ...options.additionalValues ? { additionalValues: normalizedPivotMeasures(options.additionalValues) } : {},
49165
+ ...options.additionalValues ? { additionalValues: normalizedPivotMeasures(options.additionalValues, { captions }) } : {},
49069
49166
  location: { start: { ...destination }, end: { ...destination } },
49070
49167
  ...options.columnField ? { columnField: options.columnField } : {},
49071
49168
  ...options.columnField && options.moreColumnFields?.length ? { moreColumnFields: [...options.moreColumnFields] } : {}
@@ -49088,7 +49185,7 @@ function refreshPivotTable(ctx, s, name3, patch2 = {}) {
49088
49185
  rowField: patch2.rowField ?? old.rowField,
49089
49186
  valueField,
49090
49187
  aggregate: aggregate2,
49091
- valueCaption: aggregate2 === old.aggregate && valueField === old.valueField ? old.valueCaption : pivotCaption(aggregate2, valueField)
49188
+ valueCaption: aggregate2 === old.aggregate && valueField === old.valueField ? old.valueCaption : pivotCaption(aggregate2, valueField, old)
49092
49189
  };
49093
49190
  if (patch2.columnField !== void 0) {
49094
49191
  if (patch2.columnField) next.columnField = patch2.columnField;
@@ -49138,7 +49235,7 @@ function refreshPivotTable(ctx, s, name3, patch2 = {}) {
49138
49235
  else if (patch2.valuesAxis === "columns" || patch2.secondRowField === "")
49139
49236
  delete next.valuesPosition;
49140
49237
  if (patch2.additionalValues !== void 0) {
49141
- const measures2 = normalizedPivotMeasures(patch2.additionalValues);
49238
+ const measures2 = normalizedPivotMeasures(patch2.additionalValues, old);
49142
49239
  if (measures2.length) next.additionalValues = measures2;
49143
49240
  else delete next.additionalValues;
49144
49241
  }
@@ -49147,6 +49244,12 @@ function refreshPivotTable(ctx, s, name3, patch2 = {}) {
49147
49244
  else delete next.dateFields;
49148
49245
  roundDateRecords(next, dates, ctx.workbook.date1904);
49149
49246
  if (next.dateFilter && !dates.includes(next.dateFilter.field)) delete next.dateFilter;
49247
+ if (patch2.fieldSubtotals === void 0 && next.fieldSubtotals) {
49248
+ const onAxes = [...pivotRowFields(next), ...pivotColumnFields(next)];
49249
+ const left2 = next.fieldSubtotals.filter((entry3) => onAxes.includes(entry3.field));
49250
+ if (left2.length) next.fieldSubtotals = left2;
49251
+ else delete next.fieldSubtotals;
49252
+ }
49150
49253
  const kept = pruneItemFilters(next);
49151
49254
  if (kept) next.itemFilters = kept;
49152
49255
  else delete next.itemFilters;
@@ -49602,10 +49705,10 @@ function validatePatch(group, patch2) {
49602
49705
  delete next.manualMax;
49603
49706
  validateSettings(next);
49604
49707
  }
49605
- function save2(ctx, s, next, label5, ranges) {
49708
+ function save2(ctx, s, next, label2, ranges) {
49606
49709
  const sheet = sheetAt(ctx.workbook, s);
49607
49710
  ctx.run(
49608
- label5,
49711
+ label2,
49609
49712
  "annotations",
49610
49713
  [{ kind: "parts", sheet: s, parts: ["preserved"] }],
49611
49714
  () => sheet.preserved.set("extLst", next),
@@ -49723,20 +49826,20 @@ function setSlicerSelection(ctx, cacheName, keys) {
49723
49826
  const target2 = slicerTarget(ctx.workbook, cache3);
49724
49827
  if (!target2) throw new Error("The slicer has no data source.");
49725
49828
  if (target2.kind === "table") {
49726
- const { sheet, table: table3, offset: offset2 } = target2;
49829
+ const { sheet, table: table4, offset: offset2 } = target2;
49727
49830
  ctx.run(
49728
49831
  keys === null ? "Clear slicer filter" : "Filter slicer",
49729
49832
  "view",
49730
49833
  [{ kind: "sheet", sheet: target2.sheetIndex }],
49731
49834
  () => {
49732
- const column2 = table3.columns[offset2];
49835
+ const column2 = table4.columns[offset2];
49733
49836
  if (keys === null) delete column2.filter;
49734
49837
  else
49735
49838
  column2.filter = {
49736
49839
  values: keys.filter((key2) => key2 !== ""),
49737
49840
  ...keys.includes("") ? { blank: true } : {}
49738
49841
  };
49739
- applyTableFilter(ctx.workbook, sheet, table3);
49842
+ applyTableFilter(ctx.workbook, sheet, table4);
49740
49843
  },
49741
49844
  { sheet: target2.sheetIndex, structural: true }
49742
49845
  );
@@ -49807,17 +49910,17 @@ function unique2(base2, taken) {
49807
49910
  function insertSlicer(ctx, s, ref) {
49808
49911
  const { workbook } = ctx;
49809
49912
  const sheet = sheetAt(workbook, s);
49810
- let table3;
49913
+ let table4;
49811
49914
  let pivot;
49812
49915
  let field2;
49813
49916
  if (ref.kind === "table") {
49814
- table3 = sheet.tables.find(
49917
+ table4 = sheet.tables.find(
49815
49918
  (entry3) => entry3.name === ref.table || entry3.displayName === ref.table
49816
49919
  );
49817
- if (!table3?.headerRow || table3.filterNotModeled)
49920
+ if (!table4?.headerRow || table4.filterNotModeled)
49818
49921
  throw new Error("Choose a table with a header row and value filters.");
49819
49922
  field2 = ref.column;
49820
- if (!table3.columns.some((column2) => column2.name === field2))
49923
+ if (!table4.columns.some((column2) => column2.name === field2))
49821
49924
  throw new Error("Choose a column of the table.");
49822
49925
  } else {
49823
49926
  pivot = sheet.pivotTables?.find((entry3) => entry3.name === ref.pivot);
@@ -49837,7 +49940,7 @@ function insertSlicer(ctx, s, ref) {
49837
49940
  (c2) => names.has(c2.toLowerCase())
49838
49941
  ).replace(/ /g, "_");
49839
49942
  const metrics = createGridMetrics(sheet, { zoom: 100 });
49840
- const anchorCell = table3 ? { row: table3.range.start.row, col: table3.range.end.col + 2 } : { row: pivot.location.start.row, col: pivot.location.end.col + 2 };
49943
+ const anchorCell = table4 ? { row: table4.range.start.row, col: table4.range.end.col + 2 } : { row: pivot.location.start.row, col: pivot.location.end.col + 2 };
49841
49944
  const x = Math.max(metrics.colLeft(anchorCell.col), frameBounds(sheet) + 10);
49842
49945
  const box5 = { x, y: metrics.rowTop(anchorCell.row), ...SLICER_BOX };
49843
49946
  const anchor = pixelBoxToAnchor(sheet, box5, metrics, "twoCell");
@@ -49854,13 +49957,13 @@ function insertSlicer(ctx, s, ref) {
49854
49957
  () => {
49855
49958
  const book = cloneBook(workbook);
49856
49959
  let source2;
49857
- if (table3) {
49858
- if (table3.columns.some((column2) => column2.sourceId === void 0))
49859
- table3.columns.forEach((column2, index3) => column2.sourceId ??= index3 + 1);
49960
+ if (table4) {
49961
+ if (table4.columns.some((column2) => column2.sourceId === void 0))
49962
+ table4.columns.forEach((column2, index3) => column2.sourceId ??= index3 + 1);
49860
49963
  source2 = {
49861
49964
  kind: "table",
49862
- tableId: table3.id,
49863
- column: table3.columns.find((column2) => column2.name === field2).sourceId
49965
+ tableId: table4.id,
49966
+ column: table4.columns.find((column2) => column2.name === field2).sourceId
49864
49967
  };
49865
49968
  } else {
49866
49969
  const target2 = pivot;
@@ -50346,9 +50449,9 @@ var SUBTOTAL = {
50346
50449
  var: 110
50347
50450
  };
50348
50451
  var escapeColumn = (name3) => name3.replace(/['#[\]]/g, "'$&");
50349
- function applyTotalsRow(sheet, table3) {
50350
- const row3 = table3.range.end.row;
50351
- const { columns } = table3;
50452
+ function applyTotalsRow(sheet, table4) {
50453
+ const row3 = table4.range.end.row;
50454
+ const { columns } = table4;
50352
50455
  if (!columns.some((c2) => c2.totalsRowFunction || c2.totalsRowLabel)) {
50353
50456
  const first3 = columns[0];
50354
50457
  const last = columns[columns.length - 1];
@@ -50356,12 +50459,12 @@ function applyTotalsRow(sheet, table3) {
50356
50459
  if (last) last.totalsRowFunction = "sum";
50357
50460
  }
50358
50461
  columns.forEach((column2, i2) => {
50359
- const col = table3.range.start.col + i2;
50462
+ const col = table4.range.start.col + i2;
50360
50463
  const code = SUBTOTAL[column2.totalsRowFunction ?? ""];
50361
50464
  if (code !== void 0) {
50362
50465
  const cell = ensureCell(sheet, row3, col);
50363
50466
  clearContents(cell);
50364
- cell.formula = `SUBTOTAL(${code},${table3.name}[${escapeColumn(column2.name)}])`;
50467
+ cell.formula = `SUBTOTAL(${code},${table4.name}[${escapeColumn(column2.name)}])`;
50365
50468
  } else if (column2.totalsRowLabel && column2.totalsRowFunction !== "custom")
50366
50469
  writeValue(sheet, row3, col, column2.totalsRowLabel);
50367
50470
  });
@@ -50385,8 +50488,8 @@ function validateTableName(workbook, name3, self) {
50385
50488
  ) || workbook.definedNames.some((n) => n.name.toLowerCase() === lower3);
50386
50489
  return taken ? "That name is already used by another table or name." : void 0;
50387
50490
  }
50388
- function renameTableIn(workbook, table3, name3) {
50389
- const old = table3.name;
50491
+ function renameTableIn(workbook, table4, name3) {
50492
+ const old = table4.name;
50390
50493
  if (old === name3) return;
50391
50494
  const rename = (f6) => renameTableInFormula(f6, old, name3);
50392
50495
  rewriteFormulas(workbook, rename);
@@ -50395,73 +50498,73 @@ function renameTableIn(workbook, table3, name3) {
50395
50498
  for (const column2 of t.columns)
50396
50499
  if (column2.calculatedColumnFormula)
50397
50500
  column2.calculatedColumnFormula = rename(column2.calculatedColumnFormula);
50398
- table3.name = name3;
50399
- table3.displayName = name3;
50501
+ table4.name = name3;
50502
+ table4.displayName = name3;
50400
50503
  }
50401
50504
  var byId = (sheet, id3) => {
50402
- const table3 = sheet.tables.find((t) => t.id === id3);
50403
- if (!table3) throw new Error("The table disappeared during the edit.");
50404
- return table3;
50505
+ const table4 = sheet.tables.find((t) => t.id === id3);
50506
+ if (!table4) throw new Error("The table disappeared during the edit.");
50507
+ return table4;
50405
50508
  };
50406
- function insertBandRow(workbook, sheet, table3, row3) {
50509
+ function insertBandRow(workbook, sheet, table4, row3) {
50407
50510
  const shift2 = { axis: "row", at: row3, count: 1 };
50408
- const band2 = { lo: table3.range.start.col, hi: table3.range.end.col };
50511
+ const band2 = { lo: table4.range.start.col, hi: table4.range.end.col };
50409
50512
  assertInsertFits(sheet, shift2, band2);
50410
50513
  rewriteFormulas(workbook, (f6, fs) => shiftFormulaInBand(f6, fs, sheet.name, shift2, band2));
50411
50514
  shiftSheetContent(sheet, shift2, band2);
50412
50515
  }
50413
50516
  function setHeaderRow(workbook, sheet, id3, on) {
50414
- let table3 = byId(sheet, id3);
50415
- if (table3.headerRow === on) return;
50416
- const { start, end } = table3.range;
50517
+ let table4 = byId(sheet, id3);
50518
+ if (table4.headerRow === on) return;
50519
+ const { start, end } = table4.range;
50417
50520
  if (!on) {
50418
50521
  if (start.row === end.row) throw new Error("A table needs at least one row.");
50419
50522
  clearRow(sheet, start.row, start.col, end.col);
50420
- table3.range = { start: { row: start.row + 1, col: start.col }, end };
50421
- table3.headerRow = false;
50523
+ table4.range = { start: { row: start.row + 1, col: start.col }, end };
50524
+ table4.headerRow = false;
50422
50525
  return;
50423
50526
  }
50424
50527
  if (start.row === 0 || !rowIsEmpty(sheet, start.row - 1, start.col, end.col)) {
50425
- insertBandRow(workbook, sheet, table3, start.row);
50426
- table3 = byId(sheet, id3);
50427
- }
50428
- const top = table3.range.start.row - 1;
50429
- const left2 = table3.range.start.col;
50430
- table3.range = { start: { row: top, col: left2 }, end: table3.range.end };
50431
- table3.headerRow = true;
50432
- uniqueHeaders(table3.columns.map((c2) => c2.name)).forEach((name3, i2) => {
50433
- const column2 = table3.columns[i2];
50528
+ insertBandRow(workbook, sheet, table4, start.row);
50529
+ table4 = byId(sheet, id3);
50530
+ }
50531
+ const top = table4.range.start.row - 1;
50532
+ const left2 = table4.range.start.col;
50533
+ table4.range = { start: { row: top, col: left2 }, end: table4.range.end };
50534
+ table4.headerRow = true;
50535
+ uniqueHeaders(table4.columns.map((c2) => c2.name)).forEach((name3, i2) => {
50536
+ const column2 = table4.columns[i2];
50434
50537
  if (column2) column2.name = name3;
50435
50538
  writeValue(sheet, top, left2 + i2, name3);
50436
50539
  });
50437
50540
  }
50438
50541
  function setTotalsRow(workbook, sheet, id3, on) {
50439
- let table3 = byId(sheet, id3);
50440
- if (table3.totalsRow === on) return;
50441
- const { start, end } = table3.range;
50542
+ let table4 = byId(sheet, id3);
50543
+ if (table4.totalsRow === on) return;
50544
+ const { start, end } = table4.range;
50442
50545
  if (!on) {
50443
50546
  clearRow(sheet, end.row, start.col, end.col);
50444
- table3.range = { start, end: { row: end.row - 1, col: end.col } };
50445
- table3.totalsRow = false;
50547
+ table4.range = { start, end: { row: end.row - 1, col: end.col } };
50548
+ table4.totalsRow = false;
50446
50549
  return;
50447
50550
  }
50448
50551
  if (end.row === MAX_ROW) throw new RangeError("The insert area extends beyond the sheet.");
50449
50552
  if (!rowIsEmpty(sheet, end.row + 1, start.col, end.col)) {
50450
- insertBandRow(workbook, sheet, table3, end.row + 1);
50451
- table3 = byId(sheet, id3);
50553
+ insertBandRow(workbook, sheet, table4, end.row + 1);
50554
+ table4 = byId(sheet, id3);
50452
50555
  }
50453
- table3.range = { start: table3.range.start, end: { row: table3.range.end.row + 1, col: end.col } };
50454
- table3.totalsRow = true;
50455
- applyTotalsRow(sheet, table3);
50556
+ table4.range = { start: table4.range.start, end: { row: table4.range.end.row + 1, col: end.col } };
50557
+ table4.totalsRow = true;
50558
+ applyTotalsRow(sheet, table4);
50456
50559
  }
50457
- function resizedColumns(workbook, sheet, table3, range2) {
50560
+ function resizedColumns(workbook, sheet, table4, range2) {
50458
50561
  const width = range2.end.col - range2.start.col + 1;
50459
- const oldAt = (col) => col >= table3.range.start.col && col <= table3.range.end.col ? table3.columns[col - table3.range.start.col] : void 0;
50562
+ const oldAt = (col) => col >= table4.range.start.col && col <= table4.range.end.col ? table4.columns[col - table4.range.start.col] : void 0;
50460
50563
  const texts = Array.from({ length: width }, (_v, i2) => {
50461
50564
  const col = range2.start.col + i2;
50462
50565
  const old = oldAt(col);
50463
50566
  if (old) return old.name;
50464
- return table3.headerRow ? displayText(workbook, getCell(sheet, range2.start.row, col)) : "";
50567
+ return table4.headerRow ? displayText(workbook, getCell(sheet, range2.start.row, col)) : "";
50465
50568
  });
50466
50569
  return uniqueHeaders(texts).map((name3, i2) => {
50467
50570
  const old = oldAt(range2.start.col + i2);
@@ -50469,30 +50572,30 @@ function resizedColumns(workbook, sheet, table3, range2) {
50469
50572
  });
50470
50573
  }
50471
50574
  function resizeTableIn(workbook, sheet, id3, range2) {
50472
- const table3 = byId(sheet, id3);
50575
+ const table4 = byId(sheet, id3);
50473
50576
  const r = normalizeRange(range2);
50474
- if (table3.headerRow && r.start.row !== table3.range.start.row)
50577
+ if (table4.headerRow && r.start.row !== table4.range.start.row)
50475
50578
  throw new Error("The table headers must remain in the same row.");
50476
- if (!rangesIntersect(r, table3.range)) throw new Error("The new range must overlap the table.");
50477
- if (r.end.row - r.start.row + 1 < (table3.headerRow ? 2 : 1) + (table3.totalsRow ? 1 : 0))
50579
+ if (!rangesIntersect(r, table4.range)) throw new Error("The new range must overlap the table.");
50580
+ if (r.end.row - r.start.row + 1 < (table4.headerRow ? 2 : 1) + (table4.totalsRow ? 1 : 0))
50478
50581
  throw new Error("The table range is too small.");
50479
- if (sheet.tables.some((t) => t !== table3 && rangesIntersect(t.range, r)))
50582
+ if (sheet.tables.some((t) => t !== table4 && rangesIntersect(t.range, r)))
50480
50583
  throw new Error("A table cannot overlap another table.");
50481
50584
  if (sheet.pivotTables?.some((pivot) => rangesIntersect(pivot.location, r)))
50482
50585
  throw new Error("A table cannot overlap a PivotTable.");
50483
50586
  if (sheet.merges.some((m) => rangesIntersect(m, r)))
50484
50587
  throw new Error("A table cannot contain merged cells.");
50485
- const oldEnd = table3.range.end.row;
50486
- table3.columns = resizedColumns(workbook, sheet, table3, r);
50487
- table3.range = r;
50488
- if (table3.headerRow)
50489
- table3.columns.forEach((column2, i2) => {
50588
+ const oldEnd = table4.range.end.row;
50589
+ table4.columns = resizedColumns(workbook, sheet, table4, r);
50590
+ table4.range = r;
50591
+ if (table4.headerRow)
50592
+ table4.columns.forEach((column2, i2) => {
50490
50593
  const cell = getCell(sheet, r.start.row, r.start.col + i2);
50491
50594
  if (cell?.value !== column2.name) writeValue(sheet, r.start.row, r.start.col + i2, column2.name);
50492
50595
  });
50493
- if (table3.totalsRow) {
50596
+ if (table4.totalsRow) {
50494
50597
  if (oldEnd !== r.end.row) clearRow(sheet, oldEnd, r.start.col, r.end.col);
50495
- applyTotalsRow(sheet, table3);
50598
+ applyTotalsRow(sheet, table4);
50496
50599
  }
50497
50600
  }
50498
50601
  var STYLE_KEYS = [
@@ -50520,20 +50623,20 @@ function updateTable(ctx, s, ref, patch2) {
50520
50623
  "structure",
50521
50624
  [scope],
50522
50625
  () => {
50523
- const table3 = byId(sheet, id3);
50524
- if (renaming) renameTableIn(workbook, table3, name3);
50626
+ const table4 = byId(sheet, id3);
50627
+ if (renaming) renameTableIn(workbook, table4, name3);
50525
50628
  for (const key2 of STYLE_KEYS) {
50526
50629
  if (!(key2 in patch2)) continue;
50527
50630
  const value2 = patch2[key2];
50528
- if (value2 === void 0) delete table3[key2];
50529
- else table3[key2] = value2;
50631
+ if (value2 === void 0) delete table4[key2];
50632
+ else table4[key2] = value2;
50530
50633
  }
50531
50634
  if (patch2.columns) {
50532
- const width = table3.range.end.col - table3.range.start.col + 1;
50635
+ const width = table4.range.end.col - table4.range.start.col + 1;
50533
50636
  if (patch2.columns.length !== width) throw new Error("Give one column per table column.");
50534
- const before = table3.columns;
50535
- table3.columns = structuredClone(patch2.columns);
50536
- for (const [index3, column2] of table3.columns.entries()) {
50637
+ const before = table4.columns;
50638
+ table4.columns = structuredClone(patch2.columns);
50639
+ for (const [index3, column2] of table4.columns.entries()) {
50537
50640
  const sourceId = before[index3]?.sourceId;
50538
50641
  if (column2.sourceId === void 0 && sourceId !== void 0) column2.sourceId = sourceId;
50539
50642
  const filter2 = before[index3]?.filter;
@@ -50542,7 +50645,7 @@ function updateTable(ctx, s, ref, patch2) {
50542
50645
  }
50543
50646
  if (patch2.headerRow !== void 0) setHeaderRow(workbook, sheet, id3, patch2.headerRow);
50544
50647
  if (patch2.totalsRow !== void 0) setTotalsRow(workbook, sheet, id3, patch2.totalsRow);
50545
- else if (patch2.columns && table3.totalsRow) applyTotalsRow(sheet, byId(sheet, id3));
50648
+ else if (patch2.columns && table4.totalsRow) applyTotalsRow(sheet, byId(sheet, id3));
50546
50649
  if (patch2.range) resizeTableIn(workbook, sheet, id3, patch2.range);
50547
50650
  },
50548
50651
  { sheet: s, ranges: [current.range], structural: true }
@@ -50562,13 +50665,13 @@ function resizeTable(ctx, s, ref, range2) {
50562
50665
  function convertTableToRange(ctx, s, ref) {
50563
50666
  const { workbook } = ctx;
50564
50667
  const sheet = sheetAt(workbook, s);
50565
- const table3 = sheet.tables[tableIndex(sheet, ref)];
50668
+ const table4 = sheet.tables[tableIndex(sheet, ref)];
50566
50669
  ctx.run(
50567
50670
  "Convert to range",
50568
50671
  "structure",
50569
50672
  [{ kind: "workbook" }],
50570
50673
  () => {
50571
- const live2 = byId(sheet, table3.id);
50674
+ const live2 = byId(sheet, table4.id);
50572
50675
  const base2 = { table: live2, tableSheet: sheet.name };
50573
50676
  const { start, end } = live2.range;
50574
50677
  for (const ws of workbook.sheets)
@@ -50593,7 +50696,7 @@ function convertTableToRange(ctx, s, ref) {
50593
50696
  });
50594
50697
  sheet.tables = sheet.tables.filter((t) => t.id !== live2.id);
50595
50698
  },
50596
- { sheet: s, ranges: [table3.range], structural: true }
50699
+ { sheet: s, ranges: [table4.range], structural: true }
50597
50700
  );
50598
50701
  }
50599
50702
 
@@ -53499,7 +53602,7 @@ function createTable2(ctx, s, range2, hasHeader, styleName = "TableStyleMedium2"
53499
53602
  });
53500
53603
  const name3 = nextTableName(workbook);
53501
53604
  const id3 = Math.max(0, ...workbook.sheets.flatMap((ws) => ws.tables.map((t) => t.id))) + 1;
53502
- const table3 = {
53605
+ const table4 = {
53503
53606
  id: id3,
53504
53607
  name: name3,
53505
53608
  displayName: name3,
@@ -53513,8 +53616,8 @@ function createTable2(ctx, s, range2, hasHeader, styleName = "TableStyleMedium2"
53513
53616
  showFirstColumn: false,
53514
53617
  showLastColumn: false
53515
53618
  };
53516
- sheet.tables.push(table3);
53517
- return table3;
53619
+ sheet.tables.push(table4);
53620
+ return table4;
53518
53621
  },
53519
53622
  { sheet: s, ranges: [r], structural: !hasHeader }
53520
53623
  );
@@ -53718,8 +53821,8 @@ function createEditSession(workbook, options = {}) {
53718
53821
  if (!workbook.warnings.includes(message)) workbook.warnings.push(message);
53719
53822
  }
53720
53823
  };
53721
- const begin = (label5, kind, info) => {
53722
- const step2 = { label: label5, entries: [], structural: info.structural ?? false };
53824
+ const begin = (label2, kind, info) => {
53825
+ const step2 = { label: label2, entries: [], structural: info.structural ?? false };
53723
53826
  if (info.calc) step2.calc = info.calc;
53724
53827
  return { step: step2, kind, sheet: info.sheet, ranges: [...info.ranges ?? []] };
53725
53828
  };
@@ -53743,7 +53846,7 @@ function createEditSession(workbook, options = {}) {
53743
53846
  }
53744
53847
  current.step.entries.length = from;
53745
53848
  };
53746
- const run2 = (label5, kind, scopes, fn, info = {}) => {
53849
+ const run2 = (label2, kind, scopes, fn, info = {}) => {
53747
53850
  if (kind === "cells") {
53748
53851
  for (const scope of scopes)
53749
53852
  if (scope.kind === "cells" && workbook.sheets[scope.sheet]?.pivotTables?.some(
@@ -53760,7 +53863,7 @@ function createEditSession(workbook, options = {}) {
53760
53863
  }))
53761
53864
  throw new Error(DATA_TABLE_PART_ERROR);
53762
53865
  const outer = !open;
53763
- const current = open ?? begin(label5, kind, info);
53866
+ const current = open ?? begin(label2, kind, info);
53764
53867
  if (!outer) {
53765
53868
  delete current.step.calc;
53766
53869
  if (info.structural) current.step.structural = true;
@@ -53891,9 +53994,9 @@ function createEditSession(workbook, options = {}) {
53891
53994
  removeConditionalFormat: (s, index3) => removeConditionalFormat(ctx, s, index3),
53892
53995
  setConditionalRulePriority: (s, f6, r, priority) => setConditionalRulePriority(ctx, s, f6, r, priority),
53893
53996
  moveConditionalRule: (s, f6, r, direction) => moveConditionalRule(ctx, s, f6, r, direction),
53894
- updateTable: (s, table3, patch2) => updateTable(ctx, s, table3, patch2),
53895
- resizeTable: (s, table3, range2) => resizeTable(ctx, s, table3, range2),
53896
- convertTableToRange: (s, table3) => convertTableToRange(ctx, s, table3),
53997
+ updateTable: (s, table4, patch2) => updateTable(ctx, s, table4, patch2),
53998
+ resizeTable: (s, table4, range2) => resizeTable(ctx, s, table4, range2),
53999
+ convertTableToRange: (s, table4) => convertTableToRange(ctx, s, table4),
53897
54000
  applyCellStyle: (s, ranges, name3) => applyCellStyle(ctx, s, ranges, name3),
53898
54001
  setPageSetup: (s, patch2) => setPageSetup(ctx, s, patch2),
53899
54002
  setPageBreak: (s, axis, before, present) => setPageBreak(ctx, s, axis, before, present),
@@ -53930,12 +54033,12 @@ function createEditSession(workbook, options = {}) {
53930
54033
  validate: (s, r, c2, value2) => validateCellInput(workbook, s, r, c2, value2, {
53931
54034
  evaluate: (formula, at2) => calc.evaluate(formula, at2)
53932
54035
  }),
53933
- batch(label5, fn) {
54036
+ batch(label2, fn) {
53934
54037
  if (open) {
53935
54038
  fn();
53936
54039
  return;
53937
54040
  }
53938
- const current = begin(label5, "batch", {});
54041
+ const current = begin(label2, "batch", {});
53939
54042
  open = current;
53940
54043
  try {
53941
54044
  fn();
@@ -54615,9 +54718,9 @@ var VisioPackage = class _VisioPackage {
54615
54718
  };
54616
54719
 
54617
54720
  // visio/metadata.ts
54618
- function metadata(value2, max, label5) {
54721
+ function metadata(value2, max, label2) {
54619
54722
  if (value2.length > max)
54620
- throw new VisioPackageError("METADATA_LIMIT", `${label5} exceeds its metadata length limit.`);
54723
+ throw new VisioPackageError("METADATA_LIMIT", `${label2} exceeds its metadata length limit.`);
54621
54724
  return value2;
54622
54725
  }
54623
54726
  function metadataAttributes(node3) {
@@ -58569,15 +58672,15 @@ function legacyFillGradient(cells3, width, height, resolve3) {
58569
58672
 
58570
58673
  // ../../node_modules/.bun/@christophervr+ole2@0.13.0/node_modules/@christophervr/ole2/dist/utils/png-encoder.js
58571
58674
  var CRC_TABLE = (() => {
58572
- const table3 = new Uint32Array(256);
58675
+ const table4 = new Uint32Array(256);
58573
58676
  for (let n = 0; n < 256; n++) {
58574
58677
  let c2 = n;
58575
58678
  for (let k = 0; k < 8; k++) {
58576
58679
  c2 = c2 & 1 ? 3988292384 ^ c2 >>> 1 : c2 >>> 1;
58577
58680
  }
58578
- table3[n] = c2 >>> 0;
58681
+ table4[n] = c2 >>> 0;
58579
58682
  }
58580
- return table3;
58683
+ return table4;
58581
58684
  })();
58582
58685
  function crc322(bytes) {
58583
58686
  let crc = 4294967295;
@@ -61251,7 +61354,7 @@ function property(row3, budget, report) {
61251
61354
  "Shape data has no supported current cached typed value; original cached text is retained."
61252
61355
  );
61253
61356
  }
61254
- const label5 = get("Label"), format5 = get("Format"), prompt = get("Prompt"), sortKey = get("SortKey");
61357
+ const label2 = get("Label"), format5 = get("Format"), prompt = get("Prompt"), sortKey = get("SortKey");
61255
61358
  const invisible = boolean(row3.cells, "Invisible", budget, report);
61256
61359
  const dataLinked = row3.cells.has("DataLinked") ? boolean(row3.cells, "DataLinked", budget, report) : void 0;
61257
61360
  const unit3 = row3.cells.get("Value")?.unit, error = row3.cells.get("Value")?.error;
@@ -61263,7 +61366,7 @@ function property(row3, budget, report) {
61263
61366
  ...rawType === void 0 ? {} : { rawType },
61264
61367
  ...rawValue === void 0 ? {} : { rawValue },
61265
61368
  ...value2 === void 0 ? {} : { value: value2 },
61266
- ...label5 === void 0 ? {} : { label: label5 },
61369
+ ...label2 === void 0 ? {} : { label: label2 },
61267
61370
  ...format5 === void 0 ? {} : { format: format5 },
61268
61371
  ...prompt === void 0 ? {} : { prompt },
61269
61372
  ...sortKey === void 0 ? {} : { sortKey },
@@ -61496,9 +61599,9 @@ async function readDataRecordsets(pkg, documentPart, check3) {
61496
61599
  const declared = children3(children3(set, "DataColumns")[0], "DataColumn");
61497
61600
  const columns = (declared.length ? declared : []).map((node3) => {
61498
61601
  const name4 = attribute3(node3, "ColumnNameID") ?? attribute3(node3, "Name") ?? "";
61499
- const label5 = attribute3(node3, "Label") ?? attribute3(node3, "Name") ?? name4;
61500
- if (!name4 || name4.length > 255 || label5.length > 255) invalid2("Invalid data column.");
61501
- return { name: name4, label: label5, type: typeFromCode(attribute3(node3, "DataType")) };
61602
+ const label2 = attribute3(node3, "Label") ?? attribute3(node3, "Name") ?? name4;
61603
+ if (!name4 || name4.length > 255 || label2.length > 255) invalid2("Invalid data column.");
61604
+ return { name: name4, label: label2, type: typeFromCode(attribute3(node3, "DataType")) };
61502
61605
  });
61503
61606
  if (!columns.length)
61504
61607
  for (const column2 of ado.columns)
@@ -68161,18 +68264,18 @@ function advances(family, bold) {
68161
68264
  const key2 = `${name3}|${bold ? "b" : "r"}`;
68162
68265
  const known = decoded.get(key2);
68163
68266
  if (known) return known;
68164
- const table3 = Object.hasOwn(DESIGN_ADVANCES, name3) ? DESIGN_ADVANCES[name3] : void 0;
68165
- if (!table3) return void 0;
68166
- const values2 = (bold ? table3.bold : table3.regular).split(" ").map(Number);
68267
+ const table4 = Object.hasOwn(DESIGN_ADVANCES, name3) ? DESIGN_ADVANCES[name3] : void 0;
68268
+ if (!table4) return void 0;
68269
+ const values2 = (bold ? table4.bold : table4.regular).split(" ").map(Number);
68167
68270
  decoded.set(key2, values2);
68168
68271
  return values2;
68169
68272
  }
68170
68273
  function designTextWidthEm(text8, family, bold = false) {
68171
- const table3 = advances(family, bold);
68172
- if (!table3) return void 0;
68274
+ const table4 = advances(family, bold);
68275
+ if (!table4) return void 0;
68173
68276
  let units2 = 0;
68174
68277
  for (let index3 = 0; index3 < text8.length; ++index3) {
68175
- const advance = table3[text8.charCodeAt(index3) - FIRST];
68278
+ const advance = table4[text8.charCodeAt(index3) - FIRST];
68176
68279
  if (advance === void 0 || Number.isNaN(advance)) return void 0;
68177
68280
  units2 += advance;
68178
68281
  }
@@ -71383,9 +71486,9 @@ function visioBorderShapes(style3, width, height, title = VISIO_DEFAULT_TITLE) {
71383
71486
  // visio/edit-page-setup-commands.ts
71384
71487
  var VISIO_SCALE_UNITS = Object.freeze(["IN", "FT", "MM", "CM", "M"]);
71385
71488
  var isVisioPageSetupEdit = (edit) => edit.type === "set-page-alt-text" || edit.type === "set-page-setup" || edit.type === "set-page-properties" || edit.type === "set-page-decoration" || edit.type === "set-page-layout" || edit.type === "set-snap-glue";
71386
- var pageId = (value2, label5) => {
71489
+ var pageId = (value2, label2) => {
71387
71490
  if (typeof value2 !== "string" || !value2 || value2.length > 256)
71388
- fail2("INVALID_EDIT", `Invalid ${label5}.`);
71491
+ fail2("INVALID_EDIT", `Invalid ${label2}.`);
71389
71492
  return value2;
71390
71493
  };
71391
71494
  var newPageId = (value2) => {
@@ -71492,11 +71595,11 @@ var VISIO_SHAPE_DATA_TYPES = [
71492
71595
  "date"
71493
71596
  ];
71494
71597
  var invalidText2 = /[\u0000-\u0008\u000b\u000c\u000e-\u001f￾￿]|[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/u;
71495
- function shapeDataText(value2, label5) {
71598
+ function shapeDataText(value2, label2) {
71496
71599
  if (typeof value2 !== "string" || value2.length > VISIO_METADATA_TEXT_LIMIT)
71497
- fail2("INVALID_EDIT", `${label5} must be a string within the length limit.`);
71600
+ fail2("INVALID_EDIT", `${label2} must be a string within the length limit.`);
71498
71601
  if (invalidText2.test(value2) || /[\r\n\t]/.test(value2))
71499
- fail2("INVALID_EDIT_TEXT", `${label5} contains invalid characters.`);
71602
+ fail2("INVALID_EDIT_TEXT", `${label2} contains invalid characters.`);
71500
71603
  return value2;
71501
71604
  }
71502
71605
  function shapeDataRowName(value2) {
@@ -71504,9 +71607,9 @@ function shapeDataRowName(value2) {
71504
71607
  fail2("INVALID_EDIT", "Shape Data row names use letters, digits and underscores.");
71505
71608
  return value2;
71506
71609
  }
71507
- function visioShapeDataRowName(label5, taken = []) {
71610
+ function visioShapeDataRowName(label2, taken = []) {
71508
71611
  const used = new Set([...taken].map((name4) => name4.toLowerCase()));
71509
- let base2 = label5.normalize("NFKD").replace(/[^\w]+/g, "_").replace(/^_+|_+$/g, "").slice(0, 48);
71612
+ let base2 = label2.normalize("NFKD").replace(/[^\w]+/g, "_").replace(/^_+|_+$/g, "").slice(0, 48);
71510
71613
  if (!base2) base2 = "Property";
71511
71614
  if (/^\d/.test(base2)) base2 = `_${base2}`;
71512
71615
  let name3 = base2;
@@ -71578,18 +71681,18 @@ var TYPES3 = [
71578
71681
  "unlink-data-rows"
71579
71682
  ];
71580
71683
  var isVisioDataEdit = (edit) => TYPES3.includes(edit.type);
71581
- var id = (value2, label5) => {
71684
+ var id = (value2, label2) => {
71582
71685
  if (typeof value2 !== "string" || !/^(0|[1-9]\d{0,9})$/.test(value2) || Number(value2) > 4294967295)
71583
- fail2("INVALID_EDIT", `Invalid ${label5}.`);
71686
+ fail2("INVALID_EDIT", `Invalid ${label2}.`);
71584
71687
  return value2;
71585
71688
  };
71586
- var name = (value2, label5) => {
71587
- const text8 = shapeDataText(value2, label5);
71689
+ var name = (value2, label2) => {
71690
+ const text8 = shapeDataText(value2, label2);
71588
71691
  if (!text8.trim() || text8.length > 255)
71589
- fail2("INVALID_EDIT", `${label5} must be 1 to 255 characters.`);
71692
+ fail2("INVALID_EDIT", `${label2} must be 1 to 255 characters.`);
71590
71693
  return text8;
71591
71694
  };
71592
- function table2(columns, rows) {
71695
+ function table3(columns, rows) {
71593
71696
  if (!Array.isArray(columns) || !columns.length || columns.length > VISIO_DATA_LIMITS.maxColumns)
71594
71697
  fail2("INVALID_EDIT", `A recordset needs 1 to ${VISIO_DATA_LIMITS.maxColumns} columns.`);
71595
71698
  if (!Array.isArray(rows) || rows.length > VISIO_DATA_LIMITS.maxRows)
@@ -71635,14 +71738,14 @@ function snapshotDataEdit(edit) {
71635
71738
  type: edit.type,
71636
71739
  pageId: pageId2,
71637
71740
  name: name(edit.name, "The recordset name"),
71638
- ...table2(edit.columns, edit.rows)
71741
+ ...table3(edit.columns, edit.rows)
71639
71742
  };
71640
71743
  case "refresh-data-recordset":
71641
71744
  return {
71642
71745
  type: edit.type,
71643
71746
  pageId: pageId2,
71644
71747
  recordsetId: id(edit.recordsetId, "recordset"),
71645
- ...table2(edit.columns, edit.rows)
71748
+ ...table3(edit.columns, edit.rows)
71646
71749
  };
71647
71750
  case "delete-data-recordset":
71648
71751
  return { type: edit.type, pageId: pageId2, recordsetId: id(edit.recordsetId, "recordset") };
@@ -71701,16 +71804,16 @@ function snapshotPageTheme(edit) {
71701
71804
  var isVisioCommentEdit = (edit) => edit.type === "add-comment" || edit.type === "edit-comment" || edit.type === "delete-comment";
71702
71805
  var invalidText3 = /[\u0000-\u0008\u000b\u000c\u000e-\u001f￾￿]|[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/u;
71703
71806
  var dateTime = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,7})?(?:Z|[+-]\d{2}:\d{2})?$/;
71704
- function string(value2, limit3, label5, required = true) {
71807
+ function string(value2, limit3, label2, required = true) {
71705
71808
  if (typeof value2 !== "string" || value2.length > limit3 || required && !value2.trim())
71706
- fail2("INVALID_EDIT", `${label5} must be a non-empty string within its length limit.`);
71809
+ fail2("INVALID_EDIT", `${label2} must be a non-empty string within its length limit.`);
71707
71810
  if (invalidText3.test(value2))
71708
- fail2("INVALID_EDIT_TEXT", `${label5} contains invalid XML characters.`);
71811
+ fail2("INVALID_EDIT_TEXT", `${label2} contains invalid XML characters.`);
71709
71812
  return value2;
71710
71813
  }
71711
- var id2 = (value2, label5) => {
71814
+ var id2 = (value2, label2) => {
71712
71815
  if (typeof value2 !== "string" || !/^(0|[1-9]\d{0,9})$/.test(value2) || Number(value2) > 4294967295)
71713
- fail2("INVALID_EDIT", `${label5} must be a canonical unsigned integer.`);
71816
+ fail2("INVALID_EDIT", `${label2} must be a canonical unsigned integer.`);
71714
71817
  return value2;
71715
71818
  };
71716
71819
  var date = (value2) => {
@@ -72233,7 +72336,7 @@ async function editVsdxMasterInstance(pkg, parts, pages, edit, limits, maxOutput
72233
72336
 
72234
72337
  // visio/paper-sizes.ts
72235
72338
  var mm = (value2) => value2 / 25.4;
72236
- var size = (id3, label5, width, height, paperKind) => Object.freeze({ id: id3, label: label5, width, height, ...paperKind === void 0 ? {} : { paperKind } });
72339
+ var size = (id3, label2, width, height, paperKind) => Object.freeze({ id: id3, label: label2, width, height, ...paperKind === void 0 ? {} : { paperKind } });
72237
72340
  var VISIO_PAPER_SIZES = Object.freeze([
72238
72341
  size("letter", "Letter", 8.5, 11, 1),
72239
72342
  size("tabloid", "Tabloid", 11, 17, 3),
@@ -73603,7 +73706,7 @@ function snapshotFormatting(edit) {
73603
73706
  if (!Number.isInteger(value2)) fail2("INVALID_EDIT", "Paint patterns require integers.");
73604
73707
  result2[name3] = value2;
73605
73708
  }
73606
- for (const [name3, maximum, label5] of [
73709
+ for (const [name3, maximum, label2] of [
73607
73710
  ["beginArrow", 45, "Arrowheads are numbered 0 to 45."],
73608
73711
  ["endArrow", 45, "Arrowheads are numbered 0 to 45."],
73609
73712
  ["beginArrowSize", 6, "Arrowhead sizes are numbered 0 to 6."],
@@ -73617,7 +73720,7 @@ function snapshotFormatting(edit) {
73617
73720
  const value2 = edit[name3];
73618
73721
  if (value2 === void 0) continue;
73619
73722
  if (typeof value2 !== "number" || !Number.isInteger(value2) || value2 < 0 || value2 > maximum)
73620
- fail2("INVALID_EDIT", label5);
73723
+ fail2("INVALID_EDIT", label2);
73621
73724
  result2[name3] = value2;
73622
73725
  }
73623
73726
  if (edit.rounding !== void 0) result2.rounding = points(edit.rounding, 0, 720);