@office-kit/xlsx 0.17.0 → 0.18.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 (61) hide show
  1. package/README.md +78 -4
  2. package/dist/{cell-style-DjKKPWDL.mjs → cell-style-CbB4nXTY.mjs} +11 -4
  3. package/dist/cell-style-CbB4nXTY.mjs.map +1 -0
  4. package/dist/{differential-7KGzbliB.mjs → differential-QLaKEiBk.mjs} +2 -2
  5. package/dist/{differential-7KGzbliB.mjs.map → differential-QLaKEiBk.mjs.map} +1 -1
  6. package/dist/io/load.d.ts +2 -0
  7. package/dist/io.mjs +2 -2
  8. package/dist/{iterparse-DZE0zy2M.mjs → iterparse-CZoRXvZW.mjs} +2 -2
  9. package/dist/{iterparse-DZE0zy2M.mjs.map → iterparse-CZoRXvZW.mjs.map} +1 -1
  10. package/dist/{load-DIdQ_zum.mjs → load-BpnCPv1S.mjs} +25 -13
  11. package/dist/load-BpnCPv1S.mjs.map +1 -0
  12. package/dist/{manifest-BHUYpjUG.mjs → manifest-9p0ccqmR.mjs} +10 -11
  13. package/dist/manifest-9p0ccqmR.mjs.map +1 -0
  14. package/dist/node.mjs +1 -1
  15. package/dist/packaging.mjs +1 -1
  16. package/dist/{parser-By6RWZVW.mjs → parser-B1tB9YaE.mjs} +15 -5
  17. package/dist/parser-B1tB9YaE.mjs.map +1 -0
  18. package/dist/{save-ax11Gsw0.mjs → save-1Z3344nz.mjs} +6 -6
  19. package/dist/{save-ax11Gsw0.mjs.map → save-1Z3344nz.mjs.map} +1 -1
  20. package/dist/schema.mjs +1 -1
  21. package/dist/{serialize-Dmb6Vtt9.mjs → serialize-BtxgssFK.mjs} +2 -2
  22. package/dist/{serialize-Dmb6Vtt9.mjs.map → serialize-BtxgssFK.mjs.map} +1 -1
  23. package/dist/{serializer-dhv07Z6F.mjs → serializer-N6XIwsgp.mjs} +2 -2
  24. package/dist/{serializer-dhv07Z6F.mjs.map → serializer-N6XIwsgp.mjs.map} +1 -1
  25. package/dist/streaming.mjs +34 -17
  26. package/dist/streaming.mjs.map +1 -1
  27. package/dist/styles/display-text.d.ts +95 -0
  28. package/dist/styles/format-code.d.ts +125 -0
  29. package/dist/styles/index.d.ts +1 -0
  30. package/dist/styles/numbers.d.ts +7 -0
  31. package/dist/styles.mjs +1161 -4
  32. package/dist/styles.mjs.map +1 -0
  33. package/dist/{stylesheet-writer-BBYjNSMA.mjs → stylesheet-writer-BEn-0P0x.mjs} +341 -105
  34. package/dist/stylesheet-writer-BEn-0P0x.mjs.map +1 -0
  35. package/dist/{table-BFi2WmgG.mjs → table-BxOLUZs3.mjs} +2 -2
  36. package/dist/{table-BFi2WmgG.mjs.map → table-BxOLUZs3.mjs.map} +1 -1
  37. package/dist/{tree-BX-sRRVp.mjs → tree-CspNjuYl.mjs} +12 -2
  38. package/dist/tree-CspNjuYl.mjs.map +1 -0
  39. package/dist/workbook/index.d.ts +1 -1
  40. package/dist/workbook/workbook.d.ts +9 -46
  41. package/dist/{workbook-CMel6UcI.mjs → workbook-tG9oYtzU.mjs} +46 -9
  42. package/dist/workbook-tG9oYtzU.mjs.map +1 -0
  43. package/dist/workbook.mjs +2 -2
  44. package/dist/worksheet/index.d.ts +1 -1
  45. package/dist/worksheet/worksheet.d.ts +55 -14
  46. package/dist/{worksheet-Cxn2c-jz.mjs → worksheet-DLMyDD7W.mjs} +85 -20
  47. package/dist/worksheet-DLMyDD7W.mjs.map +1 -0
  48. package/dist/worksheet.mjs +3 -3
  49. package/dist/xml/namespaces.d.ts +7 -0
  50. package/dist/xml/parser.d.ts +12 -0
  51. package/dist/xml/strict-package.d.ts +14 -0
  52. package/dist/xml.mjs +4 -4
  53. package/package.json +1 -1
  54. package/dist/cell-style-DjKKPWDL.mjs.map +0 -1
  55. package/dist/load-DIdQ_zum.mjs.map +0 -1
  56. package/dist/manifest-BHUYpjUG.mjs.map +0 -1
  57. package/dist/parser-By6RWZVW.mjs.map +0 -1
  58. package/dist/stylesheet-writer-BBYjNSMA.mjs.map +0 -1
  59. package/dist/tree-BX-sRRVp.mjs.map +0 -1
  60. package/dist/workbook-CMel6UcI.mjs.map +0 -1
  61. package/dist/worksheet-Cxn2c-jz.mjs.map +0 -1
package/README.md CHANGED
@@ -80,6 +80,10 @@ Honest list:
80
80
  projects.
81
81
  - **`.xlsx` only**: no `.xls` (BIFF), `.xlsb`, `.ods`, or `.csv`. Use
82
82
  SheetJS for those.
83
+ - **Transitional OOXML only**: a file saved through Excel's "Strict Open XML
84
+ Spreadsheet" entry is ISO 29500 **strict**, and reading it is not
85
+ implemented. `loadWorkbook` and `loadWorkbookStream` name the format and tell
86
+ you to re-save it as "Excel Workbook (.xlsx)" instead of mis-reading it.
83
87
  - **Node 22+ required**: relies on built-in `Web Streams`, `Blob`, and
84
88
  `fetch`. Node 18 / 20 (EOL) are not supported.
85
89
  - **Browser stress-test history is shorter** than ExcelJS's. If you ship
@@ -169,18 +173,61 @@ see the [Recipes](https://baseballyama.github.io/@office-kit/xlsx/docs/recipes).
169
173
 
170
174
  ```ts
171
175
  import { loadWorkbook, workbookToBytes } from '@office-kit/xlsx/io';
176
+ import { getSheetByIndex } from '@office-kit/xlsx/workbook';
172
177
  import { setCell } from '@office-kit/xlsx/worksheet';
173
178
  import { fromBuffer } from '@office-kit/xlsx/node';
174
179
  import { readFile, writeFile } from 'node:fs/promises';
175
180
 
176
181
  const wb = await loadWorkbook(fromBuffer(await readFile('input.xlsx')));
177
- const sheet = wb.sheets[0];
178
- if (sheet?.kind === 'worksheet') {
179
- setCell(sheet.sheet, /* row */ 1, /* col */ 1, 'Hello from @office-kit/xlsx');
182
+ const sheet = getSheetByIndex(wb, 0);
183
+ if (sheet) {
184
+ setCell(sheet, /* row */ 1, /* col */ 1, 'Hello from @office-kit/xlsx');
180
185
  }
181
186
  await writeFile('output.xlsx', await workbookToBytes(wb));
182
187
  ```
183
188
 
189
+ `getSheetByIndex` returns `undefined` for an out-of-range index and for a tab
190
+ holding a chartsheet rather than a worksheet, so the one check above covers
191
+ both. Look sheets up by name with `getSheet(wb, 'Sheet1')`.
192
+
193
+ ### Two answers to "where does the data end"
194
+
195
+ A sheet often carries formatting past its content: someone formats 200 rows and
196
+ types into 4. Excel keeps the two readings of that sheet apart, and so does
197
+ this library.
198
+
199
+ `getCellExtent` counts every cell the file materialises, including one that
200
+ exists only to carry a style. That is Excel's used range and the `<dimension>`
201
+ element Excel writes, and its max corner is what bounds `iterRows` /
202
+ `iterValues` by default. `getValueExtent` counts only the cells holding a
203
+ value, which is what a caller mapping rows to records means by "the data".
204
+ Spread its box into the iteration to be bounded by it:
205
+
206
+ ```ts
207
+ import { getCellExtent, getValueExtent, iterValues } from '@office-kit/xlsx/worksheet';
208
+
209
+ getCellExtent(ws)?.maxRow; // 200, the used range
210
+ getValueExtent(ws)?.maxRow; // 4
211
+
212
+ const box = getValueExtent(ws);
213
+ if (box) {
214
+ for (const row of iterValues(ws, box)) {
215
+ // four rows, not 200, starting at the first row that holds a value
216
+ }
217
+ }
218
+ ```
219
+
220
+ A cell counts towards the value extent when its `value` is neither `null` nor
221
+ `''`, so formatting, a hyperlink, a comment and the empty strings a CSV
222
+ converter leaves behind all stay outside the box. `getValueExtent` is
223
+ `undefined` for a sheet with no values at all, which is the `if` above.
224
+
225
+ Iteration pads the same way under either box: every yielded row has the full
226
+ width, position `i` is column `minCol + i` throughout, and a position with no
227
+ cell is `null`. Blank rows inside the box are still yielded, so drop them with
228
+ `filter((row) => row.some((v) => v !== null))` when only rows carrying
229
+ something are wanted.
230
+
184
231
  ### Read directly from disk (Node)
185
232
 
186
233
  ```ts
@@ -294,7 +341,9 @@ on the grounds that a wrong value is worse than a failed load.
294
341
  `loadWorkbookStream` reads that cell as empty and keeps going, because an
295
342
  iterator that throws on row 900,000 leaves you no way to finish the pass.
296
343
  Structural problems (a missing part, no `officeDocument` relationship, an
297
- unknown sheet name) throw in both.
344
+ unknown sheet name) throw in both, and so does XML inside `<sheetData>` that is
345
+ not well-formed: an unclosed `<row>`, a stray `</c>`, an undefined entity
346
+ reference. Outside `<sheetData>` the same input is still read leniently.
298
347
 
299
348
  ### Migrating from openpyxl
300
349
 
@@ -319,6 +368,25 @@ common surprise for direct ports:
319
368
  etc. — every style primitive has a `make*` constructor under
320
369
  `@office-kit/xlsx/styles`.
321
370
 
371
+ ### Migrating from SheetJS
372
+
373
+ SheetJS covers a dozen formats through one loosely typed worksheet object;
374
+ @office-kit/xlsx covers `.xlsx` / `.xlsm` through a typed model. The two
375
+ differences a port hits first:
376
+
377
+ - **There is no `cell.w`.** SheetJS caches a formatted string on the cell.
378
+ Here the text is computed on demand: `getCellDisplayText(wb, cell)` from
379
+ `@office-kit/xlsx/styles` puts the value through the cell's number format,
380
+ so `0.5` under `0.0%` reads `50.0%`. `cellValueAsString` answers the other
381
+ question, what the value is in JavaScript terms, and never sees the format.
382
+ - **There is no `cellDates` load option.** A date cell holds the serial the
383
+ file stores, and `getCellDate(wb, cell)` reads it under the cell's format
384
+ and the workbook epoch. Keeping it out of the loader keeps the value model
385
+ from depending on how the file was opened.
386
+
387
+ See [migrating from SheetJS](docs/migrate-from-sheetjs.md) for the full API
388
+ map, including the formats that stay out of scope.
389
+
322
390
  ## What's supported
323
391
 
324
392
  - ✅ Cell values: number, string (sharedStrings), boolean, error, formulas
@@ -339,6 +407,12 @@ common surprise for direct ports:
339
407
  extras and per-sheet rels chain are preserved end-to-end.
340
408
  - ✅ Encrypted xlsx detection (CFB Compound Document magic): clear error
341
409
  pointing at `msoffcrypto-tool` for decryption.
410
+ - ✅ ISO 29500 strict detection: a file saved from Excel as "Strict Open XML
411
+ Spreadsheet" carries the `.xlsx` extension but a different namespace family,
412
+ so `loadWorkbook` and `loadWorkbookStream` throw an
413
+ `OpenXmlNotImplementedError` naming the format and saying to re-save it as
414
+ "Excel Workbook (.xlsx)". Converter output that mixes the two families is
415
+ caught per part. Reading strict packages is not implemented.
342
416
  - ✅ ZIP64 write — partial: workbooks with > 65 535 entries get a ZIP64 EOCD
343
417
  record + locator spliced into the final chunk. Read works too. **Limit:**
344
418
  individual entry sizes and the central-directory offset must still fit in
@@ -1,5 +1,5 @@
1
1
  import { o as OpenXmlSchemaError } from "./exceptions-D-CFwxgm.mjs";
2
- import { Dn as makeColor, bn as colorToHex, un as parseRange, y as ensureCell } from "./worksheet-Cxn2c-jz.mjs";
2
+ import { Sn as colorToHex, fn as parseRange, kn as makeColor, y as ensureCell } from "./worksheet-DLMyDD7W.mjs";
3
3
  //#region src/utils/stable-stringify.ts
4
4
  const sortKeysReplacer = (_key, value) => {
5
5
  if (value === null || typeof value !== "object" || Array.isArray(value)) return value;
@@ -494,7 +494,14 @@ function builtinFormatId(code) {
494
494
  function isBuiltinFormat(code) {
495
495
  return REVERSE.has(code);
496
496
  }
497
- const STRIP_RE = new RegExp(`\\[(BLACK|BLUE|CYAN|GREEN|MAGENTA|RED|WHITE|YELLOW)\\]|"[^"]*"|\\[(?!hh?\\]|mm?\\]|ss?\\])[^\\]]*\\]`, "g");
497
+ /**
498
+ * The colour names Excel accepts in a bracket group (`[Red]`), as the regex
499
+ * alternation `STRIP_RE` needs them. The format-code parser needs the same
500
+ * names to tell a colour apart from a comparison or a calendar modifier, so
501
+ * they live here once.
502
+ */
503
+ const FORMAT_COLOR_NAMES = "BLACK|BLUE|CYAN|GREEN|MAGENTA|RED|WHITE|YELLOW";
504
+ const STRIP_RE = new RegExp(`${`\\[(${FORMAT_COLOR_NAMES})\\]`}|"[^"]*"|\\[(?!hh?\\]|mm?\\]|ss?\\])[^\\]]*\\]`, "g");
498
505
  const DATE_TOKEN_RE = /(?<![_\\])[dmhysDMHYS]/;
499
506
  const TIMEDELTA_RE = /\[hh?\](:mm(:ss(\.0*)?)?)?|\[mm?\](:ss(\.0*)?)?|\[ss?\](\.0*)?/i;
500
507
  /**
@@ -1613,6 +1620,6 @@ function setRangeBorderBox(wb, ws, range, opts = { style: "thin" }) {
1613
1620
  }
1614
1621
  }
1615
1622
  //#endregion
1616
- export { BUILTIN_NAMED_STYLES as $, makeAlignment as $t, setCellBorder as A, isBuiltinFormat as At, setItalic as B, PATTERN_TYPES as Bt, setBold as C, FORMAT_NUMBER_00 as Ct, setCellAsNumber as D, builtinFormatCode as Dt, setCellAsDate as E, FORMAT_TEXT as Et, setCellProtection as F, FONT_SCHEMES as Ft, setRangeNumberFormat as G, makePatternFill as Gt, setRangeBackgroundColor as H, makeFill as Ht, setCellStyle as I, UNDERLINE_STYLES as It, setRangeWrapText as J, makeBorder as Jt, setRangeProtection as K, SIDE_STYLES as Kt, setFontColor as L, VERT_ALIGNS as Lt, setCellFill as M, isTimedeltaFormat as Mt, setCellFont as N, makeNumberFormat as Nt, setCellAsPercent as O, builtinFormatId as Ot, setCellNumberFormat as P, DEFAULT_FONT as Pt, makeProtection as Q, alignmentToCss as Qt, setFontName as R, fontToCss as Rt, rotateCellText as S, FORMAT_NUMBER as St, setCellAsCurrency as T, FORMAT_PERCENTAGE_00 as Tt, setRangeBorderBox as U, makeGradientFill as Ut, setRangeAlignment as V, fillToCss as Vt, setRangeFont as W, makeGradientStop as Wt, setUnderline as X, HORIZONTAL_ALIGNMENTS as Xt, setStrikethrough as Y, makeSide as Yt, wrapCellText as Z, VERTICAL_ALIGNMENTS as Zt, getCellNumberFormat as _, BUILTIN_FORMATS_MAX_SIZE as _t, cellStyleToCss as a, addFill as at, patchCellFont as b, FORMAT_DATE_YYYYMMDD2 as bt, clearCellStyle as c, buildXfPatch as ct, copyCellStyle as d, listCellStyleXfs as dt, stableStringify as en, addNamedStyle as et, formatAsHeader as f, listCellXfs as ft, getCellFont as g, BUILTIN_FORMATS as gt, getCellFill as h, makeStylesheet as ht, applyNamedStyle as i, addCellXf as it, setCellBorderAll as j, isDateFormat as jt, setCellBackgroundColor as k, classifyDateFormat as kt, clearRangeStyle as l, defaultCellXf as lt, getCellBorder as m, listFonts as mt, alignCellVertical as n, addBorder as nt, centerCell as o, addFont as ot, getCellAlignment as p, listFills as pt, setRangeStyle as q, borderToCss as qt, applyBuiltinStyle as r, addCellStyleXf as rt, clearCellBackground as s, addNumFmt as st, alignCellHorizontal as t, ensureBuiltinStyle as tt, cloneCellStyle as u, listBorders as ut, getCellProtection as v, FORMAT_DATE_DATETIME as vt, setCellAlignment as w, FORMAT_PERCENTAGE as wt, registerCellStyle as x, FORMAT_GENERAL as xt, indentCell as y, FORMAT_DATE_TIMEDELTA as yt, setFontSize as z, makeFont as zt };
1623
+ export { BUILTIN_NAMED_STYLES as $, alignmentToCss as $t, setCellBorder as A, classifyDateFormat as At, setItalic as B, makeFont as Bt, setBold as C, FORMAT_NUMBER as Ct, setCellAsNumber as D, FORMAT_TEXT as Dt, setCellAsDate as E, FORMAT_PERCENTAGE_00 as Et, setCellProtection as F, DEFAULT_FONT as Ft, setRangeNumberFormat as G, makeGradientStop as Gt, setRangeBackgroundColor as H, fillToCss as Ht, setCellStyle as I, FONT_SCHEMES as It, setRangeWrapText as J, borderToCss as Jt, setRangeProtection as K, makePatternFill as Kt, setFontColor as L, UNDERLINE_STYLES as Lt, setCellFill as M, isDateFormat as Mt, setCellFont as N, isTimedeltaFormat as Nt, setCellAsPercent as O, builtinFormatCode as Ot, setCellNumberFormat as P, makeNumberFormat as Pt, makeProtection as Q, VERTICAL_ALIGNMENTS as Qt, setFontName as R, VERT_ALIGNS as Rt, rotateCellText as S, FORMAT_GENERAL as St, setCellAsCurrency as T, FORMAT_PERCENTAGE as Tt, setRangeBorderBox as U, makeFill as Ut, setRangeAlignment as V, PATTERN_TYPES as Vt, setRangeFont as W, makeGradientFill as Wt, setUnderline as X, makeSide as Xt, setStrikethrough as Y, makeBorder as Yt, wrapCellText as Z, HORIZONTAL_ALIGNMENTS as Zt, getCellNumberFormat as _, BUILTIN_FORMATS_MAX_SIZE as _t, cellStyleToCss as a, addFill as at, patchCellFont as b, FORMAT_DATE_TIMEDELTA as bt, clearCellStyle as c, buildXfPatch as ct, copyCellStyle as d, listCellStyleXfs as dt, makeAlignment as en, addNamedStyle as et, formatAsHeader as f, listCellXfs as ft, getCellFont as g, BUILTIN_FORMATS as gt, getCellFill as h, makeStylesheet as ht, applyNamedStyle as i, addCellXf as it, setCellBorderAll as j, isBuiltinFormat as jt, setCellBackgroundColor as k, builtinFormatId as kt, clearRangeStyle as l, defaultCellXf as lt, getCellBorder as m, listFonts as mt, alignCellVertical as n, addBorder as nt, centerCell as o, addFont as ot, getCellAlignment as p, listFills as pt, setRangeStyle as q, SIDE_STYLES as qt, applyBuiltinStyle as r, addCellStyleXf as rt, clearCellBackground as s, addNumFmt as st, alignCellHorizontal as t, stableStringify as tn, ensureBuiltinStyle as tt, cloneCellStyle as u, listBorders as ut, getCellProtection as v, FORMAT_COLOR_NAMES as vt, setCellAlignment as w, FORMAT_NUMBER_00 as wt, registerCellStyle as x, FORMAT_DATE_YYYYMMDD2 as xt, indentCell as y, FORMAT_DATE_DATETIME as yt, setFontSize as z, fontToCss as zt };
1617
1624
 
1618
- //# sourceMappingURL=cell-style-DjKKPWDL.mjs.map
1625
+ //# sourceMappingURL=cell-style-CbB4nXTY.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cell-style-CbB4nXTY.mjs","names":[],"sources":["../src/utils/stable-stringify.ts","../src/styles/alignment.ts","../src/styles/borders.ts","../src/styles/fills.ts","../src/styles/fonts.ts","../src/styles/numbers.ts","../src/styles/stylesheet.ts","../src/styles/named-styles.ts","../src/styles/protection.ts","../src/styles/cell-style.ts"],"sourcesContent":["// Deterministic JSON serialiser. Used by the Stylesheet pool to dedupe\n// value-object entries (Font / Fill / Border / CellXf …) by structural\n// equality regardless of property insertion order.\n//\n// Implemented as a JSON.stringify replacer that returns a key-sorted\n// shallow copy of every plain object it encounters; arrays keep their\n// element order. Circular references propagate as JSON.stringify's\n// native RangeError (\"Maximum call stack size exceeded\").\n\nconst sortKeysReplacer = (_key: string, value: unknown): unknown => {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) return value;\n const obj = value as Record<string, unknown>;\n const keys = Object.keys(obj).sort();\n const out: Record<string, unknown> = {};\n for (const k of keys) out[k] = obj[k];\n return out;\n};\n\n/**\n * Stringify `value` with object keys sorted recursively. Equal logical\n * values produce the same string regardless of insertion order; arrays\n * preserve their element order. Circular references throw (the error\n * comes straight from JSON.stringify's stack-overflow check).\n */\nexport function stableStringify(value: unknown): string {\n return JSON.stringify(value, sortKeysReplacer);\n}\n","// Cell alignment value object. Mirrors openpyxl/openpyxl/styles/alignment.py.\n\nimport { OpenXmlSchemaError } from '../utils/exceptions.js';\n\nexport type HorizontalAlignment =\n | 'general'\n | 'left'\n | 'center'\n | 'right'\n | 'fill'\n | 'justify'\n | 'centerContinuous'\n | 'distributed';\n\nexport type VerticalAlignment = 'top' | 'center' | 'bottom' | 'justify' | 'distributed';\n\nexport const HORIZONTAL_ALIGNMENTS: ReadonlyArray<HorizontalAlignment> = Object.freeze([\n 'general',\n 'left',\n 'center',\n 'right',\n 'fill',\n 'justify',\n 'centerContinuous',\n 'distributed',\n]);\nexport const VERTICAL_ALIGNMENTS: ReadonlyArray<VerticalAlignment> = Object.freeze([\n 'top',\n 'center',\n 'bottom',\n 'justify',\n 'distributed',\n]);\n\nconst HORIZONTAL_SET: ReadonlySet<string> = new Set(HORIZONTAL_ALIGNMENTS);\nconst VERTICAL_SET: ReadonlySet<string> = new Set(VERTICAL_ALIGNMENTS);\n\nexport interface Alignment {\n readonly horizontal?: HorizontalAlignment;\n readonly vertical?: VerticalAlignment;\n /** 0..180 (degrees) OR 255 (vertical stacked text). */\n readonly textRotation?: number;\n readonly wrapText?: boolean;\n readonly shrinkToFit?: boolean;\n /** 0..255 indent levels. */\n readonly indent?: number;\n /** -255..255 relative indent. */\n readonly relativeIndent?: number;\n readonly justifyLastLine?: boolean;\n /** 0 = context-dependent, 1 = LTR, 2 = RTL. */\n readonly readingOrder?: number;\n}\n\nexport function makeAlignment(opts: Partial<Alignment> = {}): Alignment {\n const out: { -readonly [K in keyof Alignment]: Alignment[K] } = {};\n if (opts.horizontal !== undefined) {\n if (!HORIZONTAL_SET.has(opts.horizontal)) {\n throw new OpenXmlSchemaError(\n `Alignment horizontal must be one of [${HORIZONTAL_ALIGNMENTS.join(', ')}]; got \"${opts.horizontal}\"`,\n );\n }\n out.horizontal = opts.horizontal;\n }\n if (opts.vertical !== undefined) {\n if (!VERTICAL_SET.has(opts.vertical)) {\n throw new OpenXmlSchemaError(\n `Alignment vertical must be one of [${VERTICAL_ALIGNMENTS.join(', ')}]; got \"${opts.vertical}\"`,\n );\n }\n out.vertical = opts.vertical;\n }\n if (opts.textRotation !== undefined) {\n const r = opts.textRotation;\n if (!Number.isInteger(r) || r < 0 || (r > 180 && r !== 255)) {\n throw new OpenXmlSchemaError(`Alignment textRotation must be 0..180 or 255; got ${r}`);\n }\n out.textRotation = r;\n }\n if (opts.wrapText !== undefined) out.wrapText = opts.wrapText;\n if (opts.shrinkToFit !== undefined) out.shrinkToFit = opts.shrinkToFit;\n if (opts.indent !== undefined) {\n if (!Number.isFinite(opts.indent) || opts.indent < 0 || opts.indent > 255) {\n throw new OpenXmlSchemaError(`Alignment indent must be 0..255; got ${opts.indent}`);\n }\n out.indent = opts.indent;\n }\n if (opts.relativeIndent !== undefined) {\n const r = opts.relativeIndent;\n if (!Number.isFinite(r) || r < -255 || r > 255) {\n throw new OpenXmlSchemaError(`Alignment relativeIndent must be -255..255; got ${r}`);\n }\n out.relativeIndent = r;\n }\n if (opts.justifyLastLine !== undefined) out.justifyLastLine = opts.justifyLastLine;\n if (opts.readingOrder !== undefined) {\n if (!Number.isFinite(opts.readingOrder) || opts.readingOrder < 0) {\n throw new OpenXmlSchemaError(`Alignment readingOrder must be >= 0; got ${opts.readingOrder}`);\n }\n out.readingOrder = opts.readingOrder;\n }\n return Object.freeze(out);\n}\n\nexport const DEFAULT_ALIGNMENT: Alignment = makeAlignment();\n\nconst HORIZONTAL_TO_TEXT_ALIGN: Record<HorizontalAlignment, string | undefined> = {\n general: undefined, // Excel: numbers right, text left — caller decides per cell type.\n left: 'left',\n center: 'center',\n right: 'right',\n fill: 'left', // CSS has no fill; left is the closest non-stretched approximation.\n justify: 'justify',\n centerContinuous: 'center',\n distributed: 'justify',\n};\n\nconst VERTICAL_TO_VERTICAL_ALIGN: Record<VerticalAlignment, string | undefined> = {\n top: 'top',\n center: 'middle',\n bottom: 'bottom',\n justify: 'middle',\n distributed: 'middle',\n};\n\n/**\n * Translate an {@link Alignment} to a CSS-property record suitable for\n * HTML preview. `horizontal` → `text-align`, `vertical` →\n * `vertical-align` (table-cell semantics), `wrapText` → `white-space:\n * pre-wrap`, `textRotation` → `transform: rotate(<-deg>)` (Excel rotates\n * counter-clockwise relative to CSS) plus `transform-origin` to keep\n * the text anchored, and `indent` → `padding-left: <n>em`. `255`\n * stacked-text rotation maps to a 180° flip with `writing-mode`.\n *\n * Empty / undefined Alignment returns `{}`.\n */\nexport function alignmentToCss(alignment: Alignment | undefined): Record<string, string> {\n const css: Record<string, string> = {};\n if (!alignment) return css;\n if (alignment.horizontal !== undefined) {\n const ta = HORIZONTAL_TO_TEXT_ALIGN[alignment.horizontal];\n if (ta !== undefined) css['text-align'] = ta;\n }\n if (alignment.vertical !== undefined) {\n const va = VERTICAL_TO_VERTICAL_ALIGN[alignment.vertical];\n if (va !== undefined) css['vertical-align'] = va;\n }\n if (alignment.wrapText) css['white-space'] = 'pre-wrap';\n if (alignment.textRotation !== undefined) {\n if (alignment.textRotation === 255) {\n css['writing-mode'] = 'vertical-rl';\n } else if (alignment.textRotation !== 0) {\n // Excel: positive degrees rotate counter-clockwise; CSS rotate() is clockwise → negate.\n css['transform'] = `rotate(-${alignment.textRotation}deg)`;\n css['transform-origin'] = 'center center';\n }\n }\n if (alignment.indent !== undefined && alignment.indent > 0) {\n css['padding-left'] = `${alignment.indent}em`;\n }\n return css;\n}\n","// Border / Side value objects. Mirrors openpyxl/openpyxl/styles/borders.py.\n//\n// A `Border` describes the edges drawn around a cell. Each edge is a `Side`\n// carrying a stroke style and an optional `Color`. These are plain readonly\n// objects; the `make*` constructors freeze their results so the Stylesheet pool\n// can dedupe by reference identity once we wire it up.\n\nimport { OpenXmlSchemaError } from '../utils/exceptions.js';\nimport { type Color, colorToHex, makeColor } from './colors.js';\n\nexport type SideStyle =\n // ECMA-376 §18.18.3 ST_BorderStyle lists `none` (no stroke) as a first-class\n // value; Excel omits the side element for it, but OnlyOffice writes it out\n // explicitly, so we must accept and round-trip it (issue #99).\n | 'none'\n | 'thin'\n | 'medium'\n | 'thick'\n | 'double'\n | 'hair'\n | 'dotted'\n | 'dashed'\n | 'dashDot'\n | 'dashDotDot'\n | 'mediumDashed'\n | 'mediumDashDot'\n | 'mediumDashDotDot'\n | 'slantDashDot';\n\nexport const SIDE_STYLES: ReadonlyArray<SideStyle> = Object.freeze([\n 'none',\n 'thin',\n 'medium',\n 'thick',\n 'double',\n 'hair',\n 'dotted',\n 'dashed',\n 'dashDot',\n 'dashDotDot',\n 'mediumDashed',\n 'mediumDashDot',\n 'mediumDashDotDot',\n 'slantDashDot',\n]);\n\nconst SIDE_STYLE_SET: ReadonlySet<string> = new Set(SIDE_STYLES);\n\nexport interface Side {\n readonly style?: SideStyle;\n readonly color?: Color;\n}\n\n/** Build an immutable {@link Side}. */\nexport function makeSide(opts: Partial<Side> = {}): Side {\n const out: { -readonly [K in keyof Side]: Side[K] } = {};\n if (opts.style !== undefined) {\n if (!SIDE_STYLE_SET.has(opts.style)) {\n throw new OpenXmlSchemaError(`Side style must be one of [${SIDE_STYLES.join(', ')}]; got \"${opts.style}\"`);\n }\n out.style = opts.style;\n }\n if (opts.color !== undefined) {\n // Funnel through makeColor so we re-use its validation + freezing.\n out.color = Object.isFrozen(opts.color) ? opts.color : makeColor(opts.color);\n }\n return Object.freeze(out);\n}\n\nexport interface Border {\n /** Left edge. */\n readonly left?: Side;\n readonly right?: Side;\n readonly top?: Side;\n readonly bottom?: Side;\n /** Diagonal stroke (governed together with diagonalUp / diagonalDown). */\n readonly diagonal?: Side;\n /** Vertical stroke between cells of a merged range. */\n readonly vertical?: Side;\n /** Horizontal stroke between cells of a merged range. */\n readonly horizontal?: Side;\n readonly diagonalUp?: boolean;\n readonly diagonalDown?: boolean;\n /** Outline-only flag; defaults to true. */\n readonly outline?: boolean;\n}\n\n/** Build an immutable {@link Border}. */\nexport function makeBorder(opts: Partial<Border> = {}): Border {\n const out: { -readonly [K in keyof Border]: Border[K] } = {};\n if (opts.left !== undefined) out.left = freezeSide(opts.left);\n if (opts.right !== undefined) out.right = freezeSide(opts.right);\n if (opts.top !== undefined) out.top = freezeSide(opts.top);\n if (opts.bottom !== undefined) out.bottom = freezeSide(opts.bottom);\n if (opts.diagonal !== undefined) out.diagonal = freezeSide(opts.diagonal);\n if (opts.vertical !== undefined) out.vertical = freezeSide(opts.vertical);\n if (opts.horizontal !== undefined) out.horizontal = freezeSide(opts.horizontal);\n if (opts.diagonalUp !== undefined) out.diagonalUp = opts.diagonalUp;\n if (opts.diagonalDown !== undefined) out.diagonalDown = opts.diagonalDown;\n if (opts.outline !== undefined) out.outline = opts.outline;\n return Object.freeze(out);\n}\n\nconst freezeSide = (s: Side): Side => (Object.isFrozen(s) ? s : makeSide(s));\n\n/** Default empty side — convenient sentinel for `no edge stroke`. */\nexport const EMPTY_SIDE: Side = makeSide();\n/** Default empty border — every cell starts here until styled otherwise. */\nexport const DEFAULT_BORDER: Border = makeBorder();\n\n/**\n * Map an Excel {@link SideStyle} to a CSS `border` shorthand fragment (`<width>\n * <style>`). Returns `undefined` for unmappable styles or a missing/no-style\n * side. Colour is appended by the caller.\n */\nfunction sideStyleToCss(style: SideStyle | undefined): string | undefined {\n switch (style) {\n case 'thin':\n case 'hair':\n return '1px solid';\n case 'medium':\n return '2px solid';\n case 'thick':\n return '3px solid';\n case 'double':\n return '3px double';\n case 'dotted':\n return '1px dotted';\n case 'dashed':\n case 'dashDot':\n case 'dashDotDot':\n return '1px dashed';\n case 'mediumDashed':\n case 'mediumDashDot':\n case 'mediumDashDotDot':\n case 'slantDashDot':\n return '2px dashed';\n default:\n return undefined;\n }\n}\n\n/**\n * Translate a {@link Border} to a CSS-property record suitable for HTML\n * preview. Each present side becomes `border-<edge>: <width> <style> <#color>`.\n * Theme/auto/missing colours fall back to `currentColor`. Diagonal / vertical /\n * horizontal sides are skipped (CSS has no native equivalent for in-cell\n * strokes). Empty Border returns `{}`.\n */\nexport function borderToCss(border: Border | undefined): Record<string, string> {\n const css: Record<string, string> = {};\n if (!border) return css;\n const sides: Array<['top' | 'right' | 'bottom' | 'left', Side | undefined]> = [\n ['top', border.top],\n ['right', border.right],\n ['bottom', border.bottom],\n ['left', border.left],\n ];\n for (const [edge, side] of sides) {\n if (!side) continue;\n const stroke = sideStyleToCss(side.style);\n if (stroke === undefined) continue;\n const argb = colorToHex(side.color);\n const colour = argb !== undefined ? `#${argb.slice(2)}` : 'currentColor';\n css[`border-${edge}`] = `${stroke} ${colour}`;\n }\n return css;\n}\n","// Pattern + gradient fill value objects. Mirrors\n// openpyxl/openpyxl/styles/fills.py.\n//\n// In OOXML the cell `<fill>` element wraps exactly one of:\n// * <patternFill patternType=\"…\">[<fgColor>, <bgColor>]</patternFill>\n// * <gradientFill type=\"linear|path\" …>[<stop>, …]</gradientFill>\n//\n// The TS port models the inner variants as a discriminated union via a `kind`\n// tag; the wrapper is reconstructed during XML round-trip (see\n// fills.schema.ts). All values are plain readonly + frozen so the Stylesheet\n// pool can dedupe.\n\nimport { OpenXmlSchemaError } from '../utils/exceptions.js';\nimport { type Color, colorToHex, makeColor } from './colors.js';\n\n// ---- pattern fills ---------------------------------------------------------\n\n/** Predefined Excel pattern types. `'none'` lives here too as an explicit value. */\nexport type PatternType =\n | 'none'\n | 'solid'\n | 'darkDown'\n | 'darkGray'\n | 'darkGrid'\n | 'darkHorizontal'\n | 'darkTrellis'\n | 'darkUp'\n | 'darkVertical'\n | 'gray0625'\n | 'gray125'\n | 'lightDown'\n | 'lightGray'\n | 'lightGrid'\n | 'lightHorizontal'\n | 'lightTrellis'\n | 'lightUp'\n | 'lightVertical'\n | 'mediumGray';\n\nexport const PATTERN_TYPES: ReadonlyArray<PatternType> = Object.freeze([\n 'none',\n 'solid',\n 'darkDown',\n 'darkGray',\n 'darkGrid',\n 'darkHorizontal',\n 'darkTrellis',\n 'darkUp',\n 'darkVertical',\n 'gray0625',\n 'gray125',\n 'lightDown',\n 'lightGray',\n 'lightGrid',\n 'lightHorizontal',\n 'lightTrellis',\n 'lightUp',\n 'lightVertical',\n 'mediumGray',\n]);\n\nconst PATTERN_TYPE_SET: ReadonlySet<string> = new Set(PATTERN_TYPES);\n\nexport interface PatternFill {\n readonly kind: 'pattern';\n readonly patternType?: PatternType;\n readonly fgColor?: Color;\n readonly bgColor?: Color;\n}\n\nexport function makePatternFill(opts: Partial<Omit<PatternFill, 'kind'>> = {}): PatternFill {\n const out: { -readonly [K in keyof PatternFill]: PatternFill[K] } = { kind: 'pattern' };\n if (opts.patternType !== undefined) {\n if (!PATTERN_TYPE_SET.has(opts.patternType)) {\n throw new OpenXmlSchemaError(\n `PatternFill patternType must be one of [${PATTERN_TYPES.join(', ')}]; got \"${opts.patternType}\"`,\n );\n }\n out.patternType = opts.patternType;\n }\n if (opts.fgColor !== undefined) out.fgColor = freezeColor(opts.fgColor);\n if (opts.bgColor !== undefined) out.bgColor = freezeColor(opts.bgColor);\n return Object.freeze(out);\n}\n\n// ---- gradient fills --------------------------------------------------------\n\nexport interface GradientStop {\n /** 0..1 ratio along the gradient. */\n readonly position: number;\n readonly color: Color;\n}\n\nexport type GradientFillType = 'linear' | 'path';\n\nexport interface GradientFill {\n readonly kind: 'gradient';\n readonly type: GradientFillType;\n /** Rotation angle (degrees). Ignored when `type === 'path'`. */\n readonly degree?: number;\n /** path-mode insets (0..1 from each edge). */\n readonly left?: number;\n readonly right?: number;\n readonly top?: number;\n readonly bottom?: number;\n /** Colour stops along the gradient. */\n readonly stops: ReadonlyArray<GradientStop>;\n}\n\nexport function makeGradientStop(position: number, color: Color | Partial<Color>): GradientStop {\n if (!Number.isFinite(position) || position < 0 || position > 1) {\n throw new OpenXmlSchemaError(`GradientStop position must be in [0, 1]; got ${position}`);\n }\n return Object.freeze({ position, color: freezeColor(color) });\n}\n\nexport function makeGradientFill(opts: Partial<Omit<GradientFill, 'kind'>> = {}): GradientFill {\n const out: { -readonly [K in keyof GradientFill]: GradientFill[K] } = {\n kind: 'gradient',\n type: opts.type ?? 'linear',\n stops: opts.stops?.map((s) => freezeStop(s)) ?? [],\n };\n if (out.type !== 'linear' && out.type !== 'path') {\n throw new OpenXmlSchemaError(`GradientFill type must be \"linear\" or \"path\"; got \"${String(out.type)}\"`);\n }\n if (opts.degree !== undefined) out.degree = opts.degree;\n if (opts.left !== undefined) out.left = opts.left;\n if (opts.right !== undefined) out.right = opts.right;\n if (opts.top !== undefined) out.top = opts.top;\n if (opts.bottom !== undefined) out.bottom = opts.bottom;\n Object.freeze(out.stops);\n return Object.freeze(out);\n}\n\n// ---- Fill = PatternFill | GradientFill -------------------------------------\n\nexport type Fill = PatternFill | GradientFill;\n\n/**\n * Single-arg constructor that defers to the variant-specific maker based on\n * `kind`. Useful when the caller has a plain object in hand and wants the\n * freeze invariant applied uniformly.\n */\nexport function makeFill(opts: Partial<PatternFill> | Partial<GradientFill>): Fill {\n if (opts.kind === 'gradient') return makeGradientFill(opts as Partial<Omit<GradientFill, 'kind'>>);\n return makePatternFill(opts as Partial<Omit<PatternFill, 'kind'>>);\n}\n\n/** The empty PatternFill — Excel's default cellXf[0] points here. */\nexport const DEFAULT_EMPTY_FILL: Fill = makePatternFill();\n/** The 'gray125' PatternFill — Excel's default cellXf[1]. */\nexport const DEFAULT_GRAY_FILL: Fill = makePatternFill({ patternType: 'gray125' });\n\n// ---- internal helpers ------------------------------------------------------\n\nconst freezeColor = (c: Color | Partial<Color>): Color => (Object.isFrozen(c) ? (c as Color) : makeColor(c));\nconst freezeStop = (s: GradientStop): GradientStop => (Object.isFrozen(s) ? s : makeGradientStop(s.position, s.color));\n\nconst argbToCssHex = (color: Color | undefined): string | undefined => {\n const argb = colorToHex(color);\n return argb ? `#${argb.slice(2)}` : undefined;\n};\n\n/**\n * Translate a {@link Fill} to a CSS-property record suitable for HTML preview.\n * `'solid'` PatternFill renders as `background-color`, other pattern types\n * collapse to bgColor (CSS has no built-in equivalent of Excel hatch patterns).\n * GradientFill emits a CSS `background-image` with `linear-gradient(<angle>,\n * …)` for `type='linear'` or `radial-gradient(circle, …)` for `type='path'`.\n *\n * theme/auto colours and unresolvable inputs are skipped (returns `{}`) so\n * callers can spread without overwriting upstream defaults.\n */\nexport function fillToCss(fill: Fill | undefined): Record<string, string> {\n const css: Record<string, string> = {};\n if (!fill) return css;\n if (fill.kind === 'pattern') {\n if (fill.patternType === 'none' || fill.patternType === undefined) return css;\n if (fill.patternType === 'solid') {\n const fg = argbToCssHex(fill.fgColor);\n if (fg !== undefined) css['background-color'] = fg;\n return css;\n }\n // Non-solid patterns collapse to the bg colour as a coarse approximation;\n // CSS has no native Excel hatch equivalent.\n const bg = argbToCssHex(fill.bgColor) ?? argbToCssHex(fill.fgColor);\n if (bg !== undefined) css['background-color'] = bg;\n return css;\n }\n // Gradient fill — need at least one resolvable stop to emit anything.\n const stopParts: string[] = [];\n for (const s of fill.stops) {\n const hex = argbToCssHex(s.color);\n if (hex === undefined) continue;\n stopParts.push(`${hex} ${(s.position * 100).toFixed(2)}%`);\n }\n if (stopParts.length === 0) return css;\n if (fill.type === 'linear') {\n const angle = fill.degree ?? 0;\n css['background-image'] = `linear-gradient(${angle}deg, ${stopParts.join(', ')})`;\n } else {\n css['background-image'] = `radial-gradient(circle, ${stopParts.join(', ')})`;\n }\n return css;\n}\n","// Cell font value object. Mirrors openpyxl/openpyxl/styles/fonts.py.\n//\n// Font is the most varied of the styles slots — most fields are nested\n// elements with a single `val` attribute (`<sz val=\"11\"/>`), the boolean\n// toggles (`<b/>`, `<i/>`, ...) are presence-only marker tags, and\n// `<color>` is a fully nested object element. The schema layer carries\n// each pattern as its own ElementDef kind.\n\nimport { OpenXmlSchemaError } from '../utils/exceptions.js';\nimport { type Color, colorToHex, makeColor } from './colors.js';\n\n/** Underline styles per openpyxl's NestedNoneSet. */\nexport type UnderlineStyle = 'single' | 'double' | 'singleAccounting' | 'doubleAccounting';\nexport const UNDERLINE_STYLES: ReadonlyArray<UnderlineStyle> = Object.freeze([\n 'single',\n 'double',\n 'singleAccounting',\n 'doubleAccounting',\n]);\n\nexport type VertAlign = 'baseline' | 'superscript' | 'subscript';\nexport const VERT_ALIGNS: ReadonlyArray<VertAlign> = Object.freeze(['baseline', 'superscript', 'subscript']);\n\nexport type FontScheme = 'major' | 'minor';\nexport const FONT_SCHEMES: ReadonlyArray<FontScheme> = Object.freeze(['major', 'minor']);\n\nconst UNDERLINE_SET: ReadonlySet<string> = new Set(UNDERLINE_STYLES);\nconst VERT_SET: ReadonlySet<string> = new Set(VERT_ALIGNS);\nconst SCHEME_SET: ReadonlySet<string> = new Set(FONT_SCHEMES);\n\nexport interface Font {\n readonly name?: string;\n readonly charset?: number;\n /** Font family code (0..14). */\n readonly family?: number;\n /** Point size; openpyxl name = `sz`. */\n readonly size?: number;\n readonly color?: Color;\n readonly bold?: boolean;\n readonly italic?: boolean;\n readonly strike?: boolean;\n readonly outline?: boolean;\n readonly shadow?: boolean;\n readonly condense?: boolean;\n readonly extend?: boolean;\n readonly underline?: UnderlineStyle;\n readonly vertAlign?: VertAlign;\n readonly scheme?: FontScheme;\n}\n\n/**\n * Input shape for building a Font. Wider than `Partial<Font>` under\n * `exactOptionalPropertyTypes`: a field may be present and `undefined`, which\n * {@link makeFont} drops the same way it drops an absent one. That is what lets\n * a caller merging two fonts express \"this field goes away\".\n */\nexport type FontPatch = { [K in keyof Font]?: Font[K] | undefined };\n\nexport function makeFont(opts: FontPatch = {}): Font {\n const out: { -readonly [K in keyof Font]: Font[K] } = {};\n if (opts.name !== undefined) {\n if (typeof opts.name !== 'string') {\n throw new OpenXmlSchemaError(`Font name must be a string; got ${typeof opts.name}`);\n }\n out.name = opts.name;\n }\n if (opts.charset !== undefined) {\n if (!Number.isInteger(opts.charset)) {\n throw new OpenXmlSchemaError(`Font charset must be an integer; got ${opts.charset}`);\n }\n out.charset = opts.charset;\n }\n if (opts.family !== undefined) {\n if (!Number.isInteger(opts.family) || opts.family < 0 || opts.family > 14) {\n throw new OpenXmlSchemaError(`Font family must be 0..14; got ${opts.family}`);\n }\n out.family = opts.family;\n }\n if (opts.size !== undefined) {\n if (!Number.isFinite(opts.size) || opts.size <= 0) {\n throw new OpenXmlSchemaError(`Font size must be positive; got ${opts.size}`);\n }\n out.size = opts.size;\n }\n if (opts.color !== undefined) {\n out.color = Object.isFrozen(opts.color) ? opts.color : makeColor(opts.color);\n }\n if (opts.bold !== undefined) out.bold = opts.bold;\n if (opts.italic !== undefined) out.italic = opts.italic;\n if (opts.strike !== undefined) out.strike = opts.strike;\n if (opts.outline !== undefined) out.outline = opts.outline;\n if (opts.shadow !== undefined) out.shadow = opts.shadow;\n if (opts.condense !== undefined) out.condense = opts.condense;\n if (opts.extend !== undefined) out.extend = opts.extend;\n if (opts.underline !== undefined) {\n if (!UNDERLINE_SET.has(opts.underline)) {\n throw new OpenXmlSchemaError(\n `Font underline must be one of [${UNDERLINE_STYLES.join(', ')}]; got \"${opts.underline}\"`,\n );\n }\n out.underline = opts.underline;\n }\n if (opts.vertAlign !== undefined) {\n if (!VERT_SET.has(opts.vertAlign)) {\n throw new OpenXmlSchemaError(\n `Font vertAlign must be one of [${VERT_ALIGNS.join(', ')}]; got \"${opts.vertAlign}\"`,\n );\n }\n out.vertAlign = opts.vertAlign;\n }\n if (opts.scheme !== undefined) {\n if (!SCHEME_SET.has(opts.scheme)) {\n throw new OpenXmlSchemaError(`Font scheme must be one of [${FONT_SCHEMES.join(', ')}]; got \"${opts.scheme}\"`);\n }\n out.scheme = opts.scheme;\n }\n return Object.freeze(out);\n}\n\n/** Excel's default cell font: Calibri 11, minor scheme, theme=1 colour. */\nexport const DEFAULT_FONT: Font = makeFont({\n name: 'Calibri',\n size: 11,\n family: 2,\n scheme: 'minor',\n color: makeColor({ theme: 1 }),\n});\n\n/**\n * Translate a {@link Font} to a CSS-property record suitable for HTML\n * rendering / preview. Boolean toggles map to weight/style/decoration,\n * `size` becomes `font-size: <n>pt`, and an explicit rgb/indexed\n * `color` is rendered as `#RRGGBB` (alpha dropped). theme/auto colours\n * are skipped — callers without a theme can't resolve them.\n *\n * `vertAlign='superscript'|'subscript'` lowers `font-size` to 0.83em\n * (W3C convention) and sets `vertical-align`.\n *\n * Returns `{}` for an empty Font so callers can spread it without\n * overwriting upstream defaults.\n */\nexport function fontToCss(font: Font | undefined): Record<string, string> {\n const css: Record<string, string> = {};\n if (!font) return css;\n if (font.name !== undefined) {\n // CSS expects quoted family names that contain spaces; quote unconditionally\n // to keep the generator simple.\n css['font-family'] = `'${font.name.replace(/'/g, \"\\\\'\")}'`;\n }\n if (font.size !== undefined) css['font-size'] = `${font.size}pt`;\n if (font.bold) css['font-weight'] = 'bold';\n if (font.italic) css['font-style'] = 'italic';\n const decorations: string[] = [];\n if (font.underline !== undefined) decorations.push('underline');\n if (font.strike) decorations.push('line-through');\n if (decorations.length > 0) css['text-decoration'] = decorations.join(' ');\n if (font.color !== undefined) {\n const argb = colorToHex(font.color);\n if (argb !== undefined) {\n // Drop alpha (CSS hex with alpha is poorly-supported in Excel-style preview).\n css['color'] = `#${argb.slice(2)}`;\n }\n }\n if (font.vertAlign === 'superscript' || font.vertAlign === 'subscript') {\n css['vertical-align'] = font.vertAlign;\n // Match W3C-recommended scaling for sup/sub when font-size is not explicit.\n if (css['font-size'] === undefined) css['font-size'] = '0.83em';\n }\n return css;\n}\n","// Number-format value object + the OOXML built-in format catalogue.\n// Mirrors openpyxl/openpyxl/styles/numbers.py.\n//\n// Excel keeps two parallel namespaces for number formats:\n// * IDs 0–163 are reserved for the built-in catalogue (sparsely\n// populated; only 36 of them are actually defined).\n// * IDs ≥ 164 are user-defined / locale-specific. The Stylesheet\n// pool allocates these on demand (phase 2 §3.4).\n\nimport { OpenXmlSchemaError } from '../utils/exceptions.js';\n\n/** Canonical OOXML built-in number formats — verbatim from openpyxl. */\nexport const BUILTIN_FORMATS: Readonly<Record<number, string>> = Object.freeze({\n 0: 'General',\n 1: '0',\n 2: '0.00',\n 3: '#,##0',\n 4: '#,##0.00',\n 5: '\"$\"#,##0_);(\"$\"#,##0)',\n 6: '\"$\"#,##0_);[Red](\"$\"#,##0)',\n 7: '\"$\"#,##0.00_);(\"$\"#,##0.00)',\n 8: '\"$\"#,##0.00_);[Red](\"$\"#,##0.00)',\n 9: '0%',\n 10: '0.00%',\n 11: '0.00E+00',\n 12: '# ?/?',\n 13: '# ??/??',\n 14: 'mm-dd-yy',\n 15: 'd-mmm-yy',\n 16: 'd-mmm',\n 17: 'mmm-yy',\n 18: 'h:mm AM/PM',\n 19: 'h:mm:ss AM/PM',\n 20: 'h:mm',\n 21: 'h:mm:ss',\n 22: 'm/d/yy h:mm',\n 37: '#,##0_);(#,##0)',\n 38: '#,##0_);[Red](#,##0)',\n 39: '#,##0.00_);(#,##0.00)',\n 40: '#,##0.00_);[Red](#,##0.00)',\n 41: '_(* #,##0_);_(* \\\\(#,##0\\\\);_(* \"-\"_);_(@_)',\n 42: '_(\"$\"* #,##0_);_(\"$\"* \\\\(#,##0\\\\);_(\"$\"* \"-\"_);_(@_)',\n 43: '_(* #,##0.00_);_(* \\\\(#,##0.00\\\\);_(* \"-\"??_);_(@_)',\n 44: '_(\"$\"* #,##0.00_)_(\"$\"* \\\\(#,##0.00\\\\)_(\"$\"* \"-\"??_)_(@_)',\n 45: 'mm:ss',\n 46: '[h]:mm:ss',\n 47: 'mmss.0',\n 48: '##0.0E+0',\n 49: '@',\n});\n\n/** First numFmtId Excel reserves for user-defined formats. */\nexport const BUILTIN_FORMATS_MAX_SIZE = 164;\n\nconst REVERSE: ReadonlyMap<string, number> = new Map(Object.entries(BUILTIN_FORMATS).map(([k, v]) => [v, Number(k)]));\n\n// ---- well-known format codes (named exports for ergonomics) ---------------\n//\n// Inlined rather than indexed off BUILTIN_FORMATS to keep TS' tuple\n// lookup from widening to `string | undefined`.\n\nexport const FORMAT_GENERAL = 'General';\nexport const FORMAT_TEXT = '@';\nexport const FORMAT_NUMBER = '0';\nexport const FORMAT_NUMBER_00 = '0.00';\nexport const FORMAT_PERCENTAGE = '0%';\nexport const FORMAT_PERCENTAGE_00 = '0.00%';\nexport const FORMAT_DATE_DATETIME = 'yyyy-mm-dd h:mm:ss';\nexport const FORMAT_DATE_TIMEDELTA = '[hh]:mm:ss';\nexport const FORMAT_DATE_YYYYMMDD2 = 'yyyy-mm-dd';\n\n// ---- helpers ---------------------------------------------------------------\n\n/** Look up the format code for a given numFmtId, or `undefined` if unknown. */\nexport function builtinFormatCode(id: number): string | undefined {\n return Object.hasOwn(BUILTIN_FORMATS, id) ? BUILTIN_FORMATS[id] : undefined;\n}\n\n/** Look up the numFmtId for a given format code, or `undefined` if not built-in. */\nexport function builtinFormatId(code: string): number | undefined {\n return REVERSE.get(code);\n}\n\n/** True iff `code` is one of the OOXML built-in format strings. */\nexport function isBuiltinFormat(code: string): boolean {\n return REVERSE.has(code);\n}\n\n// ---- date / timedelta heuristics ------------------------------------------\n//\n// Mirror openpyxl's regex strategy verbatim. The two patterns work together\n// to decide whether a format implies a date / time / duration interpretation.\n\n/**\n * The colour names Excel accepts in a bracket group (`[Red]`), as the regex\n * alternation `STRIP_RE` needs them. The format-code parser needs the same\n * names to tell a colour apart from a comparison or a calendar modifier, so\n * they live here once.\n */\nexport const FORMAT_COLOR_NAMES = 'BLACK|BLUE|CYAN|GREEN|MAGENTA|RED|WHITE|YELLOW';\n\nconst COLORS_GROUP = `\\\\[(${FORMAT_COLOR_NAMES})\\\\]`;\nconst LITERAL_GROUP = '\"[^\"]*\"';\nconst LOCALE_GROUP = '\\\\[(?!hh?\\\\]|mm?\\\\]|ss?\\\\])[^\\\\]]*\\\\]';\n\nconst STRIP_RE = new RegExp(`${COLORS_GROUP}|${LITERAL_GROUP}|${LOCALE_GROUP}`, 'g');\nconst DATE_TOKEN_RE = /(?<![_\\\\])[dmhysDMHYS]/;\nconst TIMEDELTA_RE = /\\[hh?\\](:mm(:ss(\\.0*)?)?)?|\\[mm?\\](:ss(\\.0*)?)?|\\[ss?\\](\\.0*)?/i;\n\n/**\n * Heuristic: does the format string imply a date / time interpretation?\n * Looks at only the first format section (positive-value branch); strips\n * literals, colour codes and locale modifiers before scanning for date\n * tokens (d/m/h/y/s, case-insensitive) that aren't escaped.\n */\nexport function isDateFormat(code: string | undefined | null): boolean {\n if (code == null) return false;\n const head = code.split(';')[0] ?? '';\n const stripped = head.replace(STRIP_RE, '');\n return DATE_TOKEN_RE.test(stripped);\n}\n\n/** Heuristic: does the format string indicate a duration ([h]:mm:ss etc.)? */\nexport function isTimedeltaFormat(code: string | undefined | null): boolean {\n if (code == null) return false;\n const head = code.split(';')[0] ?? '';\n return TIMEDELTA_RE.test(head);\n}\n\n/** Categorise a date format as 'date', 'time', 'datetime' or undefined. */\nexport function classifyDateFormat(code: string | undefined | null): 'date' | 'time' | 'datetime' | undefined {\n if (!isDateFormat(code)) return undefined;\n // Reach here only with a non-null code.\n const head = (code as string).split(';')[0] ?? '';\n // Same locale / literal stripping the date detector applies.\n const stripped = head.replace(STRIP_RE, '');\n let date = false;\n let time = false;\n for (const ch of stripped) {\n if (ch === 'd' || ch === 'D' || ch === 'y' || ch === 'Y') date = true;\n else if (ch === 'h' || ch === 'H' || ch === 's' || ch === 'S') time = true;\n if (date && time) break;\n }\n if (date && time) return 'datetime';\n if (date) return 'date';\n return 'time';\n}\n\n// ---- NumberFormat value -----------------------------------------------------\n\nexport interface NumberFormat {\n /** Stylesheet-relative numFmtId. */\n readonly numFmtId: number;\n readonly formatCode: string;\n}\n\nexport function makeNumberFormat(opts: { numFmtId: number; formatCode: string }): NumberFormat {\n if (!Number.isInteger(opts.numFmtId) || opts.numFmtId < 0) {\n throw new OpenXmlSchemaError(`NumberFormat numFmtId must be a non-negative integer; got ${opts.numFmtId}`);\n }\n if (typeof opts.formatCode !== 'string') {\n throw new OpenXmlSchemaError('NumberFormat formatCode must be a string');\n }\n return Object.freeze({ numFmtId: opts.numFmtId, formatCode: opts.formatCode });\n}\n","// Stylesheet pool. The workbook holds dedup pools per style component (fonts /\n// fills / borders / numFmts / cellXfs / cellStyleXfs); cells reference entries\n// by index via a `styleId` (an index into cellXfs).\n//\n// All adds run through `add*` free functions that look up the pool via\n// `stableStringify`-keyed maps so the same logical Font / Fill / etc. added\n// 1000× lands in a single pool slot.\n\nimport { OpenXmlSchemaError } from '../utils/exceptions.js';\nimport { stableStringify } from '../utils/stable-stringify.js';\nimport type { Alignment } from './alignment.js';\nimport type { Border } from './borders.js';\nimport { DEFAULT_BORDER } from './borders.js';\nimport type { Fill } from './fills.js';\nimport { DEFAULT_EMPTY_FILL, DEFAULT_GRAY_FILL } from './fills.js';\nimport type { Font } from './fonts.js';\nimport { DEFAULT_FONT } from './fonts.js';\nimport { BUILTIN_FORMATS_MAX_SIZE, builtinFormatId } from './numbers.js';\nimport type { Protection } from './protection.js';\n\n/**\n * One entry in the cellXfs / cellStyleXfs pool. Represents the union of\n * indexes-into-other-pools that a cell or named style points at.\n *\n * Mirrors openpyxl's CellStyle (styles/cell_style.py). The TS port keeps it as\n * a plain readonly object — no class, no methods. The Stylesheet `addCellXf`\n * allocates the index; cells store only that.\n */\nexport interface CellXf {\n readonly fontId: number;\n readonly fillId: number;\n readonly borderId: number;\n readonly numFmtId: number;\n /** Index into cellStyleXfs — only set for direct-cell xfs that point at a NamedStyle. */\n readonly xfId?: number;\n readonly alignment?: Alignment;\n readonly protection?: Protection;\n readonly applyFont?: boolean;\n readonly applyFill?: boolean;\n readonly applyBorder?: boolean;\n readonly applyNumberFormat?: boolean;\n readonly applyAlignment?: boolean;\n readonly applyProtection?: boolean;\n readonly pivotButton?: boolean;\n readonly quotePrefix?: boolean;\n}\n\nexport interface Stylesheet {\n fonts: Font[];\n fills: Fill[];\n borders: Border[];\n /** numFmtId → format code (custom IDs only; built-ins implicit). */\n numFmts: Map<number, string>;\n cellXfs: CellXf[];\n cellStyleXfs: CellXf[];\n /** Named styles (Excel's \"Cell Styles\" gallery; populated by addNamedStyle). */\n namedStyles?: Array<import('./named-styles.js').StylesheetNamedStyle>;\n /**\n * The tail of `<styleSheet>` this model doesn't cover — `<tableStyles>`,\n * `<colors>` and `<extLst>` (which is where Excel keeps its x14/x15 slicer\n * and timeline styles). Captured verbatim in document order so re-saving a\n * loaded workbook keeps them; CT_Stylesheet puts all three after `<dxfs>`,\n * so the writer appends them there.\n */\n stylesXmlTail?: Array<import('../xml/tree.js').XmlNode>;\n\n // Internal dedup maps. Underscore-prefixed so JSON / structuredClone\n // serialisation can choose to skip them; never part of the public API.\n _fontIdByKey: Map<string, number>;\n _fillIdByKey: Map<string, number>;\n _borderIdByKey: Map<string, number>;\n _xfIdByKey: Map<string, number>;\n _styleXfIdByKey: Map<string, number>;\n _numFmtIdByCode: Map<string, number>;\n _namedStyleByName?: Map<string, import('./named-styles.js').StylesheetNamedStyle>;\n}\n\n/**\n * Build a fresh Stylesheet pre-populated with Excel's required default entries.\n * Mirrors openpyxl's empty Stylesheet: fonts: [DEFAULT_FONT] (index 0) fills:\n * [DEFAULT_EMPTY_FILL,\n * DEFAULT_GRAY_FILL] (indices 0, 1 — required)\n * borders: [DEFAULT_BORDER] (index 0) cellXfs: empty (indices allocated on\n * demand)\n */\nexport function makeStylesheet(): Stylesheet {\n const fontKey = stableStringify(DEFAULT_FONT);\n const fill0Key = stableStringify(DEFAULT_EMPTY_FILL);\n const fill1Key = stableStringify(DEFAULT_GRAY_FILL);\n const borderKey = stableStringify(DEFAULT_BORDER);\n\n return {\n fonts: [DEFAULT_FONT],\n fills: [DEFAULT_EMPTY_FILL, DEFAULT_GRAY_FILL],\n borders: [DEFAULT_BORDER],\n numFmts: new Map(),\n cellXfs: [],\n cellStyleXfs: [],\n _fontIdByKey: new Map([[fontKey, 0]]),\n _fillIdByKey: new Map([\n [fill0Key, 0],\n [fill1Key, 1],\n ]),\n _borderIdByKey: new Map([[borderKey, 0]]),\n _xfIdByKey: new Map(),\n _styleXfIdByKey: new Map(),\n _numFmtIdByCode: new Map(),\n };\n}\n\n// ---- pool add helpers ------------------------------------------------------\n\n/** Add a Font to the pool, returning its 0-based index. Idempotent. */\nexport function addFont(ss: Stylesheet, font: Font): number {\n return addToPool(font, ss.fonts, ss._fontIdByKey);\n}\n\n/** Add a Fill to the pool, returning its 0-based index. Idempotent. */\nexport function addFill(ss: Stylesheet, fill: Fill): number {\n return addToPool(fill, ss.fills, ss._fillIdByKey);\n}\n\n/** Add a Border to the pool, returning its 0-based index. Idempotent. */\nexport function addBorder(ss: Stylesheet, border: Border): number {\n return addToPool(border, ss.borders, ss._borderIdByKey);\n}\n\n/**\n * Resolve a number-format string to its numFmtId.\n * - Built-in codes return their canonical OOXML ID.\n * - Otherwise the custom code is registered (and allocated an ID\n * ≥ {@link BUILTIN_FORMATS_MAX_SIZE}). Idempotent.\n */\nexport function addNumFmt(ss: Stylesheet, formatCode: string): number {\n const builtin = builtinFormatId(formatCode);\n if (builtin !== undefined) return builtin;\n const cached = ss._numFmtIdByCode.get(formatCode);\n if (cached !== undefined) return cached;\n const id = BUILTIN_FORMATS_MAX_SIZE + ss.numFmts.size;\n ss.numFmts.set(id, formatCode);\n ss._numFmtIdByCode.set(formatCode, id);\n return id;\n}\n\n/** Add a CellXf to the cellXfs pool, returning its 0-based index. Idempotent. */\nexport function addCellXf(ss: Stylesheet, xf: CellXf): number {\n validateCellXfRefs(ss, xf, /* isStyle */ false);\n return addToPool(xf, ss.cellXfs, ss._xfIdByKey);\n}\n\n/** Add a CellXf to the cellStyleXfs pool. Idempotent. */\nexport function addCellStyleXf(ss: Stylesheet, xf: CellXf): number {\n validateCellXfRefs(ss, xf, /* isStyle */ true);\n return addToPool(xf, ss.cellStyleXfs, ss._styleXfIdByKey);\n}\n\n// ---- internals -------------------------------------------------------------\n\nconst addToPool = <T>(value: T, pool: T[], byKey: Map<string, number>): number => {\n const key = stableStringify(value);\n const cached = byKey.get(key);\n if (cached !== undefined) return cached;\n const id = pool.length;\n pool.push(value);\n byKey.set(key, id);\n return id;\n};\n\nconst validateCellXfRefs = (ss: Stylesheet, xf: CellXf, isStyle: boolean): void => {\n if (xf.fontId < 0 || xf.fontId >= ss.fonts.length) {\n throw new OpenXmlSchemaError(`CellXf.fontId ${xf.fontId} out of range [0, ${ss.fonts.length})`);\n }\n if (xf.fillId < 0 || xf.fillId >= ss.fills.length) {\n throw new OpenXmlSchemaError(`CellXf.fillId ${xf.fillId} out of range [0, ${ss.fills.length})`);\n }\n if (xf.borderId < 0 || xf.borderId >= ss.borders.length) {\n throw new OpenXmlSchemaError(`CellXf.borderId ${xf.borderId} out of range [0, ${ss.borders.length})`);\n }\n // numFmtId is permissive: built-ins or any registered custom ID.\n if (!Number.isInteger(xf.numFmtId) || xf.numFmtId < 0) {\n throw new OpenXmlSchemaError(`CellXf.numFmtId must be a non-negative integer; got ${xf.numFmtId}`);\n }\n if (!isStyle && xf.xfId !== undefined) {\n if (xf.xfId < 0 || xf.xfId >= ss.cellStyleXfs.length) {\n throw new OpenXmlSchemaError(`CellXf.xfId ${xf.xfId} out of range [0, ${ss.cellStyleXfs.length})`);\n }\n }\n};\n\n/** Returns the currently registered numFmt entries (built-ins are implicit and not included). */\nexport function getCustomNumFmts(ss: Stylesheet): ReadonlyArray<{ id: number; code: string }> {\n const out: Array<{ id: number; code: string }> = [];\n for (const [id, code] of ss.numFmts.entries()) out.push({ id, code });\n // numFmts is keyed by id; sort for deterministic output.\n out.sort((a, b) => a.id - b.id);\n return out;\n}\n\n/** Read-only snapshot of every Font entry in the pool, indexed by id. */\nexport function listFonts(ss: Stylesheet): ReadonlyArray<Font> {\n return ss.fonts;\n}\n\n/** Read-only snapshot of every Fill entry in the pool, indexed by id. */\nexport function listFills(ss: Stylesheet): ReadonlyArray<Fill> {\n return ss.fills;\n}\n\n/** Read-only snapshot of every Border entry in the pool, indexed by id. */\nexport function listBorders(ss: Stylesheet): ReadonlyArray<Border> {\n return ss.borders;\n}\n\n/** Read-only snapshot of every CellXf entry in the cellXfs pool. */\nexport function listCellXfs(ss: Stylesheet): ReadonlyArray<CellXf> {\n return ss.cellXfs;\n}\n\n/** Read-only snapshot of every CellStyleXf entry (named-style xfs). */\nexport function listCellStyleXfs(ss: Stylesheet): ReadonlyArray<CellXf> {\n return ss.cellStyleXfs;\n}\n\n/**\n * Convenience: build the default `cellXfs[0]` Excel emits — points at the\n * workbook's font 0 / fill 0 / border 0 / numFmtId 0 (General).\n */\nexport function defaultCellXf(): CellXf {\n return Object.freeze({ fontId: 0, fillId: 0, borderId: 0, numFmtId: 0 });\n}\n\n/**\n * A cell's look expressed across every style axis at once. Each axis is\n * independent: pass any subset, and the axes you leave out are decided by\n * whichever function consumes the spec.\n */\nexport interface CellStyleSpec {\n font?: Font;\n fill?: Fill;\n border?: Border;\n alignment?: Alignment;\n protection?: Protection;\n numberFormat?: string;\n}\n\n/**\n * Resolve a style spec to the CellXf fields it sets, registering each component\n * in its pool. The result is a patch, not a whole xf: axes absent from `spec`\n * are absent here too, so a caller can either spread it over\n * {@link defaultCellXf} for a complete style or over an existing xf to merge.\n *\n * Every path that turns a user-facing style spec into an xf goes through this,\n * so a new axis on {@link CellStyleSpec} reaches the modelled writer and the\n * streaming write-only writer together.\n */\nexport function buildXfPatch(ss: Stylesheet, spec: CellStyleSpec): { -readonly [K in keyof CellXf]?: CellXf[K] } {\n const patch: { -readonly [K in keyof CellXf]?: CellXf[K] } = {};\n if (spec.font !== undefined) {\n patch.fontId = addFont(ss, spec.font);\n patch.applyFont = true;\n }\n if (spec.fill !== undefined) {\n patch.fillId = addFill(ss, spec.fill);\n patch.applyFill = true;\n }\n if (spec.border !== undefined) {\n patch.borderId = addBorder(ss, spec.border);\n patch.applyBorder = true;\n }\n if (spec.alignment !== undefined) {\n patch.alignment = spec.alignment;\n patch.applyAlignment = true;\n }\n if (spec.protection !== undefined) {\n patch.protection = spec.protection;\n patch.applyProtection = true;\n }\n if (spec.numberFormat !== undefined) {\n patch.numFmtId = addNumFmt(ss, spec.numberFormat);\n patch.applyNumberFormat = true;\n }\n return patch;\n}\n","// NamedStyle value object + curated built-in catalogue. Mirrors\n// openpyxl/openpyxl/styles/named_styles.py + styles/builtins.py.\n//\n// A `NamedStyle` is a label that bundles Font + Fill + Border +\n// Alignment + Protection + number-format string. Cells reference it\n// via the cellStyleXfs pool. This module:\n// 1. defines the value type;\n// 2. wires `addNamedStyle` (registers sub-objects in the Stylesheet,\n// allocates a cellStyleXf, then attaches the name);\n// 3. ships a curated subset of Excel's \"Cell Styles\" gallery as\n// plain-object specs and an `ensureBuiltinStyle` ergonomics\n// function that registers one on demand.\n//\n// The Accent1..6 with 20/40/60% variants and `pandas_highlight` are\n// deferred — they balloon the bundle without earning their keep on\n// the read/write hot path.\n\nimport { OpenXmlSchemaError } from '../utils/exceptions.js';\nimport type { Alignment } from './alignment.js';\nimport type { Border } from './borders.js';\nimport { makeColor } from './colors.js';\nimport type { Fill } from './fills.js';\nimport { makePatternFill } from './fills.js';\nimport type { Font } from './fonts.js';\nimport { makeFont } from './fonts.js';\nimport { addBorder, addCellStyleXf, addFill, addFont, addNumFmt, type CellXf, type Stylesheet } from './stylesheet.js';\n\nexport interface NamedStyle {\n readonly name: string;\n /** OOXML built-in id (0..N); absent for user-defined styles. */\n readonly builtinId?: number;\n readonly customBuiltin?: boolean;\n readonly hidden?: boolean;\n readonly iLevel?: number;\n readonly font?: Font;\n readonly fill?: Fill;\n readonly border?: Border;\n readonly alignment?: Alignment;\n readonly protection?: Protection;\n readonly numberFormat?: string;\n}\n\nimport type { Protection } from './protection.js';\n\n/**\n * NamedStyle as it sits inside the Stylesheet (an `<cellStyles>` entry).\n * Captures the resolved cellStyleXfs index so the writer can emit the\n * `<cellStyle xfId=\"…\" name=\"…\" builtinId=\"…\"/>` element directly.\n */\nexport interface StylesheetNamedStyle {\n readonly name: string;\n readonly xfId: number;\n readonly builtinId?: number;\n readonly customBuiltin?: boolean;\n readonly hidden?: boolean;\n readonly iLevel?: number;\n}\n\n/**\n * Register a NamedStyle on the Stylesheet:\n * 1. add Font / Fill / Border / NumberFormat to their pools\n * 2. push a CellXf with apply* flags into cellStyleXfs\n * 3. append a {name, xfId, builtinId} entry into the workbook's\n * namedStyles list (caller-managed; this function returns the\n * xfId so callers can connect the dots)\n * Idempotent on (name): re-registering by the same name returns the\n * cached xfId.\n */\nexport function addNamedStyle(ss: Stylesheet, style: NamedStyle): number {\n const cached = ss._namedStyleByName?.get(style.name);\n if (cached !== undefined) return cached.xfId;\n\n const fontId = style.font !== undefined ? addFont(ss, style.font) : 0;\n const fillId = style.fill !== undefined ? addFill(ss, style.fill) : 0;\n const borderId = style.border !== undefined ? addBorder(ss, style.border) : 0;\n const numFmtId = style.numberFormat !== undefined ? addNumFmt(ss, style.numberFormat) : 0;\n\n // openpyxl convention: cellStyleXfs entries (the \"base\" XFs of named\n // styles) don't carry apply* flags. The cellXf that bridges a cell to\n // a named style is the one that sets apply* — that's what Excel reads\n // to decide whether to honour the inherited font / fill / border.\n const xf: CellXf = {\n fontId,\n fillId,\n borderId,\n numFmtId,\n ...(style.alignment !== undefined ? { alignment: style.alignment } : {}),\n ...(style.protection !== undefined ? { protection: style.protection } : {}),\n };\n const xfId = addCellStyleXf(ss, xf);\n\n if (ss._namedStyleByName === undefined) ss._namedStyleByName = new Map();\n if (ss.namedStyles === undefined) ss.namedStyles = [];\n const entry: StylesheetNamedStyle = {\n name: style.name,\n xfId,\n ...(style.builtinId !== undefined ? { builtinId: style.builtinId } : {}),\n ...(style.customBuiltin !== undefined ? { customBuiltin: style.customBuiltin } : {}),\n ...(style.hidden !== undefined ? { hidden: style.hidden } : {}),\n ...(style.iLevel !== undefined ? { iLevel: style.iLevel } : {}),\n };\n ss.namedStyles.push(entry);\n ss._namedStyleByName.set(style.name, entry);\n return xfId;\n}\n\n// ---- built-in catalogue ----------------------------------------------------\n//\n// Common ground: the gallery's body fonts are all Calibri 12, family 2,\n// minor scheme, theme-1 colour. Specific styles override font / fill /\n// border / numberFormat as needed.\n\nconst BODY_FONT: Font = makeFont({\n name: 'Calibri',\n family: 2,\n size: 12,\n color: makeColor({ theme: 1 }),\n scheme: 'minor',\n});\n\nconst fillRgb = (rgb: string, fg = true): Fill =>\n makePatternFill(\n fg ? { patternType: 'solid', bgColor: makeColor({ rgb }), fgColor: makeColor({ rgb }) } : { patternType: 'solid' },\n );\n\n/** Curated subset of openpyxl's `styles` dict. Keys match the user-visible names. */\nexport const BUILTIN_NAMED_STYLES: Readonly<Record<string, NamedStyle>> = Object.freeze({\n // -------- core ----------------------------------------------------------\n Normal: { name: 'Normal', builtinId: 0, font: BODY_FONT },\n\n // -------- semantic state ------------------------------------------------\n Good: {\n name: 'Good',\n builtinId: 26,\n font: makeFont({ ...BODY_FONT, color: makeColor({ rgb: 'FF006100' }) }),\n fill: fillRgb('FFC6EFCE'),\n },\n Bad: {\n name: 'Bad',\n builtinId: 27,\n font: makeFont({ ...BODY_FONT, color: makeColor({ rgb: 'FF9C0006' }) }),\n fill: fillRgb('FFFFC7CE'),\n },\n Neutral: {\n name: 'Neutral',\n builtinId: 28,\n font: makeFont({ ...BODY_FONT, color: makeColor({ rgb: 'FF9C5700' }) }),\n fill: fillRgb('FFFFEB9C'),\n },\n\n // -------- data ----------------------------------------------------------\n Calculation: {\n name: 'Calculation',\n builtinId: 22,\n font: makeFont({ ...BODY_FONT, bold: true, color: makeColor({ rgb: 'FFFA7D00' }) }),\n fill: fillRgb('FFF2F2F2'),\n },\n 'Check Cell': {\n name: 'Check Cell',\n builtinId: 23,\n font: makeFont({ ...BODY_FONT, bold: true, color: makeColor({ rgb: 'FFFFFFFF' }) }),\n fill: fillRgb('FFA5A5A5'),\n },\n 'Linked Cell': {\n name: 'Linked Cell',\n builtinId: 24,\n font: makeFont({ ...BODY_FONT, color: makeColor({ rgb: 'FFFA7D00' }) }),\n },\n Note: {\n name: 'Note',\n builtinId: 10,\n font: BODY_FONT,\n fill: fillRgb('FFFFFFC0'),\n },\n 'Warning Text': {\n name: 'Warning Text',\n builtinId: 11,\n font: makeFont({ ...BODY_FONT, color: makeColor({ rgb: 'FFFF0000' }) }),\n },\n Input: {\n name: 'Input',\n builtinId: 20,\n font: makeFont({ ...BODY_FONT, color: makeColor({ rgb: 'FF3F3F76' }) }),\n fill: fillRgb('FFFFCC99'),\n },\n Output: {\n name: 'Output',\n builtinId: 21,\n font: makeFont({ ...BODY_FONT, bold: true, color: makeColor({ rgb: 'FF3F3F3F' }) }),\n fill: fillRgb('FFF2F2F2'),\n },\n 'Explanatory Text': {\n name: 'Explanatory Text',\n builtinId: 53,\n font: makeFont({ ...BODY_FONT, italic: true, color: makeColor({ rgb: 'FF7F7F7F' }) }),\n },\n\n // -------- titles & headings ---------------------------------------------\n Title: {\n name: 'Title',\n builtinId: 15,\n font: makeFont({ name: 'Cambria', family: 2, size: 18, scheme: 'major', color: makeColor({ theme: 3 }) }),\n },\n 'Headline 1': {\n name: 'Headline 1',\n builtinId: 16,\n font: makeFont({ ...BODY_FONT, bold: true, size: 15, color: makeColor({ theme: 3 }) }),\n },\n 'Headline 2': {\n name: 'Headline 2',\n builtinId: 17,\n font: makeFont({ ...BODY_FONT, bold: true, size: 13, color: makeColor({ theme: 3 }) }),\n },\n 'Headline 3': {\n name: 'Headline 3',\n builtinId: 18,\n font: makeFont({ ...BODY_FONT, bold: true, color: makeColor({ theme: 3 }) }),\n },\n 'Headline 4': {\n name: 'Headline 4',\n builtinId: 19,\n font: makeFont({ ...BODY_FONT, bold: true, italic: true, color: makeColor({ theme: 3 }) }),\n },\n Total: {\n name: 'Total',\n builtinId: 25,\n font: makeFont({ ...BODY_FONT, bold: true }),\n },\n\n // -------- numeric -------------------------------------------------------\n Comma: { name: 'Comma', builtinId: 3, font: BODY_FONT, numberFormat: '#,##0.00' },\n 'Comma [0]': { name: 'Comma [0]', builtinId: 6, font: BODY_FONT, numberFormat: '#,##0' },\n Currency: { name: 'Currency', builtinId: 4, font: BODY_FONT, numberFormat: '\"$\"#,##0.00' },\n 'Currency [0]': { name: 'Currency [0]', builtinId: 7, font: BODY_FONT, numberFormat: '\"$\"#,##0' },\n Percent: { name: 'Percent', builtinId: 5, font: BODY_FONT, numberFormat: '0%' },\n\n // -------- hyperlinks ----------------------------------------------------\n Hyperlink: {\n name: 'Hyperlink',\n builtinId: 8,\n font: makeFont({ ...BODY_FONT, underline: 'single', color: makeColor({ theme: 10 }) }),\n },\n 'Followed Hyperlink': {\n name: 'Followed Hyperlink',\n builtinId: 9,\n font: makeFont({ ...BODY_FONT, underline: 'single', color: makeColor({ theme: 11 }) }),\n },\n});\n\n/**\n * Register a built-in style with the supplied Stylesheet (idempotent).\n * Returns the cellStyleXfs index. Throws OpenXmlSchemaError when the\n * name is unknown.\n */\nexport function ensureBuiltinStyle(ss: Stylesheet, name: keyof typeof BUILTIN_NAMED_STYLES | string): number {\n const spec = BUILTIN_NAMED_STYLES[name as keyof typeof BUILTIN_NAMED_STYLES];\n if (spec === undefined) {\n throw new OpenXmlSchemaError(`ensureBuiltinStyle: unknown built-in style \"${String(name)}\"`);\n }\n return addNamedStyle(ss, spec);\n}\n","// Cell protection value object. Mirrors openpyxl/openpyxl/styles/protection.py.\n//\n// Protection only matters when the worksheet itself is protected; until\n// then it's metadata that round-trips with the cell's style.\n\nexport interface Protection {\n /** When true (the default), the cell can't be edited if the sheet is locked. */\n readonly locked?: boolean;\n /** When true, the formula bar hides this cell's contents on a protected sheet. */\n readonly hidden?: boolean;\n}\n\nexport function makeProtection(opts: Partial<Protection> = {}): Protection {\n const out: { -readonly [K in keyof Protection]: Protection[K] } = {};\n if (opts.locked !== undefined) out.locked = opts.locked;\n if (opts.hidden !== undefined) out.hidden = opts.hidden;\n return Object.freeze(out);\n}\n\n/** Excel's Stylesheet always contains an entry equal to {locked:true, hidden:false}. */\nexport const DEFAULT_PROTECTION: Protection = makeProtection({ locked: true, hidden: false });\n","// Cell ↔ Stylesheet bridge.\n//\n// A cell's `styleId` is an index into `Workbook.styles.cellXfs`. Each CellXf\n// points at slots in the font / fill / border / numFmt pools. To \"apply\" a Font\n// to a cell we therefore:\n// 1. read the cell's current CellXf (or `defaultCellXf` if it points\n// at a slot that hasn't been allocated yet — common right after\n// `makeCell` since `cellXfs` starts empty)\n// 2. resolve / register the new component in its pool\n// 3. build a new CellXf that carries the new id + the matching\n// `apply*` flag (Excel needs the flag to honour the override over\n// the underlying NamedStyle)\n// 4. dedup that CellXf via `addCellXf` and write the returned index\n// back to `c.styleId`\n//\n// Following the no-classes rule, this module is just a flat list of free\n// functions; the workbook is passed in so callers don't need to thread the\n// stylesheet manually.\n\nimport type { Cell } from '../cell/cell.js';\nimport { OpenXmlSchemaError } from '../utils/exceptions.js';\nimport type { Workbook } from '../workbook/workbook.js';\nimport type { RangeRef } from '../utils/coordinate.js';\nimport { parseRange } from '../worksheet/cell-range.js';\nimport { ensureCell, type Worksheet } from '../worksheet/worksheet.js';\nimport type { Alignment, HorizontalAlignment, VerticalAlignment } from './alignment.js';\nimport { alignmentToCss, makeAlignment } from './alignment.js';\nimport type { Border, SideStyle } from './borders.js';\nimport { borderToCss, DEFAULT_BORDER, makeBorder, makeSide } from './borders.js';\nimport type { Color } from './colors.js';\nimport { makeColor } from './colors.js';\nimport type { Fill } from './fills.js';\nimport { DEFAULT_EMPTY_FILL, fillToCss, makePatternFill } from './fills.js';\nimport type { Font, FontPatch, UnderlineStyle } from './fonts.js';\nimport { DEFAULT_FONT, fontToCss, makeFont } from './fonts.js';\nimport { ensureBuiltinStyle } from './named-styles.js';\nimport { builtinFormatCode } from './numbers.js';\nimport type { Protection } from './protection.js';\nimport { DEFAULT_PROTECTION } from './protection.js';\nimport {\n addBorder,\n addCellXf,\n addFill,\n addFont,\n addNumFmt,\n buildXfPatch,\n type CellStyleSpec,\n type CellXf,\n defaultCellXf,\n type Stylesheet,\n} from './stylesheet.js';\n\n/** Default General number format code (numFmtId 0). */\nconst GENERAL_FORMAT_CODE = 'General';\n\n/** Resolve a cell's current CellXf, falling back to defaults when unset. */\nfunction currentXf(ss: Stylesheet, c: Cell): CellXf {\n return ss.cellXfs[c.styleId] ?? defaultCellXf();\n}\n\n// ---- read accessors --------------------------------------------------------\n\nexport function getCellFont(wb: Workbook, c: Cell): Font {\n const xf = currentXf(wb.styles, c);\n return wb.styles.fonts[xf.fontId] ?? DEFAULT_FONT;\n}\n\nexport function getCellFill(wb: Workbook, c: Cell): Fill {\n const xf = currentXf(wb.styles, c);\n return wb.styles.fills[xf.fillId] ?? DEFAULT_EMPTY_FILL;\n}\n\nexport function getCellBorder(wb: Workbook, c: Cell): Border {\n const xf = currentXf(wb.styles, c);\n return wb.styles.borders[xf.borderId] ?? DEFAULT_BORDER;\n}\n\nexport function getCellAlignment(wb: Workbook, c: Cell): Alignment {\n return currentXf(wb.styles, c).alignment ?? {};\n}\n\nexport function getCellProtection(wb: Workbook, c: Cell): Protection {\n return currentXf(wb.styles, c).protection ?? DEFAULT_PROTECTION;\n}\n\n/**\n * Returns the cell's number-format **code** (e.g. `\"0.00\"`, `\"General\"`).\n * Built-in IDs resolve through `builtinFormatCode`; custom IDs come from the\n * workbook's numFmts map.\n */\nexport function getCellNumberFormat(wb: Workbook, c: Cell): string {\n const id = currentXf(wb.styles, c).numFmtId;\n const builtin = builtinFormatCode(id);\n if (builtin !== undefined) return builtin;\n return wb.styles.numFmts.get(id) ?? GENERAL_FORMAT_CODE;\n}\n\n/**\n * Aggregate `fontToCss` + `fillToCss` + `borderToCss` + `alignmentToCss` for a\n * cell into a single CSS-property record. Resolves the cell's `styleId` against\n * the workbook stylesheet, then merges the four partials. On key collision the\n * priority is alignment > border > fill > font (alignment is most specific,\n * font is the broad default). A fully-default cell (`styleId === 0` with empty\n * pools) returns `{}`.\n */\nexport function cellStyleToCss(wb: Workbook, c: Cell): Record<string, string> {\n // Don't pay the resolve cost when the cell points at the default xf and the\n // stylesheet is still in its initial state.\n if (c.styleId === 0) {\n const xf = wb.styles.cellXfs[0];\n if (!xf || (xf.fontId === 0 && xf.fillId === 0 && xf.borderId === 0 && xf.alignment === undefined)) {\n return {};\n }\n }\n const font = getCellFont(wb, c);\n const fill = getCellFill(wb, c);\n const border = getCellBorder(wb, c);\n const alignment = getCellAlignment(wb, c);\n return {\n ...fontToCss(font),\n ...fillToCss(fill),\n ...borderToCss(border),\n ...alignmentToCss(alignment),\n };\n}\n\n// ---- write accessors -------------------------------------------------------\n\n/**\n * Reserve cellXfs[0] for the implicit default xf when the pool is empty.\n * Excel's `<c>` elements without an `s=` attribute resolve to `cellXfs[0]`, so\n * the first time a caller styles any cell we need to make sure that slot stays\n * the default — otherwise unstyled cells in the same sheet would inherit the\n * freshly added styled xf.\n *\n * Idempotent: calling this on a non-empty pool is a no-op.\n */\nconst reserveDefaultXfSlot = (wb: Workbook): void => {\n if (wb.styles.cellXfs.length === 0) addCellXf(wb.styles, defaultCellXf());\n};\n\n/**\n * Replace one field on the cell's CellXf. Centralises the dedup + styleId\n * update so each `setCell*` is a single dispatch.\n */\nfunction applyXfPatch(wb: Workbook, c: Cell, patch: Partial<CellXf>): void {\n reserveDefaultXfSlot(wb);\n const next: CellXf = { ...currentXf(wb.styles, c), ...patch };\n c.styleId = addCellXf(wb.styles, next);\n}\n\n/**\n * Replace the cell's font outright. `font` has to be complete: anything it\n * omits is omitted from the `<font>` record too, and each viewer then falls\n * back to its own default rather than the workbook's. Reach for {@link\n * patchCellFont} unless you really mean \"this font and nothing inherited\".\n */\nexport function setCellFont(wb: Workbook, c: Cell, font: Font): void {\n const fontId = addFont(wb.styles, font);\n applyXfPatch(wb, c, { fontId, applyFont: true });\n}\n\nexport function setCellFill(wb: Workbook, c: Cell, fill: Fill): void {\n const fillId = addFill(wb.styles, fill);\n applyXfPatch(wb, c, { fillId, applyFill: true });\n}\n\nexport function setCellBorder(wb: Workbook, c: Cell, border: Border): void {\n const borderId = addBorder(wb.styles, border);\n applyXfPatch(wb, c, { borderId, applyBorder: true });\n}\n\nexport function setCellAlignment(wb: Workbook, c: Cell, alignment: Alignment): void {\n applyXfPatch(wb, c, { alignment, applyAlignment: true });\n}\n\nexport function setCellProtection(wb: Workbook, c: Cell, protection: Protection): void {\n applyXfPatch(wb, c, { protection, applyProtection: true });\n}\n\n/**\n * Set the cell's number format by its **code** string. Built-in codes resolve\n * to their canonical id; custom codes are registered via `addNumFmt`.\n */\nexport function setCellNumberFormat(wb: Workbook, c: Cell, formatCode: string): void {\n const numFmtId = addNumFmt(wb.styles, formatCode);\n applyXfPatch(wb, c, { numFmtId, applyNumberFormat: true });\n}\n\n/**\n * Copy the source cell's `styleId` to the target cell. Both cells share the\n * same workbook stylesheet, so the styled appearance carries over without\n * allocating a new xf entry. Pass cells from different workbooks via {@link\n * cloneCellStyle} if you need a deep copy across workbooks.\n */\nexport function copyCellStyle(_wb: Workbook, source: Cell, target: Cell): void {\n target.styleId = source.styleId;\n}\n\n/**\n * Reset a cell back to the default (unstyled) appearance — equivalent to\n * Excel's \"Clear Formatting\" command. After the call, the cell inherits the\n * workbook's default font / fill / border / alignment / protection /\n * numberFormat. The underlying xf pool is **not** shrunk (Excel doesn't bother\n * either; the orphaned xf is harmless).\n */\nexport function clearCellStyle(_wb: Workbook, c: Cell): void {\n c.styleId = 0;\n}\n\n/**\n * Range-level shortcut for {@link clearCellStyle}. Walks every cell actually\n * present in the range and resets its `styleId` to 0; cells that don't exist\n * yet are **not** materialised (no-op for sparse regions, unlike the styled\n * `setRange*` family which has to create cells to make the patch observable).\n */\nexport function clearRangeStyle(wb: Workbook, ws: Worksheet, range: RangeRef): void {\n const { minRow, maxRow, minCol, maxCol } = parseRange(range);\n for (let r = minRow; r <= maxRow; r++) {\n const row = ws.rows.get(r);\n if (!row) continue;\n for (let c = minCol; c <= maxCol; c++) {\n const cell = row.get(c);\n if (cell) clearCellStyle(wb, cell);\n }\n }\n}\n\n/**\n * Deep-copy the source cell's full xf (font / fill / border / alignment /\n * protection / numberFormat) into a possibly-different workbook. Returns the\n * new styleId in the target workbook.\n */\nexport function cloneCellStyle(\n sourceWb: Workbook,\n source: Cell,\n targetWb: Workbook,\n target: Cell,\n): number {\n reserveDefaultXfSlot(targetWb);\n const srcXf = currentXf(sourceWb.styles, source);\n const srcFont = sourceWb.styles.fonts[srcXf.fontId] ?? DEFAULT_FONT;\n const srcFill = sourceWb.styles.fills[srcXf.fillId] ?? DEFAULT_EMPTY_FILL;\n const srcBorder = sourceWb.styles.borders[srcXf.borderId] ?? DEFAULT_BORDER;\n const srcNumFmt = builtinFormatCode(srcXf.numFmtId)\n ?? sourceWb.styles.numFmts.get(srcXf.numFmtId)\n ?? GENERAL_FORMAT_CODE;\n const fontId = addFont(targetWb.styles, srcFont);\n const fillId = addFill(targetWb.styles, srcFill);\n const borderId = addBorder(targetWb.styles, srcBorder);\n const numFmtId = addNumFmt(targetWb.styles, srcNumFmt);\n const next: { -readonly [K in keyof CellXf]?: CellXf[K] } = {\n fontId,\n fillId,\n borderId,\n numFmtId,\n };\n if (srcXf.applyFont) next.applyFont = true;\n if (srcXf.applyFill) next.applyFill = true;\n if (srcXf.applyBorder) next.applyBorder = true;\n if (srcXf.applyNumberFormat) next.applyNumberFormat = true;\n if (srcXf.alignment !== undefined) {\n next.alignment = srcXf.alignment;\n next.applyAlignment = true;\n }\n if (srcXf.protection !== undefined) {\n next.protection = srcXf.protection;\n next.applyProtection = true;\n }\n target.styleId = addCellXf(targetWb.styles, next as CellXf);\n return target.styleId;\n}\n\n/**\n * Register a style and return its `styleId`. `setCell` and `setCellByCoord`\n * take it as their last argument, `appendRow` and `appendRows` take it inside\n * `{ styleIds: [...] }`:\n *\n * ```ts\n * const INT = registerCellStyle(wb, { numberFormat: '#,##0' });\n * setCell(ws, 2, 3, 1234, INT);\n * appendRow(ws, ['de', 71_579], { styleIds: [undefined, INT] });\n * ```\n *\n * Build each distinct look once and let the write carry the formatting,\n * instead of running a styling pass over every cell afterwards.\n *\n * The id names a **complete** style, not a patch: an axis missing from `spec`\n * resolves to slot 0 of that pool, so it renders as the workbook default even\n * when the target cell previously had something there. {@link setCellStyle} is\n * the patch-an-existing-cell counterpart.\n *\n * \"Workbook default\" means slot 0 literally. On a workbook from\n * `createWorkbook` that is the neutral font / no fill / no border. A workbook\n * loaded from another producer may hold anything in slot 0, since nothing in\n * ECMA-376 reserves it, so pass the axis explicitly when the look has to be\n * neutral regardless of what the file arrived with.\n */\nexport function registerCellStyle(wb: Workbook, spec: CellStyleSpec): number {\n reserveDefaultXfSlot(wb);\n return addCellXf(wb.styles, { ...defaultCellXf(), ...buildXfPatch(wb.styles, spec) });\n}\n\n/**\n * Build a single CellXf from a multi-axis style spec, then merge it into every\n * cell in `range`. The xf is registered once per style shape, so a 1000-cell\n * range allocates one xf, which is much faster than looping `setCellStyle` per\n * cell.\n *\n * Each cell keeps the axes `spec` leaves out, which is what separates this from\n * {@link registerCellStyle}: the id that returns is a whole style, this is a\n * patch over whatever each cell already carried.\n */\nexport function setRangeStyle(wb: Workbook, ws: Worksheet, range: RangeRef, spec: CellStyleSpec): void {\n const patch = buildXfPatch(wb.styles, spec);\n if (Object.keys(patch).length === 0) return;\n reserveDefaultXfSlot(wb);\n\n const { minRow, maxRow, minCol, maxCol } = parseRange(range);\n // Pre-register the xf for each existing cell — Excel dedupes by value, so the\n // inner xf-pool ends up the same shape for cells already carrying part of the\n // patch as for blanks.\n for (let r = minRow; r <= maxRow; r++) {\n for (let c = minCol; c <= maxCol; c++) {\n const cell = ensureCell(ws, r, c);\n const next: CellXf = { ...currentXf(wb.styles, cell), ...patch };\n cell.styleId = addCellXf(wb.styles, next);\n }\n }\n}\n\n/**\n * Combined cell-style setter, patching the cell's existing xf. Each axis is\n * independent, so pass any subset and the corresponding `applyXxx` flags get set\n * on the underlying CellXf. Avoids\n * 5+ separate stylesheet round-trips when a caller wants to style a single cell\n * across multiple axes (Excel dedupes the resulting xf record on every call).\n */\nexport function setCellStyle(wb: Workbook, c: Cell, spec: CellStyleSpec): void {\n const patch = buildXfPatch(wb.styles, spec);\n if (Object.keys(patch).length === 0) return;\n applyXfPatch(wb, c, patch as Partial<CellXf>);\n}\n\n// ---- fill presets -------------------------------------------------------\n\n/**\n * Set the cell's background to a solid color. Accepts a hex string\n * (`'FFAAFFAA'`) or a partial `Color` object (`{ theme: 4, tint: 0.4 }`).\n * Equivalent to `setCellFill(wb, c, makePatternFill({ patternType: 'solid',\n * fgColor: makeColor(...) }))`.\n */\nexport function setCellBackgroundColor(wb: Workbook, c: Cell, color: string | Partial<Color>): void {\n const colorObj = typeof color === 'string' ? makeColor({ rgb: color }) : makeColor(color);\n setCellFill(wb, c, makePatternFill({ patternType: 'solid', fgColor: colorObj }));\n}\n\n/** Strip the cell's background fill, returning it to the default. */\nexport function clearCellBackground(wb: Workbook, c: Cell): void {\n setCellFill(wb, c, DEFAULT_EMPTY_FILL);\n}\n\n/**\n * Range-level shortcut for `setCellBackgroundColor`. Each cell in the range\n * gets the same solid pattern fill via `setRangeStyle`, so the fill pool dedups\n * to a single entry across the whole range.\n */\nexport function setRangeBackgroundColor(\n wb: Workbook,\n ws: Worksheet,\n range: RangeRef,\n color: string | Partial<Color>,\n): void {\n const colorObj = typeof color === 'string' ? makeColor({ rgb: color }) : makeColor(color);\n setRangeStyle(wb, ws, range, {\n fill: makePatternFill({ patternType: 'solid', fgColor: colorObj }),\n });\n}\n\n/**\n * Range-level shortcut for `setCellFont`. Replaces the whole Font on every cell\n * in the range; there is no range-level merge, so build the complete font you\n * want rather than passing `makeFont({ bold: true })` and losing the workbook\n * default.\n */\nexport function setRangeFont(\n wb: Workbook,\n ws: Worksheet,\n range: RangeRef,\n font: Font,\n): void {\n setRangeStyle(wb, ws, range, { font });\n}\n\n/**\n * Range-level shortcut for `setCellNumberFormat`. Stamps the same format-code\n * onto every cell in the range; the numFmt pool dedups the code so callers\n * don't pay per-cell pool churn.\n */\nexport function setRangeNumberFormat(\n wb: Workbook,\n ws: Worksheet,\n range: RangeRef,\n formatCode: string,\n): void {\n setRangeStyle(wb, ws, range, { numberFormat: formatCode });\n}\n\n/**\n * Range-level shortcut for `setCellProtection`. Stamps the same Protection\n * (locked / hidden) onto every cell in the range. Pass a full `Protection`\n * value or a partial — partials default missing fields to `false` per Excel's\n * `<protection>` semantics.\n *\n * Common usage: `setRangeProtection(wb, ws, 'B2:B100', { locked: false })` to\n * leave just an input column editable when the sheet is protected.\n */\nexport function setRangeProtection(\n wb: Workbook,\n ws: Worksheet,\n range: RangeRef,\n protection: Protection | Partial<Protection>,\n): void {\n // Funnel partials through the Protection factory so frozen invariant holds.\n const p: Protection = Object.isFrozen(protection)\n ? (protection as Protection)\n : { locked: protection.locked ?? false, hidden: protection.hidden ?? false };\n setRangeStyle(wb, ws, range, { protection: p });\n}\n\n/**\n * Range-level shortcut for `wrapCellText`. Toggles \"Wrap Text\" on every cell in\n * the range while preserving each cell's existing alignment (horizontal /\n * vertical / textRotation / indent are not touched). Empty cells in the range\n * are materialised so the alignment patch is observable on round-trip.\n */\nexport function setRangeWrapText(wb: Workbook, ws: Worksheet, range: RangeRef, on = true): void {\n reserveDefaultXfSlot(wb);\n const { minRow, maxRow, minCol, maxCol } = parseRange(range);\n for (let r = minRow; r <= maxRow; r++) {\n for (let c = minCol; c <= maxCol; c++) {\n const cell = ensureCell(ws, r, c);\n wrapCellText(wb, cell, on);\n }\n }\n}\n\n/**\n * Range-level Alignment setter. Two modes:\n *\n * - `mode: 'merge'` (default) — each cell's existing alignment is\n * preserved; the supplied partial overlays it. Use this when you\n * want to set just `horizontal` or `vertical` without wiping the\n * other axes.\n * - `mode: 'replace'` — each cell's alignment is **wholly replaced**\n * by the supplied value. Indent / textRotation / wrapText that\n * weren't supplied are dropped.\n *\n * Empty cells in the range are materialised so the patch is observable on\n * round-trip.\n */\nexport function setRangeAlignment(\n wb: Workbook,\n ws: Worksheet,\n range: RangeRef,\n alignment: Partial<Alignment>,\n mode: 'merge' | 'replace' = 'merge',\n): void {\n reserveDefaultXfSlot(wb);\n const { minRow, maxRow, minCol, maxCol } = parseRange(range);\n if (mode === 'replace') {\n setRangeStyle(wb, ws, range, { alignment: makeAlignment(alignment) });\n return;\n }\n for (let r = minRow; r <= maxRow; r++) {\n for (let c = minCol; c <= maxCol; c++) {\n const cell = ensureCell(ws, r, c);\n const cur = currentXf(wb.styles, cell).alignment;\n setCellAlignment(wb, cell, mergeAlignment(cur, alignment));\n }\n }\n}\n\n// ---- font presets -------------------------------------------------------\n\n/**\n * Merge `patch` over the cell's current font, so the fields left out keep the\n * value they already had (the workbook default, on an unstyled cell). This is\n * the way to change several font fields at once: `setCellFont(wb, c,\n * makeFont({ bold: true }))` is a legal call that registers a font carrying no\n * name and no size, and Excel, LibreOffice and Sheets each substitute a\n * different one.\n *\n * A field set to `undefined` is removed rather than kept, so\n * `patchCellFont(wb, c, { underline: undefined })` un-underlines a cell while\n * leaving the rest of its font alone. Omitting the key keeps the current value.\n *\n * The single-field setters below are this function with one field filled in.\n */\nexport function patchCellFont(wb: Workbook, c: Cell, patch: FontPatch): void {\n // `makeFont` drops undefined-valued keys, and spreading `patch` over the\n // current font overwrites a field with undefined only when the key is\n // actually present, so \"remove\" and \"leave alone\" stay distinguishable.\n setCellFont(wb, c, makeFont({ ...getCellFont(wb, c), ...patch }));\n}\n\n/** Toggle bold on a cell. Preserves other font fields. */\nexport function setBold(wb: Workbook, c: Cell, on = true): void {\n patchCellFont(wb, c, { bold: on });\n}\n\n/** Toggle italic on a cell. */\nexport function setItalic(wb: Workbook, c: Cell, on = true): void {\n patchCellFont(wb, c, { italic: on });\n}\n\n/** Toggle strike-through on a cell. */\nexport function setStrikethrough(wb: Workbook, c: Cell, on = true): void {\n patchCellFont(wb, c, { strike: on });\n}\n\n/**\n * Set the underline style. Pass `false` to drop underline; pass `'single' |\n * 'double' | 'singleAccounting' | 'doubleAccounting'` to apply that style; pass\n * `true` for the most common single-line.\n */\nexport function setUnderline(\n wb: Workbook,\n c: Cell,\n style: UnderlineStyle | boolean = 'single',\n): void {\n const underline = style === false ? undefined : style === true ? 'single' : style;\n patchCellFont(wb, c, { underline });\n}\n\n/** Set the font size in points (e.g. 14). Preserves other fields. */\nexport function setFontSize(wb: Workbook, c: Cell, size: number): void {\n patchCellFont(wb, c, { size });\n}\n\n/** Set the font family name (e.g. \"Arial\"). Preserves other fields. */\nexport function setFontName(wb: Workbook, c: Cell, name: string): void {\n patchCellFont(wb, c, { name });\n}\n\n/**\n * Set the font color. Accepts a hex string (\"FFAA0033\") or a partial `Color`\n * object (`{ theme: 4, tint: 0.4 }`). Preserves other font fields.\n */\nexport function setFontColor(wb: Workbook, c: Cell, color: string | Partial<Color>): void {\n const colorObj = typeof color === 'string' ? makeColor({ rgb: color }) : makeColor(color);\n patchCellFont(wb, c, { color: colorObj });\n}\n\n// ---- alignment presets --------------------------------------------------\n\nconst mergeAlignment = (current: Alignment | undefined, patch: Partial<Alignment>): Alignment => {\n return makeAlignment({ ...current, ...patch });\n};\n\n/**\n * Center a cell horizontally + vertically. Mirrors Excel's \"Merge & Center\" UI\n * button (without the merge — see {@link mergeCells} for that). Preserves any\n * other alignment fields already present.\n */\nexport function centerCell(wb: Workbook, c: Cell): void {\n const cur = currentXf(wb.styles, c).alignment;\n setCellAlignment(wb, c, mergeAlignment(cur, { horizontal: 'center', vertical: 'center' }));\n}\n\n/** Toggle \"Wrap Text\" on a cell, preserving other alignment fields. */\nexport function wrapCellText(wb: Workbook, c: Cell, wrap = true): void {\n const cur = currentXf(wb.styles, c).alignment;\n setCellAlignment(wb, c, mergeAlignment(cur, { wrapText: wrap }));\n}\n\n/** Set the horizontal alignment in isolation. */\nexport function alignCellHorizontal(wb: Workbook, c: Cell, horizontal: HorizontalAlignment): void {\n const cur = currentXf(wb.styles, c).alignment;\n setCellAlignment(wb, c, mergeAlignment(cur, { horizontal }));\n}\n\n/** Set the vertical alignment in isolation. */\nexport function alignCellVertical(wb: Workbook, c: Cell, vertical: VerticalAlignment): void {\n const cur = currentXf(wb.styles, c).alignment;\n setCellAlignment(wb, c, mergeAlignment(cur, { vertical }));\n}\n\n/**\n * Rotate the cell's text. `degrees` accepts 0..180 (clockwise) or 255 for\n * Excel's \"vertical stacked\" mode. Mirrors the rotate icons in the alignment\n * ribbon.\n */\nexport function rotateCellText(wb: Workbook, c: Cell, degrees: number): void {\n const cur = currentXf(wb.styles, c).alignment;\n setCellAlignment(wb, c, mergeAlignment(cur, { textRotation: degrees }));\n}\n\n/** Set or clear the indent level (0..255). */\nexport function indentCell(wb: Workbook, c: Cell, levels: number): void {\n const cur = currentXf(wb.styles, c).alignment;\n setCellAlignment(wb, c, mergeAlignment(cur, { indent: levels }));\n}\n\n// ---- format presets -----------------------------------------------------\n//\n// Mirror Excel's \"Format Cells → Number → Category\" panel. Each preset builds\n// the exact format-code Excel ships with, then routes through the existing\n// `setCellNumberFormat` so the dedup pool sees the same string every time.\n\n/**\n * Format a cell as currency. Produces one of:\n * - default → `\"$#,##0.00\"` (US dollar, 2 decimals)\n * - `{ symbol: \"€\" }` → `\"€#,##0.00\"`\n * - `{ symbol: \"¥\", decimals: 0 }` → `\"¥#,##0\"`\n * - `{ accounting: true }` → `\"_-$* #,##0.00_-;-$* #,##0.00_-;_-$* \\\"-\\\"??_-;_-@_-\"`\n * (Excel's \"Accounting\" subtype with right-aligned symbol).\n */\nexport function setCellAsCurrency(\n wb: Workbook,\n c: Cell,\n opts: { symbol?: string; decimals?: number; accounting?: boolean } = {},\n): void {\n const symbol = opts.symbol ?? '$';\n const decimals = opts.decimals ?? 2;\n const decTail = decimals > 0 ? `.${'0'.repeat(decimals)}` : '';\n const code = opts.accounting\n ? `_-${symbol}* #,##0${decTail}_-;-${symbol}* #,##0${decTail}_-;_-${symbol}* \"-\"${'?'.repeat(decimals)}_-;_-@_-`\n : `${symbol}#,##0${decTail}`;\n setCellNumberFormat(wb, c, code);\n}\n\n/**\n * Format a cell as a percentage. `decimals` defaults to 0 → `\"0%\"`; `decimals:\n * 2` → `\"0.00%\"`. The cell value is multiplied by 100 by Excel during display.\n */\nexport function setCellAsPercent(wb: Workbook, c: Cell, decimals = 0): void {\n if (!Number.isInteger(decimals) || decimals < 0) {\n throw new OpenXmlSchemaError(`setCellAsPercent: decimals must be a non-negative integer; got ${decimals}`);\n }\n const code = decimals === 0 ? '0%' : `0.${'0'.repeat(decimals)}%`;\n setCellNumberFormat(wb, c, code);\n}\n\n/**\n * Format a cell as a date. `format` defaults to Excel's default\n * locale-independent ISO-style date `\"yyyy-mm-dd\"`. Common alternatives:\n * `\"m/d/yyyy\"`, `\"dd-mmm-yy\"`, `\"yyyy-mm-dd hh:mm:ss\"`.\n */\nexport function setCellAsDate(wb: Workbook, c: Cell, format = 'yyyy-mm-dd'): void {\n setCellNumberFormat(wb, c, format);\n}\n\n/**\n * Format a cell as a thousands-separated number. `decimals` defaults to 0 →\n * `\"#,##0\"`; `decimals: 2` → `\"#,##0.00\"`.\n */\nexport function setCellAsNumber(wb: Workbook, c: Cell, decimals = 0): void {\n if (!Number.isInteger(decimals) || decimals < 0) {\n throw new OpenXmlSchemaError(`setCellAsNumber: decimals must be a non-negative integer; got ${decimals}`);\n }\n const code = decimals === 0 ? '#,##0' : `#,##0.${'0'.repeat(decimals)}`;\n setCellNumberFormat(wb, c, code);\n}\n\n// ---- table-header preset ------------------------------------------------\n\n/**\n * Apply Excel's stock \"table header\" formatting to a range: bold white text on\n * a dark fill, plus a thick bottom border. Override any axis via `opts` — pass\n * `bold: false` to drop the bold, or `fillColor: 'FF305496'` for a different\n * shade. Defaults match Excel's \"Table Style Medium 2\" header row.\n */\nexport function formatAsHeader(\n wb: Workbook,\n ws: Worksheet,\n range: RangeRef,\n opts: {\n fillColor?: string | Partial<Color>;\n fontColor?: string | Partial<Color>;\n bold?: boolean;\n bottomBorder?: SideStyle | false;\n bottomBorderColor?: string | Partial<Color>;\n } = {},\n): void {\n const fillColor = opts.fillColor === undefined ? 'FF305496' : typeof opts.fillColor === 'string' ? makeColor({ rgb: opts.fillColor }) : makeColor(opts.fillColor);\n const fontColor = opts.fontColor === undefined ? 'FFFFFFFF' : typeof opts.fontColor === 'string' ? makeColor({ rgb: opts.fontColor }) : makeColor(opts.fontColor);\n const bold = opts.bold ?? true;\n const borderStyle = opts.bottomBorder ?? 'medium';\n const borderColorObj = opts.bottomBorderColor === undefined ? undefined : typeof opts.bottomBorderColor === 'string' ? makeColor({ rgb: opts.bottomBorderColor }) : makeColor(opts.bottomBorderColor);\n\n const fillColorObj = typeof fillColor === 'string' ? makeColor({ rgb: fillColor }) : fillColor;\n const fontColorObj = typeof fontColor === 'string' ? makeColor({ rgb: fontColor }) : fontColor;\n\n const styleOpts: CellStyleSpec = {\n font: makeFont({ bold, color: fontColorObj }),\n fill: makePatternFill({ patternType: 'solid', fgColor: fillColorObj }),\n };\n if (borderStyle !== false) {\n const side = makeSide({ style: borderStyle, ...(borderColorObj ? { color: borderColorObj } : {}) });\n styleOpts.border = makeBorder({ bottom: side });\n }\n setRangeStyle(wb, ws, range, styleOpts);\n}\n\n// ---- named / built-in style application --------------------------------\n\n/**\n * Apply a built-in Excel style (\"Heading 1\" / \"Total\" / \"Good\" / \"Bad\" /\n * \"Calculation\" / etc.) to a single cell. Registers the built-in on the\n * Stylesheet (idempotent) and points the cell's xf at it via `xfId` while\n * inheriting the matching font/fill/border/ numFmt ids so the cell renders\n * correctly on its own.\n *\n * Throws when `name` isn't in {@link BUILTIN_NAMED_STYLES}; use {@link\n * applyNamedStyle} for user-registered styles.\n */\nexport function applyBuiltinStyle(wb: Workbook, c: Cell, name: string): void {\n const xfId = ensureBuiltinStyle(wb.styles, name);\n applyNamedStyleByXfId(wb, c, xfId);\n}\n\n/**\n * Apply a NamedStyle that's already registered on the workbook (via\n * `addNamedStyle` or `ensureBuiltinStyle`) to a single cell, by name.\n */\nexport function applyNamedStyle(wb: Workbook, c: Cell, name: string): void {\n const entry = wb.styles._namedStyleByName?.get(name);\n if (entry === undefined) {\n throw new OpenXmlSchemaError(`applyNamedStyle: no named style \"${name}\" registered`);\n }\n applyNamedStyleByXfId(wb, c, entry.xfId);\n}\n\nconst applyNamedStyleByXfId = (wb: Workbook, c: Cell, xfId: number): void => {\n const styleXf = wb.styles.cellStyleXfs[xfId];\n if (!styleXf) {\n throw new OpenXmlSchemaError(`applyNamedStyle: cellStyleXfs[${xfId}] missing`);\n }\n // Excel only renders the cellStyleXf's font / fill / border when the cellXf\n // carries the matching `apply*` flag — even a `xfId` reference alone doesn't\n // make Excel inherit the values. So we copy every component the named style\n // touches *and* set the corresponding apply* flag, mirroring what real Excel\n // writes for `s=` referenced cells using a built-in named style.\n const patch: { -readonly [K in keyof CellXf]?: CellXf[K] } = {\n xfId,\n fontId: styleXf.fontId,\n fillId: styleXf.fillId,\n borderId: styleXf.borderId,\n numFmtId: styleXf.numFmtId,\n applyFont: true,\n applyFill: true,\n applyBorder: true,\n applyNumberFormat: true,\n };\n if (styleXf.alignment !== undefined) {\n patch.alignment = styleXf.alignment;\n patch.applyAlignment = true;\n }\n if (styleXf.protection !== undefined) {\n patch.protection = styleXf.protection;\n patch.applyProtection = true;\n }\n applyXfPatch(wb, c, patch as Partial<CellXf>);\n};\n\n// ---- border presets ----------------------------------------------------\n\n/**\n * Apply the same {@link SideStyle} to all four edges of a single cell. Optional\n * color via hex string or `Color` partial. Equivalent to `setCellBorder(wb, c,\n * makeBorder({ left, right, top, bottom: side }))` with all four sides\n * identical.\n */\nexport function setCellBorderAll(\n wb: Workbook,\n c: Cell,\n opts: { style: SideStyle; color?: string | Partial<Color> } = { style: 'thin' },\n): void {\n const colorObj = opts.color === undefined ? undefined : typeof opts.color === 'string' ? makeColor({ rgb: opts.color }) : makeColor(opts.color);\n const side = makeSide({ style: opts.style, ...(colorObj ? { color: colorObj } : {}) });\n setCellBorder(wb, c, makeBorder({ left: side, right: side, top: side, bottom: side }));\n}\n\n/**\n * Draw an outer border around a rectangular range. Cells on the perimeter\n * receive a partial border (only the edges that face outside the range); inner\n * cells are unaffected unless `inner` is provided, in which case every cell in\n * the range receives a border combining its perimeter edges with the `inner`\n * style for the inside edges.\n */\nexport function setRangeBorderBox(\n wb: Workbook,\n ws: Worksheet,\n range: RangeRef,\n opts: { style: SideStyle; color?: string | Partial<Color>; inner?: SideStyle } = { style: 'thin' },\n): void {\n const { minRow, maxRow, minCol, maxCol } = parseRange(range);\n const colorObj = opts.color === undefined ? undefined : typeof opts.color === 'string' ? makeColor({ rgb: opts.color }) : makeColor(opts.color);\n const outer = makeSide({ style: opts.style, ...(colorObj ? { color: colorObj } : {}) });\n const inner =\n opts.inner !== undefined\n ? makeSide({ style: opts.inner, ...(colorObj ? { color: colorObj } : {}) })\n : undefined;\n for (let r = minRow; r <= maxRow; r++) {\n for (let col = minCol; col <= maxCol; col++) {\n const onTop = r === minRow;\n const onBottom = r === maxRow;\n const onLeft = col === minCol;\n const onRight = col === maxCol;\n // Skip cells that wouldn't get any styling (interior cells when no\n // inner).\n if (!inner && !onTop && !onBottom && !onLeft && !onRight) continue;\n const sides: { -readonly [K in keyof Border]?: Border[K] } = {};\n const top = onTop ? outer : inner;\n const bottom = onBottom ? outer : inner;\n const left = onLeft ? outer : inner;\n const right = onRight ? outer : inner;\n if (top !== undefined) sides.top = top;\n if (bottom !== undefined) sides.bottom = bottom;\n if (left !== undefined) sides.left = left;\n if (right !== undefined) sides.right = right;\n const cell = ensureCell(ws, r, col);\n setCellBorder(wb, cell, makeBorder(sides));\n }\n }\n}\n"],"mappings":";;;AASA,MAAM,oBAAoB,MAAc,UAA4B;CAClE,IAAI,UAAU,QAAQ,OAAO,UAAU,YAAY,MAAM,QAAQ,KAAK,GAAG,OAAO;CAChF,MAAM,MAAM;CACZ,MAAM,OAAO,OAAO,KAAK,GAAG,CAAC,CAAC,KAAK;CACnC,MAAM,MAA+B,CAAC;CACtC,KAAK,MAAM,KAAK,MAAM,IAAI,KAAK,IAAI;CACnC,OAAO;AACT;;;;;;;AAQA,SAAgB,gBAAgB,OAAwB;CACtD,OAAO,KAAK,UAAU,OAAO,gBAAgB;AAC/C;;;ACVA,MAAa,wBAA4D,OAAO,OAAO;CACrF;CACA;C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KAAK,UAAU,KAAA,IAAY,KAAA,IAAY,OAAO,KAAK,UAAU,WAAW,UAAU,EAAE,KAAK,KAAK,MAAM,CAAC,IAAI,UAAU,KAAK,KAAK;CAC9I,MAAM,QAAQ,SAAS;EAAE,OAAO,KAAK;EAAO,GAAI,WAAW,EAAE,OAAO,SAAS,IAAI,CAAC;CAAG,CAAC;CACtF,MAAM,QACJ,KAAK,UAAU,KAAA,IACX,SAAS;EAAE,OAAO,KAAK;EAAO,GAAI,WAAW,EAAE,OAAO,SAAS,IAAI,CAAC;CAAG,CAAC,IACxE,KAAA;CACN,KAAK,IAAI,IAAI,QAAQ,KAAK,QAAQ,KAChC,KAAK,IAAI,MAAM,QAAQ,OAAO,QAAQ,OAAO;EAC3C,MAAM,QAAQ,MAAM;EACpB,MAAM,WAAW,MAAM;EACvB,MAAM,SAAS,QAAQ;EACvB,MAAM,UAAU,QAAQ;EAGxB,IAAI,CAAC,SAAS,CAAC,SAAS,CAAC,YAAY,CAAC,UAAU,CAAC,SAAS;EAC1D,MAAM,QAAuD,CAAC;EAC9D,MAAM,MAAM,QAAQ,QAAQ;EAC5B,MAAM,SAAS,WAAW,QAAQ;EAClC,MAAM,OAAO,SAAS,QAAQ;EAC9B,MAAM,QAAQ,UAAU,QAAQ;EAChC,IAAI,QAAQ,KAAA,GAAW,MAAM,MAAM;EACnC,IAAI,WAAW,KAAA,GAAW,MAAM,SAAS;EACzC,IAAI,SAAS,KAAA,GAAW,MAAM,OAAO;EACrC,IAAI,UAAU,KAAA,GAAW,MAAM,QAAQ;EAEvC,cAAc,IADD,WAAW,IAAI,GAAG,GACV,GAAG,WAAW,KAAK,CAAC;CAC3C;AAEJ"}
@@ -1,4 +1,4 @@
1
- import { en as stableStringify } from "./cell-style-DjKKPWDL.mjs";
1
+ import { tn as stableStringify } from "./cell-style-CbB4nXTY.mjs";
2
2
  //#region src/styles/differential.ts
3
3
  function makeDifferentialStyle(opts = {}) {
4
4
  const out = {};
@@ -34,4 +34,4 @@ function getDxfs(ss) {
34
34
  //#endregion
35
35
  export { getDxfs as n, makeDifferentialStyle as r, addDxf as t };
36
36
 
37
- //# sourceMappingURL=differential-7KGzbliB.mjs.map
37
+ //# sourceMappingURL=differential-QLaKEiBk.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"differential-7KGzbliB.mjs","names":[],"sources":["../src/styles/differential.ts"],"sourcesContent":["// DifferentialStyle (DXF) — partial style overlay used by conditional\n// formatting and Excel-table style elements. Mirrors\n// openpyxl/openpyxl/styles/differential.py.\n//\n// Where a NamedStyle / CellXf carries a *complete* style snapshot, a\n// DifferentialStyle carries only the components that override the base.\n// The Stylesheet keeps DXFs in their own pool (`dxfs`) and conditional-\n// formatting rules / table-style elements reference them by index.\n\nimport { stableStringify } from '../utils/stable-stringify.js';\nimport type { Alignment } from './alignment.js';\nimport type { Border } from './borders.js';\nimport type { Fill } from './fills.js';\nimport type { Font } from './fonts.js';\nimport type { NumberFormat } from './numbers.js';\nimport type { Protection } from './protection.js';\nimport type { Stylesheet } from './stylesheet.js';\n\n/**\n * Differential (\"partial\") style. Every component is optional; only\n * the set fields override the base style of whatever the DXF is\n * applied to.\n */\nexport interface DifferentialStyle {\n readonly font?: Font;\n readonly fill?: Fill;\n readonly border?: Border;\n readonly alignment?: Alignment;\n readonly protection?: Protection;\n /**\n * NumberFormat carries both the id and the format code so DXFs can\n * reference custom user-defined number formats without ambiguity.\n */\n readonly numFmt?: NumberFormat;\n}\n\nexport function makeDifferentialStyle(opts: Partial<DifferentialStyle> = {}): DifferentialStyle {\n const out: { -readonly [K in keyof DifferentialStyle]: DifferentialStyle[K] } = {};\n if (opts.font !== undefined) out.font = opts.font;\n if (opts.fill !== undefined) out.fill = opts.fill;\n if (opts.border !== undefined) out.border = opts.border;\n if (opts.alignment !== undefined) out.alignment = opts.alignment;\n if (opts.protection !== undefined) out.protection = opts.protection;\n if (opts.numFmt !== undefined) out.numFmt = opts.numFmt;\n return Object.freeze(out);\n}\n\n/**\n * Stylesheet pool extension. The DXF list is allocated lazily on first\n * use so empty stylesheets stay slim.\n */\nexport interface StylesheetWithDxfs extends Stylesheet {\n dxfs?: DifferentialStyle[];\n _dxfIdByKey?: Map<string, number>;\n}\n\n/**\n * Add a DifferentialStyle to the stylesheet's `dxfs` pool. Returns\n * the 0-based index. Idempotent on structural equality (via\n * stableStringify).\n */\nexport function addDxf(ss: Stylesheet, dxf: DifferentialStyle): number {\n const w = ss as StylesheetWithDxfs;\n if (w.dxfs === undefined) w.dxfs = [];\n if (w._dxfIdByKey === undefined) w._dxfIdByKey = new Map();\n const key = stableStringify(dxf);\n const cached = w._dxfIdByKey.get(key);\n if (cached !== undefined) return cached;\n const id = w.dxfs.length;\n w.dxfs.push(dxf);\n w._dxfIdByKey.set(key, id);\n return id;\n}\n\n/** Read-only access to the dxfs pool. Returns `[]` when none registered. */\nexport function getDxfs(ss: Stylesheet): ReadonlyArray<DifferentialStyle> {\n return (ss as StylesheetWithDxfs).dxfs ?? [];\n}\n"],"mappings":";;AAoCA,SAAgB,sBAAsB,OAAmC,CAAC,GAAsB;CAC9F,MAAM,MAA0E,CAAC;CACjF,IAAI,KAAK,SAAS,KAAA,GAAW,IAAI,OAAO,KAAK;CAC7C,IAAI,KAAK,SAAS,KAAA,GAAW,IAAI,OAAO,KAAK;CAC7C,IAAI,KAAK,WAAW,KAAA,GAAW,IAAI,SAAS,KAAK;CACjD,IAAI,KAAK,cAAc,KAAA,GAAW,IAAI,YAAY,KAAK;CACvD,IAAI,KAAK,eAAe,KAAA,GAAW,IAAI,aAAa,KAAK;CACzD,IAAI,KAAK,WAAW,KAAA,GAAW,IAAI,SAAS,KAAK;CACjD,OAAO,OAAO,OAAO,GAAG;AAC1B;;;;;;AAgBA,SAAgB,OAAO,IAAgB,KAAgC;CACrE,MAAM,IAAI;CACV,IAAI,EAAE,SAAS,KAAA,GAAW,EAAE,OAAO,CAAC;CACpC,IAAI,EAAE,gBAAgB,KAAA,GAAW,EAAE,8BAAc,IAAI,IAAI;CACzD,MAAM,MAAM,gBAAgB,GAAG;CAC/B,MAAM,SAAS,EAAE,YAAY,IAAI,GAAG;CACpC,IAAI,WAAW,KAAA,GAAW,OAAO;CACjC,MAAM,KAAK,EAAE,KAAK;CAClB,EAAE,KAAK,KAAK,GAAG;CACf,EAAE,YAAY,IAAI,KAAK,EAAE;CACzB,OAAO;AACT;;AAGA,SAAgB,QAAQ,IAAkD;CACxE,OAAQ,GAA0B,QAAQ,CAAC;AAC7C"}
1
+ {"version":3,"file":"differential-QLaKEiBk.mjs","names":[],"sources":["../src/styles/differential.ts"],"sourcesContent":["// DifferentialStyle (DXF) — partial style overlay used by conditional\n// formatting and Excel-table style elements. Mirrors\n// openpyxl/openpyxl/styles/differential.py.\n//\n// Where a NamedStyle / CellXf carries a *complete* style snapshot, a\n// DifferentialStyle carries only the components that override the base.\n// The Stylesheet keeps DXFs in their own pool (`dxfs`) and conditional-\n// formatting rules / table-style elements reference them by index.\n\nimport { stableStringify } from '../utils/stable-stringify.js';\nimport type { Alignment } from './alignment.js';\nimport type { Border } from './borders.js';\nimport type { Fill } from './fills.js';\nimport type { Font } from './fonts.js';\nimport type { NumberFormat } from './numbers.js';\nimport type { Protection } from './protection.js';\nimport type { Stylesheet } from './stylesheet.js';\n\n/**\n * Differential (\"partial\") style. Every component is optional; only\n * the set fields override the base style of whatever the DXF is\n * applied to.\n */\nexport interface DifferentialStyle {\n readonly font?: Font;\n readonly fill?: Fill;\n readonly border?: Border;\n readonly alignment?: Alignment;\n readonly protection?: Protection;\n /**\n * NumberFormat carries both the id and the format code so DXFs can\n * reference custom user-defined number formats without ambiguity.\n */\n readonly numFmt?: NumberFormat;\n}\n\nexport function makeDifferentialStyle(opts: Partial<DifferentialStyle> = {}): DifferentialStyle {\n const out: { -readonly [K in keyof DifferentialStyle]: DifferentialStyle[K] } = {};\n if (opts.font !== undefined) out.font = opts.font;\n if (opts.fill !== undefined) out.fill = opts.fill;\n if (opts.border !== undefined) out.border = opts.border;\n if (opts.alignment !== undefined) out.alignment = opts.alignment;\n if (opts.protection !== undefined) out.protection = opts.protection;\n if (opts.numFmt !== undefined) out.numFmt = opts.numFmt;\n return Object.freeze(out);\n}\n\n/**\n * Stylesheet pool extension. The DXF list is allocated lazily on first\n * use so empty stylesheets stay slim.\n */\nexport interface StylesheetWithDxfs extends Stylesheet {\n dxfs?: DifferentialStyle[];\n _dxfIdByKey?: Map<string, number>;\n}\n\n/**\n * Add a DifferentialStyle to the stylesheet's `dxfs` pool. Returns\n * the 0-based index. Idempotent on structural equality (via\n * stableStringify).\n */\nexport function addDxf(ss: Stylesheet, dxf: DifferentialStyle): number {\n const w = ss as StylesheetWithDxfs;\n if (w.dxfs === undefined) w.dxfs = [];\n if (w._dxfIdByKey === undefined) w._dxfIdByKey = new Map();\n const key = stableStringify(dxf);\n const cached = w._dxfIdByKey.get(key);\n if (cached !== undefined) return cached;\n const id = w.dxfs.length;\n w.dxfs.push(dxf);\n w._dxfIdByKey.set(key, id);\n return id;\n}\n\n/** Read-only access to the dxfs pool. Returns `[]` when none registered. */\nexport function getDxfs(ss: Stylesheet): ReadonlyArray<DifferentialStyle> {\n return (ss as StylesheetWithDxfs).dxfs ?? [];\n}\n"],"mappings":";;AAoCA,SAAgB,sBAAsB,OAAmC,CAAC,GAAsB;CAC9F,MAAM,MAA0E,CAAC;CACjF,IAAI,KAAK,SAAS,KAAA,GAAW,IAAI,OAAO,KAAK;CAC7C,IAAI,KAAK,SAAS,KAAA,GAAW,IAAI,OAAO,KAAK;CAC7C,IAAI,KAAK,WAAW,KAAA,GAAW,IAAI,SAAS,KAAK;CACjD,IAAI,KAAK,cAAc,KAAA,GAAW,IAAI,YAAY,KAAK;CACvD,IAAI,KAAK,eAAe,KAAA,GAAW,IAAI,aAAa,KAAK;CACzD,IAAI,KAAK,WAAW,KAAA,GAAW,IAAI,SAAS,KAAK;CACjD,OAAO,OAAO,OAAO,GAAG;AAC1B;;;;;;AAgBA,SAAgB,OAAO,IAAgB,KAAgC;CACrE,MAAM,IAAI;CACV,IAAI,EAAE,SAAS,KAAA,GAAW,EAAE,OAAO,CAAC;CACpC,IAAI,EAAE,gBAAgB,KAAA,GAAW,EAAE,8BAAc,IAAI,IAAI;CACzD,MAAM,MAAM,gBAAgB,GAAG;CAC/B,MAAM,SAAS,EAAE,YAAY,IAAI,GAAG;CACpC,IAAI,WAAW,KAAA,GAAW,OAAO;CACjC,MAAM,KAAK,EAAE,KAAK;CAClB,EAAE,KAAK,KAAK,GAAG;CACf,EAAE,YAAY,IAAI,KAAK,EAAE;CACzB,OAAO;AACT;;AAGA,SAAgB,QAAQ,IAAkD;CACxE,OAAQ,GAA0B,QAAQ,CAAC;AAC7C"}
package/dist/io/load.d.ts CHANGED
@@ -21,6 +21,8 @@ export interface LoadOptions {
21
21
  }
22
22
  /** Office Document relationship type: the package-root pointer to `xl/workbook.xml`. */
23
23
  export declare const OFFICE_DOC_REL_TYPE = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument";
24
+ /** Root element of `xl/workbook.xml`. Shared with the streaming reader. */
25
+ export declare const WORKBOOK_TAG = "{http://schemas.openxmlformats.org/spreadsheetml/2006/main}workbook";
24
26
  /**
25
27
  * Resolve an OPC relationship target against its source part path.
26
28
  *
package/dist/io.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  import { i as OpenXmlIoError } from "./exceptions-D-CFwxgm.mjs";
2
- import { i as loadWorkbook } from "./load-DIdQ_zum.mjs";
3
- import { n as workbookToBytes, t as saveWorkbook } from "./save-ax11Gsw0.mjs";
2
+ import { a as loadWorkbook } from "./load-BpnCPv1S.mjs";
3
+ import { n as workbookToBytes, t as saveWorkbook } from "./save-1Z3344nz.mjs";
4
4
  //#region src/io/browser.ts
5
5
  /**
6
6
  * Wrap a Blob (or File, since File extends Blob) as an XlsxSource. The
@@ -1,5 +1,5 @@
1
1
  import { o as OpenXmlSchemaError } from "./exceptions-D-CFwxgm.mjs";
2
- import { jt as qname } from "./tree-BX-sRRVp.mjs";
2
+ import { Nt as qname } from "./tree-CspNjuYl.mjs";
3
3
  import { SaxesParser } from "saxes";
4
4
  //#region src/xml/iterparse.ts
5
5
  /**
@@ -184,4 +184,4 @@ async function* iterParse(input) {
184
184
  //#endregion
185
185
  export { iterParse as t };
186
186
 
187
- //# sourceMappingURL=iterparse-DZE0zy2M.mjs.map
187
+ //# sourceMappingURL=iterparse-CZoRXvZW.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"iterparse-DZE0zy2M.mjs","names":[],"sources":["../src/xml/iterparse.ts"],"sourcesContent":["// SAX iterator over OOXML XML payloads. Wraps `saxes` (XMLNS-aware) and yields\n// a flat stream of {start | end | text} events with names already converted to\n// Clark notation (`{ns}local`) — same shape as the DOM parser produces for\n// static XmlNode trees, so consumers can switch between bulk and streaming\n// reads without retouching name comparison.\n//\n// Phase 1 §3 acceptance: 1 k–row sheetData walked end-to-end with cell counts\n// matching the source. The phase-4 read-only worksheet drives real-world use;\n// this layer just produces the events.\n//\n// DOCTYPE / external entity declarations are forbidden. saxes does not expand\n// external entities, and a prescan rejects a declaration before the parser\n// reaches it. A declaration is only legal in the prologue, so that is how far\n// the prescan reads.\n\nimport { SaxesParser } from 'saxes';\nimport { OpenXmlSchemaError } from '../utils/exceptions.js';\nimport { qname } from './namespaces.js';\n\nexport type SaxEvent =\n | { kind: 'start'; name: string; attrs: Record<string, string> }\n | { kind: 'end'; name: string }\n | { kind: 'text'; text: string };\n\n/**\n * Streamable input: `Uint8Array`, plain string, or a Web `ReadableStream` of\n * `Uint8Array` chunks (produced by xlsx zip entries via fflate, fetch, file\n * streams, etc.).\n */\nexport type SaxInput = Uint8Array | string | ReadableStream<Uint8Array>;\n\n/**\n * Recognize declarations only in the prologue, skipping comments and processing\n * instructions. State spans chunks, but retained text is at most one keyword or\n * terminator. Once a root tag begins, saxes handles all remaining syntax checks.\n */\nconst makeDtdScanner = (): ((chunk: string) => void) => {\n let state: 'prologue' | 'markup' | 'comment' | 'pi' | 'done' = 'prologue';\n let token = '';\n return (chunk) => {\n for (const char of chunk) {\n if (state === 'done') return;\n if (state === 'comment' || state === 'pi') {\n const terminator = state === 'comment' ? '-->' : '?>';\n token = (token + char).slice(-terminator.length);\n if (token === terminator) {\n state = 'prologue';\n token = '';\n }\n } else if (state === 'prologue') {\n if (char === '<') {\n state = 'markup';\n token = char;\n }\n } else {\n token += char;\n if (token === '<!--' || token === '<?') {\n state = token === '<!--' ? 'comment' : 'pi';\n token = '';\n } else if (/^<!DOCTYPE[ \\t\\r\\n]$/.test(token)) {\n throw new OpenXmlSchemaError('DTD declarations are not permitted in OOXML payloads');\n } else if (/^<!ENTITY[ \\t\\r\\n]$/.test(token)) {\n throw new OpenXmlSchemaError('Entity declarations are not permitted in OOXML payloads');\n } else if (!'<!--'.startsWith(token) && !'<!DOCTYPE'.startsWith(token) && !'<!ENTITY'.startsWith(token)) {\n // A root name starts here (or invalid markup, which saxes rejects).\n state = 'done';\n token = '';\n }\n }\n }\n };\n};\n\nconst isReadableStream = (v: unknown): v is ReadableStream<Uint8Array> => {\n return typeof v === 'object' && v !== null && typeof (v as ReadableStream).getReader === 'function';\n};\n\nconst decoder = (): TextDecoder => new TextDecoder('utf-8', { fatal: false });\n\n/**\n * Feed size, in code units. saxes runs its handlers synchronously inside\n * `write()`, so one `write()` queues every event its argument produces before\n * the consumer sees any of them. Capping the argument caps the queue.\n *\n * This bounds every input shape, including a `ReadableStream`, whose upstream\n * chunk size is not ours to choose: the zip reader pushes 64 KB of *compressed*\n * bytes per pull, and worksheet XML inflates roughly sevenfold, so its chunks\n * arrive around 450 KB.\n */\nconst FEED_CHUNK_SIZE = 64 * 1024;\n\n/**\n * Split text that exceeds the feed size. Boundaries fall on arbitrary offsets,\n * which is safe because saxes holds back a lone high surrogate at the end of a\n * `write()` and rejoins it with the next one, so a split codepoint still\n * surfaces as a single text event.\n */\nfunction* atFeedSize(text: string): IterableIterator<string> {\n if (text.length === 0) return;\n if (text.length <= FEED_CHUNK_SIZE) {\n yield text;\n return;\n }\n for (let i = 0; i < text.length; i += FEED_CHUNK_SIZE) {\n yield text.slice(i, i + FEED_CHUNK_SIZE);\n }\n}\n\n/**\n * Decode bytes in feed-sized slices. Slicing before the decode rather than\n * after it also bounds the decoder's output string, which matters when the\n * producer hands over a whole part at once. UTF-8 never expands, so a slice of\n * FEED_CHUNK_SIZE bytes decodes to at most that many code units and needs no\n * second split.\n *\n * `stream: true` holds back a codepoint split across a slice boundary instead\n * of emitting a replacement character for each half.\n */\nfunction* decodeAtFeedSize(bytes: Uint8Array, td: TextDecoder): IterableIterator<string> {\n for (let i = 0; i < bytes.byteLength; i += FEED_CHUNK_SIZE) {\n const text = td.decode(bytes.subarray(i, Math.min(i + FEED_CHUNK_SIZE, bytes.byteLength)), { stream: true });\n if (text.length > 0) yield text;\n }\n}\n\n/** Decode any supported input into a sequence of feed-sized text chunks. */\nasync function* decodedChunks(input: SaxInput): AsyncIterableIterator<string> {\n if (typeof input === 'string') {\n yield* atFeedSize(input);\n return;\n }\n const td = decoder();\n if (input instanceof Uint8Array) {\n yield* decodeAtFeedSize(input, td);\n } else if (isReadableStream(input)) {\n const reader = input.getReader();\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n yield* decodeAtFeedSize(value, td);\n }\n } finally {\n // Consumers abandon the iteration routinely (`iterRows({ maxRow })`\n // returns as soon as the band ends). Without this the source stays\n // locked and its `cancel()` never runs, which is what releases the zip\n // reader's inflate state. A cancel that rejects is cleanup on a stream\n // nobody will read again, and must not mask why we left the loop.\n await reader.cancel().catch(() => {});\n reader.releaseLock();\n }\n } else {\n throw new OpenXmlSchemaError('iterParse: unsupported input type');\n }\n const tail = td.decode();\n if (tail.length > 0) yield tail;\n}\n\ninterface SaxesOpenTag {\n name: string;\n uri: string;\n local: string;\n prefix: string;\n attributes: Record<string, { value: string; uri: string; local: string; prefix: string }>;\n isSelfClosing?: boolean;\n}\n\ninterface SaxesCloseTag {\n name: string;\n uri: string;\n local: string;\n prefix: string;\n}\n\nconst buildAttrsClark = (attrs: SaxesOpenTag['attributes']): Record<string, string> => {\n const out: Record<string, string> = {};\n for (const [, info] of Object.entries(attrs)) {\n // saxes already resolved the namespace when xmlns: true is set; raw xmlns /\n // xmlns:* declarations have prefix='xmlns' (or local==='xmlns' when\n // default) and we drop those — they're rebuilt by the serializer.\n if (info.prefix === 'xmlns' || (info.prefix === '' && info.local === 'xmlns')) continue;\n const key = qname(info.uri, info.local);\n out[key] = info.value;\n }\n return out;\n};\n\n/**\n * Parse the input as a stream of SAX events. Element / attribute names are\n * returned in Clark notation (`{ns}local`).\n */\nexport async function* iterParse(input: SaxInput): AsyncIterableIterator<SaxEvent> {\n // Set up the parser. xmlns: true gives us resolved {uri, local, prefix} on\n // every open / close tag and on every attribute.\n const parser = new SaxesParser({ xmlns: true, fragment: false });\n\n // Head-pointer ring instead of Array#shift: each saxes write() can produce\n // hundreds of events in a single synchronous batch (a `<row>` with dozens of\n // cells flushes one opentag + one text + one closetag per cell). `shift()`\n // is O(n) per element in V8, so a single-batch drain of N events would be\n // O(N²) before iteration. The head advances on yield; the queue is reset\n // (head + length) once it drains. Peak depth is one chunk's worth of events,\n // which is what keeps the queue bounded on a multi-GB sheet.\n let queue: SaxEvent[] = [];\n let head = 0;\n let pending: Error | undefined;\n\n parser.on('error', (err: Error) => {\n // saxes reports syntax errors as plain Error; consumers of this library\n // only ever see OpenXmlError subclasses.\n pending = new OpenXmlSchemaError(`Malformed XML: ${err.message}`, { cause: err });\n });\n parser.on('doctype', () => {\n pending = new OpenXmlSchemaError('DTD declarations are not permitted in OOXML payloads');\n });\n parser.on('opentag', (node: SaxesOpenTag) => {\n queue.push({ kind: 'start', name: qname(node.uri, node.local), attrs: buildAttrsClark(node.attributes) });\n });\n parser.on('closetag', (node: SaxesCloseTag) => {\n queue.push({ kind: 'end', name: qname(node.uri, node.local) });\n });\n parser.on('text', (text: string) => {\n if (text.length > 0) queue.push({ kind: 'text', text });\n });\n\n const drain = function* (): IterableIterator<SaxEvent> {\n for (;;) {\n const ev = head < queue.length ? queue[head] : undefined;\n if (ev === undefined) {\n // Reset rather than grow forever; the next batch starts at index 0.\n queue = [];\n head = 0;\n return;\n }\n head++;\n yield ev;\n }\n };\n\n const feed = (chunk: string): void => {\n parser.write(chunk);\n if (pending !== undefined) throw pending;\n };\n\n const scanForDtd = makeDtdScanner();\n for await (const chunk of decodedChunks(input)) {\n scanForDtd(chunk);\n feed(chunk);\n yield* drain();\n }\n\n parser.close();\n if (pending !== undefined) throw pending;\n yield* drain();\n}\n"],"mappings":";;;;;;;;;AAoCA,MAAM,uBAAkD;CACtD,IAAI,QAA2D;CAC/D,IAAI,QAAQ;CACZ,QAAQ,UAAU;EAChB,KAAK,MAAM,QAAQ,OAAO;GACxB,IAAI,UAAU,QAAQ;GACtB,IAAI,UAAU,aAAa,UAAU,MAAM;IACzC,MAAM,aAAa,UAAU,YAAY,QAAQ;IACjD,SAAS,QAAQ,KAAA,CAAM,MAAM,CAAC,WAAW,MAAM;IAC/C,IAAI,UAAU,YAAY;KACxB,QAAQ;KACR,QAAQ;IACV;GACF,OAAO,IAAI,UAAU;QACf,SAAS,KAAK;KAChB,QAAQ;KACR,QAAQ;IACV;UACK;IACL,SAAS;IACT,IAAI,UAAU,UAAU,UAAU,MAAM;KACtC,QAAQ,UAAU,SAAS,YAAY;KACvC,QAAQ;IACV,OAAO,IAAI,uBAAuB,KAAK,KAAK,GAC1C,MAAM,IAAI,mBAAmB,sDAAsD;SAC9E,IAAI,sBAAsB,KAAK,KAAK,GACzC,MAAM,IAAI,mBAAmB,yDAAyD;SACjF,IAAI,CAAC,OAAO,WAAW,KAAK,KAAK,CAAC,YAAY,WAAW,KAAK,KAAK,CAAC,WAAW,WAAW,KAAK,GAAG;KAEvG,QAAQ;KACR,QAAQ;IACV;GACF;EACF;CACF;AACF;AAEA,MAAM,oBAAoB,MAAgD;CACxE,OAAO,OAAO,MAAM,YAAY,MAAM,QAAQ,OAAQ,EAAqB,cAAc;AAC3F;AAEA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AM;CACnC;CAEA,MAAM,aAAa,eAAe;CAClC,WAAW,MAAM,SAAS,cAAc,KAAK,GAAG;EAC9C,WAAW,KAAK;EAChB,KAAK,KAAK;EACV,OAAO,MAAM;CACf;CAEA,OAAO,MAAM;CACb,IAAI,YAAY,KAAA,GAAW,MAAM;CACjC,OAAO,MAAM;AACf"}
1
+ {"version":3,"file":"iterparse-CZoRXvZW.mjs","names":[],"sources":["../src/xml/iterparse.ts"],"sourcesContent":["// SAX iterator over OOXML XML payloads. Wraps `saxes` (XMLNS-aware) and yields\n// a flat stream of {start | end | text} events with names already converted to\n// Clark notation (`{ns}local`) — same shape as the DOM parser produces for\n// static XmlNode trees, so consumers can switch between bulk and streaming\n// reads without retouching name comparison.\n//\n// Phase 1 §3 acceptance: 1 k–row sheetData walked end-to-end with cell counts\n// matching the source. The phase-4 read-only worksheet drives real-world use;\n// this layer just produces the events.\n//\n// DOCTYPE / external entity declarations are forbidden. saxes does not expand\n// external entities, and a prescan rejects a declaration before the parser\n// reaches it. A declaration is only legal in the prologue, so that is how far\n// the prescan reads.\n\nimport { SaxesParser } from 'saxes';\nimport { OpenXmlSchemaError } from '../utils/exceptions.js';\nimport { qname } from './namespaces.js';\n\nexport type SaxEvent =\n | { kind: 'start'; name: string; attrs: Record<string, string> }\n | { kind: 'end'; name: string }\n | { kind: 'text'; text: string };\n\n/**\n * Streamable input: `Uint8Array`, plain string, or a Web `ReadableStream` of\n * `Uint8Array` chunks (produced by xlsx zip entries via fflate, fetch, file\n * streams, etc.).\n */\nexport type SaxInput = Uint8Array | string | ReadableStream<Uint8Array>;\n\n/**\n * Recognize declarations only in the prologue, skipping comments and processing\n * instructions. State spans chunks, but retained text is at most one keyword or\n * terminator. Once a root tag begins, saxes handles all remaining syntax checks.\n */\nconst makeDtdScanner = (): ((chunk: string) => void) => {\n let state: 'prologue' | 'markup' | 'comment' | 'pi' | 'done' = 'prologue';\n let token = '';\n return (chunk) => {\n for (const char of chunk) {\n if (state === 'done') return;\n if (state === 'comment' || state === 'pi') {\n const terminator = state === 'comment' ? '-->' : '?>';\n token = (token + char).slice(-terminator.length);\n if (token === terminator) {\n state = 'prologue';\n token = '';\n }\n } else if (state === 'prologue') {\n if (char === '<') {\n state = 'markup';\n token = char;\n }\n } else {\n token += char;\n if (token === '<!--' || token === '<?') {\n state = token === '<!--' ? 'comment' : 'pi';\n token = '';\n } else if (/^<!DOCTYPE[ \\t\\r\\n]$/.test(token)) {\n throw new OpenXmlSchemaError('DTD declarations are not permitted in OOXML payloads');\n } else if (/^<!ENTITY[ \\t\\r\\n]$/.test(token)) {\n throw new OpenXmlSchemaError('Entity declarations are not permitted in OOXML payloads');\n } else if (!'<!--'.startsWith(token) && !'<!DOCTYPE'.startsWith(token) && !'<!ENTITY'.startsWith(token)) {\n // A root name starts here (or invalid markup, which saxes rejects).\n state = 'done';\n token = '';\n }\n }\n }\n };\n};\n\nconst isReadableStream = (v: unknown): v is ReadableStream<Uint8Array> => {\n return typeof v === 'object' && v !== null && typeof (v as ReadableStream).getReader === 'function';\n};\n\nconst decoder = (): TextDecoder => new TextDecoder('utf-8', { fatal: false });\n\n/**\n * Feed size, in code units. saxes runs its handlers synchronously inside\n * `write()`, so one `write()` queues every event its argument produces before\n * the consumer sees any of them. Capping the argument caps the queue.\n *\n * This bounds every input shape, including a `ReadableStream`, whose upstream\n * chunk size is not ours to choose: the zip reader pushes 64 KB of *compressed*\n * bytes per pull, and worksheet XML inflates roughly sevenfold, so its chunks\n * arrive around 450 KB.\n */\nconst FEED_CHUNK_SIZE = 64 * 1024;\n\n/**\n * Split text that exceeds the feed size. Boundaries fall on arbitrary offsets,\n * which is safe because saxes holds back a lone high surrogate at the end of a\n * `write()` and rejoins it with the next one, so a split codepoint still\n * surfaces as a single text event.\n */\nfunction* atFeedSize(text: string): IterableIterator<string> {\n if (text.length === 0) return;\n if (text.length <= FEED_CHUNK_SIZE) {\n yield text;\n return;\n }\n for (let i = 0; i < text.length; i += FEED_CHUNK_SIZE) {\n yield text.slice(i, i + FEED_CHUNK_SIZE);\n }\n}\n\n/**\n * Decode bytes in feed-sized slices. Slicing before the decode rather than\n * after it also bounds the decoder's output string, which matters when the\n * producer hands over a whole part at once. UTF-8 never expands, so a slice of\n * FEED_CHUNK_SIZE bytes decodes to at most that many code units and needs no\n * second split.\n *\n * `stream: true` holds back a codepoint split across a slice boundary instead\n * of emitting a replacement character for each half.\n */\nfunction* decodeAtFeedSize(bytes: Uint8Array, td: TextDecoder): IterableIterator<string> {\n for (let i = 0; i < bytes.byteLength; i += FEED_CHUNK_SIZE) {\n const text = td.decode(bytes.subarray(i, Math.min(i + FEED_CHUNK_SIZE, bytes.byteLength)), { stream: true });\n if (text.length > 0) yield text;\n }\n}\n\n/** Decode any supported input into a sequence of feed-sized text chunks. */\nasync function* decodedChunks(input: SaxInput): AsyncIterableIterator<string> {\n if (typeof input === 'string') {\n yield* atFeedSize(input);\n return;\n }\n const td = decoder();\n if (input instanceof Uint8Array) {\n yield* decodeAtFeedSize(input, td);\n } else if (isReadableStream(input)) {\n const reader = input.getReader();\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n yield* decodeAtFeedSize(value, td);\n }\n } finally {\n // Consumers abandon the iteration routinely (`iterRows({ maxRow })`\n // returns as soon as the band ends). Without this the source stays\n // locked and its `cancel()` never runs, which is what releases the zip\n // reader's inflate state. A cancel that rejects is cleanup on a stream\n // nobody will read again, and must not mask why we left the loop.\n await reader.cancel().catch(() => {});\n reader.releaseLock();\n }\n } else {\n throw new OpenXmlSchemaError('iterParse: unsupported input type');\n }\n const tail = td.decode();\n if (tail.length > 0) yield tail;\n}\n\ninterface SaxesOpenTag {\n name: string;\n uri: string;\n local: string;\n prefix: string;\n attributes: Record<string, { value: string; uri: string; local: string; prefix: string }>;\n isSelfClosing?: boolean;\n}\n\ninterface SaxesCloseTag {\n name: string;\n uri: string;\n local: string;\n prefix: string;\n}\n\nconst buildAttrsClark = (attrs: SaxesOpenTag['attributes']): Record<string, string> => {\n const out: Record<string, string> = {};\n for (const [, info] of Object.entries(attrs)) {\n // saxes already resolved the namespace when xmlns: true is set; raw xmlns /\n // xmlns:* declarations have prefix='xmlns' (or local==='xmlns' when\n // default) and we drop those — they're rebuilt by the serializer.\n if (info.prefix === 'xmlns' || (info.prefix === '' && info.local === 'xmlns')) continue;\n const key = qname(info.uri, info.local);\n out[key] = info.value;\n }\n return out;\n};\n\n/**\n * Parse the input as a stream of SAX events. Element / attribute names are\n * returned in Clark notation (`{ns}local`).\n */\nexport async function* iterParse(input: SaxInput): AsyncIterableIterator<SaxEvent> {\n // Set up the parser. xmlns: true gives us resolved {uri, local, prefix} on\n // every open / close tag and on every attribute.\n const parser = new SaxesParser({ xmlns: true, fragment: false });\n\n // Head-pointer ring instead of Array#shift: each saxes write() can produce\n // hundreds of events in a single synchronous batch (a `<row>` with dozens of\n // cells flushes one opentag + one text + one closetag per cell). `shift()`\n // is O(n) per element in V8, so a single-batch drain of N events would be\n // O(N²) before iteration. The head advances on yield; the queue is reset\n // (head + length) once it drains. Peak depth is one chunk's worth of events,\n // which is what keeps the queue bounded on a multi-GB sheet.\n let queue: SaxEvent[] = [];\n let head = 0;\n let pending: Error | undefined;\n\n parser.on('error', (err: Error) => {\n // saxes reports syntax errors as plain Error; consumers of this library\n // only ever see OpenXmlError subclasses.\n pending = new OpenXmlSchemaError(`Malformed XML: ${err.message}`, { cause: err });\n });\n parser.on('doctype', () => {\n pending = new OpenXmlSchemaError('DTD declarations are not permitted in OOXML payloads');\n });\n parser.on('opentag', (node: SaxesOpenTag) => {\n queue.push({ kind: 'start', name: qname(node.uri, node.local), attrs: buildAttrsClark(node.attributes) });\n });\n parser.on('closetag', (node: SaxesCloseTag) => {\n queue.push({ kind: 'end', name: qname(node.uri, node.local) });\n });\n parser.on('text', (text: string) => {\n if (text.length > 0) queue.push({ kind: 'text', text });\n });\n\n const drain = function* (): IterableIterator<SaxEvent> {\n for (;;) {\n const ev = head < queue.length ? queue[head] : undefined;\n if (ev === undefined) {\n // Reset rather than grow forever; the next batch starts at index 0.\n queue = [];\n head = 0;\n return;\n }\n head++;\n yield ev;\n }\n };\n\n const feed = (chunk: string): void => {\n parser.write(chunk);\n if (pending !== undefined) throw pending;\n };\n\n const scanForDtd = makeDtdScanner();\n for await (const chunk of decodedChunks(input)) {\n scanForDtd(chunk);\n feed(chunk);\n yield* drain();\n }\n\n parser.close();\n if (pending !== undefined) throw pending;\n yield* drain();\n}\n"],"mappings":";;;;;;;;;AAoCA,MAAM,uBAAkD;CACtD,IAAI,QAA2D;CAC/D,IAAI,QAAQ;CACZ,QAAQ,UAAU;EAChB,KAAK,MAAM,QAAQ,OAAO;GACxB,IAAI,UAAU,QAAQ;GACtB,IAAI,UAAU,aAAa,UAAU,MAAM;IACzC,MAAM,aAAa,UAAU,YAAY,QAAQ;IACjD,SAAS,QAAQ,KAAA,CAAM,MAAM,CAAC,WAAW,MAAM;IAC/C,IAAI,UAAU,YAAY;KACxB,QAAQ;KACR,QAAQ;IACV;GACF,OAAO,IAAI,UAAU;QACf,SAAS,KAAK;KAChB,QAAQ;KACR,QAAQ;IACV;UACK;IACL,SAAS;IACT,IAAI,UAAU,UAAU,UAAU,MAAM;KACtC,QAAQ,UAAU,SAAS,YAAY;KACvC,QAAQ;IACV,OAAO,IAAI,uBAAuB,KAAK,KAAK,GAC1C,MAAM,IAAI,mBAAmB,sDAAsD;SAC9E,IAAI,sBAAsB,KAAK,KAAK,GACzC,MAAM,IAAI,mBAAmB,yDAAyD;SACjF,IAAI,CAAC,OAAO,WAAW,KAAK,KAAK,CAAC,YAAY,WAAW,KAAK,KAAK,CAAC,WAAW,WAAW,KAAK,GAAG;KAEvG,QAAQ;KACR,QAAQ;IACV;GACF;EACF;CACF;AACF;AAEA,MAAM,oBAAoB,MAAgD;CACxE,OAAO,OAAO,MAAM,YAAY,MAAM,QAAQ,OAAQ,EAAqB,cAAc;AAC3F;AAEA,MAAM,gBAA6B,IAAI,YAAY,SAAS,EAAE,OAAO,MAAM,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