@pixerate/editor 0.52.0 → 0.54.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 (142) hide show
  1. package/dist/agent/index.cjs +37 -29
  2. package/dist/agent/index.cjs.map +1 -1
  3. package/dist/agent/index.d.cts +4 -3
  4. package/dist/agent/index.d.ts +4 -3
  5. package/dist/agent/index.js +16 -8
  6. package/dist/agent/index.js.map +1 -1
  7. package/dist/animation/index.cjs +15 -1
  8. package/dist/animation/index.cjs.map +1 -1
  9. package/dist/animation/index.d.cts +3 -226
  10. package/dist/animation/index.d.ts +3 -226
  11. package/dist/animation/index.js +14 -0
  12. package/dist/bridge/cli.cjs +36 -0
  13. package/dist/bridge/cli.cjs.map +1 -0
  14. package/dist/bridge/cli.d.cts +1 -0
  15. package/dist/bridge/cli.d.ts +1 -0
  16. package/dist/bridge/cli.js +36 -0
  17. package/dist/bridge/cli.js.map +1 -0
  18. package/dist/bridge/index.cjs +16 -0
  19. package/dist/bridge/index.cjs.map +1 -0
  20. package/dist/bridge/index.d.cts +65 -0
  21. package/dist/bridge/index.d.ts +65 -0
  22. package/dist/bridge/index.js +16 -0
  23. package/dist/bridge/index.js.map +1 -0
  24. package/dist/bridge-client-C5OziCRK.d.cts +148 -0
  25. package/dist/bridge-client-C5dRjrz5.d.ts +148 -0
  26. package/dist/canvas/index.cjs +1308 -528
  27. package/dist/canvas/index.cjs.map +1 -1
  28. package/dist/canvas/index.d.cts +309 -5
  29. package/dist/canvas/index.d.ts +309 -5
  30. package/dist/canvas/index.js +1295 -515
  31. package/dist/canvas/index.js.map +1 -1
  32. package/dist/chart/index.cjs +193 -192
  33. package/dist/chart/index.cjs.map +1 -1
  34. package/dist/chart/index.d.cts +77 -59
  35. package/dist/chart/index.d.ts +77 -59
  36. package/dist/chart/index.js +87 -86
  37. package/dist/chart/index.js.map +1 -1
  38. package/dist/{chunk-UAW5FEMD.js → chunk-3S72F46R.js} +66 -8
  39. package/dist/chunk-3S72F46R.js.map +1 -0
  40. package/dist/{chunk-5TWIN7ZJ.js → chunk-47WWV3LI.js} +34 -4
  41. package/dist/chunk-47WWV3LI.js.map +1 -0
  42. package/dist/{chunk-OV7UAKIY.js → chunk-633QC34G.js} +172 -1
  43. package/dist/chunk-633QC34G.js.map +1 -0
  44. package/dist/chunk-AWKPSOSX.js +401 -0
  45. package/dist/chunk-AWKPSOSX.js.map +1 -0
  46. package/dist/chunk-B6DSIEXA.js +96 -0
  47. package/dist/chunk-B6DSIEXA.js.map +1 -0
  48. package/dist/{chunk-5N6AQCVB.js → chunk-BQQZ6MOI.js} +3 -3
  49. package/dist/{chunk-M5Z77GFH.cjs → chunk-C3JHII3M.cjs} +53 -53
  50. package/dist/{chunk-M5Z77GFH.cjs.map → chunk-C3JHII3M.cjs.map} +1 -1
  51. package/dist/{chunk-JOX6MJW4.cjs → chunk-CKRNELPO.cjs} +176 -5
  52. package/dist/chunk-CKRNELPO.cjs.map +1 -0
  53. package/dist/{chunk-TGBCBQFV.cjs → chunk-DK6QBGCS.cjs} +45 -15
  54. package/dist/chunk-DK6QBGCS.cjs.map +1 -0
  55. package/dist/chunk-EGFUVXKK.cjs +96 -0
  56. package/dist/chunk-EGFUVXKK.cjs.map +1 -0
  57. package/dist/{chunk-AMWXSYCI.js → chunk-GPWNYQ7R.js} +2 -370
  58. package/dist/chunk-GPWNYQ7R.js.map +1 -0
  59. package/dist/chunk-H5K77C7Y.cjs +3848 -0
  60. package/dist/chunk-H5K77C7Y.cjs.map +1 -0
  61. package/dist/chunk-K73CKYUM.cjs +458 -0
  62. package/dist/chunk-K73CKYUM.cjs.map +1 -0
  63. package/dist/{chunk-GTZXF4BI.cjs → chunk-NK3WL5TJ.cjs} +298 -133
  64. package/dist/chunk-NK3WL5TJ.cjs.map +1 -0
  65. package/dist/{chunk-3ZBAXET6.cjs → chunk-NN3JGUSX.cjs} +80 -22
  66. package/dist/chunk-NN3JGUSX.cjs.map +1 -0
  67. package/dist/chunk-NV22EMOZ.cjs +401 -0
  68. package/dist/chunk-NV22EMOZ.cjs.map +1 -0
  69. package/dist/{chunk-YMKPMXZ4.js → chunk-OIKYP7XC.js} +4 -4
  70. package/dist/{chunk-FEMIVHN3.cjs → chunk-P43HUQRX.cjs} +16 -16
  71. package/dist/{chunk-FEMIVHN3.cjs.map → chunk-P43HUQRX.cjs.map} +1 -1
  72. package/dist/chunk-PTMIGXZ2.js +467 -0
  73. package/dist/chunk-PTMIGXZ2.js.map +1 -0
  74. package/dist/chunk-QIWFEEWG.cjs +467 -0
  75. package/dist/chunk-QIWFEEWG.cjs.map +1 -0
  76. package/dist/{chunk-QFTVLEVN.js → chunk-RIXTW3C4.js} +3 -3
  77. package/dist/{chunk-WBOAXDKD.js → chunk-VODBAO32.js} +222 -57
  78. package/dist/chunk-VODBAO32.js.map +1 -0
  79. package/dist/chunk-WWJNC7SX.js +3848 -0
  80. package/dist/chunk-WWJNC7SX.js.map +1 -0
  81. package/dist/{chunk-2DEBI6KU.cjs → chunk-YZZMX6V7.cjs} +10 -10
  82. package/dist/{chunk-2DEBI6KU.cjs.map → chunk-YZZMX6V7.cjs.map} +1 -1
  83. package/dist/commands/index.d.cts +1 -1
  84. package/dist/commands/index.d.ts +1 -1
  85. package/dist/{controller-DS3drIvy.d.cts → controller-CX0QfSv0.d.cts} +53 -2
  86. package/dist/{controller-BdKzaxs2.d.ts → controller-DscWQbjO.d.ts} +53 -2
  87. package/dist/diagram/index.cjs +1146 -0
  88. package/dist/diagram/index.cjs.map +1 -0
  89. package/dist/diagram/index.d.cts +787 -0
  90. package/dist/diagram/index.d.ts +787 -0
  91. package/dist/diagram/index.js +1146 -0
  92. package/dist/diagram/index.js.map +1 -0
  93. package/dist/{easing-DTmX99QG.d.cts → easing-CNGk-W6d.d.cts} +1 -1
  94. package/dist/{easing-DTmX99QG.d.ts → easing-CNGk-W6d.d.ts} +1 -1
  95. package/dist/export/index.cjs +4 -4
  96. package/dist/export/index.js +3 -3
  97. package/dist/extensions/index.cjs +6 -6
  98. package/dist/extensions/index.d.cts +2 -2
  99. package/dist/extensions/index.d.ts +2 -2
  100. package/dist/extensions/index.js +5 -5
  101. package/dist/generation/index.d.cts +2 -2
  102. package/dist/generation/index.d.ts +2 -2
  103. package/dist/image-editor/index.d.cts +1 -1
  104. package/dist/image-editor/index.d.ts +1 -1
  105. package/dist/{index-Dt9lzydb.d.ts → index-CALDD35B.d.ts} +1 -1
  106. package/dist/{index-DOy9HzfC.d.cts → index-DIWB6xMf.d.cts} +1 -1
  107. package/dist/index.cjs +13 -13
  108. package/dist/index.d.cts +3 -3
  109. package/dist/index.d.ts +3 -3
  110. package/dist/index.js +6 -6
  111. package/dist/parameters/index.d.cts +1 -1
  112. package/dist/parameters/index.d.ts +1 -1
  113. package/dist/player-DSMjdgQ9.d.cts +225 -0
  114. package/dist/player-DdfVrKWq.d.ts +225 -0
  115. package/dist/presence-Cb6WhcrQ.d.cts +77 -0
  116. package/dist/presence-Cb6WhcrQ.d.ts +77 -0
  117. package/dist/{registry-CSlH4iUn.d.ts → registry-7AZFuand.d.ts} +1 -1
  118. package/dist/{registry-B4l-lYts.d.cts → registry-DIpIaCkH.d.cts} +1 -1
  119. package/dist/tools/index.cjs +10 -2
  120. package/dist/tools/index.cjs.map +1 -1
  121. package/dist/tools/index.d.cts +3 -74
  122. package/dist/tools/index.d.ts +3 -74
  123. package/dist/tools/index.js +12 -4
  124. package/dist/types-BULrFyuQ.d.cts +316 -0
  125. package/dist/types-BULrFyuQ.d.ts +316 -0
  126. package/dist/vector/index.d.cts +1 -1
  127. package/dist/vector/index.d.ts +1 -1
  128. package/package.json +14 -1
  129. package/dist/chunk-3ZBAXET6.cjs.map +0 -1
  130. package/dist/chunk-5TWIN7ZJ.js.map +0 -1
  131. package/dist/chunk-AMWXSYCI.js.map +0 -1
  132. package/dist/chunk-GTZXF4BI.cjs.map +0 -1
  133. package/dist/chunk-JOX6MJW4.cjs.map +0 -1
  134. package/dist/chunk-OV7UAKIY.js.map +0 -1
  135. package/dist/chunk-TGBCBQFV.cjs.map +0 -1
  136. package/dist/chunk-UAW5FEMD.js.map +0 -1
  137. package/dist/chunk-WBOAXDKD.js.map +0 -1
  138. package/dist/chunk-XFYUFVAX.cjs +0 -826
  139. package/dist/chunk-XFYUFVAX.cjs.map +0 -1
  140. /package/dist/{chunk-5N6AQCVB.js.map → chunk-BQQZ6MOI.js.map} +0 -0
  141. /package/dist/{chunk-YMKPMXZ4.js.map → chunk-OIKYP7XC.js.map} +0 -0
  142. /package/dist/{chunk-QFTVLEVN.js.map → chunk-RIXTW3C4.js.map} +0 -0
@@ -6,7 +6,7 @@
6
6
 
7
7
 
8
8
 
9
- var _chunkJOX6MJW4cjs = require('./chunk-JOX6MJW4.cjs');
9
+ var _chunkCKRNELPOcjs = require('./chunk-CKRNELPO.cjs');
10
10
 
11
11
  // src/chart/ooxml.ts
12
12
  var CHART_OOXML_NS = "http://schemas.openxmlformats.org/drawingml/2006/chart";
@@ -81,6 +81,27 @@ var MARKERS = { circle: "circle", dot: "circle", square: "square", diamond: "dia
81
81
  var TREND_IN = { linear: "linear", exp: "exponential", log: "logarithmic", poly: "polynomial", power: "power", movingAvg: "moving-average" };
82
82
  var TREND_OUT = { linear: "linear", exponential: "exp", logarithmic: "log", polynomial: "poly", power: "power", "moving-average": "movingAvg" };
83
83
  var LEGEND_IN = { b: "bottom", t: "top", l: "left", r: "right", tr: "right" };
84
+ var ERR_IN = { fixedVal: "fixed", percentage: "percent", stdDev: "stddev", stdErr: "stderr", cust: "custom" };
85
+ var ERR_OUT = { fixed: "fixedVal", percent: "percentage", stddev: "stdDev", stderr: "stdErr", custom: "cust" };
86
+ function readErrorBars(e) {
87
+ const type = ERR_IN[_nullishCoalesce(val(e, "errValType"), () => ( "fixedVal"))];
88
+ if (!type) return null;
89
+ const bars = { type };
90
+ const value = numberOf(val(e, "val"));
91
+ if (value !== null && type !== "custom" && type !== "stderr") bars.value = Math.abs(value);
92
+ if (type === "custom") {
93
+ const plus = kid(e, "plus");
94
+ const minus = kid(e, "minus");
95
+ const p = plus ? numbers(plus).map((v) => v === null ? null : Math.abs(v)) : [];
96
+ const m = minus ? numbers(minus).map((v) => v === null ? null : Math.abs(v)) : [];
97
+ if (p.some((v) => v !== null)) bars.plus = p;
98
+ if (m.some((v) => v !== null) && JSON.stringify(m) !== JSON.stringify(p)) bars.minus = m;
99
+ }
100
+ const direction = val(e, "errBarType");
101
+ if (direction === "plus" || direction === "minus") bars.direction = direction;
102
+ if (bool(val(e, "noEndCap"))) bars.cap = false;
103
+ return bars;
104
+ }
84
105
  function chartFromOoxml(xml, options = {}) {
85
106
  const issues = [];
86
107
  const unsupported = [];
@@ -88,11 +109,11 @@ function chartFromOoxml(xml, options = {}) {
88
109
  try {
89
110
  doc = new (parser(options))().parseFromString(xml, "application/xml");
90
111
  } catch (error) {
91
- return { spec: _chunkJOX6MJW4cjs.normalizeChartSpec.call(void 0, {}).spec, issues: [{ path: "", message: `The chart XML could not be read: ${error.message}` }], unsupported, lossless: false };
112
+ return { spec: _chunkCKRNELPOcjs.normalizeChartSpec.call(void 0, {}).spec, issues: [{ path: "", message: `The chart XML could not be read: ${error.message}` }], unsupported, lossless: false };
92
113
  }
93
114
  const root = doc.documentElement;
94
115
  if (!root || root.localName !== "chartSpace" || doc.getElementsByTagName("parsererror").length) {
95
- return { spec: _chunkJOX6MJW4cjs.normalizeChartSpec.call(void 0, {}).spec, issues: [{ path: "", message: "This is not a chart part: expected a c:chartSpace (or cx:chartSpace) root element." }], unsupported, lossless: false };
116
+ return { spec: _chunkCKRNELPOcjs.normalizeChartSpec.call(void 0, {}).spec, issues: [{ path: "", message: "This is not a chart part: expected a c:chartSpace (or cx:chartSpace) root element." }], unsupported, lossless: false };
96
117
  }
97
118
  if (_optionalChain([root, 'access', _14 => _14.namespaceURI, 'optionalAccess', _15 => _15.includes, 'call', _16 => _16("chartex")]) || kid(root, "chartData")) return readChartex(root, issues, unsupported);
98
119
  const chart = kid(root, "chart");
@@ -240,13 +261,24 @@ function chartFromOoxml(xml, options = {}) {
240
261
  trends.push(line);
241
262
  }
242
263
  if (trends.length) out.trendlines = trends;
243
- if (kids(s, "errBars").length) unsupported.push("error bars");
264
+ for (const e of kids(s, "errBars")) {
265
+ const bars = readErrorBars(e);
266
+ if (!bars) {
267
+ unsupported.push(`error bars of type "${val(e, "errValType")}"`);
268
+ continue;
269
+ }
270
+ if (val(e, "errDir") === "x") {
271
+ if (type === "scatter" || type === "bubble") out.xErrorBars = bars;
272
+ else unsupported.push("x error bars on a category chart");
273
+ } else if (type === "pie" || type === "donut" || type === "radar") unsupported.push(`error bars on a ${type} chart`);
274
+ else out.errorBars = bars;
275
+ }
244
276
  series.push(out);
245
277
  }
246
278
  }
247
279
  if (!types.length) {
248
280
  issues.push({ path: "plotArea", message: unsupported.length ? `The chart type is not supported: ${unsupported.join(", ")}.` : "The chart has no plot groups." });
249
- return { spec: _chunkJOX6MJW4cjs.normalizeChartSpec.call(void 0, input).spec, issues, unsupported, lossless: false };
281
+ return { spec: _chunkCKRNELPOcjs.normalizeChartSpec.call(void 0, input).spec, issues, unsupported, lossless: false };
250
282
  }
251
283
  const first = types[0];
252
284
  const combo = types.some((t) => t !== first);
@@ -256,7 +288,7 @@ function chartFromOoxml(xml, options = {}) {
256
288
  if (!combo) {
257
289
  for (const s of series) if (s.axis) issues.push({ path: "series", message: `"${s.name}" is on a second value axis.` });
258
290
  }
259
- if (types.some((t) => !_chunkJOX6MJW4cjs.isCartesianChart.call(void 0, t)) && combo) unsupported.push("a pie or radar mixed with other chart types");
291
+ if (types.some((t) => !_chunkCKRNELPOcjs.isCartesianChart.call(void 0, t)) && combo) unsupported.push("a pie or radar mixed with other chart types");
260
292
  input.series = series;
261
293
  input.categories = categories.length ? categories : Array.from({ length: Math.max(0, ...series.map((s) => s.values.length)) }, (_, i) => `${i + 1}`);
262
294
  input.stacking = stacking;
@@ -273,8 +305,15 @@ function chartFromOoxml(xml, options = {}) {
273
305
  const scaling = kid(a, "scaling");
274
306
  axis.min = numberOf(val(scaling, "min"));
275
307
  axis.max = numberOf(val(scaling, "max"));
276
- if (val(scaling, "orientation") === "maxMin") unsupported.push("a reversed axis");
277
- if (kid(scaling, "logBase")) unsupported.push("a logarithmic axis");
308
+ if (val(scaling, "orientation") === "maxMin") axis.reverse = true;
309
+ if (kid(scaling, "logBase")) {
310
+ if (a.localName !== "valAx") unsupported.push("a logarithmic category axis");
311
+ else {
312
+ axis.scale = "log";
313
+ const base = _nullishCoalesce(numberOf(val(scaling, "logBase")), () => ( 10));
314
+ if (base !== 10) axis.logBase = base;
315
+ }
316
+ }
278
317
  axis.step = numberOf(val(a, "majorUnit"));
279
318
  const fmt = kid(a, "numFmt");
280
319
  const code = _optionalChain([fmt, 'optionalAccess', _23 => _23.getAttribute, 'call', _24 => _24("formatCode")]);
@@ -283,12 +322,12 @@ function chartFromOoxml(xml, options = {}) {
283
322
  };
284
323
  const xy = first === "scatter" || first === "bubble";
285
324
  const catAxis = _nullishCoalesce(_nullishCoalesce(kid(plot, "catAx"), () => ( kid(plot, "dateAx"))), () => ( (xy ? valAxes.find((a) => !vertical(a)) : void 0)));
286
- input.xAxis = readAxis(catAxis, _chunkJOX6MJW4cjs.defaultChartAxis.call(void 0, false));
325
+ input.xAxis = readAxis(catAxis, _chunkCKRNELPOcjs.defaultChartAxis.call(void 0, false));
287
326
  if (kid(plot, "dateAx")) input.xAxis.kind = "date";
288
- input.yAxis = readAxis(_nullishCoalesce(_nullishCoalesce(primaryAxis, () => ( valAxes.find(vertical))), () => ( valAxes[0])), _chunkJOX6MJW4cjs.defaultChartAxis.call(void 0, true));
327
+ input.yAxis = readAxis(_nullishCoalesce(_nullishCoalesce(primaryAxis, () => ( valAxes.find(vertical))), () => ( valAxes[0])), _chunkCKRNELPOcjs.defaultChartAxis.call(void 0, true));
289
328
  const secondaryAxis = valAxes.find((a) => a !== primaryAxis && (xy ? vertical(a) && a !== primaryAxis : true) && a !== catAxis);
290
- if (series.some((s) => s.axis === "secondary") && secondaryAxis) input.yAxis2 = readAxis(secondaryAxis, _chunkJOX6MJW4cjs.defaultChartAxis.call(void 0, false));
291
- const { spec, issues: specIssues } = _chunkJOX6MJW4cjs.normalizeChartSpec.call(void 0, input);
329
+ if (series.some((s) => s.axis === "secondary") && secondaryAxis) input.yAxis2 = readAxis(secondaryAxis, _chunkCKRNELPOcjs.defaultChartAxis.call(void 0, false));
330
+ const { spec, issues: specIssues } = _chunkCKRNELPOcjs.normalizeChartSpec.call(void 0, input);
292
331
  issues.push(...specIssues);
293
332
  const uniq = [...new Set(unsupported)];
294
333
  return { spec, issues, unsupported: uniq, lossless: uniq.length === 0 && specIssues.length === 0 };
@@ -318,7 +357,7 @@ function readChartex(root, issues, unsupported) {
318
357
  const type = layouts[layout];
319
358
  if (!type) {
320
359
  issues.push({ path: "plotArea", message: `The chart layout "${layout || "unknown"}" is not supported.` });
321
- return { spec: _chunkJOX6MJW4cjs.normalizeChartSpec.call(void 0, {}).spec, issues, unsupported: [layout || "unknown chartex layout"], lossless: false };
360
+ return { spec: _chunkCKRNELPOcjs.normalizeChartSpec.call(void 0, {}).spec, issues, unsupported: [layout || "unknown chartex layout"], lossless: false };
322
361
  }
323
362
  if (layout === "sunburst") unsupported.push("sunburst (drawn as a treemap of the innermost level)");
324
363
  if (layout === "paretoLine") unsupported.push("pareto line");
@@ -343,15 +382,15 @@ function readChartex(root, issues, unsupported) {
343
382
  categories: categories.length >= longest ? categories : Array.from({ length: longest }, (_, i) => _nullishCoalesce(categories[i], () => ( `${i + 1}`)))
344
383
  };
345
384
  if (type === "waterfall") input.showTotal = false;
346
- const { spec, issues: specIssues } = _chunkJOX6MJW4cjs.normalizeChartSpec.call(void 0, input);
385
+ const { spec, issues: specIssues } = _chunkCKRNELPOcjs.normalizeChartSpec.call(void 0, input);
347
386
  issues.push(...specIssues);
348
387
  return { spec, issues, unsupported, lossless: unsupported.length === 0 && specIssues.length === 0 };
349
388
  }
350
389
  var esc = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
351
390
  var hex = (color) => {
352
391
  if (!color) return null;
353
- const rgb = _chunkJOX6MJW4cjs.parseChartColor.call(void 0, color);
354
- return rgb ? _chunkJOX6MJW4cjs.chartRgbToHex.call(void 0, rgb).slice(1).toUpperCase() : null;
392
+ const rgb = _chunkCKRNELPOcjs.parseChartColor.call(void 0, color);
393
+ return rgb ? _chunkCKRNELPOcjs.chartRgbToHex.call(void 0, rgb).slice(1).toUpperCase() : null;
355
394
  };
356
395
  var fillXml = (color, line = false) => {
357
396
  const h = hex(color);
@@ -384,10 +423,18 @@ function chartFormatToCode(format) {
384
423
  return d !== void 0 || format.prefix || format.suffix ? wrap(`#,##0${frac(d, 0)}`) : "General";
385
424
  }
386
425
  }
426
+ function errBarsXml(bars, dir) {
427
+ let x = `<c:errBars>${dir ? `<c:errDir val="${dir}"/>` : ""}<c:errBarType val="${_nullishCoalesce(bars.direction, () => ( "both"))}"/><c:errValType val="${ERR_OUT[bars.type]}"/><c:noEndCap val="${bars.cap === false ? 1 : 0}"/>`;
428
+ if (bars.type === "custom") {
429
+ const plus = _nullishCoalesce(bars.plus, () => ( (_nullishCoalesce(bars.minus, () => ( []))).map(() => null)));
430
+ x += `<c:plus>${numLit(plus)}</c:plus><c:minus>${numLit(_nullishCoalesce(bars.minus, () => ( plus)))}</c:minus>`;
431
+ } else if (bars.type !== "stderr") x += `<c:val val="${_nullishCoalesce(bars.value, () => ( (bars.type === "percent" ? 5 : 1)))}"/>`;
432
+ return `${x}</c:errBars>`;
433
+ }
387
434
  var MARKER_OUT = { circle: "circle", square: "square", diamond: "diamond", triangle: "triangle", cross: "x", none: "none" };
388
435
  function chartToOoxml(spec) {
389
436
  const issues = [];
390
- const family = _chunkJOX6MJW4cjs.chartFamily.call(void 0, spec);
437
+ const family = _chunkCKRNELPOcjs.chartFamily.call(void 0, spec);
391
438
  let type = spec.type;
392
439
  if (family === "waterfall" || family === "histogram" || family === "box" || family === "funnel") {
393
440
  issues.push(`${spec.type} charts are written as bar charts: DrawingML has no ${spec.type} type (Office 2016 stores it as chartex).`);
@@ -402,7 +449,7 @@ function chartToOoxml(spec) {
402
449
  const ids = { cat: 500000001, val: 500000002, cat2: 500000003, val2: 500000004 };
403
450
  const xy = family === "xy" || type === "scatter" || type === "bubble";
404
451
  const pieLike = type === "pie" || type === "donut";
405
- const typed = (s) => pieLike || type === "radar" ? type : type === "bubble" ? "bubble" : xy ? "scatter" : _chunkJOX6MJW4cjs.chartSeriesType.call(void 0, { type }, s);
452
+ const typed = (s) => pieLike || type === "radar" ? type : type === "bubble" ? "bubble" : xy ? "scatter" : _chunkCKRNELPOcjs.chartSeriesType.call(void 0, { type }, s);
406
453
  const groups = [];
407
454
  visible.forEach((s) => {
408
455
  const kind = typed(s);
@@ -442,6 +489,14 @@ function chartToOoxml(spec) {
442
489
  x += `<c:dispRSqr val="${t.showR2 ? 1 : 0}"/><c:dispEq val="${t.showEquation ? 1 : 0}"/></c:trendline>`;
443
490
  parts.push(x);
444
491
  }
492
+ if (!pieLike && kind !== "radar") {
493
+ const xyKind = kind === "scatter" || kind === "bubble";
494
+ if (s.errorBars) parts.push(errBarsXml(s.errorBars, xyKind ? "y" : null));
495
+ if (s.xErrorBars) {
496
+ if (xyKind) parts.push(errBarsXml(s.xErrorBars, "x"));
497
+ else issues.push(`"${s.name}" has x error bars, which only scatter and bubble charts can hold; they are left out.`);
498
+ }
499
+ } else if (s.errorBars || s.xErrorBars) issues.push(`Error bars on "${s.name}" are left out: ${kind} charts cannot show them.`);
445
500
  const valCode = chartFormatToCode(_nullishCoalesce(s.format, () => ( (s.axis === "secondary" ? spec.yAxis2.format : spec.yAxis.format))));
446
501
  if (kind === "scatter" || kind === "bubble") {
447
502
  const xs = _nullishCoalesce(s.x, () => ( spec.categories.map((_, i) => i + 1)));
@@ -484,7 +539,7 @@ function chartToOoxml(spec) {
484
539
  return `<c:pieChart><c:varyColors val="1"/>${sers}${dLbls}<c:firstSliceAng val="0"/></c:pieChart>`;
485
540
  }
486
541
  });
487
- const scaling = (a) => `<c:scaling><c:orientation val="minMax"/>${a.max !== null ? `<c:max val="${a.max}"/>` : ""}${a.min !== null ? `<c:min val="${a.min}"/>` : ""}</c:scaling>`;
542
+ const scaling = (a) => `<c:scaling>${a.scale === "log" ? `<c:logBase val="${_nullishCoalesce(a.logBase, () => ( 10))}"/>` : ""}<c:orientation val="${a.reverse ? "maxMin" : "minMax"}"/>${a.max !== null ? `<c:max val="${a.max}"/>` : ""}${a.min !== null ? `<c:min val="${a.min}"/>` : ""}</c:scaling>`;
488
543
  const title = (a) => a.title ? `<c:title>${rich(a.title)}</c:title>` : "";
489
544
  const fmt = (a) => {
490
545
  const code = chartFormatToCode(a.format);
@@ -494,11 +549,14 @@ function chartToOoxml(spec) {
494
549
  const catPos = horizontal ? "l" : "b";
495
550
  const valPos = horizontal ? "b" : "l";
496
551
  const valAx = (id, cross, a, pos, crosses, catKind = false) => `<c:valAx><c:axId val="${id}"/>${scaling(a)}<c:delete val="${a.show ? 0 : 1}"/><c:axPos val="${pos}"/>${a.gridlines ? "<c:majorGridlines/>" : ""}${title(a)}${fmt(a)}<c:majorTickMark val="out"/><c:minorTickMark val="none"/><c:tickLblPos val="nextTo"/><c:crossAx val="${cross}"/><c:crosses val="${crosses}"/><c:crossBetween val="${catKind ? "midCat" : "between"}"/>${a.step ? `<c:majorUnit val="${a.step}"/>` : ""}</c:valAx>`;
497
- const catAx = (id, cross, a, pos, hidden = false) => `<c:${a.kind === "date" ? "dateAx" : "catAx"}><c:axId val="${id}"/><c:scaling><c:orientation val="minMax"/></c:scaling><c:delete val="${a.show && !hidden ? 0 : 1}"/><c:axPos val="${pos}"/>${a.gridlines ? "<c:majorGridlines/>" : ""}${title(a)}<c:numFmt formatCode="General" sourceLinked="1"/><c:majorTickMark val="out"/><c:minorTickMark val="none"/><c:tickLblPos val="nextTo"/><c:crossAx val="${cross}"/><c:crosses val="autoZero"/><c:auto val="1"/>${a.kind === "date" ? '<c:lblOffset val="100"/><c:baseTimeUnit val="days"/>' : '<c:lblAlgn val="ctr"/><c:lblOffset val="100"/><c:noMultiLvlLbl val="0"/>'}</c:${a.kind === "date" ? "dateAx" : "catAx"}>`;
552
+ const catAx = (id, cross, a, pos, hidden = false) => `<c:${a.kind === "date" ? "dateAx" : "catAx"}><c:axId val="${id}"/><c:scaling><c:orientation val="${a.reverse ? "maxMin" : "minMax"}"/></c:scaling><c:delete val="${a.show && !hidden ? 0 : 1}"/><c:axPos val="${pos}"/>${a.gridlines ? "<c:majorGridlines/>" : ""}${title(a)}<c:numFmt formatCode="General" sourceLinked="1"/><c:majorTickMark val="out"/><c:minorTickMark val="none"/><c:tickLblPos val="nextTo"/><c:crossAx val="${cross}"/><c:crosses val="autoZero"/><c:auto val="1"/>${a.kind === "date" ? '<c:lblOffset val="100"/><c:baseTimeUnit val="days"/>' : '<c:lblAlgn val="ctr"/><c:lblOffset val="100"/><c:noMultiLvlLbl val="0"/>'}</c:${a.kind === "date" ? "dateAx" : "catAx"}>`;
498
553
  let axes = "";
499
554
  if (!pieLike) {
500
555
  if (xy) axes = valAx(ids.cat, ids.val, spec.xAxis, "b", "autoZero", true) + valAx(ids.val, ids.cat, spec.yAxis, "l", "autoZero", true);
501
- else axes = catAx(ids.cat, ids.val, spec.xAxis, catPos) + valAx(ids.val, ids.cat, spec.yAxis, valPos, "autoZero");
556
+ else {
557
+ if (spec.xAxis.scale === "log") issues.push("The category axis cannot be logarithmic; its log scale is left out.");
558
+ axes = catAx(ids.cat, ids.val, spec.xAxis, catPos) + valAx(ids.val, ids.cat, spec.yAxis, valPos, "autoZero");
559
+ }
502
560
  if (groups.some((g) => g.secondary)) axes += catAx(ids.cat2, ids.val2, spec.xAxis, catPos, true) + valAx(ids.val2, ids.cat2, spec.yAxis2, horizontal ? "t" : "r", "max");
503
561
  }
504
562
  const legendPos = { bottom: "b", top: "t", left: "l", right: "r" }[spec.legend.position];
@@ -838,4 +896,4 @@ async function readZip(data, options = {}) {
838
896
 
839
897
 
840
898
  exports.CHART_OOXML_NS = CHART_OOXML_NS; exports.CHART_OOXML_CONTENT_TYPE = CHART_OOXML_CONTENT_TYPE; exports.CHART_OOXML_RELATIONSHIP = CHART_OOXML_RELATIONSHIP; exports.chartFromOoxml = chartFromOoxml; exports.chartFormatToCode = chartFormatToCode; exports.chartToOoxml = chartToOoxml; exports.ZipError = ZipError; exports.DEFAULT_ZIP_MAX_ENTRIES = DEFAULT_ZIP_MAX_ENTRIES; exports.DEFAULT_ZIP_MAX_TOTAL_SIZE = DEFAULT_ZIP_MAX_TOTAL_SIZE; exports.zipCrc32 = zipCrc32; exports.isUnsafeZipPath = isUnsafeZipPath; exports.ZipArchive = ZipArchive; exports.readZip = readZip;
841
- //# sourceMappingURL=chunk-3ZBAXET6.cjs.map
899
+ //# sourceMappingURL=chunk-NN3JGUSX.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/home/runner/work/editor/editor/packages/core/dist/chunk-NN3JGUSX.cjs","../src/chart/ooxml.ts","../src/import/zip.ts"],"names":["rich"],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACA;ACDO,IAAM,eAAA,EAAiB,wDAAA;AACvB,IAAM,yBAAA,EAA2B,mEAAA;AACjC,IAAM,yBAAA,EAA2B,2EAAA;AAsBxC,IAAM,WAAA,EAAa,GAAA;AAEnB,SAAS,MAAA,CAAO,OAAA,EAA4C;AAC3D,EAAA,MAAM,EAAA,mBAAI,OAAA,CAAQ,SAAA,UAAc,UAAA,CAA0C,WAAA;AAC1E,EAAA,GAAA,CAAI,CAAC,CAAA,EAAG,MAAM,IAAI,KAAA,CAAM,8GAA8G,CAAA;AACtI,EAAA,OAAO,CAAA;AACR;AAEA,IAAM,KAAA,EAAO,CAAC,EAAA,EAAgC,IAAA,EAAA,GAA8B,GAAA,EAAK,KAAA,CAAM,IAAA,CAAK,EAAA,CAAG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UAAA;AAC5B,UAAA;AACP,QAAA;AACsD,QAAA;AACxD,MAAA;AACS,MAAA;AACX,IAAA;AAEqD,IAAA;AACd,IAAA;AACnC,IAAA;AAC0B,IAAA;AACQ,MAAA;AACiB,MAAA;AACxC,QAAA;AACZ,MAAA;AACH,IAAA;AACa,IAAA;AACX,MAAA;AAC8B,MAAA;AACE,MAAA;AAChC,MAAA;AACA,MAAA;AACA,MAAA;AACA,MAAA;AACA,MAAA;AACD,IAAA;AACH,EAAA;AACkD,EAAA;AACpD;AFwc6D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/editor/editor/packages/core/dist/chunk-NN3JGUSX.cjs","sourcesContent":[null,"// The DrawingML chart reader follows deckcraft-main/crates/pptx/src/read/chart.rs (group → type mapping,\n// secondary-axis detection by axis id and position, cache / literal data, number-format precedence) and the\n// chartex reader gridcraft-main/crates/xlsx/src/chartex.rs; the \"editable only when it regenerates\" idea is\n// from wordcraft-main/crates/docx/src/chart_spec.rs (MIT OR Apache-2.0, © ArtCraft Team and contributors).\n// See THIRD_PARTY_NOTICES.md.\nimport { parseChartColor, chartRgbToHex } from './color.js';\nimport { chartFamily, chartSeriesType, defaultChartAxis, isCartesianChart, normalizeChartSpec } from './spec.js';\nimport type { ChartAxis, ChartErrorBars, ChartErrorBarType, ChartIssue, ChartLegendPosition, ChartMarker, ChartNumberFormat, ChartSeries, ChartSpec, ChartTrendline, ChartTrendlineType, ChartType, ChartValue } from './types.js';\n\nexport const CHART_OOXML_NS = 'http://schemas.openxmlformats.org/drawingml/2006/chart';\nexport const CHART_OOXML_CONTENT_TYPE = 'application/vnd.openxmlformats-officedocument.drawingml.chart+xml';\nexport const CHART_OOXML_RELATIONSHIP = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart';\n\ntype ParserCtor = { new (): DOMParser };\n\nexport interface ChartOoxmlReadOptions {\n\t/** `DOMParser` constructor (default: the global one; pass jsdom's or xmldom's in Node). */\n\tDOMParser?: ParserCtor;\n}\n\nexport interface ChartOoxmlReadResult {\n\tspec: ChartSpec;\n\t/** Problems and simplifications, as sentences. */\n\tissues: ChartIssue[];\n\t/** Features the file uses that the spec cannot hold (3-D, stock, surface, gradients, …). */\n\tunsupported: string[];\n\t/**\n\t * Nothing was dropped: writing `spec` back gives an equivalent chart. When false, keep the\n\t * original part (or show the chart read-only) if the file must stay as it was.\n\t */\n\tlossless: boolean;\n}\n\nconst MAX_POINTS = 100_000;\n\nfunction parser(options: ChartOoxmlReadOptions): ParserCtor {\n\tconst P = options.DOMParser ?? (globalThis as { DOMParser?: ParserCtor }).DOMParser;\n\tif (!P) throw new Error('Reading chart XML needs a DOMParser. In Node, pass one (e.g. from jsdom or @xmldom/xmldom) as { DOMParser }.');\n\treturn P;\n}\n\nconst kids = (el: Element | null | undefined, name?: string): Element[] => (el ? Array.from(el.childNodes).filter((n): n is Element => n.nodeType === 1 && (!name || (n as Element).localName === name)) : []);\nconst kid = (el: Element | null | undefined, name: string) => kids(el, name)[0];\nconst val = (el: Element | null | undefined, name: string) => kid(el, name)?.getAttribute('val') ?? undefined;\nconst path = (el: Element | null | undefined, ...names: string[]) => names.reduce<Element | undefined>((e, n) => kid(e, n), el ?? undefined);\nconst find = (el: Element | null | undefined, name: string): Element | undefined => {\n\tif (!el) return undefined;\n\tfor (const c of kids(el)) {\n\t\tif (c.localName === name) return c;\n\t\tconst deep = find(c, name);\n\t\tif (deep) return deep;\n\t}\n\treturn undefined;\n};\nconst bool = (v: string | undefined, fallback = false) => (v === undefined ? fallback : v === '1' || v === 'true');\nconst numberOf = (v: string | undefined) => {\n\tif (v === undefined) return null;\n\tconst n = Number(v);\n\treturn Number.isFinite(n) ? n : null;\n};\n\nfunction strings(e: Element | undefined): string[] {\n\tif (!e) return [];\n\tconst cache = find(e, 'strCache') ?? find(e, 'numCache') ?? find(e, 'strLit') ?? find(e, 'numLit');\n\tif (cache) {\n\t\tconst n = Math.min(MAX_POINTS, Number(val(cache, 'ptCount') ?? 0) || 0);\n\t\tconst out: string[] = Array(n).fill('');\n\t\tfor (const pt of kids(cache, 'pt').slice(0, MAX_POINTS)) {\n\t\t\tconst i = Number(pt.getAttribute('idx') ?? 0);\n\t\t\tif (!Number.isInteger(i) || i < 0 || i >= MAX_POINTS) continue;\n\t\t\twhile (out.length <= i) out.push('');\n\t\t\tout[i] = kid(pt, 'v')?.textContent ?? '';\n\t\t}\n\t\treturn out;\n\t}\n\tconst multi = find(e, 'multiLvlStrCache');\n\tif (multi) {\n\t\tconst lvl = kid(multi, 'lvl');\n\t\treturn kids(lvl, 'pt').map((p) => kid(p, 'v')?.textContent ?? '');\n\t}\n\tconst v = kid(e, 'v') ?? find(e, 'v');\n\treturn v ? [v.textContent ?? ''] : [];\n}\n\nconst numbers = (e: Element | undefined): ChartValue[] => strings(e).map((s) => (s.trim() === '' ? null : numberOf(s.trim())));\n\nfunction formatCodeOf(e: Element | undefined): string | undefined {\n\treturn find(e, 'numCache') ? (kid(find(e, 'numCache'), 'formatCode')?.textContent ?? undefined) : undefined;\n}\n\nfunction richText(t: Element | undefined): string | undefined {\n\tif (!t) return undefined;\n\tconst tx = kid(t, 'tx');\n\tconst rich = kid(tx, 'rich');\n\tif (rich) return kids(rich, 'p').map((p) => Array.from(p.getElementsByTagNameNS('*', 't')).map((x) => x.textContent ?? '').join('')).join('\\n');\n\tconst v = find(tx, 'v');\n\treturn v?.textContent ?? undefined;\n}\n\nfunction solidColor(spPr: Element | undefined): string | undefined {\n\tconst fill = kid(spPr, 'solidFill') ?? kid(kid(spPr, 'ln'), 'solidFill');\n\tconst srgb = kid(fill, 'srgbClr');\n\tconst v = srgb?.getAttribute('val');\n\treturn v && /^[0-9a-f]{6}$/i.test(v) ? `#${v.toLowerCase()}` : undefined;\n}\n\nconst MARKERS: Record<string, ChartMarker> = { circle: 'circle', dot: 'circle', square: 'square', diamond: 'diamond', triangle: 'triangle', x: 'cross', plus: 'cross', star: 'cross', dash: 'square', none: 'none' };\nconst TREND_IN: Record<string, ChartTrendlineType> = { linear: 'linear', exp: 'exponential', log: 'logarithmic', poly: 'polynomial', power: 'power', movingAvg: 'moving-average' };\nconst TREND_OUT: Record<ChartTrendlineType, string> = { linear: 'linear', exponential: 'exp', logarithmic: 'log', polynomial: 'poly', power: 'power', 'moving-average': 'movingAvg' };\nconst LEGEND_IN: Record<string, ChartLegendPosition> = { b: 'bottom', t: 'top', l: 'left', r: 'right', tr: 'right' };\nconst ERR_IN: Record<string, ChartErrorBarType> = { fixedVal: 'fixed', percentage: 'percent', stdDev: 'stddev', stdErr: 'stderr', cust: 'custom' };\nconst ERR_OUT: Record<ChartErrorBarType, string> = { fixed: 'fixedVal', percent: 'percentage', stddev: 'stdDev', stderr: 'stdErr', custom: 'cust' };\n\n/** Reads one `c:errBars` (Excel's error amount types map one to one); `null` for an unknown type. */\nfunction readErrorBars(e: Element): ChartErrorBars | null {\n\tconst type = ERR_IN[val(e, 'errValType') ?? 'fixedVal'];\n\tif (!type) return null;\n\tconst bars: ChartErrorBars = { type };\n\tconst value = numberOf(val(e, 'val'));\n\tif (value !== null && type !== 'custom' && type !== 'stderr') bars.value = Math.abs(value);\n\tif (type === 'custom') {\n\t\tconst plus = kid(e, 'plus');\n\t\tconst minus = kid(e, 'minus');\n\t\tconst p = plus ? numbers(plus).map((v) => (v === null ? null : Math.abs(v))) : [];\n\t\tconst m = minus ? numbers(minus).map((v) => (v === null ? null : Math.abs(v))) : [];\n\t\t// Minus amounts default to the plus ones; an empty side is left out.\n\t\tif (p.some((v) => v !== null)) bars.plus = p;\n\t\tif (m.some((v) => v !== null) && JSON.stringify(m) !== JSON.stringify(p)) bars.minus = m;\n\t}\n\tconst direction = val(e, 'errBarType');\n\tif (direction === 'plus' || direction === 'minus') bars.direction = direction;\n\tif (bool(val(e, 'noEndCap'))) bars.cap = false;\n\treturn bars;\n}\n\n/**\n * Reads a DrawingML chart part (`c:chartSpace`, e.g. `word/charts/chart1.xml`) or an Office\n * 2016 chartex part (`cx:chartSpace`: waterfall, funnel, treemap, histogram, box & whisker)\n * as a chart spec. Data comes from the cached values. Never throws for a malformed chart: it\n * returns an empty chart and says why.\n */\nexport function chartFromOoxml(xml: string, options: ChartOoxmlReadOptions = {}): ChartOoxmlReadResult {\n\tconst issues: ChartIssue[] = [];\n\tconst unsupported: string[] = [];\n\tlet doc: Document;\n\ttry {\n\t\tdoc = new (parser(options))().parseFromString(xml, 'application/xml');\n\t} catch (error) {\n\t\treturn { spec: normalizeChartSpec({}).spec, issues: [{ path: '', message: `The chart XML could not be read: ${(error as Error).message}` }], unsupported, lossless: false };\n\t}\n\tconst root = doc.documentElement;\n\tif (!root || root.localName !== 'chartSpace' || doc.getElementsByTagName('parsererror').length) {\n\t\treturn { spec: normalizeChartSpec({}).spec, issues: [{ path: '', message: 'This is not a chart part: expected a c:chartSpace (or cx:chartSpace) root element.' }], unsupported, lossless: false };\n\t}\n\tif (root.namespaceURI?.includes('chartex') || kid(root, 'chartData')) return readChartex(root, issues, unsupported);\n\n\tconst chart = kid(root, 'chart');\n\tconst plot = kid(chart, 'plotArea');\n\tconst input: Record<string, unknown> = { type: 'bar' };\n\tconst titleEl = kid(chart, 'title');\n\tif (titleEl && !bool(val(chart, 'autoTitleDeleted'))) input.title = richText(titleEl) ?? '';\n\tconst legend = kid(chart, 'legend');\n\tinput.legend = { show: !!legend, position: LEGEND_IN[val(legend, 'legendPos') ?? 'r'] ?? 'right' };\n\tif (kid(root, 'roundedCorners') && bool(val(root, 'roundedCorners'))) unsupported.push('rounded corners');\n\n\tconst valAxes = kids(plot, 'valAx');\n\tconst vertical = (a: Element) => ['l', 'r'].includes(val(a, 'axPos') ?? '');\n\tconst secondaryPlaced = (a: Element) => val(a, 'crosses') === 'max' || ['r', 't'].includes(val(a, 'axPos') ?? '');\n\tconst groupValAxis = (g: Element) => {\n\t\tconst ids = kids(g, 'axId').map((a) => a.getAttribute('val'));\n\t\tconst axes = ids.map((id) => valAxes.find((a) => val(a, 'axId') === id)).filter((a): a is Element => !!a);\n\t\treturn axes.find(vertical) ?? axes[0];\n\t};\n\tconst groups = kids(plot).filter((g) => g.localName.endsWith('Chart'));\n\tconst used = groups.map(groupValAxis).filter((a): a is Element => !!a);\n\tconst primaryAxis = used.find((a) => !secondaryPlaced(a)) ?? used[0];\n\n\tconst series: ChartSeries[] = [];\n\tlet categories: string[] = [];\n\tconst types: ChartType[] = [];\n\tlet stacking: ChartSpec['stacking'] = 'none';\n\tlet orientation: ChartSpec['orientation'] = 'vertical';\n\tlet dataLabels = false;\n\tlet points = false;\n\tfor (const g of groups) {\n\t\tconst name = g.localName;\n\t\tconst grouping = val(g, 'grouping') ?? 'clustered';\n\t\tlet type: ChartType;\n\t\tif (/3D/.test(name)) unsupported.push(`3-D ${name.replace(/3DChart$/, '')} chart (drawn flat)`);\n\t\tswitch (name) {\n\t\t\tcase 'barChart':\n\t\t\tcase 'bar3DChart':\n\t\t\t\ttype = 'bar';\n\t\t\t\tif (val(g, 'barDir') === 'bar') orientation = 'horizontal';\n\t\t\t\tbreak;\n\t\t\tcase 'lineChart':\n\t\t\tcase 'line3DChart':\n\t\t\t\ttype = 'line';\n\t\t\t\t// Points are on when a series shows a marker (the group's marker flag is usually set).\n\t\t\t\tif (kids(g, 'ser').some((s) => (val(kid(s, 'marker'), 'symbol') ?? (bool(val(g, 'marker'), true) ? 'auto' : 'none')) !== 'none')) points = true;\n\t\t\t\tbreak;\n\t\t\tcase 'areaChart':\n\t\t\tcase 'area3DChart':\n\t\t\t\ttype = 'area';\n\t\t\t\tbreak;\n\t\t\tcase 'pieChart':\n\t\t\tcase 'pie3DChart':\n\t\t\tcase 'ofPieChart':\n\t\t\t\ttype = 'pie';\n\t\t\t\tif (name === 'ofPieChart') unsupported.push('pie-of-pie (drawn as one pie)');\n\t\t\t\tbreak;\n\t\t\tcase 'doughnutChart':\n\t\t\t\ttype = 'donut';\n\t\t\t\tinput.innerRadius = Math.min(0.9, Math.max(0, (numberOf(val(g, 'holeSize')) ?? 50) / 100));\n\t\t\t\tbreak;\n\t\t\tcase 'scatterChart':\n\t\t\t\ttype = 'scatter';\n\t\t\t\tif (/line/i.test(val(g, 'scatterStyle') ?? '')) points = true;\n\t\t\t\tbreak;\n\t\t\tcase 'bubbleChart':\n\t\t\t\ttype = 'bubble';\n\t\t\t\tbreak;\n\t\t\tcase 'radarChart':\n\t\t\t\ttype = 'radar';\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tunsupported.push(`${name.replace(/Chart$/, '')} chart`);\n\t\t\t\tcontinue;\n\t\t}\n\t\tif (grouping === 'stacked') stacking = 'stacked';\n\t\telse if (grouping === 'percentStacked') stacking = 'percent';\n\t\tconst gap = numberOf(val(g, 'gapWidth'));\n\t\tconst overlap = numberOf(val(g, 'overlap'));\n\t\tif (type === 'bar') {\n\t\t\t// gapWidth is the gap between groups as a % of one bar; ours is a fraction of the category.\n\t\t\tconst n = Math.max(1, kids(g, 'ser').length);\n\t\t\tconst g100 = (gap ?? 150) / 100;\n\t\t\tconst o = Math.max(-1, Math.min(1, (overlap ?? (grouping === 'clustered' ? 0 : 100)) / 100));\n\t\t\tconst barsWidth = grouping === 'clustered' ? n - (n - 1) * o : 1;\n\t\t\tinput.gapWidth = Math.round(Math.max(0, Math.min(0.9, g100 / (barsWidth + g100))) * 100) / 100;\n\t\t\tif (grouping === 'clustered') input.overlap = o;\n\t\t}\n\t\tif (bool(val(kid(g, 'dLbls'), 'showVal'))) dataLabels = true;\n\t\ttypes.push(type);\n\t\tconst axis = groupValAxis(g);\n\t\tconst secondary = !!axis && !!primaryAxis && axis !== primaryAxis;\n\t\tfor (const s of kids(g, 'ser').slice(0, 1000)) {\n\t\t\tconst out: ChartSeries = { id: `series-${series.length + 1}`, name: strings(kid(s, 'tx'))[0] ?? `Series ${series.length + 1}`, values: [] };\n\t\t\tconst color = solidColor(kid(s, 'spPr'));\n\t\t\tif (color) out.color = color;\n\t\t\tout.type = type === 'bubble' ? undefined : (type as ChartSeries['type']);\n\t\t\tif (secondary) out.axis = 'secondary';\n\t\t\tconst marker = val(kid(s, 'marker'), 'symbol');\n\t\t\t// Circles (and none on a line chart without points) are the defaults; other shapes are kept.\n\t\t\tif (marker && MARKERS[marker] && MARKERS[marker] !== 'circle' && (type === 'scatter' || MARKERS[marker] !== 'none') && (type === 'line' || type === 'scatter')) out.marker = MARKERS[marker];\n\t\t\tif (bool(val(s, 'smooth'))) out.curve = 'smooth';\n\t\t\tconst sl = kid(s, 'dLbls');\n\t\t\tif (sl && val(sl, 'showVal') !== undefined) out.dataLabels = bool(val(sl, 'showVal'));\n\t\t\tconst labelCode = [kid(sl, 'numFmt'), kid(kid(g, 'dLbls'), 'numFmt')].find((n) => n && n.getAttribute('sourceLinked') !== '1')?.getAttribute('formatCode');\n\t\t\tconst valueEl = kid(s, 'val') ?? kid(s, 'yVal');\n\t\t\tconst code = labelCode ?? formatCodeOf(valueEl);\n\t\t\tif (code && code !== 'General') out.format = { code };\n\t\t\tconst catEl = kid(s, 'cat') ?? kid(s, 'xVal');\n\t\t\tconst cats = strings(catEl);\n\t\t\tif (type === 'scatter' || type === 'bubble') {\n\t\t\t\tconst xs = cats.map((c) => numberOf(c.trim()));\n\t\t\t\tif (xs.some((x) => x !== null)) out.x = xs;\n\t\t\t}\n\t\t\tif (!categories.length && cats.length) categories = cats;\n\t\t\tout.values = numbers(valueEl);\n\t\t\tif (type === 'bubble') out.sizes = numbers(kid(s, 'bubbleSize'));\n\t\t\tconst dPts = kids(s, 'dPt');\n\t\t\tif (dPts.length) {\n\t\t\t\tconst pc: (string | null)[] = [];\n\t\t\t\tfor (const dp of dPts) {\n\t\t\t\t\tconst i = Number(val(dp, 'idx'));\n\t\t\t\t\tconst c = solidColor(kid(dp, 'spPr'));\n\t\t\t\t\tif (Number.isInteger(i) && i >= 0 && i < MAX_POINTS && c) {\n\t\t\t\t\t\twhile (pc.length <= i) pc.push(null);\n\t\t\t\t\t\tpc[i] = c;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (pc.some(Boolean)) out.pointColors = pc;\n\t\t\t}\n\t\t\tconst trends: ChartTrendline[] = [];\n\t\t\tfor (const t of kids(s, 'trendline')) {\n\t\t\t\tconst kind = TREND_IN[val(t, 'trendlineType') ?? ''];\n\t\t\t\tif (!kind) continue;\n\t\t\t\tconst line: ChartTrendline = { type: kind };\n\t\t\t\tconst order = numberOf(val(t, 'order'));\n\t\t\t\tconst period = numberOf(val(t, 'period'));\n\t\t\t\tif (kind === 'polynomial' && order) line.order = order;\n\t\t\t\tif (kind === 'moving-average' && period) line.period = period;\n\t\t\t\tfor (const k of ['forward', 'backward', 'intercept'] as const) {\n\t\t\t\t\tconst n = numberOf(val(t, k));\n\t\t\t\t\tif (n !== null && (k === 'intercept' || n > 0)) line[k] = n;\n\t\t\t\t}\n\t\t\t\tif (bool(val(t, 'dispEq'))) line.showEquation = true;\n\t\t\t\tif (bool(val(t, 'dispRSqr'))) line.showR2 = true;\n\t\t\t\tconst tName = kid(t, 'name')?.textContent;\n\t\t\t\tif (tName) line.name = tName;\n\t\t\t\tconst tc = solidColor(kid(t, 'spPr'));\n\t\t\t\tif (tc) line.color = tc;\n\t\t\t\ttrends.push(line);\n\t\t\t}\n\t\t\tif (trends.length) out.trendlines = trends;\n\t\t\tfor (const e of kids(s, 'errBars')) {\n\t\t\t\tconst bars = readErrorBars(e);\n\t\t\t\tif (!bars) {\n\t\t\t\t\tunsupported.push(`error bars of type \"${val(e, 'errValType')}\"`);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\t// x error bars only exist on scatter and bubble series.\n\t\t\t\tif (val(e, 'errDir') === 'x') {\n\t\t\t\t\tif (type === 'scatter' || type === 'bubble') out.xErrorBars = bars;\n\t\t\t\t\telse unsupported.push('x error bars on a category chart');\n\t\t\t\t} else if (type === 'pie' || type === 'donut' || type === 'radar') unsupported.push(`error bars on a ${type} chart`);\n\t\t\t\telse out.errorBars = bars;\n\t\t\t}\n\t\t\tseries.push(out);\n\t\t}\n\t}\n\tif (!types.length) {\n\t\tissues.push({ path: 'plotArea', message: unsupported.length ? `The chart type is not supported: ${unsupported.join(', ')}.` : 'The chart has no plot groups.' });\n\t\treturn { spec: normalizeChartSpec(input).spec, issues, unsupported, lossless: false };\n\t}\n\tconst first = types[0];\n\tconst combo = types.some((t) => t !== first);\n\tinput.type = combo ? (types.includes('bar') ? 'bar' : first) : first;\n\tif (!combo) for (const s of series) delete s.type;\n\telse for (const s of series) if (s.type === input.type) delete s.type;\n\tif (!combo) for (const s of series) if (s.axis) issues.push({ path: 'series', message: `\"${s.name}\" is on a second value axis.` });\n\tif (types.some((t) => !isCartesianChart(t)) && combo) unsupported.push('a pie or radar mixed with other chart types');\n\tinput.series = series;\n\tinput.categories = categories.length ? categories : Array.from({ length: Math.max(0, ...series.map((s) => s.values.length)) }, (_, i) => `${i + 1}`);\n\tinput.stacking = stacking;\n\tinput.orientation = orientation;\n\tinput.dataLabels = dataLabels;\n\tinput.points = points || first !== 'line';\n\tif (bool(val(groups[0], 'varyColors')) && (first === 'bar' || first === 'line') && series.length === 1) unsupported.push('one colour per point (vary colours)');\n\n\t// Axes\n\tconst readAxis = (a: Element | undefined, fallback: ChartAxis): ChartAxis => {\n\t\tconst axis: ChartAxis = { ...fallback, format: {} };\n\t\tif (!a) return axis;\n\t\taxis.show = !bool(val(a, 'delete'));\n\t\taxis.title = richText(kid(a, 'title')) ?? '';\n\t\taxis.gridlines = !!kid(a, 'majorGridlines');\n\t\tconst scaling = kid(a, 'scaling');\n\t\taxis.min = numberOf(val(scaling, 'min'));\n\t\taxis.max = numberOf(val(scaling, 'max'));\n\t\tif (val(scaling, 'orientation') === 'maxMin') axis.reverse = true;\n\t\tif (kid(scaling, 'logBase')) {\n\t\t\tif (a.localName !== 'valAx') unsupported.push('a logarithmic category axis');\n\t\t\telse {\n\t\t\t\taxis.scale = 'log';\n\t\t\t\tconst base = numberOf(val(scaling, 'logBase')) ?? 10;\n\t\t\t\tif (base !== 10) axis.logBase = base;\n\t\t\t}\n\t\t}\n\t\taxis.step = numberOf(val(a, 'majorUnit'));\n\t\tconst fmt = kid(a, 'numFmt');\n\t\tconst code = fmt?.getAttribute('formatCode');\n\t\tif (code && code !== 'General' && fmt?.getAttribute('sourceLinked') !== '1') axis.format = { code };\n\t\treturn axis;\n\t};\n\tconst xy = first === 'scatter' || first === 'bubble';\n\tconst catAxis = kid(plot, 'catAx') ?? kid(plot, 'dateAx') ?? (xy ? valAxes.find((a) => !vertical(a)) : undefined);\n\tinput.xAxis = readAxis(catAxis, defaultChartAxis(false));\n\tif (kid(plot, 'dateAx')) (input.xAxis as ChartAxis).kind = 'date';\n\tinput.yAxis = readAxis(primaryAxis ?? valAxes.find(vertical) ?? valAxes[0], defaultChartAxis(true));\n\tconst secondaryAxis = valAxes.find((a) => a !== primaryAxis && (xy ? vertical(a) && a !== primaryAxis : true) && a !== catAxis);\n\tif (series.some((s) => s.axis === 'secondary') && secondaryAxis) input.yAxis2 = readAxis(secondaryAxis, defaultChartAxis(false));\n\tconst { spec, issues: specIssues } = normalizeChartSpec(input);\n\tissues.push(...specIssues);\n\tconst uniq = [...new Set(unsupported)];\n\treturn { spec, issues, unsupported: uniq, lossless: uniq.length === 0 && specIssues.length === 0 };\n}\n\nfunction readChartex(root: Element, issues: ChartIssue[], unsupported: string[]): ChartOoxmlReadResult {\n\tconst data = new Map<string, { categories: string[]; values: ChartValue[]; code?: string }>();\n\tfor (const d of kids(kid(root, 'chartData'), 'data')) {\n\t\tconst id = d.getAttribute('id') ?? String(data.size);\n\t\tconst strDim = kids(d, 'strDim')[0];\n\t\tconst numDim = kids(d, 'numDim')[0];\n\t\tconst lvl = (dim: Element | undefined) => kids(dim, 'lvl')[0];\n\t\tconst cats = kids(lvl(strDim), 'pt').map((p) => p.textContent ?? '');\n\t\tconst values: ChartValue[] = [];\n\t\tconst nl = lvl(numDim);\n\t\tfor (const p of kids(nl, 'pt')) {\n\t\t\tconst i = Number(p.getAttribute('idx') ?? values.length);\n\t\t\twhile (values.length < i) values.push(null);\n\t\t\tvalues[i] = numberOf((p.textContent ?? '').trim());\n\t\t}\n\t\tdata.set(id, { categories: cats, values, code: nl?.getAttribute('formatCode') ?? undefined });\n\t}\n\tconst chart = kid(root, 'chart');\n\tconst region = path(chart, 'plotArea', 'plotAreaRegion');\n\tconst seriesEls = kids(region, 'series');\n\tconst layouts: Record<string, ChartType> = { waterfall: 'waterfall', funnel: 'funnel', treemap: 'treemap', sunburst: 'treemap', boxWhisker: 'box', clusteredColumn: 'histogram', paretoLine: 'histogram' };\n\tconst layout = seriesEls[0]?.getAttribute('layoutId') ?? '';\n\tconst type = layouts[layout];\n\tif (!type) {\n\t\tissues.push({ path: 'plotArea', message: `The chart layout \"${layout || 'unknown'}\" is not supported.` });\n\t\treturn { spec: normalizeChartSpec({}).spec, issues, unsupported: [layout || 'unknown chartex layout'], lossless: false };\n\t}\n\tif (layout === 'sunburst') unsupported.push('sunburst (drawn as a treemap of the innermost level)');\n\tif (layout === 'paretoLine') unsupported.push('pareto line');\n\tconst series: ChartSeries[] = [];\n\tlet categories: string[] = [];\n\tfor (const s of seriesEls) {\n\t\tif (s.getAttribute('layoutId') === 'paretoLine') continue;\n\t\tconst ref = kid(s, 'dataId')?.getAttribute('val') ?? '0';\n\t\tconst d = data.get(ref);\n\t\tif (!d) continue;\n\t\tif (!categories.length) categories = d.categories;\n\t\tconst out: ChartSeries = { id: `series-${series.length + 1}`, name: strings(kid(s, 'tx'))[0] ?? `Series ${series.length + 1}`, values: d.values };\n\t\tif (d.code && d.code !== 'General') out.format = { code: d.code };\n\t\tseries.push(out);\n\t}\n\tconst title = richText(kid(chart, 'title'));\n\tconst longest = Math.max(0, ...series.map((s) => s.values.length));\n\tconst input: Record<string, unknown> = {\n\t\ttype,\n\t\ttitle: title ?? '',\n\t\tseries,\n\t\tcategories: categories.length >= longest ? categories : Array.from({ length: longest }, (_, i) => categories[i] ?? `${i + 1}`)\n\t};\n\tif (type === 'waterfall') input.showTotal = false;\n\tconst { spec, issues: specIssues } = normalizeChartSpec(input);\n\tissues.push(...specIssues);\n\treturn { spec, issues, unsupported, lossless: unsupported.length === 0 && specIssues.length === 0 };\n}\n\n// ---------------------------------------------------------------------------\n// Writing\n// ---------------------------------------------------------------------------\n\nconst esc = (s: string) => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\"/g, '&quot;');\nconst hex = (color: string | undefined) => {\n\tif (!color) return null;\n\tconst rgb = parseChartColor(color);\n\treturn rgb ? chartRgbToHex(rgb).slice(1).toUpperCase() : null;\n};\nconst fillXml = (color: string | undefined, line = false) => {\n\tconst h = hex(color);\n\tif (!h) return '';\n\treturn line ? `<c:spPr><a:ln w=\"28575\" cap=\"rnd\"><a:solidFill><a:srgbClr val=\"${h}\"/></a:solidFill><a:round/></a:ln></c:spPr>` : `<c:spPr><a:solidFill><a:srgbClr val=\"${h}\"/></a:solidFill></c:spPr>`;\n};\nconst rich = (text: string) => `<c:tx><c:rich><a:bodyPr/><a:lstStyle/><a:p><a:r><a:t>${esc(text)}</a:t></a:r></a:p></c:rich></c:tx><c:overlay val=\"0\"/>`;\nconst strLit = (items: readonly string[]) => `<c:strLit><c:ptCount val=\"${items.length}\"/>${items.map((s, i) => `<c:pt idx=\"${i}\"><c:v>${esc(s)}</c:v></c:pt>`).join('')}</c:strLit>`;\nconst numLit = (items: readonly ChartValue[], code = 'General') =>\n\t`<c:numLit><c:formatCode>${esc(code)}</c:formatCode><c:ptCount val=\"${items.length}\"/>${items.map((v, i) => (v === null || !Number.isFinite(v) ? '' : `<c:pt idx=\"${i}\"><c:v>${v}</c:v></c:pt>`)).join('')}</c:numLit>`;\n\nconst CURRENCY_SYMBOL: Record<string, string> = { USD: '$', EUR: '€', GBP: '£', JPY: '¥', CNY: '¥', INR: '₹' };\n\n/** A spreadsheet format code equivalent to a chart number format (`General` when there is none). */\nexport function chartFormatToCode(format: ChartNumberFormat): string {\n\tif (format.code) return format.code;\n\tconst d = format.decimals;\n\tconst frac = (n: number | undefined, fallback: number) => {\n\t\tconst k = n ?? fallback;\n\t\treturn k > 0 ? `.${'0'.repeat(k)}` : '';\n\t};\n\tconst wrap = (body: string) => `${format.prefix ? `\"${format.prefix.replace(/\"/g, '')}\"` : ''}${body}${format.suffix ? `\"${format.suffix.replace(/\"/g, '')}\"` : ''}`;\n\tswitch (format.style) {\n\t\tcase 'percent':\n\t\t\treturn wrap(`#,##0${frac(d, 0)}%`);\n\t\tcase 'currency': {\n\t\t\tconst code = (format.currency || 'USD').toUpperCase();\n\t\t\tconst sym = CURRENCY_SYMBOL[code] ?? `${code} `;\n\t\t\treturn wrap(`\"${sym}\"#,##0${frac(d, 0)}`);\n\t\t}\n\t\tcase 'compact':\n\t\t\treturn wrap('#,##0.0,,\"M\"');\n\t\tdefault:\n\t\t\treturn d !== undefined || format.prefix || format.suffix ? wrap(`#,##0${frac(d, 0)}`) : 'General';\n\t}\n}\n\n/** One `c:errBars` (CT_ErrBars order: errDir, errBarType, errValType, noEndCap, plus, minus, val). */\nfunction errBarsXml(bars: ChartErrorBars, dir: 'x' | 'y' | null): string {\n\tlet x = `<c:errBars>${dir ? `<c:errDir val=\"${dir}\"/>` : ''}<c:errBarType val=\"${bars.direction ?? 'both'}\"/><c:errValType val=\"${ERR_OUT[bars.type]}\"/><c:noEndCap val=\"${bars.cap === false ? 1 : 0}\"/>`;\n\tif (bars.type === 'custom') {\n\t\tconst plus = bars.plus ?? (bars.minus ?? []).map(() => null);\n\t\tx += `<c:plus>${numLit(plus)}</c:plus><c:minus>${numLit(bars.minus ?? plus)}</c:minus>`;\n\t} else if (bars.type !== 'stderr') x += `<c:val val=\"${bars.value ?? (bars.type === 'percent' ? 5 : 1)}\"/>`;\n\treturn `${x}</c:errBars>`;\n}\n\nconst MARKER_OUT: Record<ChartMarker, string> = { circle: 'circle', square: 'square', diamond: 'diamond', triangle: 'triangle', cross: 'x', none: 'none' };\n\nexport interface ChartOoxmlWriteResult {\n\t/** The `c:chartSpace` part. */\n\txml: string;\n\t/** What could not be written as DrawingML, as sentences (empty when nothing was lost). */\n\tissues: string[];\n}\n\n/**\n * Writes a chart as a DrawingML chart part (`c:chartSpace`) with the data as literals (no\n * embedded workbook), for `word/charts/chartN.xml` or `ppt/charts/chartN.xml`. Waterfall,\n * histogram, box, funnel and treemap charts need Office 2016 chartex parts; they are written\n * as the closest classic chart and reported in `issues`.\n */\nexport function chartToOoxml(spec: ChartSpec): ChartOoxmlWriteResult {\n\tconst issues: string[] = [];\n\tconst family = chartFamily(spec);\n\tlet type = spec.type;\n\tif (family === 'waterfall' || family === 'histogram' || family === 'box' || family === 'funnel') {\n\t\tissues.push(`${spec.type} charts are written as bar charts: DrawingML has no ${spec.type} type (Office 2016 stores it as chartex).`);\n\t\ttype = 'bar';\n\t} else if (family === 'treemap') {\n\t\tissues.push('Treemaps are written as pie charts: DrawingML has no treemap type.');\n\t\ttype = 'pie';\n\t}\n\tconst visible = spec.series.filter((s) => !s.hidden);\n\tif (visible.length < spec.series.length) issues.push(`${spec.series.length - visible.length} hidden series ${spec.series.length - visible.length === 1 ? 'is' : 'are'} left out.`);\n\tconst grouping = spec.stacking === 'stacked' ? 'stacked' : spec.stacking === 'percent' ? 'percentStacked' : 'standard';\n\tconst ids = { cat: 500000001, val: 500000002, cat2: 500000003, val2: 500000004 };\n\tconst xy = family === 'xy' || type === 'scatter' || type === 'bubble';\n\tconst pieLike = type === 'pie' || type === 'donut';\n\tconst typed = (s: ChartSeries) => (pieLike || type === 'radar' ? type : type === 'bubble' ? 'bubble' : xy ? 'scatter' : chartSeriesType({ type }, s));\n\t// Groups: (kind, axis) in first-appearance order.\n\tconst groups: { kind: string; secondary: boolean; series: { s: ChartSeries; index: number }[] }[] = [];\n\tvisible.forEach((s) => {\n\t\tconst kind = typed(s);\n\t\tconst secondary = !pieLike && s.axis === 'secondary';\n\t\tlet g = groups.find((x) => x.kind === kind && x.secondary === secondary);\n\t\tif (!g) groups.push((g = { kind, secondary, series: [] }));\n\t\tg.series.push({ s, index: spec.series.indexOf(s) });\n\t});\n\tif (pieLike && visible.length > 1) issues.push('Only the first series of a pie is drawn; the others are kept in the part.');\n\tconst catLit = strLit(spec.categories);\n\tlet order = 0;\n\tconst serXml = (kind: string, s: ChartSeries, index: number) => {\n\t\tconst parts = [`<c:idx val=\"${index}\"/>`, `<c:order val=\"${order++}\"/>`, `<c:tx><c:v>${esc(s.name)}</c:v></c:tx>`];\n\t\tconst lineLike = kind === 'line' || kind === 'scatter' || kind === 'radar';\n\t\tparts.push(fillXml(s.color, lineLike));\n\t\tif (kind === 'bar' || kind === 'bubble') parts.push('<c:invertIfNegative val=\"0\"/>');\n\t\tif (lineLike) {\n\t\t\tconst marker = s.marker ?? (spec.points || kind === 'scatter' ? 'circle' : 'none');\n\t\t\tparts.push(`<c:marker><c:symbol val=\"${MARKER_OUT[marker]}\"/>${marker !== 'none' ? '<c:size val=\"5\"/>' : ''}</c:marker>`);\n\t\t}\n\t\t(s.pointColors ?? []).forEach((c, i) => {\n\t\t\tconst h = hex(c ?? undefined);\n\t\t\tif (h) parts.push(`<c:dPt><c:idx val=\"${i}\"/>${kind === 'bar' ? '<c:invertIfNegative val=\"0\"/>' : ''}<c:bubble3D val=\"0\"/><c:spPr><a:solidFill><a:srgbClr val=\"${h}\"/></a:solidFill></c:spPr></c:dPt>`);\n\t\t});\n\t\tconst labels = s.dataLabels ?? spec.dataLabels;\n\t\tconst code = s.format ? chartFormatToCode(s.format) : undefined;\n\t\tif (s.dataLabels !== undefined || code)\n\t\t\tparts.push(`<c:dLbls>${code ? `<c:numFmt formatCode=\"${esc(code)}\" sourceLinked=\"0\"/>` : ''}<c:showLegendKey val=\"0\"/><c:showVal val=\"${labels ? 1 : 0}\"/><c:showCatName val=\"0\"/><c:showSerName val=\"0\"/><c:showPercent val=\"0\"/><c:showBubbleSize val=\"0\"/></c:dLbls>`);\n\t\tif (!pieLike && kind !== 'radar')\n\t\t\tfor (const t of s.trendlines ?? []) {\n\t\t\t\tlet x = `<c:trendline>${t.name ? `<c:name>${esc(t.name)}</c:name>` : ''}${fillXml(t.color, true)}<c:trendlineType val=\"${TREND_OUT[t.type]}\"/>`;\n\t\t\t\tif (t.type === 'polynomial') x += `<c:order val=\"${t.order ?? 2}\"/>`;\n\t\t\t\tif (t.type === 'moving-average') x += `<c:period val=\"${t.period ?? 2}\"/>`;\n\t\t\t\tif (t.forward) x += `<c:forward val=\"${t.forward}\"/>`;\n\t\t\t\tif (t.backward) x += `<c:backward val=\"${t.backward}\"/>`;\n\t\t\t\tif (t.intercept !== undefined && t.intercept !== null) x += `<c:intercept val=\"${t.intercept}\"/>`;\n\t\t\t\tx += `<c:dispRSqr val=\"${t.showR2 ? 1 : 0}\"/><c:dispEq val=\"${t.showEquation ? 1 : 0}\"/></c:trendline>`;\n\t\t\t\tparts.push(x);\n\t\t\t}\n\t\tif (!pieLike && kind !== 'radar') {\n\t\t\tconst xyKind = kind === 'scatter' || kind === 'bubble';\n\t\t\tif (s.errorBars) parts.push(errBarsXml(s.errorBars, xyKind ? 'y' : null));\n\t\t\tif (s.xErrorBars) {\n\t\t\t\tif (xyKind) parts.push(errBarsXml(s.xErrorBars, 'x'));\n\t\t\t\telse issues.push(`\"${s.name}\" has x error bars, which only scatter and bubble charts can hold; they are left out.`);\n\t\t\t}\n\t\t} else if (s.errorBars || s.xErrorBars) issues.push(`Error bars on \"${s.name}\" are left out: ${kind} charts cannot show them.`);\n\t\tconst valCode = chartFormatToCode(s.format ?? (s.axis === 'secondary' ? spec.yAxis2.format : spec.yAxis.format));\n\t\tif (kind === 'scatter' || kind === 'bubble') {\n\t\t\tconst xs = s.x ?? spec.categories.map((_, i) => i + 1);\n\t\t\tparts.push(`<c:xVal>${numLit(xs)}</c:xVal><c:yVal>${numLit(s.values, valCode)}</c:yVal>`);\n\t\t\tif (kind === 'bubble') parts.push(`<c:bubbleSize>${numLit(s.sizes ?? s.values.map(() => 1))}</c:bubbleSize><c:bubble3D val=\"0\"/>`);\n\t\t\telse parts.push(`<c:smooth val=\"${(s.curve ?? spec.curve) === 'smooth' ? 1 : 0}\"/>`);\n\t\t} else {\n\t\t\tparts.push(`<c:cat>${catLit}</c:cat><c:val>${numLit(s.values, valCode)}</c:val>`);\n\t\t\tif (kind === 'line') parts.push(`<c:smooth val=\"${(s.curve ?? spec.curve) === 'smooth' ? 1 : 0}\"/>`);\n\t\t}\n\t\tif ((s.curve ?? spec.curve) === 'step' && lineLike) issues.push(`\"${s.name}\" uses step lines, which DrawingML cannot express; they are written straight.`);\n\t\tif ((s.curve ?? spec.curve) === 'smooth' && kind === 'area') issues.push(`\"${s.name}\" is a smoothed area, which DrawingML cannot express; it is written straight.`);\n\t\treturn `<c:ser>${parts.join('')}</c:ser>`;\n\t};\n\tconst dLbls = `<c:dLbls><c:showLegendKey val=\"0\"/><c:showVal val=\"${spec.dataLabels ? 1 : 0}\"/><c:showCatName val=\"0\"/><c:showSerName val=\"0\"/><c:showPercent val=\"0\"/><c:showBubbleSize val=\"0\"/></c:dLbls>`;\n\tconst groupXml = groups.map((g) => {\n\t\tconst axes = g.secondary ? `<c:axId val=\"${ids.cat2}\"/><c:axId val=\"${ids.val2}\"/>` : `<c:axId val=\"${ids.cat}\"/><c:axId val=\"${ids.val}\"/>`;\n\t\tconst sers = g.series.map(({ s, index }) => serXml(g.kind, s, index)).join('');\n\t\tswitch (g.kind) {\n\t\t\tcase 'bar': {\n\t\t\t\tconst n = g.series.length;\n\t\t\t\tconst barsWidth = spec.stacking === 'none' ? n - (n - 1) * spec.overlap : 1;\n\t\t\t\tconst gapPct = Math.round(Math.min(500, (spec.gapWidth / Math.max(0.01, 1 - spec.gapWidth)) * barsWidth * 100));\n\t\t\t\tconst overlapPct = spec.stacking === 'none' ? Math.round(spec.overlap * 100) : 100;\n\t\t\t\treturn `<c:barChart><c:barDir val=\"${spec.orientation === 'horizontal' ? 'bar' : 'col'}\"/><c:grouping val=\"${spec.stacking === 'none' ? 'clustered' : grouping}\"/><c:varyColors val=\"0\"/>${sers}${dLbls}<c:gapWidth val=\"${gapPct}\"/><c:overlap val=\"${overlapPct}\"/>${axes}</c:barChart>`;\n\t\t\t}\n\t\t\tcase 'line':\n\t\t\t\treturn `<c:lineChart><c:grouping val=\"${spec.stacking === 'none' ? 'standard' : 'standard'}\"/><c:varyColors val=\"0\"/>${sers}${dLbls}<c:marker val=\"1\"/>${axes}</c:lineChart>`;\n\t\t\tcase 'area':\n\t\t\t\treturn `<c:areaChart><c:grouping val=\"${grouping}\"/><c:varyColors val=\"0\"/>${sers}${dLbls}${axes}</c:areaChart>`;\n\t\t\tcase 'scatter':\n\t\t\t\treturn `<c:scatterChart><c:scatterStyle val=\"lineMarker\"/><c:varyColors val=\"0\"/>${sers}${dLbls}${axes}</c:scatterChart>`;\n\t\t\tcase 'bubble':\n\t\t\t\treturn `<c:bubbleChart><c:varyColors val=\"0\"/>${sers}${dLbls}<c:bubbleScale val=\"100\"/>${axes}</c:bubbleChart>`;\n\t\t\tcase 'radar':\n\t\t\t\treturn `<c:radarChart><c:radarStyle val=\"marker\"/><c:varyColors val=\"0\"/>${sers}${dLbls}${axes}</c:radarChart>`;\n\t\t\tcase 'donut':\n\t\t\t\treturn `<c:doughnutChart><c:varyColors val=\"1\"/>${sers}${dLbls}<c:firstSliceAng val=\"0\"/><c:holeSize val=\"${Math.round(Math.max(10, Math.min(90, spec.innerRadius * 100)))}\"/></c:doughnutChart>`;\n\t\t\tdefault:\n\t\t\t\treturn `<c:pieChart><c:varyColors val=\"1\"/>${sers}${dLbls}<c:firstSliceAng val=\"0\"/></c:pieChart>`;\n\t\t}\n\t});\n\t// CT_Scaling order: logBase, orientation, max, min.\n\tconst scaling = (a: ChartAxis) =>\n\t\t`<c:scaling>${a.scale === 'log' ? `<c:logBase val=\"${a.logBase ?? 10}\"/>` : ''}<c:orientation val=\"${a.reverse ? 'maxMin' : 'minMax'}\"/>${a.max !== null ? `<c:max val=\"${a.max}\"/>` : ''}${a.min !== null ? `<c:min val=\"${a.min}\"/>` : ''}</c:scaling>`;\n\tconst title = (a: ChartAxis) => (a.title ? `<c:title>${rich(a.title)}</c:title>` : '');\n\tconst fmt = (a: ChartAxis) => {\n\t\tconst code = chartFormatToCode(a.format);\n\t\treturn code !== 'General' ? `<c:numFmt formatCode=\"${esc(code)}\" sourceLinked=\"0\"/>` : `<c:numFmt formatCode=\"${spec.stacking === 'percent' ? '0%' : 'General'}\" sourceLinked=\"1\"/>`;\n\t};\n\tconst horizontal = spec.orientation === 'horizontal';\n\tconst catPos = horizontal ? 'l' : 'b';\n\tconst valPos = horizontal ? 'b' : 'l';\n\tconst valAx = (id: number, cross: number, a: ChartAxis, pos: string, crosses: string, catKind = false) =>\n\t\t`<c:valAx><c:axId val=\"${id}\"/>${scaling(a)}<c:delete val=\"${a.show ? 0 : 1}\"/><c:axPos val=\"${pos}\"/>${a.gridlines ? '<c:majorGridlines/>' : ''}${title(a)}${fmt(a)}<c:majorTickMark val=\"out\"/><c:minorTickMark val=\"none\"/><c:tickLblPos val=\"nextTo\"/><c:crossAx val=\"${cross}\"/><c:crosses val=\"${crosses}\"/><c:crossBetween val=\"${catKind ? 'midCat' : 'between'}\"/>${a.step ? `<c:majorUnit val=\"${a.step}\"/>` : ''}</c:valAx>`;\n\tconst catAx = (id: number, cross: number, a: ChartAxis, pos: string, hidden = false) =>\n\t\t`<c:${a.kind === 'date' ? 'dateAx' : 'catAx'}><c:axId val=\"${id}\"/><c:scaling><c:orientation val=\"${a.reverse ? 'maxMin' : 'minMax'}\"/></c:scaling><c:delete val=\"${a.show && !hidden ? 0 : 1}\"/><c:axPos val=\"${pos}\"/>${a.gridlines ? '<c:majorGridlines/>' : ''}${title(a)}<c:numFmt formatCode=\"General\" sourceLinked=\"1\"/><c:majorTickMark val=\"out\"/><c:minorTickMark val=\"none\"/><c:tickLblPos val=\"nextTo\"/><c:crossAx val=\"${cross}\"/><c:crosses val=\"autoZero\"/><c:auto val=\"1\"/>${a.kind === 'date' ? '<c:lblOffset val=\"100\"/><c:baseTimeUnit val=\"days\"/>' : '<c:lblAlgn val=\"ctr\"/><c:lblOffset val=\"100\"/><c:noMultiLvlLbl val=\"0\"/>'}</c:${a.kind === 'date' ? 'dateAx' : 'catAx'}>`;\n\tlet axes = '';\n\tif (!pieLike) {\n\t\tif (xy) axes = valAx(ids.cat, ids.val, spec.xAxis, 'b', 'autoZero', true) + valAx(ids.val, ids.cat, spec.yAxis, 'l', 'autoZero', true);\n\t\telse {\n\t\t\tif (spec.xAxis.scale === 'log') issues.push('The category axis cannot be logarithmic; its log scale is left out.');\n\t\t\taxes = catAx(ids.cat, ids.val, spec.xAxis, catPos) + valAx(ids.val, ids.cat, spec.yAxis, valPos, 'autoZero');\n\t\t}\n\t\tif (groups.some((g) => g.secondary)) axes += catAx(ids.cat2, ids.val2, spec.xAxis, catPos, true) + valAx(ids.val2, ids.cat2, spec.yAxis2, horizontal ? 't' : 'r', 'max');\n\t}\n\tconst legendPos = { bottom: 'b', top: 't', left: 'l', right: 'r' }[spec.legend.position];\n\tconst legend = spec.legend.show ? `<c:legend><c:legendPos val=\"${legendPos}\"/><c:overlay val=\"0\"/></c:legend>` : '';\n\tconst titleXml = spec.title ? `<c:title>${rich(spec.title)}</c:title><c:autoTitleDeleted val=\"0\"/>` : '<c:autoTitleDeleted val=\"1\"/>';\n\tif (spec.subtitle) issues.push('The subtitle is left out: DrawingML charts have one title.');\n\tif (family === 'radar' && spec.series.some((s) => s.trendlines?.length)) issues.push('Trendlines on a radar chart are left out.');\n\tconst xml =\n\t\t`<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>` +\n\t\t`<c:chartSpace xmlns:c=\"${CHART_OOXML_NS}\" xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\">` +\n\t\t`<c:roundedCorners val=\"0\"/><c:chart>${titleXml}<c:plotArea><c:layout/>${groupXml.join('')}${axes}</c:plotArea>${legend}<c:plotVisOnly val=\"1\"/><c:dispBlanksAs val=\"gap\"/></c:chart>` +\n\t\t`<c:txPr><a:bodyPr/><a:lstStyle/><a:p><a:pPr><a:defRPr sz=\"${Math.round(10 * 100)}\"/></a:pPr><a:endParaRPr lang=\"en-US\"/></a:p></c:txPr></c:chartSpace>`;\n\treturn { xml, issues: [...new Set(issues)] };\n}\n","/**\n * Minimal, dependency-free ZIP reader used by the DOCX and zipped-export\n * import adapters.\n *\n * - Reads the central directory (including ZIP64 end records and extra\n * fields), so sizes come from the authoritative directory rather than local\n * headers or data descriptors.\n * - Supports stored (method 0) and deflate (method 8) entries; deflate is\n * inflated with the platform `DecompressionStream(\"deflate-raw\")` (modern\n * browsers, Node ≥ 18).\n * - Guards against zip bombs (entry-count and total-uncompressed-size caps,\n * enforced on the bytes actually inflated, not only the declared sizes),\n * path traversal in entry names and encrypted entries.\n * - Verifies CRC-32 checksums of extracted entries.\n */\n\nexport type ZipErrorCode =\n /** Not a ZIP archive, or its directory is truncated / inconsistent. */\n | \"invalid_archive\"\n /** Compression method other than stored/deflate, multi-disk archives, … */\n | \"unsupported_feature\"\n /** The entry is encrypted (general-purpose flag bit 0). */\n | \"encrypted\"\n /** An entry name is absolute or contains `..` segments. */\n | \"unsafe_path\"\n /** More entries than `maxEntries`. */\n | \"too_many_entries\"\n /** Extracting would exceed `maxTotalSize` uncompressed bytes. */\n | \"too_large\"\n /** The entry data is corrupt (bad header, size or CRC mismatch, bad deflate stream). */\n | \"corrupt_entry\"\n /** No entry with the requested name. */\n | \"entry_not_found\"\n /** `DecompressionStream` is unavailable in this environment. */\n | \"unsupported_environment\";\n\nexport class ZipError extends Error {\n readonly code: ZipErrorCode;\n readonly entryName?: string;\n\n constructor(code: ZipErrorCode, message: string, details: { entryName?: string; cause?: unknown } = {}) {\n super(message, details.cause !== undefined ? { cause: details.cause } : undefined);\n this.name = \"ZipError\";\n this.code = code;\n this.entryName = details.entryName;\n }\n}\n\nexport interface ZipEntry {\n /** Entry path with `/` separators (backslashes are normalized). */\n name: string;\n /** Whether the entry is a directory (name ends with `/`). */\n isDirectory: boolean;\n /** Whether the entry is encrypted; reading it throws `ZipError(\"encrypted\")`. */\n encrypted: boolean;\n /** Compression method (0 = stored, 8 = deflate). */\n method: number;\n /** Declared compressed size in bytes. */\n compressedSize: number;\n /** Declared uncompressed size in bytes. */\n size: number;\n /** CRC-32 of the uncompressed data. */\n crc32: number;\n /** Offset of the entry's local file header. */\n localHeaderOffset: number;\n}\n\nexport interface ZipReadOptions {\n /** Maximum number of entries in the central directory (default 10 000). */\n maxEntries?: number;\n /**\n * Maximum number of uncompressed bytes extracted from the archive, summed\n * over every `read` call (default 256 MiB). Enforced while inflating.\n */\n maxTotalSize?: number;\n /**\n * What to do with entries whose names are absolute or contain `..`\n * segments: `\"error\"` (default) rejects the archive, `\"skip\"` leaves them\n * out of `entries`.\n */\n unsafePaths?: \"error\" | \"skip\";\n}\n\nexport const DEFAULT_ZIP_MAX_ENTRIES = 10_000;\nexport const DEFAULT_ZIP_MAX_TOTAL_SIZE = 256 * 1024 * 1024;\n\nconst SIG_EOCD = 0x06054b50;\nconst SIG_ZIP64_EOCD = 0x06064b50;\nconst SIG_ZIP64_LOCATOR = 0x07064b50;\nconst SIG_CENTRAL = 0x02014b50;\nconst SIG_LOCAL = 0x04034b50;\nconst EOCD_SIZE = 22;\nconst MAX_COMMENT = 0xffff;\n\nlet crcTable: Uint32Array | null = null;\n\n/** CRC-32 (IEEE 802.3), as used by ZIP. */\nexport function zipCrc32(data: Uint8Array): number {\n if (!crcTable) {\n crcTable = new Uint32Array(256);\n for (let n = 0; n < 256; n++) {\n let c = n;\n for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;\n crcTable[n] = c >>> 0;\n }\n }\n let crc = 0xffffffff;\n for (let i = 0; i < data.length; i++) crc = crcTable[(crc ^ data[i]) & 0xff] ^ (crc >>> 8);\n return (crc ^ 0xffffffff) >>> 0;\n}\n\nfunction toBytes(data: ArrayBuffer | ArrayBufferView): Uint8Array {\n // Duck-typed so ArrayBuffers from other realms (iframes, jsdom) work too.\n if (ArrayBuffer.isView(data)) return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);\n return new Uint8Array(data as ArrayBuffer);\n}\n\n/** Whether `name` is absolute, has a drive letter, or contains `..` / NUL. */\nexport function isUnsafeZipPath(name: string): boolean {\n if (!name || name.includes(\"\\0\")) return true;\n const normalized = name.replace(/\\\\/g, \"/\");\n if (normalized.startsWith(\"/\") || /^[a-zA-Z]:/.test(normalized)) return true;\n return normalized.split(\"/\").some((segment) => segment === \"..\");\n}\n\nconst utf8 = new TextDecoder(\"utf-8\");\n\n/** CP437 high half, used for names without the UTF-8 flag. */\nconst CP437_HIGH =\n \"ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ \";\n\nfunction decodeName(bytes: Uint8Array, isUtf8: boolean): string {\n if (isUtf8 || bytes.every((b) => b < 0x80)) return utf8.decode(bytes);\n let out = \"\";\n for (const b of bytes) out += b < 0x80 ? String.fromCharCode(b) : CP437_HIGH[b - 0x80];\n return out;\n}\n\n/**\n * A parsed ZIP archive. Entry data is extracted lazily with {@link read}.\n * Create it with {@link readZip}.\n */\nexport class ZipArchive {\n /** Entries in central-directory order. */\n readonly entries: readonly ZipEntry[];\n private readonly byName = new Map<string, ZipEntry>();\n private extracted = 0;\n\n constructor(\n private readonly bytes: Uint8Array,\n entries: ZipEntry[],\n private readonly maxTotalSize: number,\n ) {\n this.entries = entries;\n entries.forEach((entry) => {\n if (!this.byName.has(entry.name)) this.byName.set(entry.name, entry);\n });\n }\n\n /** Looks up an entry by exact name (a leading `/` is ignored). */\n get(name: string): ZipEntry | undefined {\n return this.byName.get(name.replace(/^\\/+/, \"\"));\n }\n\n has(name: string): boolean {\n return !!this.get(name);\n }\n\n /** Uncompressed bytes extracted so far (counted against `maxTotalSize`). */\n get extractedSize(): number {\n return this.extracted;\n }\n\n /** Extracts an entry's data, verifying its size and CRC-32. */\n async read(entryOrName: ZipEntry | string): Promise<Uint8Array> {\n const entry = typeof entryOrName === \"string\" ? this.get(entryOrName) : entryOrName;\n if (!entry) {\n throw new ZipError(\"entry_not_found\", `ZIP entry \"${String(entryOrName)}\" not found.`, {\n entryName: String(entryOrName),\n });\n }\n const name = entry.name;\n if (entry.encrypted) {\n throw new ZipError(\"encrypted\", `ZIP entry \"${name}\" is encrypted; encrypted archives are not supported.`, {\n entryName: name,\n });\n }\n if (entry.isDirectory) return new Uint8Array(0);\n const remaining = this.maxTotalSize - this.extracted;\n if (entry.size > remaining) {\n throw new ZipError(\n \"too_large\",\n `Extracting \"${name}\" (${entry.size} bytes) would exceed the ${this.maxTotalSize}-byte limit.`,\n { entryName: name },\n );\n }\n\n const { bytes } = this;\n const offset = entry.localHeaderOffset;\n if (offset + 30 > bytes.length || readU32(bytes, offset) !== SIG_LOCAL) {\n throw new ZipError(\"corrupt_entry\", `ZIP entry \"${name}\" has no valid local header.`, { entryName: name });\n }\n const dataStart = offset + 30 + readU16(bytes, offset + 26) + readU16(bytes, offset + 28);\n const dataEnd = dataStart + entry.compressedSize;\n if (dataEnd > bytes.length) {\n throw new ZipError(\"corrupt_entry\", `ZIP entry \"${name}\" is truncated.`, { entryName: name });\n }\n const raw = bytes.subarray(dataStart, dataEnd);\n\n let data: Uint8Array;\n if (entry.method === 0) {\n if (entry.compressedSize !== entry.size) {\n throw new ZipError(\"corrupt_entry\", `Stored ZIP entry \"${name}\" has inconsistent sizes.`, { entryName: name });\n }\n data = raw.slice();\n } else if (entry.method === 8) {\n // Cap at the declared size: more output means a lying header (or a bomb).\n data = await inflateRaw(raw, entry.size, name);\n } else {\n throw new ZipError(\n \"unsupported_feature\",\n `ZIP entry \"${name}\" uses unsupported compression method ${entry.method}; only stored and deflate are supported.`,\n { entryName: name },\n );\n }\n if (data.length !== entry.size) {\n throw new ZipError(\"corrupt_entry\", `ZIP entry \"${name}\" size does not match the directory.`, { entryName: name });\n }\n this.extracted += data.length;\n if (zipCrc32(data) !== entry.crc32) {\n throw new ZipError(\"corrupt_entry\", `ZIP entry \"${name}\" failed its CRC-32 check.`, { entryName: name });\n }\n return data;\n }\n\n /** Extracts an entry and decodes it as UTF-8 (a leading BOM is removed). */\n async readText(entryOrName: ZipEntry | string): Promise<string> {\n const text = utf8.decode(await this.read(entryOrName));\n return text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;\n }\n}\n\nfunction readU16(bytes: Uint8Array, offset: number): number {\n return bytes[offset] | (bytes[offset + 1] << 8);\n}\n\nfunction readU32(bytes: Uint8Array, offset: number): number {\n return (bytes[offset] | (bytes[offset + 1] << 8) | (bytes[offset + 2] << 16) | (bytes[offset + 3] << 24)) >>> 0;\n}\n\nfunction readU64(bytes: Uint8Array, offset: number): number {\n const value = readU32(bytes, offset) + readU32(bytes, offset + 4) * 0x100000000;\n if (!Number.isSafeInteger(value)) {\n throw new ZipError(\"unsupported_feature\", \"ZIP64 value exceeds the supported range.\");\n }\n return value;\n}\n\n/** Inflates a raw deflate stream, failing as soon as output exceeds `limit` bytes. */\nasync function inflateRaw(raw: Uint8Array, limit: number, entryName: string): Promise<Uint8Array> {\n const Stream: typeof DecompressionStream | undefined = (globalThis as any).DecompressionStream;\n if (typeof Stream !== \"function\") {\n throw new ZipError(\n \"unsupported_environment\",\n \"Inflating ZIP entries needs DecompressionStream (modern browsers, Node 18+).\",\n { entryName },\n );\n }\n const stream = new Stream(\"deflate-raw\");\n const writer = stream.writable.getWriter();\n const reader = stream.readable.getReader();\n // Feed the input in slices so output is pulled (and checked) incrementally.\n const CHUNK = 64 * 1024;\n const feeding = (async () => {\n for (let i = 0; i < raw.length; i += CHUNK) await writer.write(raw.subarray(i, i + CHUNK) as unknown as BufferSource);\n await writer.close();\n })();\n feeding.catch(() => {});\n\n const chunks: Uint8Array[] = [];\n let total = 0;\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n total += value.length;\n if (total > limit) {\n throw new ZipError(\n \"corrupt_entry\",\n `ZIP entry \"${entryName}\" inflates beyond its declared size of ${limit} bytes.`,\n { entryName },\n );\n }\n chunks.push(value);\n }\n } catch (error) {\n reader.cancel().catch(() => {});\n writer.abort().catch(() => {});\n if (error instanceof ZipError) throw error;\n throw new ZipError(\"corrupt_entry\", `ZIP entry \"${entryName}\" has an invalid deflate stream.`, {\n entryName,\n cause: error,\n });\n }\n await feeding.catch(() => {});\n const out = new Uint8Array(total);\n let pos = 0;\n for (const chunk of chunks) {\n out.set(chunk, pos);\n pos += chunk.length;\n }\n return out;\n}\n\nfunction findEndOfCentralDirectory(bytes: Uint8Array): number {\n const min = Math.max(0, bytes.length - EOCD_SIZE - MAX_COMMENT);\n for (let i = bytes.length - EOCD_SIZE; i >= min; i--) {\n if (readU32(bytes, i) === SIG_EOCD && i + EOCD_SIZE + readU16(bytes, i + 20) <= bytes.length) return i;\n }\n return -1;\n}\n\n/**\n * Parses a ZIP archive's central directory. Entry data is not extracted until\n * {@link ZipArchive.read} is called. Throws {@link ZipError}.\n */\nexport async function readZip(data: ArrayBuffer | ArrayBufferView, options: ZipReadOptions = {}): Promise<ZipArchive> {\n const bytes = toBytes(data);\n const maxEntries = options.maxEntries ?? DEFAULT_ZIP_MAX_ENTRIES;\n const maxTotalSize = options.maxTotalSize ?? DEFAULT_ZIP_MAX_TOTAL_SIZE;\n\n const eocd = findEndOfCentralDirectory(bytes);\n if (eocd < 0) throw new ZipError(\"invalid_archive\", \"Not a ZIP archive (no end of central directory record).\");\n\n let diskNumber = readU16(bytes, eocd + 4);\n let cdDisk = readU16(bytes, eocd + 6);\n let count = readU16(bytes, eocd + 10);\n let cdSize = readU32(bytes, eocd + 12);\n let cdOffset = readU32(bytes, eocd + 16);\n\n if (count === 0xffff || cdSize === 0xffffffff || cdOffset === 0xffffffff) {\n const locator = eocd - 20;\n if (locator < 0 || readU32(bytes, locator) !== SIG_ZIP64_LOCATOR) {\n throw new ZipError(\"invalid_archive\", \"ZIP64 archive is missing its end of central directory locator.\");\n }\n const record = readU64(bytes, locator + 8);\n if (record + 56 > bytes.length || readU32(bytes, record) !== SIG_ZIP64_EOCD) {\n throw new ZipError(\"invalid_archive\", \"ZIP64 end of central directory record not found.\");\n }\n diskNumber = readU32(bytes, record + 16);\n cdDisk = readU32(bytes, record + 20);\n count = readU64(bytes, record + 32);\n cdSize = readU64(bytes, record + 40);\n cdOffset = readU64(bytes, record + 48);\n }\n if (diskNumber !== 0 || cdDisk !== 0) {\n throw new ZipError(\"unsupported_feature\", \"Multi-disk (spanned) ZIP archives are not supported.\");\n }\n if (count > maxEntries) {\n throw new ZipError(\"too_many_entries\", `ZIP archive has ${count} entries; the limit is ${maxEntries}.`);\n }\n if (cdOffset + cdSize > bytes.length) {\n throw new ZipError(\"invalid_archive\", \"ZIP central directory lies outside the file.\");\n }\n\n const entries: ZipEntry[] = [];\n let p = cdOffset;\n for (let i = 0; i < count; i++) {\n if (p + 46 > bytes.length || readU32(bytes, p) !== SIG_CENTRAL) {\n throw new ZipError(\"invalid_archive\", \"ZIP central directory is corrupt.\");\n }\n const flags = readU16(bytes, p + 8);\n const method = readU16(bytes, p + 10);\n const crc32 = readU32(bytes, p + 16);\n let compressedSize = readU32(bytes, p + 20);\n let size = readU32(bytes, p + 24);\n const nameLength = readU16(bytes, p + 28);\n const extraLength = readU16(bytes, p + 30);\n const commentLength = readU16(bytes, p + 32);\n let localHeaderOffset = readU32(bytes, p + 42);\n const nameStart = p + 46;\n const extraStart = nameStart + nameLength;\n const next = extraStart + extraLength + commentLength;\n if (next > bytes.length) throw new ZipError(\"invalid_archive\", \"ZIP central directory is truncated.\");\n\n // ZIP64 extended information: only the fields that overflowed are present, in order.\n for (let e = extraStart; e + 4 <= extraStart + extraLength; ) {\n const id = readU16(bytes, e);\n const len = readU16(bytes, e + 2);\n if (id === 0x0001) {\n let f = e + 4;\n const end = f + len;\n if (size === 0xffffffff && f + 8 <= end) {\n size = readU64(bytes, f);\n f += 8;\n }\n if (compressedSize === 0xffffffff && f + 8 <= end) {\n compressedSize = readU64(bytes, f);\n f += 8;\n }\n if (localHeaderOffset === 0xffffffff && f + 8 <= end) localHeaderOffset = readU64(bytes, f);\n }\n e += 4 + len;\n }\n\n const rawName = decodeName(bytes.subarray(nameStart, extraStart), (flags & 0x0800) !== 0);\n const name = rawName.replace(/\\\\/g, \"/\");\n p = next;\n if (isUnsafeZipPath(rawName)) {\n if (options.unsafePaths === \"skip\") continue;\n throw new ZipError(\"unsafe_path\", `ZIP entry name \"${rawName}\" is absolute or escapes the archive root.`, {\n entryName: rawName,\n });\n }\n entries.push({\n name,\n isDirectory: name.endsWith(\"/\"),\n encrypted: (flags & 0x0001) !== 0,\n method,\n compressedSize,\n size,\n crc32,\n localHeaderOffset,\n });\n }\n return new ZipArchive(bytes, entries, maxTotalSize);\n}\n"]}