@office-open/xlsx 0.7.0 → 0.8.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.
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["localName"],"sources":["../src/file/content-types.ts","../src/file/core-properties.ts","../src/file/media/media.ts","../src/file/shared-strings.ts","../src/file/styles.ts","../src/file/theme.ts","../src/file/workbook.ts","../src/file/worksheet.ts","../src/file/file.ts","../src/file/comments.ts","../src/file/drawing/drawing.ts","../src/file/pivot/pivot-utils.ts","../src/file/pivot/pivot-cache-definition-xml.ts","../src/file/pivot/pivot-cache-records-xml.ts","../src/file/pivot/pivot-table-xml.ts","../src/file/vml-notes.ts","../src/export/packer/next-compiler.ts","../src/export/packer/packer.ts","../src/util/index.ts","../src/parse.ts","../src/patcher.ts"],"sourcesContent":["/**\n * Content Types module for XLSX packages.\n *\n * @module\n */\nimport { BaseXmlComponent } from \"@file/xml-components\";\nimport type { Context } from \"@file/xml-components\";\n\nconst XLSX_MAIN = \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml\";\nconst XLSX_WORKSHEET = \"application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml\";\nconst XLSX_STYLES = \"application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml\";\nconst XLSX_SHARED_STRINGS =\n \"application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml\";\nconst XLSX_THEME = \"application/vnd.openxmlformats-officedocument.theme+xml\";\nconst XLSX_CHART = \"application/vnd.openxmlformats-officedocument.drawingml.chart+xml\";\n\ntype EntryType = \"Default\" | \"Override\";\n\ninterface ContentEntry {\n readonly type: EntryType;\n readonly contentType: string;\n readonly key: string;\n}\n\nconst STATIC_ENTRIES: readonly ContentEntry[] = [\n {\n type: \"Default\",\n contentType: \"application/vnd.openxmlformats-package.relationships+xml\",\n key: \"rels\",\n },\n { type: \"Default\", contentType: \"application/xml\", key: \"xml\" },\n { type: \"Override\", contentType: XLSX_MAIN, key: \"/xl/workbook.xml\" },\n {\n type: \"Override\",\n contentType: \"application/vnd.openxmlformats-package.core-properties+xml\",\n key: \"/docProps/core.xml\",\n },\n {\n type: \"Override\",\n contentType: \"application/vnd.openxmlformats-officedocument.extended-properties+xml\",\n key: \"/docProps/app.xml\",\n },\n];\n\n// Pre-compiled static XML fragment (module-level constant)\nconst STATIC_XML = STATIC_ENTRIES.map((e) =>\n e.type === \"Default\"\n ? `<Default ContentType=\"${e.contentType}\" Extension=\"${e.key}\"/>`\n : `<Override ContentType=\"${e.contentType}\" PartName=\"${e.key}\"/>`,\n).join(\"\");\n\nexport class ContentTypes extends BaseXmlComponent {\n private readonly dynamicEntries: ContentEntry[] = [];\n\n public constructor() {\n super(\"Types\");\n }\n\n public addWorksheet(index: number): void {\n this.dynamicEntries.push({\n type: \"Override\",\n contentType: XLSX_WORKSHEET,\n key: `/xl/worksheets/sheet${index}.xml`,\n });\n }\n\n public addStyles(): void {\n this.dynamicEntries.push({\n type: \"Override\",\n contentType: XLSX_STYLES,\n key: \"/xl/styles.xml\",\n });\n }\n\n public addSharedStrings(): void {\n this.dynamicEntries.push({\n type: \"Override\",\n contentType: XLSX_SHARED_STRINGS,\n key: \"/xl/sharedStrings.xml\",\n });\n }\n\n public addTheme(index: number = 1): void {\n this.dynamicEntries.push({\n type: \"Override\",\n contentType: XLSX_THEME,\n key: `/xl/theme/theme${index}.xml`,\n });\n }\n\n public addChart(index: number): void {\n this.dynamicEntries.push({\n type: \"Override\",\n contentType: XLSX_CHART,\n key: `/xl/charts/chart${index}.xml`,\n });\n }\n\n public addDrawing(index: number): void {\n this.dynamicEntries.push({\n type: \"Override\",\n contentType: \"application/vnd.openxmlformats-officedocument.drawing+xml\",\n key: `/xl/drawings/drawing${index}.xml`,\n });\n }\n\n public addComments(index: number): void {\n this.dynamicEntries.push({\n type: \"Override\",\n contentType: \"application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml\",\n key: `/xl/comments${index}.xml`,\n });\n }\n\n public addVmlDrawing(): void {\n if (this.dynamicEntries.some((e) => e.type === \"Default\" && e.key === \"vml\")) return;\n this.dynamicEntries.push({\n type: \"Default\",\n contentType: \"application/vnd.openxmlformats-officedocument.vmlDrawing\",\n key: \"vml\",\n });\n }\n\n public addImageType(extension: \"png\" | \"jpeg\"): void {\n const contentType = extension === \"png\" ? \"image/png\" : \"image/jpeg\";\n if (this.dynamicEntries.some((e) => e.type === \"Default\" && e.key === extension)) return;\n this.dynamicEntries.push({ type: \"Default\", contentType, key: extension });\n }\n\n public addPivotTable(index: number): void {\n this.dynamicEntries.push({\n type: \"Override\",\n contentType: \"application/vnd.openxmlformats-officedocument.spreadsheetml.pivotTable+xml\",\n key: `/xl/pivotTables/pivotTable${index}.xml`,\n });\n }\n\n public addPivotCacheDefinition(index: number): void {\n this.dynamicEntries.push({\n type: \"Override\",\n contentType:\n \"application/vnd.openxmlformats-officedocument.spreadsheetml.pivotCacheDefinition+xml\",\n key: `/xl/pivotCache/pivotCacheDefinition${index}.xml`,\n });\n }\n\n public addPivotCacheRecords(index: number): void {\n this.dynamicEntries.push({\n type: \"Override\",\n contentType:\n \"application/vnd.openxmlformats-officedocument.spreadsheetml.pivotCacheRecords+xml\",\n key: `/xl/pivotCache/pivotCacheRecords${index}.xml`,\n });\n }\n\n public override toXml(_context: Context): string {\n const p: string[] = [\n '<Types xmlns=\"http://schemas.openxmlformats.org/package/2006/content-types\">',\n STATIC_XML,\n ];\n for (const e of this.dynamicEntries) {\n if (e.type === \"Default\") {\n p.push(`<Default ContentType=\"${e.contentType}\" Extension=\"${e.key}\"/>`);\n } else {\n p.push(`<Override ContentType=\"${e.contentType}\" PartName=\"${e.key}\"/>`);\n }\n }\n p.push(\"</Types>\");\n return p.join(\"\");\n }\n}\n","/**\n * Core Properties module for SpreadsheetML documents.\n *\n * @module\n */\nimport { BaseXmlComponent } from \"@file/xml-components\";\nimport type { Context } from \"@file/xml-components\";\nimport { buildCorePropertiesXmlString } from \"@office-open/core\";\n\nexport interface CorePropertiesOptions {\n readonly title?: string;\n readonly subject?: string;\n readonly creator?: string;\n readonly keywords?: string;\n readonly description?: string;\n readonly lastModifiedBy?: string;\n readonly revision?: number;\n}\n\nexport class CoreProperties extends BaseXmlComponent {\n private readonly options: CorePropertiesOptions;\n\n public constructor(options: CorePropertiesOptions) {\n super(\"cp:coreProperties\");\n this.options = options;\n }\n\n public override toXml(_context: Context): string {\n return buildCorePropertiesXmlString(this.options);\n }\n}\n","/**\n * Media collection for XLSX files — stores image binary data.\n *\n * @module\n */\n\nexport interface MediaData {\n readonly fileName: string;\n readonly type: string;\n readonly data: Uint8Array;\n readonly width: number;\n readonly height: number;\n}\n\nexport class Media {\n private readonly map = new Map<string, MediaData>();\n\n public addImage(key: string, data: MediaData): void {\n this.map.set(key, data);\n }\n\n public get array(): readonly MediaData[] {\n return [...this.map.values()];\n }\n}\n","/**\n * Shared Strings Table — generates xl/sharedStrings.xml.\n *\n * XLSX stores repeated string values in a central table to reduce file size.\n * Cells reference strings by index into this table.\n *\n * @module\n */\nimport { BaseXmlComponent } from \"@file/xml-components\";\nimport type { Context } from \"@file/xml-components\";\nimport { escapeXml } from \"@office-open/xml\";\n\nexport class SharedStrings extends BaseXmlComponent {\n private readonly strings: string[] = [];\n private readonly indexMap = new Map<string, number>();\n\n public constructor() {\n super(\"sst\");\n }\n\n /**\n * Register a string and return its index.\n * Returns existing index if the string is already registered.\n */\n public register(s: string): number {\n const existing = this.indexMap.get(s);\n if (existing !== undefined) return existing;\n\n const idx = this.strings.length;\n this.strings.push(s);\n this.indexMap.set(s, idx);\n return idx;\n }\n\n public get count(): number {\n return this.strings.length;\n }\n\n /**\n * Zero-allocation fast path: directly concatenate XML string.\n * Bypasses the IXmlableObject intermediate tree entirely.\n */\n public override toXml(_context: Context): string {\n const p: string[] = [\n '<sst xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\"',\n ` count=\"${this.strings.length}\" uniqueCount=\"${this.indexMap.size}\">`,\n ];\n for (const s of this.strings) {\n p.push(`<si><t>${escapeXml(s)}</t></si>`);\n }\n p.push(\"</sst>\");\n return p.join(\"\");\n }\n}\n","/**\n * Styles component — generates xl/styles.xml.\n *\n * XLSX uses an index-based style system: cells reference style entries\n * via the `s` attribute, which is an index into `cellXfs`.\n *\n * @module\n */\nimport { BaseXmlComponent } from \"@file/xml-components\";\nimport type { Context } from \"@file/xml-components\";\nimport { attrs, escapeXml } from \"@office-open/xml\";\n\n// ── Sub-style option interfaces ──\n\nexport interface FontOptions {\n readonly bold?: boolean;\n readonly italic?: boolean;\n readonly underline?: boolean;\n readonly strike?: boolean;\n readonly size?: number;\n readonly color?: string;\n readonly fontName?: string;\n}\n\nexport interface FillOptions {\n readonly type?: \"solid\" | \"pattern\";\n readonly color?: string;\n readonly patternType?: string;\n}\n\nexport interface BorderOptions {\n readonly style?: \"thin\" | \"medium\" | \"thick\" | \"dotted\" | \"dashed\" | \"hair\" | \"none\";\n readonly color?: string;\n}\n\nexport interface BorderSideOptions {\n readonly top?: BorderOptions;\n readonly bottom?: BorderOptions;\n readonly left?: BorderOptions;\n readonly right?: BorderOptions;\n readonly diagonal?: BorderOptions;\n}\n\nexport interface AlignmentOptions {\n readonly horizontal?: \"left\" | \"center\" | \"right\" | \"fill\" | \"justify\";\n readonly vertical?: \"top\" | \"center\" | \"bottom\";\n readonly wrapText?: boolean;\n readonly textRotation?: number;\n readonly indent?: number;\n}\n\nexport interface StyleOptions {\n readonly font?: FontOptions;\n readonly fill?: FillOptions;\n readonly border?: BorderSideOptions;\n readonly numFmt?: string;\n readonly alignment?: AlignmentOptions;\n}\n\n/** Differential format — used by conditional formatting to specify what changes. */\nexport interface DxfOptions {\n readonly font?: FontOptions;\n readonly fill?: FillOptions;\n readonly border?: BorderSideOptions;\n readonly numFmt?: string;\n}\n\n// ── Style key helpers for deduplication ──\n\nfunction fontKey(f: FontOptions): string {\n return `b${f.bold ? 1 : 0}i${f.italic ? 1 : 0}u${f.underline ? 1 : 0}s${f.strike ? 1 : 0}z${f.size ?? 0}c${f.color ?? \"\"}n${f.fontName ?? \"\"}`;\n}\n\nfunction fillKey(f: FillOptions): string {\n return `t${f.type ?? \"\"}c${f.color ?? \"\"}p${f.patternType ?? \"\"}`;\n}\n\nfunction borderKey(b: BorderSideOptions): string {\n const sk = (o?: BorderOptions) => `${o?.style ?? \"\"}_${o?.color ?? \"\"}`;\n return `t${sk(b.top)}b${sk(b.bottom)}l${sk(b.left)}r${sk(b.right)}d${sk(b.diagonal)}`;\n}\n\n// ── Built-in number format IDs ──\n\nconst BUILTIN_NUMFMTS: Record<string, number> = {\n General: 0,\n \"0\": 1,\n \"0.00\": 2,\n \"#,##0\": 3,\n \"#,##0.00\": 4,\n \"0%\": 9,\n \"0.00%\": 10,\n \"0.00E+00\": 11,\n \"mm-dd-yy\": 14,\n \"d-mmm-yy\": 15,\n \"d-mmm\": 16,\n \"mmm-yy\": 17,\n \"h:mm AM/PM\": 18,\n \"h:mm:ss AM/PM\": 19,\n \"h:mm\": 20,\n \"h:mm:ss\": 21,\n \"m/d/yy h:mm\": 22,\n \"#,##0 ;(#,##0)\": 37,\n \"#,##0 ;[Red](#,##0)\": 38,\n \"#,##0.00;(#,##0.00)\": 39,\n \"#,##0.00;[Red](#,##0.00)\": 40,\n \"mm:ss\": 45,\n \"[h]:mm:ss\": 46,\n \"mmss.0\": 47,\n \"##0.0E+0\": 48,\n \"@\": 49,\n};\n\nexport class Styles extends BaseXmlComponent {\n private readonly fonts: FontOptions[] = [\n { size: 11, fontName: \"Calibri\" }, // default font (index 0)\n ];\n private readonly fontKeys = new Map<string, number>();\n\n private readonly fills: FillOptions[] = [\n { patternType: \"none\" }, // default fill (index 0)\n { patternType: \"gray125\" }, // required fill (index 1)\n ];\n private readonly fillKeys = new Map<string, number>();\n\n private readonly borders: BorderSideOptions[] = [\n {}, // default empty border (index 0)\n ];\n private readonly borderKeys = new Map<string, number>();\n\n private readonly customNumFmts = new Map<string, number>();\n private nextCustomNumFmtId = 164; // custom numFmts start at 164\n\n private readonly cellXfs: Array<{\n readonly fontId: number;\n readonly fillId: number;\n readonly borderId: number;\n readonly numFmtId: number;\n readonly alignment?: AlignmentOptions;\n }> = [\n { fontId: 0, fillId: 0, borderId: 0, numFmtId: 0 }, // default xf (index 0)\n ];\n private readonly cellXfKeys = new Map<string, number>();\n\n private readonly dxfs: DxfOptions[] = [];\n\n public constructor() {\n super(\"styleSheet\");\n\n // Pre-register default font/fill/border keys\n this.fontKeys.set(fontKey(this.fonts[0]), 0);\n this.fillKeys.set(fillKey(this.fills[0]), 0);\n this.fillKeys.set(fillKey(this.fills[1]), 1);\n this.borderKeys.set(borderKey(this.borders[0]), 0);\n this.cellXfKeys.set(this.cellXfKey(this.cellXfs[0]), 0);\n }\n\n /**\n * Register a style and return its index (for the cell `s` attribute).\n * Deduplicates across fonts, fills, borders, numFmts, and cellXfs.\n */\n public register(opts: StyleOptions): number {\n const fontId = this.registerFont(opts.font);\n const fillId = this.registerFill(opts.fill);\n const borderId = this.registerBorder(opts.border);\n const numFmtId = this.registerNumFmt(opts.numFmt);\n\n const xf = {\n fontId,\n fillId,\n borderId,\n numFmtId,\n alignment: opts.alignment,\n };\n\n const key = this.cellXfKey(xf);\n const existing = this.cellXfKeys.get(key);\n if (existing !== undefined) return existing;\n\n const idx = this.cellXfs.length;\n this.cellXfs.push(xf);\n this.cellXfKeys.set(key, idx);\n return idx;\n }\n\n /**\n * Register a differential format and return its index (dxfId).\n * Used by conditional formatting rules.\n */\n public registerDxf(opts: DxfOptions): number {\n const idx = this.dxfs.length;\n this.dxfs.push(opts);\n return idx;\n }\n\n private registerFont(opts?: FontOptions): number {\n if (!opts) return 0;\n const key = fontKey(opts);\n const existing = this.fontKeys.get(key);\n if (existing !== undefined) return existing;\n\n const idx = this.fonts.length;\n this.fonts.push(opts);\n this.fontKeys.set(key, idx);\n return idx;\n }\n\n private registerFill(opts?: FillOptions): number {\n if (!opts) return 0;\n const key = fillKey(opts);\n const existing = this.fillKeys.get(key);\n if (existing !== undefined) return existing;\n\n const idx = this.fills.length;\n this.fills.push(opts);\n this.fillKeys.set(key, idx);\n return idx;\n }\n\n private registerBorder(opts?: BorderSideOptions): number {\n if (!opts) return 0;\n const key = borderKey(opts);\n const existing = this.borderKeys.get(key);\n if (existing !== undefined) return existing;\n\n const idx = this.borders.length;\n this.borders.push(opts);\n this.borderKeys.set(key, idx);\n return idx;\n }\n\n private registerNumFmt(fmt?: string): number {\n if (!fmt) return 0;\n const builtin = BUILTIN_NUMFMTS[fmt];\n if (builtin !== undefined) return builtin;\n\n const existing = this.customNumFmts.get(fmt);\n if (existing !== undefined) return existing;\n\n const id = this.nextCustomNumFmtId++;\n this.customNumFmts.set(fmt, id);\n return id;\n }\n\n private cellXfKey(xf: {\n readonly fontId: number;\n readonly fillId: number;\n readonly borderId: number;\n readonly numFmtId: number;\n readonly alignment?: AlignmentOptions;\n }): string {\n const a = xf.alignment;\n const ak = a\n ? `h${a.horizontal ?? \"\"}v${a.vertical ?? \"\"}w${a.wrapText ? 1 : 0}r${a.textRotation ?? \"\"}i${a.indent ?? \"\"}`\n : \"\";\n return `${xf.fontId}|${xf.fillId}|${xf.borderId}|${xf.numFmtId}|${ak}`;\n }\n\n // ── XML generation ──\n\n /**\n * Zero-allocation fast path: directly concatenate XML string.\n * Bypasses the IXmlableObject intermediate tree entirely.\n */\n public override toXml(_context: Context): string {\n const p: string[] = [\n '<styleSheet xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\">',\n ];\n\n // numFmts\n if (this.customNumFmts.size > 0) {\n p.push(`<numFmts count=\"${this.customNumFmts.size}\">`);\n for (const [fmt, id] of this.customNumFmts) {\n p.push(`<numFmt numFmtId=\"${id}\" formatCode=\"${escapeXml(fmt)}\"/>`);\n }\n p.push(\"</numFmts>\");\n }\n\n // fonts\n p.push(`<fonts count=\"${this.fonts.length}\">`);\n for (const f of this.fonts) {\n p.push(`<font>${this.fontXmlStr(f)}</font>`);\n }\n p.push(\"</fonts>\");\n\n // fills\n p.push(`<fills count=\"${this.fills.length}\">`);\n for (const f of this.fills) {\n const patternAttrs = attrs({ patternType: f.patternType ?? \"solid\" });\n const fgColor = f.color ? `<fgColor rgb=\"FF${f.color}\"/>` : \"\";\n p.push(\n fgColor\n ? `<fill><patternFill${patternAttrs}>${fgColor}</patternFill></fill>`\n : `<fill><patternFill${patternAttrs}/></fill>`,\n );\n }\n p.push(\"</fills>\");\n\n // borders\n p.push(`<borders count=\"${this.borders.length}\">`);\n for (const b of this.borders) {\n p.push(`<border>${this.borderXmlStr(b)}</border>`);\n }\n p.push(\"</borders>\");\n\n // cellStyleXfs\n p.push(\n '<cellStyleXfs count=\"1\"><xf numFmtId=\"0\" fontId=\"0\" fillId=\"0\" borderId=\"0\"/></cellStyleXfs>',\n );\n\n // cellXfs\n p.push(`<cellXfs count=\"${this.cellXfs.length}\">`);\n for (const xf of this.cellXfs) {\n const xAttrs: Record<string, string | number | boolean | undefined> = {\n numFmtId: xf.numFmtId,\n fontId: xf.fontId,\n fillId: xf.fillId,\n borderId: xf.borderId,\n xfId: 0,\n };\n if (xf.alignment) xAttrs.applyAlignment = 1;\n if (xf.fontId > 0) xAttrs.applyFont = 1;\n if (xf.fillId > 0) xAttrs.applyFill = 1;\n if (xf.borderId > 0) xAttrs.applyBorder = 1;\n\n const alignStr = xf.alignment ? this.alignmentXmlStr(xf.alignment) : \"\";\n p.push(alignStr ? `<xf${attrs(xAttrs)}>${alignStr}</xf>` : `<xf${attrs(xAttrs)}/>`);\n }\n p.push(\"</cellXfs>\");\n\n // cellStyles\n p.push('<cellStyles count=\"1\"><cellStyle name=\"Normal\" xfId=\"0\" builtinId=\"0\"/></cellStyles>');\n\n // dxfs\n if (this.dxfs.length > 0) {\n p.push(`<dxfs count=\"${this.dxfs.length}\">`);\n for (const dxf of this.dxfs) {\n const dParts: string[] = [];\n if (dxf.font) dParts.push(`<font>${this.fontXmlStr(dxf.font)}</font>`);\n if (dxf.fill) {\n const bgColor = dxf.fill.color ? `<bgColor rgb=\"FF${dxf.fill.color}\"/>` : \"\";\n const patAttrs = attrs({ patternType: dxf.fill.patternType ?? \"solid\" });\n dParts.push(`<fill><patternFill${patAttrs}>${bgColor}</patternFill></fill>`);\n }\n if (dxf.numFmt) dParts.push(`<numFmt formatCode=\"${escapeXml(dxf.numFmt)}\"/>`);\n if (dParts.length > 0) {\n p.push(`<dxf>${dParts.join(\"\")}</dxf>`);\n } else {\n p.push(\"<dxf/>\");\n }\n }\n p.push(\"</dxfs>\");\n } else {\n p.push('<dxfs count=\"0\"/>');\n }\n p.push(\n '<tableStyles count=\"0\" defaultTableStyle=\"TableStyleMedium2\" defaultPivotStyle=\"PivotStyleLight16\"/>',\n );\n p.push(\"<extLst/>\");\n\n p.push(\"</styleSheet>\");\n return p.join(\"\");\n }\n\n private fontXmlStr(f: FontOptions): string {\n const parts: string[] = [];\n if (f.bold) parts.push(\"<b/>\");\n if (f.italic) parts.push(\"<i/>\");\n if (f.underline) parts.push(\"<u/>\");\n if (f.strike) parts.push(\"<strike/>\");\n if (f.size) parts.push(`<sz val=\"${f.size}\"/>`);\n if (f.color) parts.push(`<color rgb=\"FF${f.color}\"/>`);\n if (f.fontName) parts.push(`<name val=\"${escapeXml(f.fontName)}\"/>`);\n return parts.join(\"\");\n }\n\n private borderXmlStr(b: BorderSideOptions): string {\n const parts: string[] = [];\n for (const side of [\"left\", \"right\", \"top\", \"bottom\", \"diagonal\"] as const) {\n const opts = b[side] as BorderOptions | undefined;\n if (opts && opts.style && opts.style !== \"none\") {\n const colorStr = opts.color ? `<color rgb=\"FF${opts.color}\"/>` : \"\";\n parts.push(`<${side} style=\"${opts.style}\">${colorStr}</${side}>`);\n } else {\n parts.push(`<${side}/>`);\n }\n }\n return parts.join(\"\");\n }\n\n private alignmentXmlStr(a: AlignmentOptions): string {\n const aAttrs: Record<string, string | number | boolean | undefined> = {};\n if (a.horizontal) aAttrs.horizontal = a.horizontal;\n if (a.vertical) aAttrs.vertical = a.vertical;\n if (a.wrapText) aAttrs.wrapText = 1;\n if (a.textRotation !== undefined) aAttrs.textRotation = a.textRotation;\n if (a.indent !== undefined) aAttrs.indent = a.indent;\n return `<alignment${attrs(aAttrs)}/>`;\n }\n}\n","/**\n * Default theme for XLSX files — matches Microsoft Office's output structure.\n * Produces xl/theme/theme1.xml that Excel accepts without repair warnings.\n *\n * The theme XML is completely static — identical for every XLSX file.\n * Pre-serialized as a string constant to avoid building the IXmlableObject\n * tree and re-serializing on every compile.\n *\n * @module\n */\nimport { BaseXmlComponent } from \"@file/xml-components\";\nimport type { Context } from \"@file/xml-components\";\n\n// Pre-serialized theme XML. Generated once via xml(buildThemeObj()) and inlined.\n// To regenerate: run `pnpm tsx scripts/gen-theme.ts` from packages/xlsx.\nconst THEME_XML =\n '<a:theme xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\" name=\"Office Theme\"><a:themeElements><a:clrScheme name=\"Office\"><a:dk1><a:sysClr val=\"windowText\" lastClr=\"000000\"/></a:dk1><a:lt1><a:sysClr val=\"window\" lastClr=\"FFFFFF\"/></a:lt1><a:dk2><a:srgbClr val=\"44546A\"/></a:dk2><a:lt2><a:srgbClr val=\"E7E6E6\"/></a:lt2><a:accent1><a:srgbClr val=\"5B9BD5\"/></a:accent1><a:accent2><a:srgbClr val=\"ED7D31\"/></a:accent2><a:accent3><a:srgbClr val=\"A5A5A5\"/></a:accent3><a:accent4><a:srgbClr val=\"FFC000\"/></a:accent4><a:accent5><a:srgbClr val=\"4472C4\"/></a:accent5><a:accent6><a:srgbClr val=\"70AD47\"/></a:accent6><a:hlink><a:srgbClr val=\"0563C1\"/></a:hlink><a:folHlink><a:srgbClr val=\"954F72\"/></a:folHlink></a:clrScheme><a:fontScheme name=\"Office\"><a:majorFont><a:latin typeface=\"Calibri Light\" panose=\"020F0302020204030204\"/><a:ea typeface=\"\"/><a:cs typeface=\"\"/></a:majorFont><a:minorFont><a:latin typeface=\"Calibri\" panose=\"020F0502020204030204\"/><a:ea typeface=\"\"/><a:cs typeface=\"\"/></a:minorFont></a:fontScheme><a:fmtScheme name=\"Office\"><a:fillStyleLst><a:solidFill><a:schemeClr val=\"phClr\"/></a:solidFill><a:gradFill rotWithShape=\"1\"><a:gsLst><a:gs pos=\"0\"><a:schemeClr val=\"phClr\"><a:lumMod val=\"110000\"/><a:satMod val=\"105000\"/><a:tint val=\"67000\"/></a:schemeClr></a:gs><a:gs pos=\"50000\"><a:schemeClr val=\"phClr\"><a:lumMod val=\"105000\"/><a:satMod val=\"103000\"/><a:tint val=\"73000\"/></a:schemeClr></a:gs><a:gs pos=\"100000\"><a:schemeClr val=\"phClr\"><a:lumMod val=\"105000\"/><a:satMod val=\"109000\"/><a:tint val=\"81000\"/></a:schemeClr></a:gs></a:gsLst><a:lin ang=\"5400000\" scaled=\"0\"/></a:gradFill><a:gradFill rotWithShape=\"1\"><a:gsLst><a:gs pos=\"0\"><a:schemeClr val=\"phClr\"><a:lumMod val=\"102000\"/><a:satMod val=\"103000\"/><a:tint val=\"94000\"/></a:schemeClr></a:gs><a:gs pos=\"50000\"><a:schemeClr val=\"phClr\"><a:lumMod val=\"100000\"/><a:satMod val=\"110000\"/><a:shade val=\"100000\"/></a:schemeClr></a:gs><a:gs pos=\"100000\"><a:schemeClr val=\"phClr\"><a:lumMod val=\"99000\"/><a:satMod val=\"120000\"/><a:shade val=\"78000\"/></a:schemeClr></a:gs></a:gsLst><a:lin ang=\"5400000\" scaled=\"0\"/></a:gradFill></a:fillStyleLst><a:lnStyleLst><a:ln w=\"6350\" cap=\"flat\" cmpd=\"sng\" algn=\"ctr\"><a:solidFill><a:schemeClr val=\"phClr\"/></a:solidFill><a:prstDash val=\"solid\"/><a:miter lim=\"800000\"/></a:ln><a:ln w=\"12700\" cap=\"flat\" cmpd=\"sng\" algn=\"ctr\"><a:solidFill><a:schemeClr val=\"phClr\"/></a:solidFill><a:prstDash val=\"solid\"/><a:miter lim=\"800000\"/></a:ln><a:ln w=\"19050\" cap=\"flat\" cmpd=\"sng\" algn=\"ctr\"><a:solidFill><a:schemeClr val=\"phClr\"/></a:solidFill><a:prstDash val=\"solid\"/><a:miter lim=\"800000\"/></a:ln></a:lnStyleLst><a:effectStyleLst><a:effectStyle><a:effectLst/></a:effectStyle><a:effectStyle><a:effectLst/></a:effectStyle><a:effectStyle><a:effectLst><a:outerShdw blurRad=\"57150\" dist=\"19050\" dir=\"5400000\" algn=\"ctr\" rotWithShape=\"0\"><a:srgbClr val=\"000000\"><a:alpha val=\"63000\"/></a:srgbClr></a:outerShdw></a:effectLst></a:effectStyle></a:effectStyleLst><a:bgFillStyleLst><a:solidFill><a:schemeClr val=\"phClr\"/></a:solidFill><a:solidFill><a:schemeClr val=\"phClr\"><a:tint val=\"95000\"/><a:satMod val=\"170000\"/></a:schemeClr></a:solidFill><a:gradFill rotWithShape=\"1\"><a:gsLst><a:gs pos=\"0\"><a:schemeClr val=\"phClr\"><a:lumMod val=\"102000\"/><a:satMod val=\"150000\"/><a:tint val=\"93000\"/><a:shade val=\"98000\"/></a:schemeClr></a:gs><a:gs pos=\"50000\"><a:schemeClr val=\"phClr\"><a:lumMod val=\"103000\"/><a:satMod val=\"130000\"/><a:tint val=\"98000\"/><a:shade val=\"90000\"/></a:schemeClr></a:gs><a:gs pos=\"100000\"><a:schemeClr val=\"phClr\"><a:satMod val=\"120000\"/><a:shade val=\"63000\"/></a:schemeClr></a:gs></a:gsLst><a:lin ang=\"5400000\" scaled=\"0\"/></a:gradFill></a:bgFillStyleLst></a:fmtScheme></a:themeElements><a:objectDefaults/><a:extraClrSchemeLst/></a:theme>';\n\nexport class DefaultTheme extends BaseXmlComponent {\n public constructor() {\n super(\"a:theme\");\n }\n\n /** Return pre-cached static theme XML — zero allocation. */\n public override toXml(_context: Context): string {\n return THEME_XML;\n }\n}\n","/**\n * Workbook component — generates xl/workbook.xml.\n *\n * @module\n */\nimport { BaseXmlComponent } from \"@file/xml-components\";\nimport type { Context } from \"@file/xml-components\";\nimport { escapeXml } from \"@office-open/xml\";\n\nexport interface SheetDefinition {\n readonly name: string;\n readonly sheetId: number;\n readonly rId: string;\n readonly state?: \"visible\" | \"hidden\" | \"veryHidden\";\n}\n\nexport interface PivotCacheReference {\n readonly cacheId: number;\n readonly rId: string;\n}\n\nexport class WorkbookXml extends BaseXmlComponent {\n private readonly sheets: readonly SheetDefinition[];\n private readonly pivotCaches: readonly PivotCacheReference[];\n\n public constructor(\n sheets: readonly SheetDefinition[],\n pivotCaches?: readonly PivotCacheReference[],\n ) {\n super(\"workbook\");\n this.sheets = sheets;\n this.pivotCaches = pivotCaches ?? [];\n }\n\n public override toXml(_context: Context): string {\n const p: string[] = [\n '<workbook xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\"' +\n ' xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\"' +\n ' xmlns:mc=\"http://schemas.openxmlformats.org/markup-compatibility/2006\"' +\n ' mc:Ignorable=\"x15 xr xr6 xr10 xr2\"' +\n ' xmlns:x15=\"http://schemas.microsoft.com/office/spreadsheetml/2010/11/main\"' +\n ' xmlns:xr=\"http://schemas.microsoft.com/office/spreadsheetml/2014/revision\"' +\n ' xmlns:xr6=\"http://schemas.microsoft.com/office/spreadsheetml/2016/revision6\"' +\n ' xmlns:xr10=\"http://schemas.microsoft.com/office/spreadsheetml/2016/revision10\"' +\n ' xmlns:xr2=\"http://schemas.microsoft.com/office/spreadsheetml/2015/revision2\">',\n '<fileVersion appName=\"xl\" lastEdited=\"7\" lowestEdited=\"6\" rupBuild=\"29929\"/>',\n \"<workbookPr/>\",\n '<bookViews><workbookView xWindow=\"0\" yWindow=\"0\" windowWidth=\"28800\" windowHeight=\"12300\"/></bookViews>',\n \"<sheets>\",\n ];\n for (const s of this.sheets) {\n const stateAttr = s.state && s.state !== \"visible\" ? ` state=\"${s.state}\"` : \"\";\n p.push(\n `<sheet name=\"${escapeXml(s.name)}\" sheetId=\"${s.sheetId}\" r:id=\"${s.rId}\"${stateAttr}/>`,\n );\n }\n p.push(\"</sheets>\");\n\n p.push('<calcPr calcId=\"162913\"/>');\n\n if (this.pivotCaches.length > 0) {\n p.push(\"<pivotCaches>\");\n for (const pc of this.pivotCaches) {\n p.push(`<pivotCache cacheId=\"${pc.cacheId}\" r:id=\"${pc.rId}\"/>`);\n }\n p.push(\"</pivotCaches>\");\n }\n\n p.push(\"</workbook>\");\n return p.join(\"\");\n }\n}\n","import type { SharedStrings } from \"@file/shared-strings\";\nimport type { Styles, StyleOptions } from \"@file/styles\";\n/**\n * Worksheet component — generates xl/worksheets/sheet{n}.xml.\n *\n * @module\n */\nimport { IgnoreIfEmptyXmlComponent } from \"@file/xml-components\";\nimport type { Context } from \"@file/xml-components\";\nimport type { ChartSpaceOptions } from \"@office-open/core\";\nimport { attrs, escapeXml, selfCloseElement } from \"@office-open/xml\";\n\nimport type { PivotTableOptions } from \"./pivot\";\n\nexport interface ColumnOptions {\n readonly min: number;\n readonly max: number;\n readonly width?: number;\n readonly hidden?: boolean;\n readonly customWidth?: boolean;\n readonly outlineLevel?: number;\n readonly collapsed?: boolean;\n}\n\nexport interface RowOptions {\n readonly cells?: readonly CellOptions[];\n readonly height?: number;\n readonly hidden?: boolean;\n readonly rowNumber?: number;\n}\n\nexport interface CellOptions {\n readonly value?: string | number | boolean | Date | null;\n readonly reference?: string;\n /** Direct style index (for pre-resolved styles) */\n readonly styleIndex?: number;\n /** Style options (resolved to index at compile time) */\n readonly style?: StyleOptions;\n /** Formula options. When set, value becomes the cached result. */\n readonly formula?: FormulaOptions;\n}\n\n/** Cell formula type (maps to ST_CellFormulaType). */\nexport const FormulaType = {\n NORMAL: \"normal\",\n ARRAY: \"array\",\n SHARED: \"shared\",\n} as const;\n\nexport type FormulaType = (typeof FormulaType)[keyof typeof FormulaType];\n\n/** Options for a cell formula (maps to CT_CellFormula). */\nexport interface FormulaOptions {\n /** Formula expression, e.g. \"SUM(A1:B1)\" */\n readonly formula: string;\n /** Formula type (default: \"normal\") */\n readonly type?: FormulaType;\n /** Reference range for array/shared formulas, e.g. \"C1:C10\" */\n readonly reference?: string;\n /** Shared formula group index (required for shared formulas) */\n readonly sharedIndex?: number;\n}\n\nexport interface MergeCellOptions {\n readonly from: { readonly row: number; readonly col: number };\n readonly to: { readonly row: number; readonly col: number };\n}\n\nexport interface SheetProtectionOptions {\n /** Plain-text password — legacy Excel hash is computed automatically */\n readonly password?: string;\n /** Set true to enable sheet protection (required for protection flags to take effect) */\n readonly sheet?: boolean;\n readonly objects?: boolean;\n readonly scenarios?: boolean;\n readonly formatCells?: boolean;\n readonly formatColumns?: boolean;\n readonly formatRows?: boolean;\n readonly insertColumns?: boolean;\n readonly insertRows?: boolean;\n readonly insertHyperlinks?: boolean;\n readonly deleteColumns?: boolean;\n readonly deleteRows?: boolean;\n readonly selectLockedCells?: boolean;\n readonly sort?: boolean;\n readonly autoFilter?: boolean;\n readonly pivotTables?: boolean;\n readonly selectUnlockedCells?: boolean;\n}\n\nexport interface FreezePaneOptions {\n /** Row split position (1-based, freezes rows above) */\n readonly row?: number;\n /** Column split position (1-based, freezes columns to the left) */\n readonly col?: number;\n}\n\nexport interface WorksheetImageOptions {\n readonly data: Uint8Array;\n readonly type: \"png\" | \"jpeg\" | \"jpg\";\n readonly col: number;\n readonly row: number;\n}\n\nexport interface WorksheetChartOptions extends ChartSpaceOptions {\n /** 1-based column position for the chart */\n readonly col: number;\n /** 1-based row position for the chart */\n readonly row: number;\n}\n\nexport interface SheetViewOptions {\n readonly showGridLines?: boolean;\n readonly showRowColHeaders?: boolean;\n readonly showZeros?: boolean;\n readonly zoomScale?: number;\n readonly tabSelected?: boolean;\n readonly rightToLeft?: boolean;\n}\n\nexport type HyperlinkTarget =\n | { readonly type: \"external\"; readonly url: string }\n | { readonly type: \"internal\"; readonly location: string };\n\nexport interface HyperlinkOptions {\n /** Cell reference, e.g. \"A1\" */\n readonly cell: string;\n /** Hyperlink target */\n readonly target: HyperlinkTarget;\n /** Tooltip text */\n readonly tooltip?: string;\n /** Display text */\n readonly display?: string;\n}\n\nexport interface HeaderFooterOptions {\n readonly oddHeader?: string;\n readonly oddFooter?: string;\n readonly evenHeader?: string;\n readonly evenFooter?: string;\n readonly firstHeader?: string;\n readonly firstFooter?: string;\n readonly differentOddEven?: boolean;\n readonly differentFirst?: boolean;\n}\n\nexport type PageOrientation = \"default\" | \"portrait\" | \"landscape\";\n\nexport interface PageSetupOptions {\n readonly paperSize?: number;\n readonly orientation?: PageOrientation;\n readonly scale?: number;\n readonly fitToWidth?: number;\n readonly fitToHeight?: number;\n readonly pageOrder?: \"downThenOver\" | \"overThenDown\";\n readonly useFirstPageNumber?: boolean;\n readonly firstPageNumber?: number;\n}\n\nexport interface TabColorOptions {\n /** RGB color string, e.g. \"FF0000\" */\n readonly rgb?: string;\n /** Theme color index (0-based) */\n readonly theme?: number;\n /** Tint value (-1.0 to 1.0) */\n readonly tint?: number;\n}\n\nexport interface CommentOptions {\n /** Cell reference, e.g. \"A1\" */\n readonly cell: string;\n /** Author name */\n readonly author: string;\n /** Comment text */\n readonly text: string;\n}\n\nexport type DataValidationType =\n | \"none\"\n | \"whole\"\n | \"decimal\"\n | \"list\"\n | \"date\"\n | \"time\"\n | \"textLength\"\n | \"custom\";\nexport type DataValidationOperator =\n | \"between\"\n | \"notBetween\"\n | \"equal\"\n | \"notEqual\"\n | \"greaterThan\"\n | \"lessThan\"\n | \"greaterThanOrEqual\"\n | \"lessThanOrEqual\";\n\nexport interface DataValidationOptions {\n /** Cell range, e.g. \"A1:A10\" */\n readonly sqref: string;\n readonly type?: DataValidationType;\n readonly operator?: DataValidationOperator;\n readonly formula1?: string;\n readonly formula2?: string;\n readonly allowBlank?: boolean;\n readonly showErrorMessage?: boolean;\n readonly errorTitle?: string;\n readonly error?: string;\n readonly showInputMessage?: boolean;\n readonly promptTitle?: string;\n readonly prompt?: string;\n}\n\nexport type ConditionalFormatType =\n | \"cellIs\"\n | \"containsText\"\n | \"expression\"\n | \"top10\"\n | \"aboveAverage\";\nexport type ConditionalFormatOperator =\n | \"lessThan\"\n | \"lessThanOrEqual\"\n | \"equal\"\n | \"notEqual\"\n | \"greaterThanOrEqual\"\n | \"greaterThan\"\n | \"between\"\n | \"notBetween\"\n | \"containsText\"\n | \"notContains\"\n | \"beginsWith\"\n | \"endsWith\";\n\nexport interface ConditionalFormatRule {\n readonly type: ConditionalFormatType;\n readonly operator?: ConditionalFormatOperator;\n /** Formula(s) — up to 3 */\n readonly formulas?: readonly string[];\n readonly priority?: number;\n /** Reference to a dxf (differential format) in the styles table */\n readonly dxfId?: number;\n}\n\nexport interface ConditionalFormatOptions {\n /** Cell range, e.g. \"A1:A10\" */\n readonly sqref: string;\n readonly rules: readonly ConditionalFormatRule[];\n}\n\nexport interface Top10FilterOptions {\n readonly colId: number;\n readonly top?: boolean;\n readonly percent?: boolean;\n readonly val: number;\n}\n\nexport interface CustomFilterOptions {\n readonly colId: number;\n readonly operator?:\n | \"equal\"\n | \"notEqual\"\n | \"greaterThan\"\n | \"greaterThanOrEqual\"\n | \"lessThan\"\n | \"lessThanOrEqual\";\n readonly val?: string;\n readonly and?: boolean;\n readonly val2?: string;\n}\n\nexport interface SortCondition {\n /** Cell reference for the sort column, e.g. \"B1\" */\n readonly ref: string;\n readonly descending?: boolean;\n}\n\nexport interface AutoFilterOptions {\n /** Range, e.g. \"A1:D10\" */\n readonly ref: string;\n readonly top10?: readonly Top10FilterOptions[];\n readonly customFilters?: readonly CustomFilterOptions[];\n readonly sort?: readonly SortCondition[];\n}\n\nexport interface WorksheetOptions {\n readonly name?: string;\n readonly rows?: readonly RowOptions[];\n readonly columns?: readonly ColumnOptions[];\n readonly mergeCells?: readonly MergeCellOptions[];\n readonly freezePanes?: FreezePaneOptions;\n readonly protection?: SheetProtectionOptions;\n /** Auto-filter configuration */\n readonly autoFilter?: string | AutoFilterOptions;\n readonly images?: readonly WorksheetImageOptions[];\n readonly charts?: readonly WorksheetChartOptions[];\n readonly dataValidations?: readonly DataValidationOptions[];\n readonly conditionalFormats?: readonly ConditionalFormatOptions[];\n readonly hyperlinks?: readonly HyperlinkOptions[];\n readonly comments?: readonly CommentOptions[];\n readonly headerFooter?: HeaderFooterOptions;\n readonly pageSetup?: PageSetupOptions;\n readonly tabColor?: TabColorOptions;\n readonly sheetView?: SheetViewOptions;\n readonly pivotTables?: readonly PivotTableOptions[];\n}\n\nexport class Worksheet extends IgnoreIfEmptyXmlComponent {\n private readonly rows: readonly RowOptions[];\n private readonly columns: readonly ColumnOptions[];\n private readonly mergeCells: readonly MergeCellOptions[];\n private readonly freezePanes?: FreezePaneOptions;\n private readonly protection?: SheetProtectionOptions;\n private readonly autoFilter?: string | AutoFilterOptions;\n private readonly images: readonly WorksheetImageOptions[];\n private readonly chartOptions: readonly WorksheetChartOptions[];\n private readonly dataValidations: readonly DataValidationOptions[];\n private readonly conditionalFormats: readonly ConditionalFormatOptions[];\n private readonly hyperlinks: readonly HyperlinkOptions[];\n private readonly comments: readonly CommentOptions[];\n private readonly headerFooter?: HeaderFooterOptions;\n private readonly pageSetup?: PageSetupOptions;\n private readonly tabColor?: TabColorOptions;\n private readonly sheetView?: SheetViewOptions;\n private readonly pivotTableOptions: readonly PivotTableOptions[];\n\n public constructor(options: WorksheetOptions) {\n super(\"worksheet\");\n this.rows = options.rows ?? [];\n this.columns = options.columns ?? [];\n this.mergeCells = options.mergeCells ?? [];\n this.freezePanes = options.freezePanes;\n this.protection = options.protection;\n this.autoFilter = options.autoFilter;\n this.images = options.images ?? [];\n this.chartOptions = options.charts ?? [];\n this.dataValidations = options.dataValidations ?? [];\n this.conditionalFormats = options.conditionalFormats ?? [];\n this.hyperlinks = options.hyperlinks ?? [];\n this.comments = options.comments ?? [];\n this.headerFooter = options.headerFooter;\n this.pageSetup = options.pageSetup;\n this.tabColor = options.tabColor;\n this.sheetView = options.sheetView;\n this.pivotTableOptions = options.pivotTables ?? [];\n }\n\n public get imageOptions(): readonly WorksheetImageOptions[] {\n return this.images;\n }\n\n public get charts(): readonly WorksheetChartOptions[] {\n return this.chartOptions;\n }\n\n public get hyperlinkOptions(): readonly HyperlinkOptions[] {\n return this.hyperlinks;\n }\n\n public get worksheetRows(): readonly RowOptions[] {\n return this.rows;\n }\n\n public get commentOptions(): readonly CommentOptions[] {\n return this.comments;\n }\n\n public get pivotTables(): readonly PivotTableOptions[] {\n return this.pivotTableOptions;\n }\n\n /**\n * Zero-allocation fast path: directly concatenate XML string.\n * Bypasses the IXmlableObject intermediate tree entirely.\n */\n public override toXml(context: Context): string {\n const fileData = context.fileData as\n | { sharedStrings?: SharedStrings; styles?: Styles }\n | undefined;\n const sharedStrings = fileData?.sharedStrings;\n const styles = fileData?.styles;\n\n const p: string[] = [\n '<worksheet xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\"' +\n ' xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\"' +\n ' xmlns:mc=\"http://schemas.openxmlformats.org/markup-compatibility/2006\"' +\n ' mc:Ignorable=\"x14ac xr xr2 xr3\"' +\n ' xmlns:x14ac=\"http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac\"' +\n ' xmlns:xr=\"http://schemas.microsoft.com/office/spreadsheetml/2014/revision\"' +\n ' xmlns:xr2=\"http://schemas.microsoft.com/office/spreadsheetml/2015/revision2\"' +\n ' xmlns:xr3=\"http://schemas.microsoft.com/office/spreadsheetml/2016/revision3\">',\n ];\n\n // Sheet properties (tabColor, outlinePr go here)\n const hasTabColor = !!this.tabColor;\n const hasOutline = this.columns.some((c) => c.outlineLevel !== undefined);\n if (hasTabColor || hasOutline) {\n const prParts: string[] = [];\n if (this.tabColor) {\n const tc = this.tabColor;\n const tcAttrs: Record<string, string | number | boolean | undefined> = {};\n if (tc.rgb) tcAttrs.rgb = tc.rgb;\n if (tc.theme !== undefined) tcAttrs.theme = tc.theme;\n if (tc.tint !== undefined) tcAttrs.tint = tc.tint;\n prParts.push(`<tabColor${attrs(tcAttrs)}/>`);\n }\n if (hasOutline) {\n prParts.push('<outlinePr summaryBelow=\"1\" summaryRight=\"1\"/>');\n }\n p.push(`<sheetPr>${prParts.join(\"\")}</sheetPr>`);\n }\n\n // Dimension — defines the used range of the sheet\n const maxRow = this.rows.length;\n let maxCol = 0;\n for (const row of this.rows) {\n if (row.cells && row.cells.length > maxCol) maxCol = row.cells.length;\n }\n if (maxRow > 0 && maxCol > 0) {\n const dimRef = `A1:${this.defaultCellRef(maxRow, maxCol)}`;\n p.push(`<dimension ref=\"${dimRef}\"/>`);\n }\n\n // Sheet views\n if (this.freezePanes) {\n const fp = this.freezePanes;\n const ySplit = fp.row ? fp.row : 0;\n const xSplit = fp.col ? fp.col : 0;\n const topRow = fp.row ? fp.row + 1 : 1;\n const leftCol = fp.col ? fp.col + 1 : 1;\n const topLeftCell = this.defaultCellRef(topRow, leftCol);\n const activePane =\n ySplit > 0 && xSplit > 0 ? \"bottomRight\" : ySplit > 0 ? \"bottomLeft\" : \"topRight\";\n const svAttrs = this.buildSheetViewAttrs();\n p.push(\n `<sheetViews><sheetView${svAttrs}>`,\n `<pane ySplit=\"${ySplit}\" xSplit=\"${xSplit}\" topLeftCell=\"${topLeftCell}\" activePane=\"${activePane}\" state=\"frozen\"/>`,\n \"</sheetView></sheetViews>\",\n );\n } else {\n const svAttrs = this.buildSheetViewAttrs();\n p.push(`<sheetViews><sheetView${svAttrs}/></sheetViews>`);\n }\n\n // Sheet format — default row height\n p.push('<sheetFormatPr defaultRowHeight=\"15\"/>');\n\n // Column definitions\n if (this.columns.length > 0) {\n p.push(\"<cols>\");\n for (const col of this.columns) {\n const colAttrs: Record<string, string | number | boolean | undefined> = {\n min: col.min,\n max: col.max,\n };\n if (col.width !== undefined) {\n colAttrs.width = col.width;\n colAttrs.customWidth = 1;\n }\n if (col.hidden) {\n colAttrs.hidden = 1;\n }\n if (col.outlineLevel !== undefined) {\n colAttrs.outlineLevel = col.outlineLevel;\n }\n if (col.collapsed) {\n colAttrs.collapsed = 1;\n }\n p.push(selfCloseElement(\"col\", attrs(colAttrs)));\n }\n p.push(\"</cols>\");\n }\n\n // Sheet data (rows + cells) — the hot path\n p.push(\"<sheetData>\");\n for (let i = 0; i < this.rows.length; i++) {\n const rowOpts = this.rows[i];\n const rowNumber = rowOpts.rowNumber ?? i + 1;\n const rowAttrs: Record<string, string | number | boolean | undefined> = { r: rowNumber };\n if (rowOpts.height !== undefined) {\n rowAttrs.ht = rowOpts.height;\n rowAttrs.customHeight = 1;\n }\n if (rowOpts.hidden) {\n rowAttrs.hidden = 1;\n }\n\n if (rowOpts.cells) {\n const rowParts: string[] = [];\n for (let j = 0; j < rowOpts.cells.length; j++) {\n const cell = rowOpts.cells[j];\n const ref = cell.reference ?? this.defaultCellRef(rowNumber, j + 1);\n const cellStr = this.buildCellString(ref, cell, sharedStrings, styles);\n if (cellStr) rowParts.push(cellStr);\n }\n p.push(`<row${attrs(rowAttrs)}>`, ...rowParts, \"</row>\");\n } else {\n p.push(`<row${attrs(rowAttrs)}/>`);\n }\n }\n p.push(\"</sheetData>\");\n\n // Sheet protection (before autoFilter per XSD sequence)\n if (this.protection) {\n const prot = this.protection;\n const protAttrs: Record<string, string | number | boolean | undefined> = {};\n if (prot.password) protAttrs.password = this.hashPassword(prot.password);\n if (prot.sheet) protAttrs.sheet = 1;\n if (prot.objects) protAttrs.objects = 1;\n if (prot.scenarios) protAttrs.scenarios = 1;\n if (prot.formatCells === false) protAttrs.formatCells = 0;\n if (prot.formatColumns === false) protAttrs.formatColumns = 0;\n if (prot.formatRows === false) protAttrs.formatRows = 0;\n if (prot.insertColumns === false) protAttrs.insertColumns = 0;\n if (prot.insertRows === false) protAttrs.insertRows = 0;\n if (prot.insertHyperlinks === false) protAttrs.insertHyperlinks = 0;\n if (prot.deleteColumns === false) protAttrs.deleteColumns = 0;\n if (prot.deleteRows === false) protAttrs.deleteRows = 0;\n if (prot.selectLockedCells) protAttrs.selectLockedCells = 1;\n if (prot.sort === false) protAttrs.sort = 0;\n if (prot.autoFilter === false) protAttrs.autoFilter = 0;\n if (prot.pivotTables === false) protAttrs.pivotTables = 0;\n if (prot.selectUnlockedCells) protAttrs.selectUnlockedCells = 1;\n p.push(selfCloseElement(\"sheetProtection\", attrs(protAttrs)));\n }\n\n // Auto filter\n if (this.autoFilter) {\n if (typeof this.autoFilter === \"string\") {\n p.push(selfCloseElement(\"autoFilter\", attrs({ ref: this.autoFilter })));\n } else {\n const af = this.autoFilter;\n const inner: string[] = [];\n for (const t10 of af.top10 ?? []) {\n const t10Attrs: Record<string, string | number | boolean | undefined> = { val: t10.val };\n if (t10.top === false) t10Attrs.top = 0;\n if (t10.percent) t10Attrs.percent = 1;\n inner.push(\n `<filterColumn colId=\"${t10.colId}\"><top10${attrs(t10Attrs)}/></filterColumn>`,\n );\n }\n for (const cf of af.customFilters ?? []) {\n const cfAttrs: Record<string, string | number | boolean | undefined> = {};\n if (cf.and) cfAttrs.and = 1;\n const filters: string[] = [];\n if (cf.val !== undefined) {\n const fAttrs: Record<string, string | number | boolean | undefined> = { val: cf.val };\n if (cf.operator) fAttrs.operator = cf.operator;\n filters.push(selfCloseElement(\"customFilter\", attrs(fAttrs)));\n }\n if (cf.val2 !== undefined) {\n filters.push(selfCloseElement(\"customFilter\", attrs({ val: cf.val2 })));\n }\n if (filters.length > 0) {\n inner.push(\n `<filterColumn colId=\"${cf.colId}\"><customFilters${attrs(cfAttrs)}>${filters.join(\"\")}</customFilters></filterColumn>`,\n );\n }\n }\n if (af.sort && af.sort.length > 0) {\n const sortParts: string[] = [];\n for (const sc of af.sort) {\n const scAttrs: Record<string, string | number | boolean | undefined> = { ref: sc.ref };\n if (sc.descending) scAttrs.descending = 1;\n sortParts.push(selfCloseElement(\"sortCondition\", attrs(scAttrs)));\n }\n inner.push(`<sortState ref=\"${af.ref}\">${sortParts.join(\"\")}</sortState>`);\n }\n if (inner.length > 0) {\n p.push(`<autoFilter ref=\"${af.ref}\">`, ...inner, \"</autoFilter>\");\n } else {\n p.push(selfCloseElement(\"autoFilter\", attrs({ ref: af.ref })));\n }\n }\n }\n\n // Merge cells\n if (this.mergeCells.length > 0) {\n p.push(`<mergeCells count=\"${this.mergeCells.length}\">`);\n for (const mc of this.mergeCells) {\n const fromRef = this.defaultCellRef(mc.from.row, mc.from.col);\n const toRef = this.defaultCellRef(mc.to.row, mc.to.col);\n p.push(selfCloseElement(\"mergeCell\", attrs({ ref: `${fromRef}:${toRef}` })));\n }\n p.push(\"</mergeCells>\");\n }\n\n // Conditional formatting\n if (this.conditionalFormats.length > 0) {\n for (const cf of this.conditionalFormats) {\n p.push(`<conditionalFormatting sqref=\"${cf.sqref}\">`);\n for (let ri = 0; ri < cf.rules.length; ri++) {\n const rule = cf.rules[ri];\n const ruleAttrs: Record<string, string | number | boolean | undefined> = {\n type: rule.type,\n priority: rule.priority ?? ri + 1,\n };\n if (rule.operator) ruleAttrs.operator = rule.operator;\n if (rule.dxfId !== undefined) ruleAttrs.dxfId = rule.dxfId;\n if (rule.formulas && rule.formulas.length > 0) {\n const formulaParts = rule.formulas.map((f) => `<formula>${escapeXml(f)}</formula>`);\n p.push(`<cfRule${attrs(ruleAttrs)}>`, ...formulaParts, \"</cfRule>\");\n } else {\n p.push(selfCloseElement(\"cfRule\", attrs(ruleAttrs)));\n }\n }\n p.push(\"</conditionalFormatting>\");\n }\n }\n\n // Data validations\n if (this.dataValidations.length > 0) {\n p.push(`<dataValidations count=\"${this.dataValidations.length}\">`);\n for (const dv of this.dataValidations) {\n const dvAttrs: Record<string, string | number | boolean | undefined> = { sqref: dv.sqref };\n if (dv.type && dv.type !== \"none\") dvAttrs.type = dv.type;\n if (dv.operator) dvAttrs.operator = dv.operator;\n if (dv.allowBlank) dvAttrs.allowBlank = 1;\n if (dv.showErrorMessage) dvAttrs.showErrorMessage = 1;\n if (dv.showInputMessage) dvAttrs.showInputMessage = 1;\n if (dv.errorTitle) dvAttrs.errorTitle = dv.errorTitle;\n if (dv.error) dvAttrs.error = dv.error;\n if (dv.promptTitle) dvAttrs.promptTitle = dv.promptTitle;\n if (dv.prompt) dvAttrs.prompt = dv.prompt;\n const inner: string[] = [];\n if (dv.formula1 !== undefined) inner.push(`<formula1>${escapeXml(dv.formula1)}</formula1>`);\n if (dv.formula2 !== undefined) inner.push(`<formula2>${escapeXml(dv.formula2)}</formula2>`);\n if (inner.length > 0) {\n p.push(`<dataValidation${attrs(dvAttrs)}>`, ...inner, \"</dataValidation>\");\n } else {\n p.push(selfCloseElement(\"dataValidation\", attrs(dvAttrs)));\n }\n }\n p.push(\"</dataValidations>\");\n }\n\n // Hyperlinks — r:id numbering must match worksheet rels order (compiler handles rels)\n if (this.hyperlinks.length > 0) {\n p.push(\"<hyperlinks>\");\n let hlIdx = 0;\n for (const hl of this.hyperlinks) {\n const hlAttrs: Record<string, string | number | boolean | undefined> = { ref: hl.cell };\n if (hl.target.type === \"external\") {\n hlIdx++;\n hlAttrs[\"r:id\"] = `rId${hlIdx}`;\n } else {\n hlAttrs.location = hl.target.location;\n }\n if (hl.tooltip) hlAttrs.tooltip = hl.tooltip;\n if (hl.display) hlAttrs.display = hl.display;\n p.push(selfCloseElement(\"hyperlink\", attrs(hlAttrs)));\n }\n p.push(\"</hyperlinks>\");\n }\n\n p.push('<pageMargins left=\"0.75\" right=\"0.75\" top=\"1\" bottom=\"1\" header=\"0.5\" footer=\"0.5\"/>');\n\n // Page setup\n if (this.pageSetup) {\n const ps = this.pageSetup;\n const psAttrs: Record<string, string | number | boolean | undefined> = {};\n if (ps.paperSize !== undefined) psAttrs.paperSize = ps.paperSize;\n if (ps.orientation && ps.orientation !== \"default\") psAttrs.orientation = ps.orientation;\n if (ps.scale !== undefined) psAttrs.scale = ps.scale;\n if (ps.fitToWidth !== undefined) psAttrs.fitToWidth = ps.fitToWidth;\n if (ps.fitToHeight !== undefined) psAttrs.fitToHeight = ps.fitToHeight;\n if (ps.pageOrder && ps.pageOrder !== \"downThenOver\") psAttrs.pageOrder = ps.pageOrder;\n if (ps.useFirstPageNumber) psAttrs.useFirstPageNumber = 1;\n if (ps.firstPageNumber !== undefined) psAttrs.firstPageNumber = ps.firstPageNumber;\n p.push(selfCloseElement(\"pageSetup\", attrs(psAttrs)));\n }\n\n // Header/footer\n if (this.headerFooter) {\n const hf = this.headerFooter;\n const hfAttrs: Record<string, string | number | boolean | undefined> = {};\n if (hf.differentOddEven) hfAttrs.differentOddEven = 1;\n if (hf.differentFirst) hfAttrs.differentFirst = 1;\n const inner: string[] = [];\n if (hf.oddHeader) inner.push(`<oddHeader>${escapeXml(hf.oddHeader)}</oddHeader>`);\n if (hf.oddFooter) inner.push(`<oddFooter>${escapeXml(hf.oddFooter)}</oddFooter>`);\n if (hf.evenHeader) inner.push(`<evenHeader>${escapeXml(hf.evenHeader)}</evenHeader>`);\n if (hf.evenFooter) inner.push(`<evenFooter>${escapeXml(hf.evenFooter)}</evenFooter>`);\n if (hf.firstHeader) inner.push(`<firstHeader>${escapeXml(hf.firstHeader)}</firstHeader>`);\n if (hf.firstFooter) inner.push(`<firstFooter>${escapeXml(hf.firstFooter)}</firstFooter>`);\n if (inner.length > 0) {\n p.push(`<headerFooter${attrs(hfAttrs)}>`, ...inner, \"</headerFooter>\");\n } else if (hfAttrs.differentOddEven || hfAttrs.differentFirst) {\n p.push(selfCloseElement(\"headerFooter\", attrs(hfAttrs)));\n }\n }\n\n p.push(\"</worksheet>\");\n return p.join(\"\");\n }\n\n private buildSheetViewAttrs(): string {\n const sv = this.sheetView;\n const svMap: Record<string, string | number | boolean | undefined> = {\n workbookViewId: 0,\n };\n if (sv?.tabSelected !== undefined) svMap.tabSelected = sv.tabSelected ? 1 : 0;\n else svMap.tabSelected = 1;\n if (sv?.showGridLines === false) svMap.showGridLines = 0;\n if (sv?.showRowColHeaders === false) svMap.showRowColHeaders = 0;\n if (sv?.showZeros === false) svMap.showZeros = 0;\n if (sv?.zoomScale !== undefined) svMap.zoomScale = sv.zoomScale;\n if (sv?.rightToLeft) svMap.rightToLeft = 1;\n return attrs(svMap);\n }\n\n /**\n * Excel legacy password hash (16-bit, little-endian hex).\n * Matches the algorithm used by ECMA-376 Part 1, §18.2.27.\n */\n private hashPassword(password: string): string {\n let hash = 0;\n for (let i = 0; i < password.length; i++) {\n const c = password.charCodeAt(i);\n hash = ((hash >> 14) & 1) + ((hash << 1) & 0x7fff);\n hash ^= c;\n hash = hash & 0x4000 ? hash ^ 0x1 : hash;\n }\n hash = ((hash >> 14) & 1) + ((hash << 1) & 0x7fff);\n hash = ((hash >> 14) & 1) + ((hash << 1) & 0x7fff);\n hash ^= password.length;\n return hash.toString(16).toUpperCase().padStart(4, \"0\");\n }\n\n /**\n * Build the <f> element string for a cell formula.\n */\n private buildFormulaString(fOpts: FormulaOptions): string {\n const fAttrs: Record<string, string | number | boolean | undefined> = {};\n if (fOpts.type && fOpts.type !== FormulaType.NORMAL) fAttrs.t = fOpts.type;\n if (fOpts.reference) fAttrs.ref = fOpts.reference;\n if (fOpts.sharedIndex !== undefined) fAttrs.si = fOpts.sharedIndex;\n\n const hasContent = fOpts.formula !== undefined && fOpts.formula !== \"\";\n\n if (hasContent) {\n return `<f${attrs(fAttrs)}>${escapeXml(fOpts.formula)}</f>`;\n }\n if (Object.keys(fAttrs).length > 0) {\n return selfCloseElement(\"f\", attrs(fAttrs));\n }\n return \"\";\n }\n\n /**\n * Direct string serialization of a single cell — zero intermediate objects.\n */\n private buildCellString(\n ref: string,\n cell: CellOptions,\n sharedStrings?: SharedStrings,\n styles?: Styles,\n ): string {\n const cellAttrs: Record<string, string | number | boolean | undefined> = { r: ref };\n\n // Resolve style\n if (cell.style !== undefined && styles) {\n cellAttrs.s = styles.register(cell.style);\n } else if (cell.styleIndex !== undefined) {\n cellAttrs.s = cell.styleIndex;\n }\n\n const value = cell.value;\n\n // Formula path — formula takes precedence; value is the cached result.\n if (cell.formula) {\n const fStr = this.buildFormulaString(cell.formula);\n let vStr = \"\";\n if (value === null || value === undefined) {\n return `<c${attrs(cellAttrs)}>${fStr}</c>`;\n }\n if (typeof value === \"number\") {\n vStr = `<v>${value}</v>`;\n } else if (typeof value === \"boolean\") {\n cellAttrs.t = \"b\";\n vStr = `<v>${value ? 1 : 0}</v>`;\n } else if (typeof value === \"string\") {\n cellAttrs.t = \"str\";\n vStr = `<v>${escapeXml(value)}</v>`;\n } else if (value instanceof Date) {\n vStr = `<v>${this.dateToSerialNumber(value)}</v>`;\n }\n if (vStr) {\n return `<c${attrs(cellAttrs)}>${fStr}${vStr}</c>`;\n }\n return `<c${attrs(cellAttrs)}>${fStr}</c>`;\n }\n\n if (value === null || value === undefined) {\n if (cell.styleIndex !== undefined) {\n return selfCloseElement(\"c\", attrs(cellAttrs));\n }\n return \"\";\n }\n\n if (typeof value === \"string\") {\n if (sharedStrings) {\n cellAttrs.t = \"s\";\n const idx = sharedStrings.register(value);\n return `<c${attrs(cellAttrs)}><v>${idx}</v></c>`;\n }\n cellAttrs.t = \"inlineStr\";\n return `<c${attrs(cellAttrs)}><is><t>${escapeXml(value)}</t></is></c>`;\n }\n\n if (typeof value === \"number\") {\n return `<c${attrs(cellAttrs)}><v>${value}</v></c>`;\n }\n\n if (typeof value === \"boolean\") {\n cellAttrs.t = \"b\";\n return `<c${attrs(cellAttrs)}><v>${value ? 1 : 0}</v></c>`;\n }\n\n if (value instanceof Date) {\n const serial = this.dateToSerialNumber(value);\n return `<c${attrs(cellAttrs)}><v>${serial}</v></c>`;\n }\n\n return \"\";\n }\n\n private defaultCellRef(row: number, col: number): string {\n return this.columnToLetter(col) + row;\n }\n\n private columnToLetter(col: number): string {\n let result = \"\";\n let n = col;\n while (n > 0) {\n const remainder = (n - 1) % 26;\n result = String.fromCharCode(65 + remainder) + result;\n n = Math.floor((n - 1) / 26);\n }\n return result;\n }\n\n private dateToSerialNumber(date: Date): number {\n const epoch = new Date(1899, 11, 30);\n const msPerDay = 86400000;\n return (date.getTime() - epoch.getTime()) / msPerDay;\n }\n}\n","import { ContentTypes } from \"@file/content-types\";\nimport { CoreProperties, type CorePropertiesOptions } from \"@file/core-properties\";\nimport { Media } from \"@file/media/media\";\nimport { SharedStrings } from \"@file/shared-strings\";\nimport { Styles } from \"@file/styles\";\nimport type { DxfOptions } from \"@file/styles\";\nimport { DefaultTheme } from \"@file/theme\";\nimport { WorkbookXml, type SheetDefinition, type PivotCacheReference } from \"@file/workbook\";\nimport { Worksheet, type WorksheetOptions } from \"@file/worksheet\";\n/**\n * File class (exported as Workbook) — the top-level container for XLSX documents.\n *\n * @module\n */\nimport { AppProperties, ChartCollection, Relationships } from \"@office-open/core\";\n\nexport interface WorkbookOptions extends CorePropertiesOptions {\n readonly worksheets?: readonly WorksheetOptions[];\n /** Pre-defined differential formats for conditional formatting */\n readonly dxfs?: readonly DxfOptions[];\n}\n\nexport class File {\n private readonly worksheetOptions: readonly WorksheetOptions[];\n private readonly corePropsOptions: CorePropertiesOptions;\n private readonly dxfOptions: readonly DxfOptions[];\n\n // Lazy components\n private _coreProperties?: CoreProperties;\n private _appProperties?: AppProperties;\n private _contentTypes?: ContentTypes;\n private _styles?: Styles;\n private _theme?: DefaultTheme;\n private _workbookXml?: WorkbookXml;\n private _worksheets?: Worksheet[];\n private _sharedStrings?: SharedStrings;\n private _media?: Media;\n private _fileRels?: Relationships;\n private _workbookRels?: Relationships;\n private _charts?: ChartCollection;\n private _pivotCacheRefs: PivotCacheReference[] = [];\n\n public constructor(options: WorkbookOptions) {\n this.worksheetOptions = options.worksheets ?? [];\n this.corePropsOptions = options;\n this.dxfOptions = options.dxfs ?? [];\n }\n\n // ── Lazy getters ──\n\n public get coreProperties(): CoreProperties {\n return (this._coreProperties ??= new CoreProperties(this.corePropsOptions));\n }\n\n public get appProperties(): AppProperties {\n return (this._appProperties ??= new AppProperties());\n }\n\n public get contentTypes(): ContentTypes {\n if (!this._contentTypes) {\n this._contentTypes = new ContentTypes();\n for (let i = 0; i < this.worksheetOptions.length; i++) {\n this._contentTypes.addWorksheet(i + 1);\n }\n this._contentTypes.addStyles();\n this._contentTypes.addSharedStrings();\n this._contentTypes.addTheme();\n }\n return this._contentTypes;\n }\n\n public get styles(): Styles {\n return (this._styles ??= new Styles());\n }\n\n /**\n * Register a differential format and return its dxfId.\n * Call this before generating XML to use the ID in conditional formatting rules.\n */\n public registerDxf(opts: DxfOptions): number {\n return this.styles.registerDxf(opts);\n }\n\n public get theme(): DefaultTheme {\n return (this._theme ??= new DefaultTheme());\n }\n\n public get workbookXml(): WorkbookXml {\n if (!this._workbookXml) {\n const sheets: SheetDefinition[] = this.worksheetOptions.map((ws, i) => ({\n name: ws.name ?? `Sheet${i + 1}`,\n sheetId: i + 1,\n rId: `rId${i + 1}`,\n }));\n this._workbookXml = new WorkbookXml(sheets, this._pivotCacheRefs);\n }\n return this._workbookXml;\n }\n\n public get sharedStrings(): SharedStrings {\n return (this._sharedStrings ??= new SharedStrings());\n }\n\n public get media(): Media {\n return (this._media ??= new Media());\n }\n\n public get charts(): ChartCollection {\n return (this._charts ??= new ChartCollection());\n }\n\n public get dxfEntries(): readonly DxfOptions[] {\n return this.dxfOptions;\n }\n\n public get pivotCacheRefs(): readonly PivotCacheReference[] {\n return this._pivotCacheRefs;\n }\n\n public registerPivotCache(cacheId: number, rId: string): void {\n this._pivotCacheRefs.push({ cacheId, rId });\n }\n\n public get worksheetConfigs(): readonly WorksheetOptions[] {\n return this.worksheetOptions;\n }\n\n public get worksheets(): readonly Worksheet[] {\n if (!this._worksheets) {\n this._worksheets = this.worksheetOptions.map((ws) => new Worksheet(ws));\n }\n return this._worksheets;\n }\n\n public get fileRelationships(): Relationships {\n if (!this._fileRels) {\n this._fileRels = new Relationships();\n this._fileRels.addRelationship(\n 1,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument\",\n \"xl/workbook.xml\",\n );\n this._fileRels.addRelationship(\n 2,\n \"http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties\",\n \"docProps/core.xml\",\n );\n this._fileRels.addRelationship(\n 3,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties\",\n \"docProps/app.xml\",\n );\n }\n return this._fileRels;\n }\n\n public get workbookRelationships(): Relationships {\n if (!this._workbookRels) {\n this._workbookRels = new Relationships();\n let rid = 1;\n for (let i = 0; i < this.worksheetOptions.length; i++) {\n this._workbookRels.addRelationship(\n rid++,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet\",\n `worksheets/sheet${i + 1}.xml`,\n );\n }\n this._workbookRels.addRelationship(\n rid++,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles\",\n \"styles.xml\",\n );\n this._workbookRels.addRelationship(\n rid++,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme\",\n \"theme/theme1.xml\",\n );\n this._workbookRels.addRelationship(\n rid++,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings\",\n \"sharedStrings.xml\",\n );\n }\n return this._workbookRels;\n }\n}\n","import { BaseXmlComponent } from \"@file/xml-components\";\nimport type { Context } from \"@file/xml-components\";\nimport { escapeXml } from \"@office-open/xml\";\n\nimport type { CommentOptions } from \"./worksheet\";\n\n/**\n * Generates xl/comments{n}.xml — cell comment data.\n *\n * @module\n */\nexport class Comments extends BaseXmlComponent {\n public constructor(private readonly entries: readonly CommentOptions[]) {\n super(\"comments\");\n }\n\n public override toXml(_context: Context): string {\n const authors = this.collectAuthors();\n const p: string[] = [\n '<comments xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\">',\n `<authors>`,\n ];\n\n for (const author of authors) {\n p.push(`<author>${escapeXml(author)}</author>`);\n }\n\n p.push(\"</authors><commentList>\");\n\n for (const entry of this.entries) {\n const authorId = authors.indexOf(entry.author);\n p.push(\n `<comment ref=\"${entry.cell}\" authorId=\"${authorId}\"><text><t>${escapeXml(entry.text)}</t></text></comment>`,\n );\n }\n\n p.push(\"</commentList></comments>\");\n return p.join(\"\");\n }\n\n private collectAuthors(): string[] {\n const seen = new Set<string>();\n const result: string[] = [];\n for (const entry of this.entries) {\n if (!seen.has(entry.author)) {\n seen.add(entry.author);\n result.push(entry.author);\n }\n }\n return result.length > 0 ? result : [\"\"];\n }\n}\n","/**\n * XLSX Drawing component — generates xl/drawings/drawing{n}.xml.\n *\n * Uses the spreadsheetDrawing namespace (default, no prefix) for anchoring\n * images and charts to worksheet cells.\n *\n * @module\n */\nimport { BaseXmlComponent } from \"@file/xml-components\";\nimport type { Context } from \"@file/xml-components\";\n\nexport interface ImageOptions {\n /** 1-based column */\n readonly col: number;\n /** Column offset in EMU (default 0) */\n readonly colOffset?: number;\n /** 1-based row */\n readonly row: number;\n /** Row offset in EMU (default 0) */\n readonly rowOffset?: number;\n /** Relationship ID for the image */\n readonly rId: string;\n}\n\nexport interface ChartAnchorOptions {\n /** 1-based column */\n readonly col: number;\n /** Column offset in EMU (default 0) */\n readonly colOffset?: number;\n /** 1-based row */\n readonly row: number;\n /** Row offset in EMU (default 0) */\n readonly rowOffset?: number;\n /** Relationship ID for the chart */\n readonly rId: string;\n}\n\nconst XDR_NS = \"http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing\";\nconst A_NS = \"http://schemas.openxmlformats.org/drawingml/2006/main\";\nconst R_NS = \"http://schemas.openxmlformats.org/officeDocument/2006/relationships\";\nconst C_URI = \"http://schemas.openxmlformats.org/drawingml/2006/chart\";\n\nexport class Drawing extends BaseXmlComponent {\n private readonly images: readonly ImageOptions[];\n private readonly charts: readonly ChartAnchorOptions[];\n\n public constructor(images: readonly ImageOptions[], charts: readonly ChartAnchorOptions[] = []) {\n super(\"wsDr\");\n this.images = images;\n this.charts = charts;\n }\n\n public override toXml(_context: Context): string {\n const p: string[] = [`<wsDr xmlns=\"${XDR_NS}\" xmlns:a=\"${A_NS}\" xmlns:r=\"${R_NS}\">`];\n let id = 1;\n for (const img of this.images) {\n p.push(\n `<twoCellAnchor editAs=\"oneCell\"><from><col>${img.col - 1}</col><colOff>${img.colOffset ?? 0}</colOff><row>${img.row - 1}</row><rowOff>${img.rowOffset ?? 0}</rowOff></from>`,\n `<to><col>${img.col}</col><colOff>0</colOff><row>${img.row}</row><rowOff>0</rowOff></to>`,\n `<pic><nvPicPr><cNvPr id=\"${id}\" name=\"Picture ${id}\"/><cNvPicPr preferRelativeResize=\"1\"/></nvPicPr>`,\n `<blipFill><a:blip r:embed=\"${img.rId}\"/><a:stretch><a:fillRect/></a:stretch></blipFill>`,\n `<spPr><a:xfrm><a:off x=\"0\" y=\"0\"/><a:ext cx=\"400000\" cy=\"300000\"/></a:xfrm><a:prstGeom prst=\"rect\"><a:avLst/></a:prstGeom></spPr></pic>`,\n `<clientData/></twoCellAnchor>`,\n );\n id++;\n }\n for (const chart of this.charts) {\n p.push(\n `<twoCellAnchor editAs=\"oneCell\"><from><col>${chart.col - 1}</col><colOff>${chart.colOffset ?? 0}</colOff><row>${chart.row - 1}</row><rowOff>${chart.rowOffset ?? 0}</rowOff></from>`,\n `<to><col>${chart.col + 8}</col><colOff>0</colOff><row>${chart.row + 15}</row><rowOff>0</rowOff></to>`,\n `<graphicFrame><nvGraphicFramePr><cNvPr id=\"${id}\" name=\"Chart ${id}\"/><cNvGraphicFramePr><a:graphicFrameLocks noGrp=\"1\"/></cNvGraphicFramePr></nvGraphicFramePr>`,\n `<xfrm><a:off x=\"0\" y=\"0\"/><a:ext cx=\"0\" cy=\"0\"/></xfrm>`,\n `<a:graphic><a:graphicData uri=\"${C_URI}\"><c:chart xmlns:c=\"http://schemas.openxmlformats.org/drawingml/2006/chart\" xmlns:r=\"${R_NS}\" r:id=\"${chart.rId}\"/></a:graphicData></a:graphic></graphicFrame>`,\n `<clientData/></twoCellAnchor>`,\n );\n id++;\n }\n p.push(\"</wsDr>\");\n return p.join(\"\");\n }\n}\n","/**\n * Pivot table utility types and helper functions.\n *\n * @module\n */\n\n/** Aggregation function for data fields (maps to ST_DataConsolidateFunction). */\nexport const ConsolidateFunction = {\n SUM: \"sum\",\n COUNT: \"count\",\n AVERAGE: \"average\",\n MAX: \"max\",\n MIN: \"min\",\n PRODUCT: \"product\",\n COUNT_NUMS: \"countNums\",\n STD_DEV: \"stdDev\",\n STD_DEV_P: \"stdDevp\",\n VAR: \"var\",\n VAR_P: \"varp\",\n} as const;\n\nexport type ConsolidateFunction = (typeof ConsolidateFunction)[keyof typeof ConsolidateFunction];\n\n/** A data field definition for pivot table aggregation. */\nexport interface PivotDataField {\n /** Source column name to aggregate */\n readonly field: string;\n /** Aggregation function (default: \"sum\") */\n readonly summarize?: ConsolidateFunction;\n /** Custom name for the data field (default: \"Sum of {field}\") */\n readonly name?: string;\n}\n\n/** Options for a single pivot table on a worksheet. */\nexport interface PivotTableOptions {\n /** Pivot table name (default: \"PivotTable{N}\") */\n readonly name?: string;\n /** Source data range, e.g. \"A1:D11\" — must be on the same or a different sheet */\n readonly source: string;\n /** Source sheet name (default: current sheet) */\n readonly sourceSheet?: string;\n /** Target cell for the pivot table output (default: \"A3\") */\n readonly location?: string;\n /** Field names to use as row labels */\n readonly rows: readonly string[];\n /** Field names to use as column labels */\n readonly columns?: readonly string[];\n /** Data fields with aggregation settings */\n readonly data: readonly PivotDataField[];\n /** Pivot style name (default: \"PivotStyleLight16\") */\n readonly style?: string;\n}\n\n/** Parsed source data for pivot cache generation. */\nexport interface PivotSourceData {\n readonly fieldNames: readonly string[];\n readonly records: readonly (string | number)[][];\n}\n\n/**\n * Extract unique values from source data for a given field index.\n */\nexport function collectUniqueValues(\n records: readonly (string | number)[][],\n fieldIdx: number,\n): (string | number)[] {\n const seen = new Set<string>();\n const result: (string | number)[] = [];\n for (const row of records) {\n const val = row[fieldIdx];\n const key = String(val);\n if (!seen.has(key)) {\n seen.add(key);\n result.push(val);\n }\n }\n return result;\n}\n\n/**\n * Check if a field is numeric (all non-empty values are numbers).\n */\nexport function isNumericField(records: readonly (string | number)[][], fieldIdx: number): boolean {\n for (const row of records) {\n const val = row[fieldIdx];\n if (typeof val === \"string\" && val !== \"\") return false;\n }\n return true;\n}\n\n/**\n * Aggregate values using the specified function.\n */\nexport function aggregate(values: readonly number[], func: ConsolidateFunction): number {\n if (values.length === 0) return 0;\n switch (func) {\n case \"sum\":\n return values.reduce((a, b) => a + b, 0);\n case \"count\":\n case \"countNums\":\n return values.length;\n case \"average\":\n return values.reduce((a, b) => a + b, 0) / values.length;\n case \"max\":\n return Math.max(...values);\n case \"min\":\n return Math.min(...values);\n case \"product\":\n return values.reduce((a, b) => a * b, 1);\n case \"var\":\n return sampleVariance(values);\n case \"varp\":\n return populationVariance(values);\n case \"stdDev\":\n return Math.sqrt(sampleVariance(values));\n case \"stdDevp\":\n return Math.sqrt(populationVariance(values));\n default:\n return values.reduce((a, b) => a + b, 0);\n }\n}\n\nfunction populationVariance(values: readonly number[]): number {\n const mean = values.reduce((a, b) => a + b, 0) / values.length;\n return values.reduce((sum, v) => sum + (v - mean) ** 2, 0) / values.length;\n}\n\nfunction sampleVariance(values: readonly number[]): number {\n if (values.length < 2) return 0;\n const mean = values.reduce((a, b) => a + b, 0) / values.length;\n return values.reduce((sum, v) => sum + (v - mean) ** 2, 0) / (values.length - 1);\n}\n","/**\n * PivotCacheDefinition XML generator.\n *\n * Generates xl/pivotCache/pivotCacheDefinition{N}.xml.\n * Follows CT_PivotCacheDefinition from sml.xsd.\n *\n * @module\n */\nimport { BaseXmlComponent } from \"@file/xml-components\";\nimport type { Context } from \"@file/xml-components\";\nimport { escapeXml } from \"@office-open/xml\";\n\nimport type { PivotSourceData } from \"./pivot-utils\";\nimport { collectUniqueValues, isNumericField } from \"./pivot-utils\";\n\nexport class PivotCacheDefinitionXml extends BaseXmlComponent {\n private readonly sourceRef: string;\n private readonly sourceSheet: string;\n private readonly sourceData: PivotSourceData;\n private readonly recordsRid: string;\n\n public constructor(\n _cacheIdx: number,\n sourceRef: string,\n sourceSheet: string,\n sourceData: PivotSourceData,\n recordsRid: string,\n ) {\n super(\"pivotCacheDefinition\");\n this.sourceRef = sourceRef;\n this.sourceSheet = sourceSheet;\n this.sourceData = sourceData;\n this.recordsRid = recordsRid;\n }\n\n public override toXml(_context: Context): string {\n const p: string[] = [];\n\n p.push(\n '<pivotCacheDefinition xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\"' +\n ' xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\"' +\n ` r:id=\"${escapeXml(this.recordsRid)}\"` +\n ` recordCount=\"${this.sourceData.records.length}\"` +\n ` createdVersion=\"6\" refreshedVersion=\"6\" minRefreshableVersion=\"3\">`,\n );\n\n // cacheSource\n p.push(\n `<cacheSource type=\"worksheet\">` +\n `<worksheetSource ref=\"${escapeXml(this.sourceRef)}\" sheet=\"${escapeXml(this.sourceSheet)}\"/>` +\n `</cacheSource>`,\n );\n\n // cacheFields\n const fields = this.sourceData.fieldNames;\n p.push(`<cacheFields count=\"${fields.length}\">`);\n\n for (let i = 0; i < fields.length; i++) {\n const fieldName = fields[i];\n const numeric = isNumericField(this.sourceData.records, i);\n const uniqueVals = collectUniqueValues(this.sourceData.records, i);\n\n if (numeric) {\n // Numeric field: sharedItems with type metadata only, no inline values\n let min = Infinity;\n let max = -Infinity;\n for (const row of this.sourceData.records) {\n const v = row[i];\n if (typeof v === \"number\") {\n if (v < min) min = v;\n if (v > max) max = v;\n }\n }\n if (!isFinite(min)) {\n min = 0;\n max = 0;\n }\n const allInteger = this.sourceData.records.every(\n (row) => typeof row[i] === \"number\" && Number.isInteger(row[i]),\n );\n p.push(\n `<cacheField name=\"${escapeXml(fieldName)}\" numFmtId=\"0\">` +\n `<sharedItems containsSemiMixedTypes=\"0\" containsString=\"0\"` +\n ` containsNumber=\"1\" containsInteger=\"${allInteger ? \"1\" : \"0\"}\"` +\n ` minValue=\"${min}\" maxValue=\"${max}\" count=\"${uniqueVals.length}\"/>` +\n `</cacheField>`,\n );\n } else {\n // String/categorical field: list unique values in sharedItems\n p.push(\n `<cacheField name=\"${escapeXml(fieldName)}\" numFmtId=\"0\"><sharedItems count=\"${uniqueVals.length}\">`,\n );\n for (const v of uniqueVals) {\n p.push(`<s v=\"${escapeXml(String(v))}\"/>`);\n }\n p.push(\"</sharedItems></cacheField>\");\n }\n }\n\n p.push(\"</cacheFields>\");\n p.push(\"</pivotCacheDefinition>\");\n\n return p.join(\"\");\n }\n}\n","/**\n * PivotCacheRecords XML generator.\n *\n * Generates xl/pivotCache/pivotCacheRecords{N}.xml.\n * Follows CT_PivotCacheRecords from sml.xsd.\n *\n * @module\n */\nimport { BaseXmlComponent } from \"@file/xml-components\";\nimport type { Context } from \"@file/xml-components\";\n\nimport type { PivotSourceData } from \"./pivot-utils\";\nimport { collectUniqueValues, isNumericField } from \"./pivot-utils\";\n\nexport class PivotCacheRecordsXml extends BaseXmlComponent {\n private readonly sourceData: PivotSourceData;\n private readonly numericFields: readonly boolean[];\n /** For string fields: value → sharedItems index */\n private readonly fieldIndexMaps: readonly Map<string, number>[];\n\n public constructor(sourceData: PivotSourceData) {\n super(\"pivotCacheRecords\");\n this.sourceData = sourceData;\n this.numericFields = sourceData.fieldNames.map((_, i) => isNumericField(sourceData.records, i));\n this.fieldIndexMaps = sourceData.fieldNames.map((_, i) => {\n if (this.numericFields[i]) return new Map<string, number>();\n const unique = collectUniqueValues(sourceData.records, i);\n const map = new Map<string, number>();\n for (let j = 0; j < unique.length; j++) {\n map.set(String(unique[j]), j);\n }\n return map;\n });\n }\n\n public override toXml(_context: Context): string {\n const p: string[] = [];\n\n p.push(\n '<pivotCacheRecords xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\"' +\n ` count=\"${this.sourceData.records.length}\">`,\n );\n\n for (const row of this.sourceData.records) {\n p.push(\"<r>\");\n for (let i = 0; i < row.length; i++) {\n const val = row[i];\n if (this.numericFields[i]) {\n p.push(`<n v=\"${val}\"/>`);\n } else {\n const idx = this.fieldIndexMaps[i].get(String(val)) ?? 0;\n p.push(`<x v=\"${idx}\"/>`);\n }\n }\n p.push(\"</r>\");\n }\n\n p.push(\"</pivotCacheRecords>\");\n return p.join(\"\");\n }\n}\n","/**\n * PivotTableDefinition XML generator.\n *\n * Generates xl/pivotTables/pivotTable{N}.xml.\n * Follows CT_pivotTableDefinition from sml.xsd.\n *\n * @module\n */\nimport { BaseXmlComponent } from \"@file/xml-components\";\nimport type { Context } from \"@file/xml-components\";\nimport { escapeXml } from \"@office-open/xml\";\n\nimport type { PivotSourceData } from \"./pivot-utils\";\nimport type { PivotTableOptions, PivotDataField } from \"./pivot-utils\";\nimport { collectUniqueValues } from \"./pivot-utils\";\n\nexport class PivotTableXml extends BaseXmlComponent {\n private readonly options: PivotTableOptions;\n private readonly sourceData: PivotSourceData;\n private readonly cacheId: number;\n\n public constructor(options: PivotTableOptions, sourceData: PivotSourceData, cacheId: number) {\n super(\"pivotTableDefinition\");\n this.options = options;\n this.sourceData = sourceData;\n this.cacheId = cacheId;\n }\n\n public override toXml(_context: Context): string {\n const o = this.options;\n const sd = this.sourceData;\n const fields = sd.fieldNames;\n const rowFieldNames = o.rows;\n const colFieldNames = o.columns ?? [];\n const dataFields = o.data;\n const style = o.style ?? \"PivotStyleLight16\";\n const location = o.location ?? \"A3\";\n const name = o.name ?? \"PivotTable1\";\n\n // Compute field indices\n const rowFieldIndices = rowFieldNames.map((n) => fields.indexOf(n));\n const colFieldIndices = colFieldNames.map((n) => fields.indexOf(n));\n const dataFieldIndices = dataFields.map((df) => fields.indexOf(df.field));\n\n // Build pivotFields\n const pivotFieldsXml = this.buildPivotFields(\n rowFieldIndices,\n colFieldIndices,\n dataFieldIndices,\n );\n\n // Build rowFields + rowItems\n const rowFieldsXml = this.buildRowFields(rowFieldIndices);\n const rowItemsXml = this.buildRowItems(rowFieldIndices);\n\n // Build colFields + colItems\n const colFieldsXml = this.buildColFields(colFieldIndices);\n const colItemsXml = this.buildColItems(colFieldIndices, dataFields);\n\n // Build dataFields\n const dataFieldsXml = this.buildDataFields(dataFields, dataFieldIndices);\n\n // Compute location ref\n const locationRef = this.computeLocationRef(\n location,\n rowFieldIndices,\n colFieldIndices,\n dataFields,\n );\n\n const p: string[] = [];\n p.push(\n `<pivotTableDefinition xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\"` +\n ` name=\"${escapeXml(name)}\" cacheId=\"${this.cacheId}\"` +\n ` dataCaption=\"Values\" updatedVersion=\"6\" minRefreshableVersion=\"3\" createdVersion=\"6\"` +\n ` applyNumberFormats=\"0\" applyBorderFormats=\"0\" applyFontFormats=\"0\"` +\n ` applyPatternFormats=\"0\" applyAlignmentFormats=\"0\" applyWidthHeightFormats=\"1\"` +\n ` autoFormatId=\"0\" useAutoFormatting=\"1\" itemPrintTitles=\"1\" indent=\"0\"` +\n ` outline=\"1\" outlineData=\"1\" compact=\"1\" compactData=\"1\" rowGrandTotals=\"1\" colGrandTotals=\"1\">`,\n );\n\n // location\n p.push(\n `<location ref=\"${escapeXml(locationRef)}\" firstHeaderRow=\"1\" firstDataRow=\"${colFieldIndices.length + 1}\" firstDataCol=\"${rowFieldIndices.length}\"/>`,\n );\n\n // pivotFields\n p.push(pivotFieldsXml);\n\n // rowFields\n p.push(rowFieldsXml);\n\n // rowItems\n p.push(rowItemsXml);\n\n // colFields (only when column fields exist)\n if (colFieldIndices.length > 0) {\n p.push(colFieldsXml);\n }\n\n // colItems (always present)\n p.push(colItemsXml);\n\n // dataFields\n if (dataFields.length > 0) {\n p.push(dataFieldsXml);\n }\n\n // style\n p.push(\n `<pivotTableStyleInfo name=\"${escapeXml(style)}\" showRowHeaders=\"1\" showColHeaders=\"1\" showRowStripes=\"0\" showColStripes=\"0\" showLastColumn=\"1\"/>`,\n );\n\n p.push(\"</pivotTableDefinition>\");\n return p.join(\"\");\n }\n\n private buildPivotFields(\n rowIndices: readonly number[],\n colIndices: readonly number[],\n dataIndices: readonly number[],\n ): string {\n const fields = this.sourceData.fieldNames;\n const parts: string[] = [`<pivotFields count=\"${fields.length}\">`];\n\n for (let i = 0; i < fields.length; i++) {\n const isRow = rowIndices.includes(i);\n const isCol = colIndices.includes(i);\n const isData = dataIndices.includes(i);\n\n if (isData) {\n parts.push(`<pivotField dataField=\"1\" showAll=\"0\"/>`);\n } else if (isRow) {\n const uniqueVals = collectUniqueValues(this.sourceData.records, i);\n parts.push(`<pivotField axis=\"axisRow\" showAll=\"0\">`);\n parts.push(`<items count=\"${uniqueVals.length + 1}\">`);\n for (let j = 0; j < uniqueVals.length; j++) {\n parts.push(`<item x=\"${j}\"/>`);\n }\n parts.push(`<item t=\"default\"/>`);\n parts.push(\"</items></pivotField>\");\n } else if (isCol) {\n const uniqueVals = collectUniqueValues(this.sourceData.records, i);\n parts.push(`<pivotField axis=\"axisCol\" showAll=\"0\">`);\n parts.push(`<items count=\"${uniqueVals.length + 1}\">`);\n for (let j = 0; j < uniqueVals.length; j++) {\n parts.push(`<item x=\"${j}\"/>`);\n }\n parts.push(`<item t=\"default\"/>`);\n parts.push(\"</items></pivotField>\");\n } else {\n parts.push(`<pivotField showAll=\"0\"/>`);\n }\n }\n\n parts.push(\"</pivotFields>\");\n return parts.join(\"\");\n }\n\n private buildRowFields(rowIndices: readonly number[]): string {\n if (rowIndices.length === 0) return '<rowFields count=\"0\"/>';\n const parts: string[] = [`<rowFields count=\"${rowIndices.length}\">`];\n for (const idx of rowIndices) {\n parts.push(`<field x=\"${idx}\"/>`);\n }\n parts.push(\"</rowFields>\");\n return parts.join(\"\");\n }\n\n private buildRowItems(rowIndices: readonly number[]): string {\n if (rowIndices.length === 0) return '<rowItems count=\"1\"><i/></rowItems>';\n\n const allUniqueCounts: number[] = [];\n for (const idx of rowIndices) {\n const vals = collectUniqueValues(this.sourceData.records, idx);\n allUniqueCounts.push(vals.length);\n }\n\n // Simple case: single row field\n if (rowIndices.length === 1) {\n const count = allUniqueCounts[0];\n const parts: string[] = [`<rowItems count=\"${count + 1}\">`];\n for (let i = 0; i < count; i++) {\n parts.push(`<i><x v=\"${i}\"/></i>`);\n }\n parts.push(`<i t=\"grand\"><x/></i>`);\n parts.push(\"</rowItems>\");\n return parts.join(\"\");\n }\n\n // Multi-field: build cartesian product indices\n const combos = cartesianOfCounts(allUniqueCounts);\n const rowItems: string[] = [];\n for (const combo of combos) {\n const xParts = combo.map((v) => `<x v=\"${v}\"/>`).join(\"\");\n rowItems.push(`<i>${xParts}</i>`);\n }\n // Grand total\n rowItems.push(`<i t=\"grand\">${rowIndices.map(() => \"<x/>\").join(\"\")}</i>`);\n\n return `<rowItems count=\"${rowItems.length}\">${rowItems.join(\"\")}</rowItems>`;\n }\n\n private buildColFields(colIndices: readonly number[]): string {\n if (colIndices.length === 0) return '<colFields count=\"0\"/>';\n const parts: string[] = [`<colFields count=\"${colIndices.length}\">`];\n for (const idx of colIndices) {\n parts.push(`<field x=\"${idx}\"/>`);\n }\n parts.push(\"</colFields>\");\n return parts.join(\"\");\n }\n\n private buildColItems(\n colIndices: readonly number[],\n dataFields: readonly PivotDataField[],\n ): string {\n if (colIndices.length > 0) {\n const allUniqueCounts: number[] = [];\n for (const idx of colIndices) {\n const vals = collectUniqueValues(this.sourceData.records, idx);\n allUniqueCounts.push(vals.length);\n }\n\n const combos = cartesianOfCounts(allUniqueCounts);\n const items: string[] = [];\n for (const combo of combos) {\n const xParts = combo.map((v) => `<x v=\"${v}\"/>`).join(\"\");\n items.push(`<i>${xParts}</i>`);\n }\n items.push(`<i t=\"grand\">${colIndices.map(() => \"<x/>\").join(\"\")}</i>`);\n return `<colItems count=\"${items.length}\">${items.join(\"\")}</colItems>`;\n }\n\n // No column fields: if multiple data fields, each becomes a column\n if (dataFields.length > 1) {\n const items = dataFields.map((_, i) => `<i><x v=\"${i}\"/></i>`);\n return `<colItems count=\"${items.length}\">${items.join(\"\")}</colItems>`;\n }\n\n // Single or no data fields, no column fields\n return '<colItems count=\"1\"><i/></colItems>';\n }\n\n private buildDataFields(\n dataFields: readonly PivotDataField[],\n dataFieldIndices: readonly number[],\n ): string {\n if (dataFields.length === 0) return '<dataFields count=\"0\"/>';\n const parts: string[] = [`<dataFields count=\"${dataFields.length}\">`];\n for (let i = 0; i < dataFields.length; i++) {\n const df = dataFields[i];\n const subtotal = df.summarize ?? \"sum\";\n const name = df.name ?? `${subtotal === \"sum\" ? \"Sum\" : subtotal} of ${df.field}`;\n parts.push(\n `<dataField name=\"${escapeXml(name)}\" fld=\"${dataFieldIndices[i]}\" subtotal=\"${subtotal}\"/>`,\n );\n }\n parts.push(\"</dataFields>\");\n return parts.join(\"\");\n }\n\n private computeLocationRef(\n location: string,\n rowFieldIndices: readonly number[],\n colFieldIndices: readonly number[],\n dataFields: readonly PivotDataField[],\n ): string {\n const startCell = location.split(\":\")[0];\n const match = startCell.match(/^([A-Z]+)(\\d+)$/);\n if (!match) return location;\n\n const startCol = match[1];\n const startRow = parseInt(match[2], 10);\n\n // Count rows: unique row values + header + grand total\n let rowCount = 1; // header\n if (rowFieldIndices.length > 0) {\n rowCount += collectUniqueValues(this.sourceData.records, rowFieldIndices[0]).length;\n }\n rowCount += 1; // grand total\n\n // Count columns: row fields + column values or data fields\n let colCount = Math.max(rowFieldIndices.length, 1);\n if (colFieldIndices.length > 0) {\n colCount += collectUniqueValues(this.sourceData.records, colFieldIndices[0]).length;\n } else if (dataFields.length > 1) {\n colCount += dataFields.length - 1;\n }\n colCount += 1; // grand total column\n\n const endCol = colIndexToLetter(letterToColIndex(startCol) + colCount - 1);\n const endRow = startRow + rowCount - 1;\n\n return `${startCol}${startRow}:${endCol}${endRow}`;\n }\n}\n\nfunction letterToColIndex(letters: string): number {\n let col = 0;\n for (let i = 0; i < letters.length; i++) {\n col = col * 26 + (letters.charCodeAt(i) - 64);\n }\n return col;\n}\n\nfunction colIndexToLetter(col: number): string {\n let result = \"\";\n let n = col;\n while (n > 0) {\n n--;\n result = String.fromCharCode(65 + (n % 26)) + result;\n n = Math.floor(n / 26);\n }\n return result;\n}\n\n/** Cartesian product from counts: e.g. [2, 3] → [[0,0],[0,1],[0,2],[1,0],[1,1],[1,2]] */\nfunction cartesianOfCounts(counts: readonly number[]): number[][] {\n if (counts.length === 0) return [[]];\n let result: number[][] = [[]];\n for (const count of counts) {\n const next: number[][] = [];\n for (const prefix of result) {\n for (let i = 0; i < count; i++) {\n next.push([...prefix, i]);\n }\n }\n result = next;\n }\n return result;\n}\n","/**\n * VML Notes — generates legacy VML drawing for worksheet comments.\n *\n * Excel requires a VML drawing file (xl/drawings/vmlDrawing{N}.vml)\n * referenced by <legacyDrawing r:id=\"...\"/> in the worksheet XML.\n *\n * @module\n */\nimport type { CommentOptions } from \"@file/worksheet\";\n\nexport class VmlNotes {\n public constructor(private readonly comments: readonly CommentOptions[]) {}\n\n public toXml(): string {\n const p: string[] = [\n '<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>',\n '<xml xmlns:v=\"urn:schemas-microsoft-com:vml\" xmlns:o=\"urn:schemas-microsoft-com:office:office\" xmlns:x=\"urn:schemas-microsoft-com:office:excel\">',\n '<o:shapelayout v:ext=\"edit\"><o:idmap v:ext=\"edit\" data=\"1\"/></o:shapelayout>',\n '<v:shapetype id=\"_x0000_t202\" coordsize=\"21600,21600\" o:spt=\"202\" path=\"m,l,21600r21600,l21600,xe\">',\n '<v:stroke joinstyle=\"miter\"/>',\n '<v:path gradientshapeok=\"t\" o:connecttype=\"rect\"/>',\n \"</v:shapetype>\",\n ];\n\n for (let i = 0; i < this.comments.length; i++) {\n const c = this.comments[i];\n const col = c.cell.charCodeAt(0) - 65;\n const row = parseInt(c.cell.slice(1), 10) - 1;\n // 8-value anchor: fromCol, fromColOffset, fromRow, fromRowOffset, toCol, toColOffset, toRow, toRowOffset\n const anchor = `${col}, 0, ${row}, 0, ${col + 2}, 0, ${row + 2}, 0`;\n p.push(\n `<v:shape id=\"_x0000_s${1025 + i}\" type=\"#_x0000_t202\" ` +\n `style=\"position:absolute;margin-left:59.25pt;margin-top:1.5pt;width:108pt;height:59.25pt;` +\n `z-index:1;visibility:hidden\" fillcolor=\"infoBackground [80]\" strokecolor=\"none [81]\" o:insetmode=\"auto\">`,\n `<v:fill color2=\"infoBackground [80]\"/>`,\n `<v:shadow color=\"none [81]\" obscured=\"t\"/>`,\n `<v:path o:connecttype=\"none\"/>`,\n `<v:textbox style=\"mso-direction-alt:auto\"><div style=\"text-align:left\"/></v:textbox>`,\n `<x:ClientData ObjectType=\"Note\"><x:MoveWithCells/><x:SizeWithCells/>`,\n `<x:Anchor>${anchor}</x:Anchor>`,\n `<x:AutoFill>False</x:AutoFill>`,\n `<x:Row>${row}</x:Row>`,\n `<x:Column>${col}</x:Column>`,\n `</x:ClientData>`,\n `</v:shape>`,\n );\n }\n\n p.push(\"</xml>\");\n return p.join(\"\");\n }\n}\n","/**\n * XLSX Compiler — compiles a File object into a Zippable structure.\n *\n * @module\n */\nimport { Formatter } from \"@export/formatter\";\nimport { Comments } from \"@file/comments\";\nimport { Drawing, type ImageOptions, type ChartAnchorOptions } from \"@file/drawing/drawing\";\nimport type { File } from \"@file/file\";\nimport {\n PivotCacheDefinitionXml,\n PivotCacheRecordsXml,\n PivotTableXml,\n aggregate,\n} from \"@file/pivot\";\nimport type { PivotSourceData, PivotTableOptions } from \"@file/pivot\";\nimport { VmlNotes } from \"@file/vml-notes\";\nimport type { BaseXmlComponent, Context } from \"@file/xml-components\";\nimport {\n ChartSpace,\n Relationships,\n compileMapping,\n type XmlifyedFile,\n type Zippable,\n} from \"@office-open/core\";\n\nexport class Compiler {\n private readonly formatter = new Formatter();\n\n public compile(\n file: File,\n overrides: readonly XmlifyedFile[] = [],\n mediaLevel: number = 0,\n ): Zippable {\n const context: Context = { fileData: file, stack: [] };\n const f = this.formatter;\n\n const mapping: Record<string, { data: string; path: string }> = {};\n\n const fmt = (component: BaseXmlComponent) => f.formatToXml(component, context);\n\n // Core properties\n mapping[\"Properties\"] = {\n data: fmt(file.coreProperties),\n path: \"docProps/core.xml\",\n };\n\n // App properties\n mapping[\"AppProperties\"] = {\n data: fmt(file.appProperties),\n path: \"docProps/app.xml\",\n };\n\n // File-level relationships (_rels/.rels)\n mapping[\"FileRelationships\"] = {\n data: fmt(file.fileRelationships),\n path: \"_rels/.rels\",\n };\n\n // Worksheets — formatted BEFORE SharedStrings so strings are registered\n const worksheets = file.worksheets;\n let globalMediaIdx = 0;\n let globalChartIdx = 0;\n let globalPivotIdx = 0;\n let globalPivotCacheIdx = 0;\n const pivotCacheDataMap = new Map<string, { cacheId: number; cacheIdx: number }>();\n\n for (let i = 0; i < worksheets.length; i++) {\n const ws = worksheets[i];\n const imgOpts = ws.imageOptions;\n const chartOpts = ws.charts;\n const hlOpts = ws.hyperlinkOptions;\n const sheetName = file.worksheetConfigs[i]?.name ?? `Sheet${i + 1}`;\n\n // Worksheet uses toXml() fast path (zero-allocation string concat)\n let sheetXml = fmt(ws);\n\n const hasMedia = imgOpts.length > 0 || chartOpts.length > 0;\n const hasExternalHyperlinks = hlOpts.some((h) => h.target.type === \"external\");\n const commentOpts = ws.commentOptions;\n const hasComments = commentOpts.length > 0;\n const pivotOpts = ws.pivotTables;\n const hasPivots = pivotOpts.length > 0;\n\n // Worksheet-level relationships\n let wsRels: Relationships | undefined;\n let nextRid = 0;\n\n if (hasMedia || hasExternalHyperlinks || hasComments || hasPivots) {\n wsRels = new Relationships();\n }\n\n if (hasExternalHyperlinks) {\n for (const hl of hlOpts) {\n if (hl.target.type !== \"external\") continue;\n const rid = ++nextRid;\n wsRels!.addRelationship(\n rid,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink\",\n hl.target.url,\n \"External\",\n );\n }\n }\n\n if (hasMedia) {\n const drawingImages: ImageOptions[] = [];\n const drawingCharts: ChartAnchorOptions[] = [];\n const drawingRels = new Relationships();\n let rid = 1;\n\n // Process images\n for (const img of imgOpts) {\n const mediaKey = `image_${globalMediaIdx}`;\n const ext = img.type === \"jpeg\" || img.type === \"jpg\" ? \"jpeg\" : \"png\";\n file.media.addImage(mediaKey, {\n fileName: `image${globalMediaIdx + 1}.${ext}`,\n type: ext,\n data: img.data,\n width: 0,\n height: 0,\n });\n\n drawingRels.addRelationship(\n rid,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/image\",\n `../media/image${globalMediaIdx + 1}.${ext}`,\n );\n\n drawingImages.push({\n col: img.col,\n row: img.row,\n rId: `rId${rid}`,\n });\n rid++;\n globalMediaIdx++;\n }\n\n // Process charts\n for (const chart of chartOpts) {\n const chartKey = `chart_${globalChartIdx}`;\n file.charts.addChart(chartKey, {\n key: chartKey,\n chartSpace: new ChartSpace(chart),\n });\n\n drawingRels.addRelationship(\n rid,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart\",\n `../charts/chart${globalChartIdx + 1}.xml`,\n );\n\n drawingCharts.push({\n col: chart.col,\n row: chart.row,\n rId: `rId${rid}`,\n });\n rid++;\n globalChartIdx++;\n }\n\n // Generate drawing XML\n const drawing = new Drawing(drawingImages, drawingCharts);\n const drawingIdx = i + 1;\n mapping[`Drawing${i}`] = {\n data: fmt(drawing),\n path: `xl/drawings/drawing${drawingIdx}.xml`,\n };\n\n // Drawing relationships\n mapping[`DrawingRels${i}`] = {\n data: fmt(drawingRels),\n path: `xl/drawings/_rels/drawing${drawingIdx}.xml.rels`,\n };\n\n // Insert drawing reference before the closing </worksheet> tag.\n const drawingRid = ++nextRid;\n const closingTag = \"</worksheet>\";\n sheetXml =\n sheetXml.slice(0, -closingTag.length) + `<drawing r:id=\"rId${drawingRid}\"/>` + closingTag;\n\n // Add drawing relationship to worksheet rels\n wsRels!.addRelationship(\n drawingRid,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing\",\n `../drawings/drawing${drawingIdx}.xml`,\n );\n\n file.contentTypes.addDrawing(drawingIdx);\n }\n\n // Comments\n if (hasComments) {\n const commentsIdx = i + 1;\n\n // Comments XML\n const commentsXml = new Comments(commentOpts);\n mapping[`Comments${i}`] = {\n data: fmt(commentsXml),\n path: `xl/comments${commentsIdx}.xml`,\n };\n\n // VML drawing (required by Excel for legacy comment rendering)\n const vmlNotes = new VmlNotes(commentOpts);\n mapping[`VmlDrawing${i}`] = {\n data: vmlNotes.toXml(),\n path: `xl/drawings/vmlDrawing${commentsIdx}.vml`,\n };\n\n // Worksheet rels: comments → comments XML, legacyDrawing → VML file\n const commentsRid = ++nextRid;\n wsRels!.addRelationship(\n commentsRid,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments\",\n `../comments${commentsIdx}.xml`,\n );\n\n const vmlRid = ++nextRid;\n wsRels!.addRelationship(\n vmlRid,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing\",\n `../drawings/vmlDrawing${commentsIdx}.vml`,\n );\n\n // Insert legacyDrawing reference before closing </worksheet>\n const closingTag = \"</worksheet>\";\n sheetXml =\n sheetXml.slice(0, -closingTag.length) +\n `<legacyDrawing r:id=\"rId${vmlRid}\"/>` +\n closingTag;\n\n // Register content types\n file.contentTypes.addComments(commentsIdx);\n file.contentTypes.addVmlDrawing();\n }\n\n // Pivot tables\n if (hasPivots) {\n for (const pt of pivotOpts) {\n globalPivotIdx++;\n const pivotIdx = globalPivotIdx;\n\n // Extract source data from source sheet\n const sourceSheet = pt.sourceSheet ?? sheetName;\n const sourceWsIdx = file.worksheetConfigs.findIndex(\n (ws) => (ws.name ?? `Sheet${file.worksheetConfigs.indexOf(ws) + 1}`) === sourceSheet,\n );\n if (sourceWsIdx === -1) continue;\n\n const sourceWs = worksheets[sourceWsIdx];\n const sourceData = extractPivotSourceData(sourceWs.worksheetRows, pt.source);\n\n // Deduplicate pivot caches by source reference\n const cacheKey = `${sourceSheet}:${pt.source}`;\n let cacheId: number;\n let cacheIdx: number;\n const existing = pivotCacheDataMap.get(cacheKey);\n if (existing) {\n cacheId = existing.cacheId;\n cacheIdx = existing.cacheIdx;\n } else {\n globalPivotCacheIdx++;\n cacheIdx = globalPivotCacheIdx;\n cacheId = cacheIdx - 1;\n pivotCacheDataMap.set(cacheKey, { cacheId, cacheIdx });\n\n // Generate pivotCacheDefinition\n const cacheDefRels = new Relationships();\n cacheDefRels.addRelationship(\n 1,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/pivotCacheRecords\",\n \"pivotCacheRecords1.xml\",\n );\n\n const cacheDef = new PivotCacheDefinitionXml(\n cacheIdx,\n pt.source.split(\":\")[0] ? pt.source : \"A1\",\n sourceSheet,\n sourceData,\n \"rId1\",\n );\n\n mapping[`PivotCacheDef${cacheIdx}`] = {\n data: fmt(cacheDef),\n path: `xl/pivotCache/pivotCacheDefinition${cacheIdx}.xml`,\n };\n mapping[`PivotCacheDefRels${cacheIdx}`] = {\n data: fmt(cacheDefRels),\n path: `xl/pivotCache/_rels/pivotCacheDefinition${cacheIdx}.xml.rels`,\n };\n\n // Generate pivotCacheRecords\n const cacheRecords = new PivotCacheRecordsXml(sourceData);\n mapping[`PivotCacheRecords${cacheIdx}`] = {\n data: fmt(cacheRecords),\n path: `xl/pivotCache/pivotCacheRecords${cacheIdx}.xml`,\n };\n\n // Content types\n file.contentTypes.addPivotCacheDefinition(cacheIdx);\n file.contentTypes.addPivotCacheRecords(cacheIdx);\n\n // Register in workbook\n const wbPivotRid = file.workbookRelationships.relationshipCount + 1;\n file.workbookRelationships.addRelationship(\n wbPivotRid,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/pivotCacheDefinition\",\n `pivotCache/pivotCacheDefinition${cacheIdx}.xml`,\n );\n file.registerPivotCache(cacheId, `rId${wbPivotRid}`);\n }\n\n // Generate pivotTable\n const pivotTable = new PivotTableXml(pt, sourceData, cacheId);\n mapping[`PivotTable${pivotIdx}`] = {\n data: fmt(pivotTable),\n path: `xl/pivotTables/pivotTable${pivotIdx}.xml`,\n };\n\n // pivotTable rels → cacheDefinition\n const ptRels = new Relationships();\n ptRels.addRelationship(\n 1,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/pivotCacheDefinition\",\n `../pivotCache/pivotCacheDefinition${cacheIdx}.xml`,\n );\n mapping[`PivotTableRels${pivotIdx}`] = {\n data: fmt(ptRels),\n path: `xl/pivotTables/_rels/pivotTable${pivotIdx}.xml.rels`,\n };\n\n // Worksheet rels → pivotTable\n const ptRid = ++nextRid;\n wsRels!.addRelationship(\n ptRid,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/pivotTable\",\n `../pivotTables/pivotTable${pivotIdx}.xml`,\n );\n\n file.contentTypes.addPivotTable(pivotIdx);\n }\n }\n\n // Pre-render pivot table data into sheetData\n if (hasPivots) {\n const rendered = renderPivotSheetData(\n pivotOpts,\n worksheets,\n file.sharedStrings,\n file.worksheetConfigs,\n sheetName,\n );\n if (rendered.sheetData.length > 0) {\n // Replace empty <sheetData/> or <sheetData></sheetData> with rendered data\n sheetXml = sheetXml.replace(/<sheetData\\/>|<sheetData><\\/sheetData>/, rendered.sheetData);\n // Inject <dimension> before <sheetViews> (XSD sequence order: dimension before sheetViews)\n if (!sheetXml.includes(\"<dimension\")) {\n sheetXml = sheetXml.replace(\n \"<sheetViews\",\n `<dimension ref=\"${rendered.dimensionRef}\"/><sheetViews`,\n );\n }\n }\n }\n\n // Write worksheet rels if needed\n if (wsRels) {\n mapping[`WorksheetRels${i}`] = {\n data: fmt(wsRels),\n path: `xl/worksheets/_rels/sheet${i + 1}.xml.rels`,\n };\n }\n\n mapping[`Worksheet${i}`] = {\n data: sheetXml,\n path: `xl/worksheets/sheet${i + 1}.xml`,\n };\n }\n\n // Workbook XML\n mapping[\"Workbook\"] = {\n data: fmt(file.workbookXml),\n path: \"xl/workbook.xml\",\n };\n\n // Workbook relationships\n mapping[\"WorkbookRelationships\"] = {\n data: fmt(file.workbookRelationships),\n path: \"xl/_rels/workbook.xml.rels\",\n };\n\n // Shared Strings — AFTER worksheets so all strings are collected\n const sharedStrings = file.sharedStrings;\n if (sharedStrings.count > 0) {\n mapping[\"SharedStrings\"] = {\n data: fmt(sharedStrings),\n path: \"xl/sharedStrings.xml\",\n };\n }\n\n // Register predefined DXFs before styles XML is generated\n for (const dxf of file.dxfEntries) {\n file.registerDxf(dxf);\n }\n\n // Styles\n mapping[\"Styles\"] = {\n data: fmt(file.styles),\n path: \"xl/styles.xml\",\n };\n\n // Theme\n mapping[\"Theme\"] = {\n data: fmt(file.theme),\n path: \"xl/theme/theme1.xml\",\n };\n\n // Charts — AFTER worksheets so charts are registered\n for (let i = 0; i < file.charts.array.length; i++) {\n const chartData = file.charts.array[i];\n mapping[`Chart${i}`] = {\n data: fmt(chartData.chartSpace),\n path: `xl/charts/chart${i + 1}.xml`,\n };\n file.contentTypes.addChart(i + 1);\n }\n\n // Register image content types\n const imageExts = new Set<string>();\n for (const img of file.media.array) {\n const ext = img.fileName.endsWith(\".png\") ? \"png\" : \"jpeg\";\n if (!imageExts.has(ext)) {\n imageExts.add(ext);\n file.contentTypes.addImageType(ext as \"png\" | \"jpeg\");\n }\n }\n\n // Content Types — must be last\n mapping[\"ContentTypes\"] = {\n data: fmt(file.contentTypes),\n path: \"[Content_Types].xml\",\n };\n\n // Convert mapping to Zippable\n const mediaFiles: Array<{ data: Uint8Array; path: string }> = [];\n for (const img of file.media.array) {\n mediaFiles.push({ data: img.data, path: `xl/media/${img.fileName}` });\n }\n\n return compileMapping(mapping, overrides, mediaFiles, mediaLevel);\n }\n}\n\n/**\n * Extract source data from worksheet rows for pivot cache generation.\n */\nfunction extractPivotSourceData(\n rows: readonly import(\"@file/worksheet\").RowOptions[],\n sourceRef: string,\n): PivotSourceData {\n // Parse source range like \"A1:D11\"\n const parts = sourceRef.split(\":\");\n const startMatch = parts[0]?.match(/^([A-Z]+)(\\d+)$/);\n const endMatch = parts[1]?.match(/^([A-Z]+)(\\d+)$/);\n if (!startMatch) {\n return { fieldNames: [], records: [] };\n }\n\n const startRow = parseInt(startMatch[2], 10) - 1;\n const endRow = endMatch ? parseInt(endMatch[2], 10) - 1 : startRow;\n const startCol = colLetterToIndex(startMatch[1]);\n const endCol = endMatch ? colLetterToIndex(endMatch[1]) : startCol;\n const colCount = endCol - startCol + 1;\n\n // First row is headers\n const headerRow = rows[startRow];\n const fieldNames: string[] = [];\n if (headerRow?.cells) {\n for (let c = startCol; c <= endCol && c < headerRow.cells.length; c++) {\n fieldNames.push(String(headerRow.cells[c]?.value ?? `Col${c}`));\n }\n }\n\n // Remaining rows are data\n const records: (string | number)[][] = [];\n for (let r = startRow + 1; r <= endRow; r++) {\n const row = rows[r];\n if (!row?.cells) continue;\n const record: (string | number)[] = [];\n for (let c = startCol; c <= endCol; c++) {\n const val = row.cells[c]?.value;\n if (typeof val === \"number\") {\n record.push(val);\n } else if (val instanceof Date) {\n record.push(val.getTime());\n } else {\n record.push(String(val ?? \"\"));\n }\n }\n if (record.length === colCount) {\n records.push(record);\n }\n }\n\n return { fieldNames, records };\n}\n\nfunction colLetterToIndex(letters: string): number {\n let col = 0;\n for (let i = 0; i < letters.length; i++) {\n col = col * 26 + (letters.charCodeAt(i) - 64);\n }\n return col - 1;\n}\n\n/**\n * Pre-render pivot table output as sheetData cells.\n * Excel requires this so the pivot table is visible on open without manual refresh.\n */\nfunction renderPivotSheetData(\n pivotOpts: readonly PivotTableOptions[],\n worksheets: readonly import(\"@file/worksheet\").Worksheet[],\n sharedStrings: import(\"@file/shared-strings\").SharedStrings,\n worksheetConfigs: readonly import(\"@file/worksheet\").WorksheetOptions[],\n currentSheetName: string,\n): { sheetData: string; dimensionRef: string } {\n // Collect cells by row number to merge cells from different pivot tables on the same row\n const rowCells = new Map<number, string[]>();\n let maxRow = 0;\n let maxCol = 0;\n let minRow = Infinity;\n let minCol = Infinity;\n\n for (const pt of pivotOpts) {\n const location = pt.location ?? \"A3\";\n const locMatch = location.match(/^([A-Z]+)(\\d+)$/);\n if (!locMatch) continue;\n\n const startCol = colLetterToIndex(locMatch[1]);\n const startRow = parseInt(locMatch[2], 10);\n const rowFieldNames = pt.rows;\n const dataFields = pt.data;\n\n const sourceSheetName = pt.sourceSheet ?? currentSheetName;\n const sourceWsIdx = worksheetConfigs.findIndex(\n (ws) => (ws.name ?? `Sheet${worksheetConfigs.indexOf(ws) + 1}`) === sourceSheetName,\n );\n if (sourceWsIdx === -1) continue;\n\n const sourceRows = worksheets[sourceWsIdx]?.worksheetRows ?? [];\n const sourceData = extractPivotSourceData(sourceRows, pt.source);\n if (sourceData.fieldNames.length === 0) continue;\n\n const fields = sourceData.fieldNames;\n const rowFieldIndices = rowFieldNames.map((n) => fields.indexOf(n));\n const dataFieldIndices = dataFields.map((df) => fields.indexOf(df.field));\n\n if (rowFieldIndices.some((idx) => idx === -1)) continue;\n if (dataFieldIndices.some((idx) => idx === -1)) continue;\n\n // Group records by row field values\n const groupMap = new Map<string, { keys: (string | number)[]; values: number[][] }>();\n for (const record of sourceData.records) {\n const groupKey = rowFieldIndices.map((fi) => String(record[fi])).join(\"|\");\n let group = groupMap.get(groupKey);\n if (!group) {\n group = {\n keys: rowFieldIndices.map((fi) => record[fi]),\n values: dataFieldIndices.map(() => []),\n };\n groupMap.set(groupKey, group);\n }\n for (let di = 0; di < dataFieldIndices.length; di++) {\n const val = record[dataFieldIndices[di]];\n if (typeof val === \"number\") {\n group.values[di].push(val);\n }\n }\n }\n\n const endCol = startCol + rowFieldNames.length + dataFields.length - 1;\n minCol = Math.min(minCol, startCol);\n maxCol = Math.max(maxCol, endCol);\n\n // Helper to add cells to a row\n const addCells = (rowIdx: number, cells: string[]) => {\n let arr = rowCells.get(rowIdx);\n if (!arr) {\n arr = [];\n rowCells.set(rowIdx, arr);\n }\n arr.push(...cells);\n minRow = Math.min(minRow, rowIdx);\n maxRow = Math.max(maxRow, rowIdx);\n };\n\n // Header row\n const headerCells: string[] = [];\n for (const rfName of rowFieldNames) {\n const cellRef = colIndexToLetterCompiler(startCol + headerCells.length) + startRow;\n const strIdx = sharedStrings.register(rfName);\n headerCells.push(`<c r=\"${cellRef}\" t=\"s\"><v>${strIdx}</v></c>`);\n }\n for (const df of dataFields) {\n const cellRef = colIndexToLetterCompiler(startCol + headerCells.length) + startRow;\n const subtotal = df.summarize ?? \"sum\";\n const dfName = df.name ?? `${subtotal === \"sum\" ? \"Sum\" : subtotal} of ${df.field}`;\n const strIdx = sharedStrings.register(dfName);\n headerCells.push(`<c r=\"${cellRef}\" t=\"s\"><v>${strIdx}</v></c>`);\n }\n addCells(startRow, headerCells);\n\n // Data rows\n let currentRow = startRow + 1;\n for (const [, group] of groupMap) {\n const cells: string[] = [];\n for (let ri = 0; ri < group.keys.length; ri++) {\n const cellRef = colIndexToLetterCompiler(startCol + ri) + currentRow;\n const strIdx = sharedStrings.register(String(group.keys[ri]));\n cells.push(`<c r=\"${cellRef}\" t=\"s\"><v>${strIdx}</v></c>`);\n }\n for (let di = 0; di < dataFields.length; di++) {\n const colOffset = rowFieldNames.length + di;\n const cellRef = colIndexToLetterCompiler(startCol + colOffset) + currentRow;\n const subtotal = dataFields[di].summarize ?? \"sum\";\n const result = aggregate(group.values[di], subtotal);\n cells.push(`<c r=\"${cellRef}\"><v>${result}</v></c>`);\n }\n addCells(currentRow, cells);\n currentRow++;\n }\n\n // Grand total row\n const gtCells: string[] = [];\n const gtStrIdx = sharedStrings.register(\"Grand Total\");\n gtCells.push(\n `<c r=\"${colIndexToLetterCompiler(startCol)}${currentRow}\" t=\"s\"><v>${gtStrIdx}</v></c>`,\n );\n for (let di = 0; di < dataFields.length; di++) {\n const colOffset = rowFieldNames.length + di;\n const cellRef = colIndexToLetterCompiler(startCol + colOffset) + currentRow;\n const subtotal = dataFields[di].summarize ?? \"sum\";\n const allValues = sourceData.records\n .map((r) => r[dataFieldIndices[di]])\n .filter((v): v is number => typeof v === \"number\");\n const result = aggregate(allValues, subtotal);\n gtCells.push(`<c r=\"${cellRef}\"><v>${result}</v></c>`);\n }\n addCells(currentRow, gtCells);\n }\n\n if (rowCells.size === 0) return { sheetData: \"\", dimensionRef: \"\" };\n\n // Build sheetData — rows must be sorted by row number\n const parts: string[] = [\"<sheetData>\"];\n const sortedRows = [...rowCells.entries()].sort((a, b) => a[0] - b[0]);\n for (const [rowIdx, cells] of sortedRows) {\n parts.push(`<row r=\"${rowIdx}\" x14ac:dyDescent=\"0.25\">`);\n parts.push(...cells);\n parts.push(\"</row>\");\n }\n parts.push(\"</sheetData>\");\n\n const dimStartCol = colIndexToLetterCompiler(minCol === Infinity ? 0 : minCol);\n const dimStartRow = minRow === Infinity ? 1 : minRow;\n const dimensionRef = `${dimStartCol}${dimStartRow}:${colIndexToLetterCompiler(maxCol)}${maxRow}`;\n return { sheetData: parts.join(\"\"), dimensionRef };\n}\n\nfunction colIndexToLetterCompiler(col: number): string {\n let result = \"\";\n let n = col + 1; // 0-indexed to 1-indexed\n while (n > 0) {\n n--;\n result = String.fromCharCode(65 + (n % 26)) + result;\n n = Math.floor(n / 26);\n }\n return result;\n}\n","import type { File } from \"@file/file\";\n/**\n * Packer module — export API for XLSX files.\n *\n * @module\n */\nimport { createPacker, OoxmlMimeType } from \"@office-open/core\";\n\nimport { Compiler } from \"./next-compiler\";\n\nconst compiler = new Compiler();\n\nexport const Packer = createPacker<File>({\n compile: (file, overrides, mediaLevel) => compiler.compile(file, overrides, mediaLevel),\n mimeType: OoxmlMimeType.XLSX,\n});\n","/**\n * Convert a 1-based column number to Excel column letter(s).\n * 1 → \"A\", 26 → \"Z\", 27 → \"AA\", 28 → \"AB\"\n */\nexport function columnToLetter(col: number): string {\n let result = \"\";\n let n = col;\n while (n > 0) {\n const remainder = (n - 1) % 26;\n result = String.fromCharCode(65 + remainder) + result;\n n = Math.floor((n - 1) / 26);\n }\n return result;\n}\n\n/**\n * Convert Excel column letter(s) to a 1-based column number.\n * \"A\" → 1, \"Z\" → 26, \"AA\" → 27\n */\nexport function letterToColumn(s: string): number {\n let result = 0;\n for (let i = 0; i < s.length; i++) {\n result = result * 26 + (s.charCodeAt(i) - 64);\n }\n return result;\n}\n\n/**\n * Convert a JavaScript Date to an Excel serial number.\n * Excel epoch: January 1, 1900 = 1 (with the 1900 leap year bug).\n */\nexport function dateToSerialNumber(date: Date): number {\n // Excel treats 1900 as a leap year (bug inherited from Lotus 1-2-3).\n // The epoch is effectively December 30, 1899 = 0.\n const epoch = new Date(1899, 11, 30);\n const msPerDay = 86400000;\n const diff = date.getTime() - epoch.getTime();\n return diff / msPerDay;\n}\n","/**\n * XLSX parsing — parse .xlsx files into structured data.\n *\n * @module\n */\nimport { parseArchive, parseCorePropsElement } from \"@office-open/core\";\nimport type { ParsedArchive } from \"@office-open/core\";\nimport type { Element } from \"@office-open/xml\";\nimport { attr, attrNum, findChild, textOf } from \"@office-open/xml\";\nimport { toUint8Array } from \"undio\";\nimport type { DataType } from \"undio\";\n\nimport type { WorkbookOptions } from \"./file/file\";\nimport type {\n WorksheetOptions,\n RowOptions,\n CellOptions,\n ColumnOptions,\n MergeCellOptions,\n} from \"./file/worksheet\";\nimport { letterToColumn } from \"./util\";\n\nexport { parseArchive };\n\n// ── Low-level parse result ──\n\nexport interface XlsxPartRefs {\n worksheets: string[];\n charts: string[];\n media: string[];\n drawings: string[];\n}\n\nexport interface XlsxDocument {\n doc: ParsedArchive;\n /** xl/workbook.xml root element */\n workbook?: Element;\n /** Worksheet paths (xl/worksheets/sheet{n}.xml) */\n worksheets: string[];\n /** xl/styles.xml root element */\n styles?: Element;\n /** xl/sharedStrings.xml root element */\n sharedStrings?: Element;\n partRefs: XlsxPartRefs;\n /** docProps/core.xml path */\n coreProps?: string;\n /** docProps/app.xml path */\n appProps?: string;\n}\n\nfunction sortByNumber(paths: string[]): string[] {\n return paths.sort((a, b) => {\n const numA = parseInt(a.match(/(\\d+)/)?.[1] ?? \"0\", 10);\n const numB = parseInt(b.match(/(\\d+)/)?.[1] ?? \"0\", 10);\n return numA - numB;\n });\n}\n\n/**\n * Parse raw .xlsx data into a low-level XlsxDocument.\n */\nexport function parseXlsx(data: DataType): XlsxDocument {\n const uint8 = toUint8Array(data);\n const doc = parseArchive(uint8);\n\n const workbook = doc.get(\"xl/workbook.xml\");\n const styles = doc.get(\"xl/styles.xml\");\n const sharedStrings = doc.get(\"xl/sharedStrings.xml\");\n\n // Resolve worksheet paths from workbook rels\n const worksheets: string[] = [];\n const charts: string[] = [];\n const drawings: string[] = [];\n const media: string[] = [];\n\n const wbRels = doc.get(\"xl/_rels/workbook.xml.rels\");\n if (wbRels) {\n for (const child of wbRels.elements ?? []) {\n if (child.name !== \"Relationship\") continue;\n const type = attr(child, \"Type\") ?? \"\";\n const target = attr(child, \"Target\") ?? \"\";\n if (!target) continue;\n\n if (type.includes(\"/worksheet\")) {\n worksheets.push(target.startsWith(\"/\") ? target.slice(1) : `xl/${target}`);\n }\n }\n }\n sortByNumber(worksheets);\n\n // Scan for drawings, charts, media\n drawings.push(...doc.keys(\"xl/drawings/\").filter((k) => k.endsWith(\".xml\")));\n charts.push(...doc.keys(\"xl/charts/\").filter((k) => k.endsWith(\".xml\")));\n media.push(...doc.keys(\"xl/media/\"));\n sortByNumber(drawings);\n sortByNumber(charts);\n\n // Root rels → core/app props\n let coreProps: string | undefined;\n let appProps: string | undefined;\n const rootRels = doc.get(\"_rels/.rels\");\n if (rootRels) {\n for (const child of rootRels.elements ?? []) {\n if (child.name !== \"Relationship\") continue;\n const type = attr(child, \"Type\") ?? \"\";\n const target = attr(child, \"Target\") ?? \"\";\n if (type.includes(\"/core-properties\")) coreProps = target;\n else if (type.includes(\"/extended-properties\")) appProps = target;\n }\n }\n\n return {\n doc,\n workbook,\n worksheets,\n styles,\n sharedStrings,\n partRefs: { worksheets, charts, media, drawings },\n coreProps,\n appProps,\n };\n}\n\n// ── Shared strings helper ──\n\nfunction parseSharedStrings(el: Element | undefined): string[] {\n if (!el) return [];\n const strings: string[] = [];\n for (const si of el.elements ?? []) {\n if (si.name !== \"si\") continue;\n // Handle both <si><t>text</t></si> and <si><r><t>text</t></r>...</si>\n const t = findChild(si, \"t\");\n if (t) {\n strings.push(textOf(t) ?? \"\");\n } else {\n // Rich text: concatenate all <r><t> segments\n const parts: string[] = [];\n for (const r of si.elements ?? []) {\n if (r.name !== \"r\") continue;\n const rt = findChild(r, \"t\");\n if (rt) parts.push(textOf(rt) ?? \"\");\n }\n strings.push(parts.join(\"\"));\n }\n }\n return strings;\n}\n\n// ── Cell reference helpers ──\n\nfunction colFromRef(ref: string): number {\n const match = ref.match(/^([A-Z]+)/);\n return match ? letterToColumn(match[1]) : 1;\n}\n\nfunction rowFromRef(ref: string): number {\n const match = ref.match(/(\\d+)$/);\n return match ? parseInt(match[1], 10) : 1;\n}\n\n// ── Worksheet parsing ──\n\nfunction parseWorksheetElement(wsEl: Element, strings: string[]): WorksheetOptions {\n const opts: Record<string, unknown> = {};\n\n // Sheet name from the parent workbook's sheet element (not available here)\n // Caller should set it\n\n // Columns\n // Elements might be prefixed or unprefixed depending on how the XML parser handles default namespaces.\n const colsEl = findChild(wsEl, \"cols\") ?? findChildByLocalName(wsEl, \"cols\");\n if (colsEl) {\n const columns: ColumnOptions[] = [];\n for (const col of colsEl.elements ?? []) {\n if (localName(col) !== \"col\") continue;\n const min = attrNum(col, \"min\");\n const max = attrNum(col, \"max\");\n if (min === undefined || max === undefined) continue;\n const colOpts: Record<string, unknown> = { min, max };\n const width = attrNum(col, \"width\");\n if (width !== undefined) colOpts.width = width;\n if (attr(col, \"hidden\") === \"1\") colOpts.hidden = true;\n columns.push(colOpts as unknown as ColumnOptions);\n }\n if (columns.length > 0) opts.columns = columns;\n }\n\n // Freeze panes\n const sheetViews = findChildByLocalName(wsEl, \"sheetViews\");\n if (sheetViews) {\n const sheetView = findChildByLocalName(sheetViews, \"sheetView\");\n if (sheetView) {\n const pane = findChildByLocalName(sheetView, \"pane\");\n if (pane) {\n const state = attr(pane, \"state\");\n if (state === \"frozen\") {\n const freezePanes: Record<string, unknown> = {};\n const ySplit = attrNum(pane, \"ySplit\");\n const xSplit = attrNum(pane, \"xSplit\");\n if (ySplit && ySplit > 0) freezePanes.row = ySplit;\n if (xSplit && xSplit > 0) freezePanes.col = xSplit;\n if (Object.keys(freezePanes).length > 0) opts.freezePanes = freezePanes;\n }\n }\n }\n }\n\n // Sheet data (rows)\n const sheetData = findChildByLocalName(wsEl, \"sheetData\");\n const rows: RowOptions[] = [];\n if (sheetData) {\n for (const rowEl of sheetData.elements ?? []) {\n if (localName(rowEl) !== \"row\") continue;\n const rowNumber = attrNum(rowEl, \"r\");\n const rowOpts: Record<string, unknown> = {};\n if (rowNumber !== undefined) rowOpts.rowNumber = rowNumber;\n\n const ht = attrNum(rowEl, \"ht\");\n if (ht !== undefined) rowOpts.height = ht;\n if (attr(rowEl, \"hidden\") === \"1\") rowOpts.hidden = true;\n\n const cells: CellOptions[] = [];\n for (const cellEl of rowEl.elements ?? []) {\n if (localName(cellEl) !== \"c\") continue;\n const ref = attr(cellEl, \"r\");\n const type = attr(cellEl, \"t\");\n const cellOpts: Record<string, unknown> = {};\n if (ref) cellOpts.reference = ref;\n\n const styleIdx = attrNum(cellEl, \"s\");\n if (styleIdx !== undefined) cellOpts.styleIndex = styleIdx;\n\n // Cell value\n const vEl = findChildByLocalName(cellEl, \"v\");\n const isEl = findChildByLocalName(cellEl, \"is\");\n\n if (type === \"s\" && vEl) {\n // Shared string\n const idx = parseInt(textOf(vEl) ?? \"\", 10);\n cellOpts.value = strings[idx] ?? \"\";\n } else if (type === \"b\" && vEl) {\n cellOpts.value = textOf(vEl) === \"1\";\n } else if (type === \"inlineStr\" && isEl) {\n const t = findChildByLocalName(isEl, \"t\");\n cellOpts.value = textOf(t) ?? \"\";\n } else if (vEl) {\n const raw = textOf(vEl) ?? \"\";\n const num = Number(raw);\n cellOpts.value = isNaN(num) ? raw : num;\n }\n\n cells.push(cellOpts as CellOptions);\n }\n\n rowOpts.cells = cells;\n rows.push(rowOpts as RowOptions);\n }\n }\n opts.rows = rows;\n\n // Merge cells\n const mergeCellsEl = findChildByLocalName(wsEl, \"mergeCells\");\n if (mergeCellsEl) {\n const mergeCells: MergeCellOptions[] = [];\n for (const mc of mergeCellsEl.elements ?? []) {\n if (localName(mc) !== \"mergeCell\") continue;\n const ref = attr(mc, \"ref\");\n if (!ref) continue;\n const parts = ref.split(\":\");\n if (parts.length === 2) {\n mergeCells.push({\n from: { row: rowFromRef(parts[0]), col: colFromRef(parts[0]) },\n to: { row: rowFromRef(parts[1]), col: colFromRef(parts[1]) },\n });\n }\n }\n if (mergeCells.length > 0) opts.mergeCells = mergeCells;\n }\n\n // Auto filter\n const autoFilterEl = findChildByLocalName(wsEl, \"autoFilter\");\n if (autoFilterEl) {\n const ref = attr(autoFilterEl, \"ref\");\n if (ref) opts.autoFilter = ref;\n }\n\n return opts as WorksheetOptions;\n}\n\n// ── Helpers ──\n\nfunction localName(el: Element): string {\n const name = el.name ?? \"\";\n const colonIdx = name.indexOf(\":\");\n return colonIdx >= 0 ? name.slice(colonIdx + 1) : name;\n}\n\nfunction findChildByLocalName(parent: Element, name: string): Element | undefined {\n return (parent.elements ?? []).find((el) => localName(el) === name);\n}\n\n/**\n * Parse a .xlsx file and convert it into WorkbookOptions.\n *\n * The returned options can be passed to `new Workbook(parsed)`.\n */\nexport function parseWorkbook(data: DataType): WorkbookOptions {\n const xlsx = parseXlsx(data);\n\n const opts: Record<string, unknown> = {};\n\n // Core properties\n if (xlsx.coreProps) {\n const corePropsEl = xlsx.doc.get(xlsx.coreProps);\n if (corePropsEl) {\n const cp = parseCorePropsElement(corePropsEl);\n if (cp.title) opts.title = cp.title;\n if (cp.subject) opts.subject = cp.subject;\n if (cp.creator) opts.creator = cp.creator;\n if (cp.keywords) opts.keywords = cp.keywords;\n if (cp.description) opts.description = cp.description;\n if (cp.lastModifiedBy) opts.lastModifiedBy = cp.lastModifiedBy;\n if (cp.revision) opts.revision = parseInt(cp.revision, 10);\n }\n }\n\n // Shared strings\n const strings = parseSharedStrings(xlsx.sharedStrings);\n\n // Sheet names from workbook\n const sheetNames: string[] = [];\n if (xlsx.workbook) {\n const sheetsEl = findChildByLocalName(xlsx.workbook, \"sheets\");\n if (sheetsEl) {\n for (const s of sheetsEl.elements ?? []) {\n if (localName(s) !== \"sheet\") continue;\n sheetNames.push(attr(s, \"name\") ?? \"\");\n }\n }\n }\n\n // Parse worksheets\n const worksheets: WorksheetOptions[] = [];\n for (let i = 0; i < xlsx.worksheets.length; i++) {\n const wsPath = xlsx.worksheets[i];\n const wsEl = xlsx.doc.get(wsPath);\n if (!wsEl) continue;\n\n const wsOpts = parseWorksheetElement(wsEl, strings) as Record<string, unknown>;\n if (sheetNames[i]) wsOpts.name = sheetNames[i];\n worksheets.push(wsOpts as WorksheetOptions);\n }\n\n opts.worksheets = worksheets;\n return opts as WorkbookOptions;\n}\n","/**\n * XLSX patching — replace placeholders in existing .xlsx files.\n *\n * Unlike DOCX/PPTX (paragraph-based), XLSX patching targets cell values:\n * - Replaces placeholders in the shared strings table (most common)\n * - Replaces placeholders in inline strings within worksheet cells\n *\n * @module\n */\nimport { OoxmlMimeType, unzipSync, zipAndConvert, strFromU8, toJson } from \"@office-open/core\";\nimport type { OutputByType, OutputType } from \"@office-open/core\";\nimport { js2xml } from \"@office-open/xml\";\nimport type { Element } from \"@office-open/xml\";\nimport { toUint8Array } from \"undio\";\n\n/** Reusable TextEncoder (stateless, safe to share). */\nconst encoder = new TextEncoder();\n\nexport type InputDataType = Buffer | string | number[] | Uint8Array | ArrayBuffer | Blob;\n\nexport type PatchDocumentOutputType = OutputType;\n\nexport const PatchType = {\n CELL: \"cell\",\n} as const;\n\nexport interface CellPatch {\n /** Replacement value (string, number, boolean, or Date) */\n readonly value: string | number | boolean | Date;\n}\n\nexport type IPatch = CellPatch;\n\nexport interface PatchWorkbookOptions<T extends PatchDocumentOutputType = PatchDocumentOutputType> {\n readonly outputType: T;\n readonly data: InputDataType;\n readonly patches: Readonly<Record<string, IPatch>>;\n readonly placeholderDelimiters?: Readonly<{\n readonly start: string;\n readonly end: string;\n }>;\n}\n\n/**\n * Patch an existing .xlsx workbook by replacing placeholder text in cells.\n *\n * Placeholders are matched in shared strings and inline strings.\n * For string replacements, the shared string value is updated in-place.\n * For non-string replacements, the cell type and value are updated.\n */\nexport const patchWorkbook = async <T extends PatchDocumentOutputType = PatchDocumentOutputType>({\n outputType,\n data,\n patches,\n placeholderDelimiters = { start: \"{{\", end: \"}}\" } as const,\n}: PatchWorkbookOptions<T>): Promise<OutputByType[T]> => {\n const zipContent = unzipSync(toUint8Array(data));\n\n const xmlMap = new Map<string, Element>();\n const binaryMap = new Map<string, Uint8Array>();\n\n // Separate XML files from binary files\n for (const [key, value] of Object.entries(zipContent)) {\n if (key.endsWith(\".xml\") || key.endsWith(\".rels\")) {\n xmlMap.set(key, toJson(strFromU8(value)));\n } else {\n binaryMap.set(key, value);\n }\n }\n\n const { start, end } = placeholderDelimiters;\n\n // Build placeholder → patch map\n const patchMap = new Map<string, IPatch>();\n for (const [key, patch] of Object.entries(patches)) {\n patchMap.set(`${start}${key}${end}`, patch);\n }\n\n // 1. Patch shared strings\n const sst = xmlMap.get(\"xl/sharedStrings.xml\");\n if (sst) {\n patchSharedStrings(sst, patchMap);\n }\n\n // 2. Patch inline strings in worksheets\n const worksheetKeys = Object.keys(zipContent).filter(\n (k) => k.startsWith(\"xl/worksheets/sheet\") && k.endsWith(\".xml\"),\n );\n for (const wsKey of worksheetKeys) {\n const ws = xmlMap.get(wsKey);\n if (ws) patchWorksheetInlineStrings(ws, patchMap);\n }\n\n // Rebuild ZIP\n const files: Record<string, Uint8Array> = {};\n for (const [key, value] of xmlMap) {\n files[key] = encoder.encode(js2xml(value));\n }\n for (const [key, value] of binaryMap) {\n files[key] = value;\n }\n\n return await zipAndConvert(files, outputType, OoxmlMimeType.XLSX);\n};\n\nfunction patchSharedStrings(sst: Element, patchMap: Map<string, IPatch>): void {\n // toJson returns {elements: [{name: \"sst\", ...}]} — unwrap to actual root\n const root = sst.name ? sst : sst.elements?.[0];\n if (!root) return;\n\n for (const si of root.elements ?? []) {\n if (si.name !== \"si\") continue;\n\n // Simple: <si><t>text</t></si>\n const t = findLocalChild(si, \"t\");\n if (t) {\n patchTextElement(t, patchMap);\n } else {\n // Rich text: <si><r><t>text</t></r>...</si>\n for (const r of si.elements ?? []) {\n if (r.name !== \"r\") continue;\n const rt = findLocalChild(r, \"t\");\n if (rt) patchTextElement(rt, patchMap);\n }\n }\n }\n}\n\nfunction patchWorksheetInlineStrings(ws: Element, patchMap: Map<string, IPatch>): void {\n const root = ws.name ? ws : ws.elements?.[0];\n if (!root) return;\n\n const sheetData = findLocalChild(root, \"sheetData\");\n if (!sheetData) return;\n\n for (const row of sheetData.elements ?? []) {\n if (localName(row) !== \"row\") continue;\n for (const cell of row.elements ?? []) {\n if (localName(cell) !== \"c\") continue;\n\n // Check inline strings: <c t=\"inlineStr\"><is><t>text</t></is></c>\n const isEl = findLocalChild(cell, \"is\");\n if (isEl) {\n const t = findLocalChild(isEl, \"t\");\n if (t) patchTextElement(t, patchMap);\n }\n }\n }\n}\n\nfunction patchTextElement(tEl: Element, patchMap: Map<string, IPatch>): void {\n const text = tEl.elements?.[0]?.text;\n if (typeof text !== \"string\") return;\n\n for (const [placeholder, patch] of patchMap) {\n if (text.includes(placeholder)) {\n const newValue = String(patch.value);\n const replaced = text.replace(placeholder, newValue);\n if (tEl.elements) {\n tEl.elements[0] = { ...tEl.elements[0], text: replaced };\n }\n }\n }\n}\n\nfunction localName(el: Element): string {\n const name = el.name ?? \"\";\n const colonIdx = name.indexOf(\":\");\n return colonIdx >= 0 ? name.slice(colonIdx + 1) : name;\n}\n\nfunction findLocalChild(parent: Element, name: string): Element | undefined {\n return (parent.elements ?? []).find((el) => localName(el) === name);\n}\n"],"mappings":";;;;;;;;;AAQA,MAAM,YAAY;AAClB,MAAM,iBAAiB;AACvB,MAAM,cAAc;AACpB,MAAM,sBACJ;AACF,MAAM,aAAa;AACnB,MAAM,aAAa;AA+BnB,MAAM,aAAa;CApBjB;EACE,MAAM;EACN,aAAa;EACb,KAAK;CACP;CACA;EAAE,MAAM;EAAW,aAAa;EAAmB,KAAK;CAAM;CAC9D;EAAE,MAAM;EAAY,aAAa;EAAW,KAAK;CAAmB;CACpE;EACE,MAAM;EACN,aAAa;EACb,KAAK;CACP;CACA;EACE,MAAM;EACN,aAAa;EACb,KAAK;CACP;AAI8B,EAAE,KAAK,MACrC,EAAE,SAAS,YACP,yBAAyB,EAAE,YAAY,eAAe,EAAE,IAAI,OAC5D,0BAA0B,EAAE,YAAY,cAAc,EAAE,IAAI,IAClE,EAAE,KAAK,EAAE;AAET,IAAa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W,CAAC,IAAI;AACpD;AAEA,SAAS,eAAe,QAAiB,MAAmC;CAC1E,QAAQ,OAAO,YAAY,CAAC,GAAG,MAAM,OAAO,UAAU,EAAE,MAAM,IAAI;AACpE"}
1
+ {"version":3,"file":"index.mjs","names":["columnToLetter","localName"],"sources":["../src/file/content-types.ts","../src/file/core-properties.ts","../src/file/media/media.ts","../src/file/shared-strings.ts","../src/file/styles.ts","../src/file/workbook.ts","../src/file/worksheet.ts","../src/file/file.ts","../src/file/pivot/pivot-utils.ts","../src/file/pivot/pivot-cache-definition-xml.ts","../src/file/pivot/pivot-cache-records-xml.ts","../src/file/pivot/pivot-table-xml.ts","../src/file/table/table-xml.ts","../src/file/dialogsheet/dialogsheet.ts","../src/file/query-table/query-table-xml.ts","../src/file/metadata/metadata-xml.ts","../src/file/revision-log/revision-headers-xml.ts","../src/file/revision-log/revision-xml.ts","../src/file/connection/connection-xml.ts","../src/file/xml-mapping/xml-mapping-xml.ts","../src/file/calc-chain.ts","../src/file/chartsheet/chartsheet.ts","../src/file/comments.ts","../src/file/drawing/drawing.ts","../src/file/external-link/external-link-xml.ts","../src/file/vml-notes.ts","../src/export/packer/next-compiler.ts","../src/export/packer/packer.ts","../src/util/index.ts","../src/parse.ts","../src/patcher.ts"],"sourcesContent":["/**\n * Content Types module for XLSX packages.\n *\n * @module\n */\nimport { BaseXmlComponent } from \"@file/xml-components\";\nimport type { Context } from \"@file/xml-components\";\n\nconst XLSX_MAIN = \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml\";\nconst XLSX_WORKSHEET = \"application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml\";\nconst XLSX_CHARTSHEET =\n \"application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml\";\nconst XLSX_STYLES = \"application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml\";\nconst XLSX_SHARED_STRINGS =\n \"application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml\";\nconst XLSX_THEME = \"application/vnd.openxmlformats-officedocument.theme+xml\";\nconst XLSX_CHART = \"application/vnd.openxmlformats-officedocument.drawingml.chart+xml\";\n\ntype EntryType = \"Default\" | \"Override\";\n\ninterface ContentEntry {\n readonly type: EntryType;\n readonly contentType: string;\n readonly key: string;\n}\n\nconst STATIC_ENTRIES: readonly ContentEntry[] = [\n {\n type: \"Default\",\n contentType: \"application/vnd.openxmlformats-package.relationships+xml\",\n key: \"rels\",\n },\n { type: \"Default\", contentType: \"application/xml\", key: \"xml\" },\n { type: \"Override\", contentType: XLSX_MAIN, key: \"/xl/workbook.xml\" },\n {\n type: \"Override\",\n contentType: \"application/vnd.openxmlformats-package.core-properties+xml\",\n key: \"/docProps/core.xml\",\n },\n {\n type: \"Override\",\n contentType: \"application/vnd.openxmlformats-officedocument.extended-properties+xml\",\n key: \"/docProps/app.xml\",\n },\n];\n\n// Pre-compiled static XML fragment (module-level constant)\nconst STATIC_XML = STATIC_ENTRIES.map((e) =>\n e.type === \"Default\"\n ? `<Default ContentType=\"${e.contentType}\" Extension=\"${e.key}\"/>`\n : `<Override ContentType=\"${e.contentType}\" PartName=\"${e.key}\"/>`,\n).join(\"\");\n\nexport class ContentTypes extends BaseXmlComponent {\n private readonly dynamicEntries: ContentEntry[] = [];\n\n public constructor() {\n super(\"Types\");\n }\n\n public addWorksheet(index: number): void {\n this.dynamicEntries.push({\n type: \"Override\",\n contentType: XLSX_WORKSHEET,\n key: `/xl/worksheets/sheet${index}.xml`,\n });\n }\n\n public addChartsheet(index: number): void {\n this.dynamicEntries.push({\n type: \"Override\",\n contentType: XLSX_CHARTSHEET,\n key: `/xl/chartsheets/sheet${index}.xml`,\n });\n }\n\n public addStyles(): void {\n this.dynamicEntries.push({\n type: \"Override\",\n contentType: XLSX_STYLES,\n key: \"/xl/styles.xml\",\n });\n }\n\n public addSharedStrings(): void {\n this.dynamicEntries.push({\n type: \"Override\",\n contentType: XLSX_SHARED_STRINGS,\n key: \"/xl/sharedStrings.xml\",\n });\n }\n\n public addTheme(index: number = 1): void {\n this.dynamicEntries.push({\n type: \"Override\",\n contentType: XLSX_THEME,\n key: `/xl/theme/theme${index}.xml`,\n });\n }\n\n public addChart(index: number): void {\n this.dynamicEntries.push({\n type: \"Override\",\n contentType: XLSX_CHART,\n key: `/xl/charts/chart${index}.xml`,\n });\n }\n\n public addDrawing(index: number): void {\n this.dynamicEntries.push({\n type: \"Override\",\n contentType: \"application/vnd.openxmlformats-officedocument.drawing+xml\",\n key: `/xl/drawings/drawing${index}.xml`,\n });\n }\n\n public addComments(index: number): void {\n this.dynamicEntries.push({\n type: \"Override\",\n contentType: \"application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml\",\n key: `/xl/comments${index}.xml`,\n });\n }\n\n public addVmlDrawing(): void {\n if (this.dynamicEntries.some((e) => e.type === \"Default\" && e.key === \"vml\")) return;\n this.dynamicEntries.push({\n type: \"Default\",\n contentType: \"application/vnd.openxmlformats-officedocument.vmlDrawing\",\n key: \"vml\",\n });\n }\n\n public addImageType(extension: \"png\" | \"jpeg\"): void {\n const contentType = extension === \"png\" ? \"image/png\" : \"image/jpeg\";\n if (this.dynamicEntries.some((e) => e.type === \"Default\" && e.key === extension)) return;\n this.dynamicEntries.push({ type: \"Default\", contentType, key: extension });\n }\n\n public addPivotTable(index: number): void {\n this.dynamicEntries.push({\n type: \"Override\",\n contentType: \"application/vnd.openxmlformats-officedocument.spreadsheetml.pivotTable+xml\",\n key: `/xl/pivotTables/pivotTable${index}.xml`,\n });\n }\n\n public addPivotCacheDefinition(index: number): void {\n this.dynamicEntries.push({\n type: \"Override\",\n contentType:\n \"application/vnd.openxmlformats-officedocument.spreadsheetml.pivotCacheDefinition+xml\",\n key: `/xl/pivotCache/pivotCacheDefinition${index}.xml`,\n });\n }\n\n public addPivotCacheRecords(index: number): void {\n this.dynamicEntries.push({\n type: \"Override\",\n contentType:\n \"application/vnd.openxmlformats-officedocument.spreadsheetml.pivotCacheRecords+xml\",\n key: `/xl/pivotCache/pivotCacheRecords${index}.xml`,\n });\n }\n\n public addTable(index: number): void {\n this.dynamicEntries.push({\n type: \"Override\",\n contentType: \"application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml\",\n key: `/xl/tables/table${index}.xml`,\n });\n }\n\n public addExternalLink(index: number): void {\n this.dynamicEntries.push({\n type: \"Override\",\n contentType: \"application/vnd.openxmlformats-officedocument.spreadsheetml.externalLink+xml\",\n key: `/xl/externalLinks/externalLink${index}.xml`,\n });\n }\n\n public addCalcChain(): void {\n this.dynamicEntries.push({\n type: \"Override\",\n contentType: \"application/vnd.openxmlformats-officedocument.spreadsheetml.calcChain+xml\",\n key: \"/xl/calcChain.xml\",\n });\n }\n\n public addDialogsheet(index: number): void {\n this.dynamicEntries.push({\n type: \"Override\",\n contentType: \"application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml\",\n key: `/xl/dialogsheets/sheet${index}.xml`,\n });\n }\n\n public addRevisionHeaders(): void {\n this.dynamicEntries.push({\n type: \"Override\",\n contentType:\n \"application/vnd.openxmlformats-officedocument.spreadsheetml.revisionHeaders+xml\",\n key: \"/xl/revisionHeaders.xml\",\n });\n }\n\n public addRevisionLog(index: number): void {\n this.dynamicEntries.push({\n type: \"Override\",\n contentType: \"application/vnd.openxmlformats-officedocument.spreadsheetml.revisionLog+xml\",\n key: `/xl/revisions/revision${index}.xml`,\n });\n }\n\n public addQueryTable(index: number): void {\n this.dynamicEntries.push({\n type: \"Override\",\n contentType: \"application/vnd.openxmlformats-officedocument.spreadsheetml.queryTable+xml\",\n key: `/xl/queryTables/queryTable${index}.xml`,\n });\n }\n\n public addMetadata(): void {\n this.dynamicEntries.push({\n type: \"Override\",\n contentType: \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheetMetadata+xml\",\n key: \"/xl/metadata.xml\",\n });\n }\n\n public override toXml(_context: Context): string {\n const p: string[] = [\n '<Types xmlns=\"http://schemas.openxmlformats.org/package/2006/content-types\">',\n STATIC_XML,\n ];\n for (const e of this.dynamicEntries) {\n if (e.type === \"Default\") {\n p.push(`<Default ContentType=\"${e.contentType}\" Extension=\"${e.key}\"/>`);\n } else {\n p.push(`<Override ContentType=\"${e.contentType}\" PartName=\"${e.key}\"/>`);\n }\n }\n p.push(\"</Types>\");\n return p.join(\"\");\n }\n}\n","/**\n * Core Properties module for SpreadsheetML documents.\n *\n * @module\n */\nimport { BaseXmlComponent } from \"@file/xml-components\";\nimport type { Context } from \"@file/xml-components\";\nimport { buildCorePropertiesXmlString } from \"@office-open/core\";\n\nexport interface CorePropertiesOptions {\n readonly title?: string;\n readonly subject?: string;\n readonly creator?: string;\n readonly keywords?: string;\n readonly description?: string;\n readonly lastModifiedBy?: string;\n readonly revision?: number;\n}\n\nexport class CoreProperties extends BaseXmlComponent {\n private readonly options: CorePropertiesOptions;\n\n public constructor(options: CorePropertiesOptions) {\n super(\"cp:coreProperties\");\n this.options = options;\n }\n\n public override toXml(_context: Context): string {\n return buildCorePropertiesXmlString(this.options);\n }\n}\n","/**\n * Media collection for XLSX files — stores image binary data.\n *\n * @module\n */\n\nexport interface MediaData {\n readonly fileName: string;\n readonly type: string;\n readonly data: Uint8Array;\n readonly width: number;\n readonly height: number;\n}\n\nexport class Media {\n private readonly map = new Map<string, MediaData>();\n\n public addImage(key: string, data: MediaData): void {\n this.map.set(key, data);\n }\n\n public get array(): readonly MediaData[] {\n return [...this.map.values()];\n }\n}\n","/**\n * Shared Strings Table — generates xl/sharedStrings.xml.\n *\n * XLSX stores repeated string values in a central table to reduce file size.\n * Cells reference strings by index into this table.\n *\n * @module\n */\nimport { BaseXmlComponent } from \"@file/xml-components\";\nimport type { Context } from \"@file/xml-components\";\nimport { escapeXml } from \"@office-open/xml\";\n\nimport type { RichTextOptions } from \"./worksheet\";\n\n/** String or rich text entry in the SST. */\ntype SstEntry = string | RichTextOptions;\n\n/**\n * Build rich text run properties XML (CT_RPrElt).\n * Exported for reuse by Comments and other components.\n */\nexport function buildRPrXml(\n pr: NonNullable<RichTextOptions[\"runs\"]>[number][\"properties\"],\n): string {\n if (!pr) return \"\";\n const parts: string[] = [];\n if (pr.font) parts.push(`<rFont val=\"${escapeXml(pr.font)}\"/>`);\n if (pr.charset !== undefined) parts.push(`<charset val=\"${pr.charset}\"/>`);\n if (pr.family !== undefined) parts.push(`<family val=\"${pr.family}\"/>`);\n if (pr.bold) parts.push(\"<b/>\");\n if (pr.italic) parts.push(\"<i/>\");\n if (pr.strike) parts.push(\"<strike/>\");\n if (pr.outline) parts.push(\"<outline/>\");\n if (pr.shadow) parts.push(\"<shadow/>\");\n if (pr.condense) parts.push(\"<condense/>\");\n if (pr.extend) parts.push(\"<extend/>\");\n if (pr.color) parts.push(`<color rgb=\"${escapeXml(pr.color)}\"/>`);\n if (pr.size !== undefined) parts.push(`<sz val=\"${pr.size}\"/>`);\n if (pr.underline) {\n if (pr.underline === \"none\") {\n parts.push(\"<u/>\");\n } else {\n parts.push(`<u val=\"${pr.underline}\"/>`);\n }\n }\n if (pr.vertAlign) parts.push(`<vertAlign val=\"${pr.vertAlign}\"/>`);\n if (pr.scheme) parts.push(`<scheme val=\"${pr.scheme}\"/>`);\n return parts.length > 0 ? `<rPr>${parts.join(\"\")}</rPr>` : \"\";\n}\n\n/** Build a CT_Rst XML string from RichTextOptions. */\nexport function buildRstXml(rst: RichTextOptions): string {\n const parts: string[] = [];\n if (rst.runs && rst.runs.length > 0) {\n for (const run of rst.runs) {\n const rPr = buildRPrXml(run.properties);\n parts.push(`<r>${rPr}<t>${escapeXml(run.text)}</t></r>`);\n }\n } else if (rst.text !== undefined) {\n parts.push(`<t>${escapeXml(rst.text)}</t>`);\n }\n // rPh (phonetics)\n if (rst.phonetics) {\n for (const ph of rst.phonetics) {\n parts.push(`<rPh sb=\"${ph.sb}\" eb=\"${ph.eb}\"><t>${escapeXml(ph.text)}</t></rPh>`);\n }\n }\n return parts.join(\"\");\n}\n\nexport class SharedStrings extends BaseXmlComponent {\n private readonly entries: SstEntry[] = [];\n /** Dedup map for plain strings only. Rich text is not deduped. */\n private readonly indexMap = new Map<string, number>();\n\n public constructor() {\n super(\"sst\");\n }\n\n /**\n * Register a plain string and return its index.\n * Returns existing index if the string is already registered.\n */\n public register(s: string): number {\n const existing = this.indexMap.get(s);\n if (existing !== undefined) return existing;\n\n const idx = this.entries.length;\n this.entries.push(s);\n this.indexMap.set(s, idx);\n return idx;\n }\n\n /**\n * Register a rich text entry and return its index.\n * Rich text is not deduped (each call creates a new entry).\n */\n public registerRich(rst: RichTextOptions): number {\n const idx = this.entries.length;\n this.entries.push(rst);\n return idx;\n }\n\n public get count(): number {\n return this.entries.length;\n }\n\n /**\n * Zero-allocation fast path: directly concatenate XML string.\n * Bypasses the IXmlableObject intermediate tree entirely.\n */\n public override toXml(_context: Context): string {\n const p: string[] = [\n '<sst xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\"',\n ` count=\"${this.entries.length}\" uniqueCount=\"${this.indexMap.size}\">`,\n ];\n for (const entry of this.entries) {\n if (typeof entry === \"string\") {\n p.push(`<si><t>${escapeXml(entry)}</t></si>`);\n } else {\n // Rich text (CT_Rst)\n p.push(`<si>${buildRstXml(entry)}</si>`);\n }\n }\n p.push(\"</sst>\");\n return p.join(\"\");\n }\n}\n","/**\n * Styles component — generates xl/styles.xml.\n *\n * XLSX uses an index-based style system: cells reference style entries\n * via the `s` attribute, which is an index into `cellXfs`.\n *\n * @module\n */\nimport { BaseXmlComponent } from \"@file/xml-components\";\nimport type { Context } from \"@file/xml-components\";\nimport { attrs, escapeXml } from \"@office-open/xml\";\n\n// ── Sub-style option interfaces ──\n\nexport interface FontOptions {\n readonly bold?: boolean;\n readonly italic?: boolean;\n readonly underline?: boolean;\n readonly strike?: boolean;\n readonly size?: number;\n readonly color?: string;\n readonly fontName?: string;\n /** Character set (CT_Font/charset @val) */\n readonly charset?: number;\n /** Font family (CT_Font/family @val) */\n readonly family?: number;\n /** Condense (macOS, CT_Font/condense) */\n readonly condense?: boolean;\n /** Extend (macOS, CT_Font/extend) */\n readonly extend?: boolean;\n /** Vertical alignment: superscript/subscript (CT_Font/vertAlign @val) */\n readonly vertAlign?: \"superscript\" | \"subscript\" | \"baseline\";\n /** Font scheme (CT_Font/scheme @val) */\n readonly scheme?: \"major\" | \"minor\" | \"none\";\n /** Font shadow (CT_Font/shadow) */\n readonly shadow?: boolean;\n /** Font outline (CT_Font/outline) */\n readonly outline?: boolean;\n}\n\n/** Gradient stop (CT_GradientStop) */\nexport interface GradientStopOptions {\n /** Position (0.0–1.0) */\n readonly position: number;\n /** RGB color hex without alpha, e.g. \"FF0000\" */\n readonly color: string;\n}\n\nexport interface FillOptions {\n readonly type?: \"solid\" | \"pattern\" | \"gradient\";\n readonly color?: string;\n readonly patternType?: string;\n /** Background color for pattern fill (CT_PatternFill/bgColor) */\n readonly bgColor?: string;\n /** Gradient stops (CT_GradientFill/stop) */\n readonly stops?: readonly GradientStopOptions[];\n /** Gradient type (CT_GradientFill @type) */\n readonly gradientType?: \"linear\" | \"path\";\n /** Gradient degree for linear (CT_GradientFill @degree) */\n readonly gradientDegree?: number;\n /** Gradient left position for path (CT_GradientFill @left) */\n readonly gradientLeft?: number;\n /** Gradient right position for path (CT_GradientFill @right) */\n readonly gradientRight?: number;\n /** Gradient top position for path (CT_GradientFill @top) */\n readonly gradientTop?: number;\n /** Gradient bottom position for path (CT_GradientFill @bottom) */\n readonly gradientBottom?: number;\n}\n\nexport interface BorderOptions {\n readonly style?: \"thin\" | \"medium\" | \"thick\" | \"dotted\" | \"dashed\" | \"hair\" | \"none\";\n readonly color?: string;\n /** Diagonal up (CT_Border @diagonalUp) — on the parent border element */\n readonly diagonalUp?: boolean;\n /** Diagonal down (CT_Border @diagonalDown) — on the parent border element */\n readonly diagonalDown?: boolean;\n}\n\nexport interface BorderSideOptions {\n readonly top?: BorderOptions;\n readonly bottom?: BorderOptions;\n readonly left?: BorderOptions;\n readonly right?: BorderOptions;\n readonly diagonal?: BorderOptions;\n /** Leading edge border (CT_Border/start, for RTL support) */\n readonly start?: BorderOptions;\n /** Trailing edge border (CT_Border/end, for RTL support) */\n readonly end?: BorderOptions;\n /** Vertical inner border (CT_Border/vertical, for cell range borders) */\n readonly vertical?: BorderOptions;\n /** Horizontal inner border (CT_Border/horizontal, for cell range borders) */\n readonly horizontal?: BorderOptions;\n}\n\nexport interface AlignmentOptions {\n readonly horizontal?: \"left\" | \"center\" | \"right\" | \"fill\" | \"justify\";\n readonly vertical?: \"top\" | \"center\" | \"bottom\";\n readonly wrapText?: boolean;\n readonly textRotation?: number;\n readonly indent?: number;\n /** Relative indent (CT_CellAlignment @relativeIndent) */\n readonly relativeIndent?: number;\n /** Justify last line (CT_CellAlignment @justifyLastLine) */\n readonly justifyLastLine?: boolean;\n /** Shrink to fit (CT_CellAlignment @shrinkToFit) */\n readonly shrinkToFit?: boolean;\n /** Reading order (CT_CellAlignment @readingOrder) */\n readonly readingOrder?: number;\n}\n\nexport interface StyleOptions {\n readonly font?: FontOptions;\n readonly fill?: FillOptions;\n readonly border?: BorderSideOptions;\n readonly numFmt?: string;\n readonly alignment?: AlignmentOptions;\n /** Quote prefix (CT_Xf @quotePrefix) */\n readonly quotePrefix?: boolean;\n /** Pivot button (CT_Xf @pivotButton) */\n readonly pivotButton?: boolean;\n /** Cell protection (CT_CellProtection) */\n readonly protection?: CellProtectionOptions;\n}\n\n/** Cell-level protection settings (CT_CellProtection) */\nexport interface CellProtectionOptions {\n /** Cell is locked (CT_CellProtection @locked) */\n readonly locked?: boolean;\n /** Cell formula is hidden (CT_CellProtection @hidden) */\n readonly hidden?: boolean;\n}\n\n/** Indexed color entry (CT_RgbColor) */\nexport interface IndexedColorOptions {\n /** RGB hex value, e.g. \"FF000000\" */\n readonly rgb: string;\n}\n\n/** Colors palette (CT_Colors) */\nexport interface ColorsOptions {\n /** Indexed color palette (CT_IndexedColors) */\n readonly indexedColors?: readonly IndexedColorOptions[];\n /** Most recently used colors (CT_MRUColors) */\n readonly mruColors?: readonly string[];\n}\n\n/** Differential format — used by conditional formatting to specify what changes. */\nexport interface DxfOptions {\n readonly font?: FontOptions;\n readonly fill?: FillOptions;\n readonly border?: BorderSideOptions;\n readonly numFmt?: string;\n}\n\n// ── Style key helpers for deduplication ──\n\nfunction fontKey(f: FontOptions): string {\n return `b${f.bold ? 1 : 0}i${f.italic ? 1 : 0}u${f.underline ? 1 : 0}s${f.strike ? 1 : 0}z${f.size ?? 0}c${f.color ?? \"\"}n${f.fontName ?? \"\"}cs${f.charset ?? \"\"}fm${f.family ?? \"\"}co${f.condense ? 1 : 0}ex${f.extend ? 1 : 0}va${f.vertAlign ?? \"\"}sc${f.scheme ?? \"\"}sh${f.shadow ? 1 : 0}ol${f.outline ? 1 : 0}`;\n}\n\nfunction fillKey(f: FillOptions): string {\n return `t${f.type ?? \"\"}c${f.color ?? \"\"}p${f.patternType ?? \"\"}bg${f.bgColor ?? \"\"}g${f.stops?.map((s) => `${s.position}_${s.color}`).join(\"|\") ?? \"\"}`;\n}\n\nfunction borderKey(b: BorderSideOptions): string {\n const sk = (o?: BorderOptions) => `${o?.style ?? \"\"}_${o?.color ?? \"\"}`;\n return `t${sk(b.top)}b${sk(b.bottom)}l${sk(b.left)}r${sk(b.right)}d${sk(b.diagonal)}st${sk(b.start)}en${sk(b.end)}v${sk(b.vertical)}h${sk(b.horizontal)}`;\n}\n\n// ── Built-in number format IDs ──\n\nconst BUILTIN_NUMFMTS: Record<string, number> = {\n General: 0,\n \"0\": 1,\n \"0.00\": 2,\n \"#,##0\": 3,\n \"#,##0.00\": 4,\n \"0%\": 9,\n \"0.00%\": 10,\n \"0.00E+00\": 11,\n \"mm-dd-yy\": 14,\n \"d-mmm-yy\": 15,\n \"d-mmm\": 16,\n \"mmm-yy\": 17,\n \"h:mm AM/PM\": 18,\n \"h:mm:ss AM/PM\": 19,\n \"h:mm\": 20,\n \"h:mm:ss\": 21,\n \"m/d/yy h:mm\": 22,\n \"#,##0 ;(#,##0)\": 37,\n \"#,##0 ;[Red](#,##0)\": 38,\n \"#,##0.00;(#,##0.00)\": 39,\n \"#,##0.00;[Red](#,##0.00)\": 40,\n \"mm:ss\": 45,\n \"[h]:mm:ss\": 46,\n \"mmss.0\": 47,\n \"##0.0E+0\": 48,\n \"@\": 49,\n};\n\n/** Table style element type (ST_TableStyleType). */\nexport type TableStyleElementType =\n | \"wholeTable\"\n | \"headerRow\"\n | \"totalRow\"\n | \"firstColumn\"\n | \"lastColumn\"\n | \"firstRowStripe\"\n | \"secondRowStripe\"\n | \"firstColumnStripe\"\n | \"secondColumnStripe\"\n | \"firstHeaderCell\"\n | \"lastHeaderCell\"\n | \"firstTotalCell\"\n | \"lastTotalCell\"\n | \"subtotalRow1\"\n | \"subtotalRow2\"\n | \"subtotalRow3\"\n | \"subtotalColumn1\"\n | \"subtotalColumn2\"\n | \"subtotalColumn3\"\n | \"blankRow\"\n | \"firstColumnSubheading\"\n | \"secondColumnSubheading\"\n | \"thirdColumnSubheading\"\n | \"firstRowSubheading\"\n | \"secondRowSubheading\"\n | \"thirdRowSubheading\"\n | \"pageFieldLabels\"\n | \"pageFieldValues\";\n\n/** Table style element (CT_TableStyleElement). */\nexport interface TableStyleElementOptions {\n /** Element type */\n readonly type: TableStyleElementType;\n /** Differential format index (dxf) */\n readonly dxfId?: number;\n /** Button style (for pivot tables) */\n readonly button?: boolean;\n}\n\n/** Custom table/pivot table style (CT_TableStyle). */\n/** Style sheet extension (CT_Extension) */\nexport interface StyleExtensionOptions {\n /** Extension URI (required) */\n readonly uri: string;\n /** Extension content (raw XML fragment) */\n readonly content?: string;\n}\n\nexport interface CustomTableStyleOptions {\n /** Style name (must be unique) */\n readonly name: string;\n /** Pivot style (vs table style) */\n readonly pivot?: boolean;\n /** Table style elements */\n readonly elements?: readonly TableStyleElementOptions[];\n}\n\nexport class Styles extends BaseXmlComponent {\n private readonly fonts: FontOptions[] = [\n { size: 11, fontName: \"Calibri\" }, // default font (index 0)\n ];\n private readonly fontKeys = new Map<string, number>();\n\n private readonly fills: FillOptions[] = [\n { patternType: \"none\" }, // default fill (index 0)\n { patternType: \"gray125\" }, // required fill (index 1)\n ];\n private readonly fillKeys = new Map<string, number>();\n\n private readonly borders: BorderSideOptions[] = [\n {}, // default empty border (index 0)\n ];\n private readonly borderKeys = new Map<string, number>();\n\n private readonly customNumFmts = new Map<string, number>();\n private nextCustomNumFmtId = 164; // custom numFmts start at 164\n\n private readonly cellXfs: Array<{\n readonly fontId: number;\n readonly fillId: number;\n readonly borderId: number;\n readonly numFmtId: number;\n readonly alignment?: AlignmentOptions;\n readonly quotePrefix?: boolean;\n readonly pivotButton?: boolean;\n readonly protection?: CellProtectionOptions;\n }> = [\n { fontId: 0, fillId: 0, borderId: 0, numFmtId: 0 }, // default xf (index 0)\n ];\n private readonly cellXfKeys = new Map<string, number>();\n\n private readonly dxfs: DxfOptions[] = [];\n\n private colors?: ColorsOptions;\n private tableStyles?: readonly CustomTableStyleOptions[];\n /** Style sheet extensions (CT_ExtensionList) */\n private styleExtensions?: readonly StyleExtensionOptions[];\n\n public constructor() {\n super(\"styleSheet\");\n\n // Pre-register default font/fill/border keys\n this.fontKeys.set(fontKey(this.fonts[0]), 0);\n this.fillKeys.set(fillKey(this.fills[0]), 0);\n this.fillKeys.set(fillKey(this.fills[1]), 1);\n this.borderKeys.set(borderKey(this.borders[0]), 0);\n this.cellXfKeys.set(this.cellXfKey(this.cellXfs[0]), 0);\n }\n\n /**\n * Register a style and return its index (for the cell `s` attribute).\n * Deduplicates across fonts, fills, borders, numFmts, and cellXfs.\n */\n public register(opts: StyleOptions): number {\n const fontId = this.registerFont(opts.font);\n const fillId = this.registerFill(opts.fill);\n const borderId = this.registerBorder(opts.border);\n const numFmtId = this.registerNumFmt(opts.numFmt);\n\n const xf = {\n fontId,\n fillId,\n borderId,\n numFmtId,\n alignment: opts.alignment,\n quotePrefix: opts.quotePrefix,\n pivotButton: opts.pivotButton,\n protection: opts.protection,\n };\n\n const key = this.cellXfKey(xf);\n const existing = this.cellXfKeys.get(key);\n if (existing !== undefined) return existing;\n\n const idx = this.cellXfs.length;\n this.cellXfs.push(xf);\n this.cellXfKeys.set(key, idx);\n return idx;\n }\n\n /**\n * Register a differential format and return its index (dxfId).\n * Used by conditional formatting rules.\n */\n public registerDxf(opts: DxfOptions): number {\n const idx = this.dxfs.length;\n this.dxfs.push(opts);\n return idx;\n }\n\n /**\n * Set color palette (indexed colors and MRU colors).\n */\n public setColors(opts: ColorsOptions): void {\n this.colors = opts;\n }\n\n public setTableStyles(styles: readonly CustomTableStyleOptions[]): void {\n this.tableStyles = styles;\n }\n\n public setExtensions(extensions: readonly StyleExtensionOptions[]): void {\n this.styleExtensions = extensions;\n }\n\n private registerFont(opts?: FontOptions): number {\n if (!opts) return 0;\n const key = fontKey(opts);\n const existing = this.fontKeys.get(key);\n if (existing !== undefined) return existing;\n\n const idx = this.fonts.length;\n this.fonts.push(opts);\n this.fontKeys.set(key, idx);\n return idx;\n }\n\n private registerFill(opts?: FillOptions): number {\n if (!opts) return 0;\n const key = fillKey(opts);\n const existing = this.fillKeys.get(key);\n if (existing !== undefined) return existing;\n\n const idx = this.fills.length;\n this.fills.push(opts);\n this.fillKeys.set(key, idx);\n return idx;\n }\n\n private registerBorder(opts?: BorderSideOptions): number {\n if (!opts) return 0;\n const key = borderKey(opts);\n const existing = this.borderKeys.get(key);\n if (existing !== undefined) return existing;\n\n const idx = this.borders.length;\n this.borders.push(opts);\n this.borderKeys.set(key, idx);\n return idx;\n }\n\n private registerNumFmt(fmt?: string): number {\n if (!fmt) return 0;\n const builtin = BUILTIN_NUMFMTS[fmt];\n if (builtin !== undefined) return builtin;\n\n const existing = this.customNumFmts.get(fmt);\n if (existing !== undefined) return existing;\n\n const id = this.nextCustomNumFmtId++;\n this.customNumFmts.set(fmt, id);\n return id;\n }\n\n private cellXfKey(xf: {\n readonly fontId: number;\n readonly fillId: number;\n readonly borderId: number;\n readonly numFmtId: number;\n readonly alignment?: AlignmentOptions;\n readonly quotePrefix?: boolean;\n readonly pivotButton?: boolean;\n readonly protection?: CellProtectionOptions;\n }): string {\n const a = xf.alignment;\n const ak = a\n ? `h${a.horizontal ?? \"\"}v${a.vertical ?? \"\"}w${a.wrapText ? 1 : 0}r${a.textRotation ?? \"\"}i${a.indent ?? \"\"}ri${a.relativeIndent ?? \"\"}jl${a.justifyLastLine ? 1 : 0}st${a.shrinkToFit ? 1 : 0}ro${a.readingOrder ?? \"\"}`\n : \"\";\n const pr = xf.protection;\n const pk = pr ? `l${pr.locked ?? \"\"}h${pr.hidden ?? \"\"}` : \"\";\n return `${xf.fontId}|${xf.fillId}|${xf.borderId}|${xf.numFmtId}|${ak}|qp${xf.quotePrefix ? 1 : 0}|pb${xf.pivotButton ? 1 : 0}|${pk}`;\n }\n\n // ── XML generation ──\n\n /**\n * Zero-allocation fast path: directly concatenate XML string.\n * Bypasses the IXmlableObject intermediate tree entirely.\n */\n public override toXml(_context: Context): string {\n const p: string[] = [\n '<styleSheet xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\">',\n ];\n\n // numFmts\n if (this.customNumFmts.size > 0) {\n p.push(`<numFmts count=\"${this.customNumFmts.size}\">`);\n for (const [fmt, id] of this.customNumFmts) {\n p.push(`<numFmt numFmtId=\"${id}\" formatCode=\"${escapeXml(fmt)}\"/>`);\n }\n p.push(\"</numFmts>\");\n }\n\n // fonts\n p.push(`<fonts count=\"${this.fonts.length}\">`);\n for (const f of this.fonts) {\n p.push(`<font>${this.fontXmlStr(f)}</font>`);\n }\n p.push(\"</fonts>\");\n\n // fills\n p.push(`<fills count=\"${this.fills.length}\">`);\n for (const f of this.fills) {\n if (f.type === \"gradient\" && f.stops && f.stops.length > 0) {\n const gfAttrs: Record<string, string | number | boolean | undefined> = {};\n if (f.gradientType && f.gradientType !== \"linear\") gfAttrs.type = f.gradientType;\n if (f.gradientDegree !== undefined) gfAttrs.degree = f.gradientDegree;\n if (f.gradientLeft !== undefined) gfAttrs.left = f.gradientLeft;\n if (f.gradientRight !== undefined) gfAttrs.right = f.gradientRight;\n if (f.gradientTop !== undefined) gfAttrs.top = f.gradientTop;\n if (f.gradientBottom !== undefined) gfAttrs.bottom = f.gradientBottom;\n const stopParts = f.stops\n .map((s) => `<stop position=\"${s.position}\"><color rgb=\"FF${s.color}\"/></stop>`)\n .join(\"\");\n p.push(`<fill><gradientFill${attrs(gfAttrs)}>${stopParts}</gradientFill></fill>`);\n } else {\n const patternAttrs = attrs({ patternType: f.patternType ?? \"solid\" });\n const fgColor = f.color ? `<fgColor rgb=\"FF${f.color}\"/>` : \"\";\n const bgColor = f.bgColor ? `<bgColor rgb=\"FF${f.bgColor}\"/>` : \"\";\n const colorContent = fgColor + bgColor;\n p.push(\n colorContent\n ? `<fill><patternFill${patternAttrs}>${colorContent}</patternFill></fill>`\n : `<fill><patternFill${patternAttrs}/></fill>`,\n );\n }\n }\n p.push(\"</fills>\");\n\n // borders\n p.push(`<borders count=\"${this.borders.length}\">`);\n for (const b of this.borders) {\n p.push(`<border>${this.borderXmlStr(b)}</border>`);\n }\n p.push(\"</borders>\");\n\n // cellStyleXfs\n p.push(\n '<cellStyleXfs count=\"1\"><xf numFmtId=\"0\" fontId=\"0\" fillId=\"0\" borderId=\"0\"/></cellStyleXfs>',\n );\n\n // cellXfs\n p.push(`<cellXfs count=\"${this.cellXfs.length}\">`);\n for (const xf of this.cellXfs) {\n const xAttrs: Record<string, string | number | boolean | undefined> = {\n numFmtId: xf.numFmtId,\n fontId: xf.fontId,\n fillId: xf.fillId,\n borderId: xf.borderId,\n xfId: 0,\n };\n if (xf.alignment) xAttrs.applyAlignment = 1;\n if (xf.fontId > 0) xAttrs.applyFont = 1;\n if (xf.fillId > 0) xAttrs.applyFill = 1;\n if (xf.borderId > 0) xAttrs.applyBorder = 1;\n if (xf.numFmtId > 0) xAttrs.applyNumberFormat = 1;\n if (xf.quotePrefix) xAttrs.quotePrefix = 1;\n if (xf.pivotButton) xAttrs.pivotButton = 1;\n\n const alignStr = xf.alignment ? this.alignmentXmlStr(xf.alignment) : \"\";\n const protStr = xf.protection ? this.protectionXmlStr(xf.protection) : \"\";\n const inner = alignStr + protStr;\n p.push(inner ? `<xf${attrs(xAttrs)}>${inner}</xf>` : `<xf${attrs(xAttrs)}/>`);\n }\n p.push(\"</cellXfs>\");\n\n // cellStyles\n p.push('<cellStyles count=\"1\"><cellStyle name=\"Normal\" xfId=\"0\" builtinId=\"0\"/></cellStyles>');\n\n // dxfs\n if (this.dxfs.length > 0) {\n p.push(`<dxfs count=\"${this.dxfs.length}\">`);\n for (const dxf of this.dxfs) {\n const dParts: string[] = [];\n if (dxf.font) dParts.push(`<font>${this.fontXmlStr(dxf.font)}</font>`);\n if (dxf.fill) {\n const bgColor = dxf.fill.color ? `<bgColor rgb=\"FF${dxf.fill.color}\"/>` : \"\";\n const patAttrs = attrs({ patternType: dxf.fill.patternType ?? \"solid\" });\n dParts.push(`<fill><patternFill${patAttrs}>${bgColor}</patternFill></fill>`);\n }\n if (dxf.numFmt) dParts.push(`<numFmt formatCode=\"${escapeXml(dxf.numFmt)}\"/>`);\n if (dParts.length > 0) {\n p.push(`<dxf>${dParts.join(\"\")}</dxf>`);\n } else {\n p.push(\"<dxf/>\");\n }\n }\n p.push(\"</dxfs>\");\n } else {\n p.push('<dxfs count=\"0\"/>');\n }\n // tableStyles (CT_TableStyles)\n if (this.tableStyles && this.tableStyles.length > 0) {\n const tsParts: string[] = [\n `<tableStyles count=\"${this.tableStyles.length}\" defaultTableStyle=\"TableStyleMedium2\" defaultPivotStyle=\"PivotStyleLight16\">`,\n ];\n for (const ts of this.tableStyles) {\n const tsAttrs: string[] = [`name=\"${escapeXml(ts.name)}\"`];\n if (ts.pivot) tsAttrs.push('pivot=\"1\"');\n if (ts.elements && ts.elements.length > 0) {\n tsParts.push(`<tableStyle ${tsAttrs.join(\" \")}>`);\n for (const el of ts.elements) {\n const elAttrs: string[] = [`type=\"${el.type}\"`];\n if (el.dxfId !== undefined) elAttrs.push(`dxfId=\"${el.dxfId}\"`);\n if (el.button) elAttrs.push('button=\"1\"');\n tsParts.push(`<tableStyleElement ${elAttrs.join(\" \")}/>`);\n }\n tsParts.push(\"</tableStyle>\");\n } else {\n tsParts.push(`<tableStyle ${tsAttrs.join(\" \")}/>`);\n }\n }\n tsParts.push(\"</tableStyles>\");\n p.push(tsParts.join(\"\"));\n } else {\n p.push(\n '<tableStyles count=\"0\" defaultTableStyle=\"TableStyleMedium2\" defaultPivotStyle=\"PivotStyleLight16\"/>',\n );\n }\n\n // colors (optional color palette)\n if (this.colors) {\n const c = this.colors;\n const colorParts: string[] = [\"<colors>\"];\n if (c.indexedColors && c.indexedColors.length > 0) {\n colorParts.push(\"<indexedColors>\");\n for (const ic of c.indexedColors) {\n colorParts.push(`<rgbColor rgb=\"${ic.rgb}\"/>`);\n }\n colorParts.push(\"</indexedColors>\");\n }\n if (c.mruColors && c.mruColors.length > 0) {\n colorParts.push(\"<mruColors>\");\n for (const mc of c.mruColors) {\n colorParts.push(`<color rgb=\"FF${mc}\"/>`);\n }\n colorParts.push(\"</mruColors>\");\n }\n colorParts.push(\"</colors>\");\n p.push(colorParts.join(\"\"));\n }\n\n // extLst — style sheet extensions\n if (this.styleExtensions && this.styleExtensions.length > 0) {\n const extParts: string[] = [\"<extLst>\"];\n for (const ext of this.styleExtensions) {\n if (ext.content) {\n extParts.push(`<ext uri=\"${ext.uri}\">${ext.content}</ext>`);\n } else {\n extParts.push(`<ext uri=\"${ext.uri}\"/>`);\n }\n }\n extParts.push(\"</extLst>\");\n p.push(extParts.join(\"\"));\n } else {\n p.push(\"<extLst/>\");\n }\n\n p.push(\"</styleSheet>\");\n return p.join(\"\");\n }\n\n private fontXmlStr(f: FontOptions): string {\n const parts: string[] = [];\n if (f.bold) parts.push(\"<b/>\");\n if (f.italic) parts.push(\"<i/>\");\n if (f.underline) parts.push(\"<u/>\");\n if (f.strike) parts.push(\"<strike/>\");\n if (f.outline) parts.push(\"<outline/>\");\n if (f.shadow) parts.push(\"<shadow/>\");\n if (f.condense) parts.push(\"<condense/>\");\n if (f.extend) parts.push(\"<extend/>\");\n if (f.size) parts.push(`<sz val=\"${f.size}\"/>`);\n if (f.color) parts.push(`<color rgb=\"FF${f.color}\"/>`);\n if (f.fontName) parts.push(`<name val=\"${escapeXml(f.fontName)}\"/>`);\n if (f.charset !== undefined) parts.push(`<charset val=\"${f.charset}\"/>`);\n if (f.family !== undefined) parts.push(`<family val=\"${f.family}\"/>`);\n if (f.vertAlign) parts.push(`<vertAlign val=\"${f.vertAlign}\"/>`);\n if (f.scheme) parts.push(`<scheme val=\"${f.scheme}\"/>`);\n return parts.join(\"\");\n }\n\n private borderXmlStr(b: BorderSideOptions): string {\n const parts: string[] = [];\n const renderSide = (name: string, opts: BorderOptions | undefined, required = true) => {\n if (opts && opts.style && opts.style !== \"none\") {\n const colorStr = opts.color ? `<color rgb=\"FF${opts.color}\"/>` : \"\";\n parts.push(`<${name} style=\"${opts.style}\">${colorStr}</${name}>`);\n } else if (required) {\n parts.push(`<${name}/>`);\n }\n };\n for (const side of [\n \"left\",\n \"right\",\n \"top\",\n \"bottom\",\n \"diagonal\",\n \"vertical\",\n \"horizontal\",\n ] as const) {\n renderSide(side, b[side] as BorderOptions | undefined);\n }\n // start/end not in transitional XSD — only emit when styled\n renderSide(\"start\", b.start, false);\n renderSide(\"end\", b.end, false);\n return parts.join(\"\");\n }\n\n private alignmentXmlStr(a: AlignmentOptions): string {\n const aAttrs: Record<string, string | number | boolean | undefined> = {};\n if (a.horizontal) aAttrs.horizontal = a.horizontal;\n if (a.vertical) aAttrs.vertical = a.vertical;\n if (a.wrapText) aAttrs.wrapText = 1;\n if (a.textRotation !== undefined) aAttrs.textRotation = a.textRotation;\n if (a.indent !== undefined) aAttrs.indent = a.indent;\n if (a.relativeIndent !== undefined) aAttrs.relativeIndent = a.relativeIndent;\n if (a.justifyLastLine) aAttrs.justifyLastLine = 1;\n if (a.shrinkToFit) aAttrs.shrinkToFit = 1;\n if (a.readingOrder !== undefined) aAttrs.readingOrder = a.readingOrder;\n return `<alignment${attrs(aAttrs)}/>`;\n }\n\n private protectionXmlStr(pr: CellProtectionOptions): string {\n const prAttrs: Record<string, string | number | boolean | undefined> = {};\n if (pr.locked !== undefined) prAttrs.locked = pr.locked ? 1 : 0;\n if (pr.hidden !== undefined) prAttrs.hidden = pr.hidden ? 1 : 0;\n return `<protection${attrs(prAttrs)}/>`;\n }\n}\n","/**\n * Workbook component — generates xl/workbook.xml.\n *\n * @module\n */\nimport { BaseXmlComponent } from \"@file/xml-components\";\nimport type { Context } from \"@file/xml-components\";\nimport { derivePasswordHash } from \"@office-open/core\";\nimport { escapeXml } from \"@office-open/xml\";\n\nexport interface SheetDefinition {\n readonly name: string;\n readonly sheetId: number;\n readonly rId: string;\n readonly state?: \"visible\" | \"hidden\" | \"veryHidden\";\n}\n\nexport interface PivotCacheReference {\n readonly cacheId: number;\n readonly rId: string;\n}\n\nexport interface TablePartReference {\n readonly rId: string;\n}\n\n/** Custom workbook view for storing display preferences. */\nexport interface CustomWorkbookViewOptions {\n /** View name */\n readonly name: string;\n /** GUID (e.g. \"{00000000-0000-0000-0000-000000000000}\") */\n readonly guid: string;\n /** Window width in twips */\n readonly windowWidth: number;\n /** Window height in twips */\n readonly windowHeight: number;\n /** Active sheet ID (1-based sheetId) */\n readonly activeSheetId: number;\n /** X position of the window */\n readonly xWindow?: number;\n /** Y position of the window */\n readonly yWindow?: number;\n /** Show formula bar (default true) */\n readonly showFormulaBar?: boolean;\n /** Show status bar (default true) */\n readonly showStatusbar?: boolean;\n /** Show horizontal scroll (default true) */\n readonly showHorizontalScroll?: boolean;\n /** Show vertical scroll (default true) */\n readonly showVerticalScroll?: boolean;\n /** Show sheet tabs (default true) */\n readonly showSheetTabs?: boolean;\n /** Tab ratio (default 600) */\n readonly tabRatio?: number;\n /** Include hidden rows/columns (default true) */\n readonly includeHiddenRowCol?: boolean;\n /** Include print settings (default true) */\n readonly includePrintSettings?: boolean;\n /** Personal view (default false) */\n readonly personalView?: boolean;\n /** Maximized (default false) */\n readonly maximized?: boolean;\n /** Minimized (default false) */\n readonly minimized?: boolean;\n /** Auto update (CT_CustomWorkbookView @autoUpdate) */\n readonly autoUpdate?: boolean;\n /** Merge interval (CT_CustomWorkbookView @mergeInterval) */\n readonly mergeInterval?: number;\n /** Changes saved in window (CT_CustomWorkbookView @changesSavedWin) */\n readonly changesSavedWin?: boolean;\n /** Only sync (CT_CustomWorkbookView @onlySync) */\n readonly onlySync?: boolean;\n /** Show comments (CT_CustomWorkbookView @showComments) */\n readonly showComments?: string;\n}\n\nexport interface WorkbookProtectionOptions {\n /** Lock workbook structure (add/delete/rename/move sheets) */\n readonly lockStructure?: boolean;\n /** Lock workbook windows */\n readonly lockWindows?: boolean;\n /** Lock revisions */\n readonly lockRevision?: boolean;\n /** Plain-text password — legacy Excel hash computed automatically */\n readonly workbookPassword?: string;\n /** Modern encryption: algorithm name (e.g. \"SHA-512\") */\n readonly workbookAlgorithmName?: string;\n /** Modern encryption: base64-encoded hash value */\n readonly workbookHashValue?: string;\n /** Modern encryption: base64-encoded salt value */\n readonly workbookSaltValue?: string;\n /** Modern encryption: spin count */\n readonly workbookSpinCount?: number;\n /** Revisions password (legacy) */\n readonly revisionsPassword?: string;\n /** Revisions modern encryption: algorithm name */\n readonly revisionsAlgorithmName?: string;\n /** Revisions modern encryption: base64-encoded hash value */\n readonly revisionsHashValue?: string;\n /** Revisions modern encryption: base64-encoded salt value */\n readonly revisionsSaltValue?: string;\n /** Revisions modern encryption: spin count */\n readonly revisionsSpinCount?: number;\n}\n\n/** File recovery properties (CT_FileRecoveryPr) */\nexport interface FileRecoveryPrOptions {\n /** Enable auto-recover (default true) */\n readonly autoRecover?: boolean;\n /** Crash save (default false) */\n readonly crashSave?: boolean;\n /** Data extract load (default false) */\n readonly dataExtractLoad?: boolean;\n /** Repair load (default false) */\n readonly repairLoad?: boolean;\n}\n\n/** Web publishing properties (CT_WebPublishing) */\nexport interface WebPublishingOptions {\n /** Use CSS (default true) */\n readonly css?: boolean;\n /** Use thicket format (default true) */\n readonly thicket?: boolean;\n /** Use long file names (default true) */\n readonly longFileNames?: boolean;\n /** Use VML (default false) */\n readonly vml?: boolean;\n /** Allow PNG (default false) */\n readonly allowPng?: boolean;\n /** Target screen size (default \"800x600\") */\n readonly targetScreenSize?: string;\n /** DPI (default 96) */\n readonly dpi?: number;\n /** Code page */\n readonly codePage?: number;\n /** Character set */\n readonly characterSet?: string;\n}\n\n/** File sharing properties (CT_FileSharing) */\nexport interface FileSharingOptions {\n /** Recommend read-only mode (default false) */\n readonly readOnlyRecommended?: boolean;\n /** User name who has the file locked */\n readonly userName?: string;\n /** Legacy reservation password (hex) */\n readonly reservationPassword?: string;\n /** Modern encryption: algorithm name */\n readonly algorithmName?: string;\n /** Modern encryption: base64 hash value */\n readonly hashValue?: string;\n /** Modern encryption: base64 salt value */\n readonly saltValue?: string;\n /** Modern encryption: spin count */\n readonly spinCount?: number;\n}\n\n/** Workbook properties (CT_WorkbookPr) */\nexport interface WorkbookPrOptions {\n /** Use 1904 date system (default false) */\n readonly date1904?: boolean;\n /** Default theme version */\n readonly defaultThemeVersion?: number;\n /** Show objects: \"all\" | \"placeholders\" | \"none\" */\n readonly showObjects?: string;\n /** Hide pivot field list (default false) */\n readonly hidePivotFieldList?: boolean;\n /** Allow refresh queries (default false) */\n readonly allowRefreshQuery?: boolean;\n /** Filter privacy (default false) */\n readonly filterPrivacy?: boolean;\n /** Backup file (default false) */\n readonly backupFile?: boolean;\n /** Code name */\n readonly codeName?: string;\n /** Show border unselected tables (CT_WorkbookPr @showBorderUnselectedTables) */\n readonly showBorderUnselectedTables?: boolean;\n /** Prompted solutions (CT_WorkbookPr @promptedSolutions) */\n readonly promptedSolutions?: boolean;\n /** Show ink annotation (CT_WorkbookPr @showInkAnnotation) */\n readonly showInkAnnotation?: boolean;\n /** Save external link values (CT_WorkbookPr @saveExternalLinkValues) */\n readonly saveExternalLinkValues?: boolean;\n /** Update links mode (CT_WorkbookPr @updateLinks) */\n readonly updateLinks?: string;\n /** Show pivot chart filter (CT_WorkbookPr @showPivotChartFilter) */\n readonly showPivotChartFilter?: boolean;\n /** Publish items (CT_WorkbookPr @publishItems) */\n readonly publishItems?: boolean;\n /** Check compatibility (CT_WorkbookPr @checkCompatibility) */\n readonly checkCompatibility?: boolean;\n /** Auto compress pictures (CT_WorkbookPr @autoCompressPictures) */\n readonly autoCompressPictures?: boolean;\n /** Refresh all connections (CT_WorkbookPr @refreshAllConnections) */\n readonly refreshAllConnections?: boolean;\n}\n\n/** Volatile type entry (CT_VolType) */\nexport interface VolTypeOptions {\n /** Type of volatile dependency (default: \"realTimeData\") */\n readonly type?: \"realTimeData\" | \"olapFunctions\";\n /** Main volatile dependencies (CT_VolMain, required) */\n readonly mains?: readonly VolMainOptions[];\n}\n\n/** Main volatile dependency (CT_VolMain) */\nexport interface VolMainOptions {\n /** First reference (required) */\n readonly first: string;\n /** Volatile topics (CT_VolTopic) */\n readonly topics?: readonly VolTopicOptions[];\n}\n\n/** Volatile topic (CT_VolTopic) */\nexport interface VolTopicOptions {\n /** Topic value (required) */\n readonly value: string;\n /** Value type (default: \"n\") */\n readonly valueType?: string;\n /** String topics (stp elements) */\n readonly stringTopics?: readonly string[];\n /** Topic references (CT_VolTopicRef) */\n readonly refs?: readonly VolTopicRefOptions[];\n}\n\n/** Volatile topic reference (CT_VolTopicRef) */\nexport interface VolTopicRefOptions {\n /** Cell reference (required) */\n readonly reference: string;\n /** Sheet index (required) */\n readonly sheetIndex: number;\n}\n\n/** Web publish object (CT_WebPublishObject) */\nexport interface WebPublishObjectOptions {\n /** Relationship ID to the published item */\n readonly rId: string;\n /** Destination file name */\n readonly destinationFile?: string;\n /** Auto republish (default: false) */\n readonly autoRepublish?: boolean;\n /** Title of the published item */\n readonly title?: string;\n /** Source object reference */\n readonly sourceObject?: string;\n /** App name (default: \"Excel\") */\n readonly appName?: string;\n}\n\n/** Calculation properties (CT_CalcPr) */\nexport interface CalcPrOptions {\n /** Calculation mode: \"manual\" | \"auto\" | \"autoNoTable\" */\n readonly calcMode?: string;\n /** Calc ID (default 162913) */\n readonly calcId?: number;\n /** Full calc on load (default false) */\n readonly fullCalcOnLoad?: boolean;\n /** Calc on save (default true) */\n readonly calcOnSave?: boolean;\n /** Force full calc */\n readonly forceFullCalc?: boolean;\n /** Concurrent calc (default true) */\n readonly concurrentCalc?: boolean;\n /** Concurrent manual count */\n readonly concurrentManualCount?: number;\n /** Iterate (default false) */\n readonly iterate?: boolean;\n /** Iterate count (default 100) */\n readonly iterateCount?: number;\n /** Iterate delta (default 0.001) */\n readonly iterateDelta?: number;\n /** Reference mode: \"A1\" | \"R1C1\" */\n readonly refMode?: string;\n /** Full precision (default true) */\n readonly fullPrecision?: boolean;\n /** Calc completed (CT_CalcPr @calcCompleted) */\n readonly calcCompleted?: boolean;\n}\n\n/** Workbook view options (CT_BookView) */\nexport interface WorkbookViewOptions {\n /** Active tab index (0-based) */\n readonly activeTab?: number;\n /** Auto filter date grouping (default true) */\n readonly autoFilterDateGrouping?: boolean;\n /** First sheet tab */\n readonly firstSheet?: number;\n /** Show horizontal scroll (default true) */\n readonly showHorizontalScroll?: boolean;\n /** Show sheet tabs (default true) */\n readonly showSheetTabs?: boolean;\n /** Show vertical scroll (default true) */\n readonly showVerticalScroll?: boolean;\n /** Tab ratio (default 600) */\n readonly tabRatio?: number;\n /** Window width in twips */\n readonly windowWidth?: number;\n /** Window height in twips */\n readonly windowHeight?: number;\n /** X position of the window */\n readonly xWindow?: number;\n /** Y position of the window */\n readonly yWindow?: number;\n}\n\nexport class WorkbookXml extends BaseXmlComponent {\n private readonly sheets: readonly SheetDefinition[];\n private readonly pivotCaches: readonly PivotCacheReference[];\n private readonly protection?: WorkbookProtectionOptions;\n private readonly customViews?: readonly CustomWorkbookViewOptions[];\n private readonly fileRecoveryPr?: FileRecoveryPrOptions;\n private readonly functionGroupNames: readonly string[];\n private readonly webPublishing?: WebPublishingOptions;\n private readonly fileSharing?: FileSharingOptions;\n private readonly workbookPr?: WorkbookPrOptions;\n private readonly calcPr?: CalcPrOptions;\n private readonly bookView?: WorkbookViewOptions;\n private readonly volTypes?: readonly VolTypeOptions[];\n private readonly webPublishObjects?: readonly WebPublishObjectOptions[];\n\n public constructor(\n sheets: readonly SheetDefinition[],\n pivotCaches?: readonly PivotCacheReference[],\n protection?: WorkbookProtectionOptions,\n customViews?: readonly CustomWorkbookViewOptions[],\n fileRecoveryPr?: FileRecoveryPrOptions,\n functionGroups?: readonly string[],\n webPublishing?: WebPublishingOptions,\n fileSharing?: FileSharingOptions,\n workbookPr?: WorkbookPrOptions,\n calcPr?: CalcPrOptions,\n bookView?: WorkbookViewOptions,\n volTypes?: readonly VolTypeOptions[],\n webPublishObjects?: readonly WebPublishObjectOptions[],\n ) {\n super(\"workbook\");\n this.sheets = sheets;\n this.pivotCaches = pivotCaches ?? [];\n this.protection = protection;\n this.customViews = customViews;\n this.fileRecoveryPr = fileRecoveryPr;\n this.functionGroupNames = functionGroups ?? [];\n this.webPublishing = webPublishing;\n this.fileSharing = fileSharing;\n this.workbookPr = workbookPr;\n this.calcPr = calcPr;\n this.bookView = bookView;\n this.volTypes = volTypes;\n this.webPublishObjects = webPublishObjects;\n }\n\n public override toXml(_context: Context): string {\n const parts: string[] = [\n '<workbook xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\"' +\n ' xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\"' +\n ' xmlns:mc=\"http://schemas.openxmlformats.org/markup-compatibility/2006\"' +\n ' mc:Ignorable=\"x15 xr xr6 xr10 xr2\"' +\n ' xmlns:x15=\"http://schemas.microsoft.com/office/spreadsheetml/2010/11/main\"' +\n ' xmlns:xr=\"http://schemas.microsoft.com/office/spreadsheetml/2014/revision\"' +\n ' xmlns:xr6=\"http://schemas.microsoft.com/office/spreadsheetml/2016/revision6\"' +\n ' xmlns:xr10=\"http://schemas.microsoft.com/office/spreadsheetml/2016/revision10\"' +\n ' xmlns:xr2=\"http://schemas.microsoft.com/office/spreadsheetml/2015/revision2\">',\n '<fileVersion appName=\"xl\" lastEdited=\"7\" lowestEdited=\"6\" rupBuild=\"29929\"/>',\n ];\n\n // File sharing (after fileVersion, before workbookPr per XSD sequence)\n if (this.fileSharing) {\n const fileSharing = this.fileSharing;\n const fsAttrs: string[] = [];\n if (fileSharing.readOnlyRecommended) fsAttrs.push('readOnlyRecommended=\"1\"');\n if (fileSharing.userName) fsAttrs.push(`userName=\"${escapeXml(fileSharing.userName)}\"`);\n if (fileSharing.reservationPassword) {\n fsAttrs.push(`reservationPassword=\"${escapeXml(fileSharing.reservationPassword)}\"`);\n // Auto-derive modern hash when reservationPassword provided without explicit hashValue\n if (fileSharing.hashValue === undefined) {\n const derived = derivePasswordHash(fileSharing.reservationPassword);\n fsAttrs.push(`algorithmName=\"${escapeXml(derived.algorithmName)}\"`);\n fsAttrs.push(`hashValue=\"${escapeXml(derived.hashValue)}\"`);\n fsAttrs.push(`saltValue=\"${escapeXml(derived.saltValue)}\"`);\n fsAttrs.push(`spinCount=\"${derived.spinCount}\"`);\n }\n }\n if (fileSharing.algorithmName)\n fsAttrs.push(`algorithmName=\"${escapeXml(fileSharing.algorithmName)}\"`);\n if (fileSharing.hashValue) fsAttrs.push(`hashValue=\"${escapeXml(fileSharing.hashValue)}\"`);\n if (fileSharing.saltValue) fsAttrs.push(`saltValue=\"${escapeXml(fileSharing.saltValue)}\"`);\n if (fileSharing.spinCount !== undefined) fsAttrs.push(`spinCount=\"${fileSharing.spinCount}\"`);\n if (fsAttrs.length > 0) {\n parts.push(`<fileSharing ${fsAttrs.join(\" \")}/>`);\n }\n }\n\n // Workbook properties\n if (this.workbookPr) {\n const wbPr = this.workbookPr;\n const wbPrAttrs: string[] = [];\n if (wbPr.date1904) wbPrAttrs.push('date1904=\"1\"');\n if (wbPr.defaultThemeVersion !== undefined)\n wbPrAttrs.push(`defaultThemeVersion=\"${wbPr.defaultThemeVersion}\"`);\n if (wbPr.showObjects) wbPrAttrs.push(`showObjects=\"${escapeXml(wbPr.showObjects)}\"`);\n if (wbPr.hidePivotFieldList) wbPrAttrs.push('hidePivotFieldList=\"1\"');\n if (wbPr.allowRefreshQuery) wbPrAttrs.push('allowRefreshQuery=\"1\"');\n if (wbPr.filterPrivacy) wbPrAttrs.push('filterPrivacy=\"1\"');\n if (wbPr.backupFile) wbPrAttrs.push('backupFile=\"1\"');\n if (wbPr.codeName) wbPrAttrs.push(`codeName=\"${escapeXml(wbPr.codeName)}\"`);\n if (wbPr.showBorderUnselectedTables) wbPrAttrs.push('showBorderUnselectedTables=\"1\"');\n if (wbPr.promptedSolutions) wbPrAttrs.push('promptedSolutions=\"1\"');\n if (wbPr.showInkAnnotation === false) wbPrAttrs.push('showInkAnnotation=\"0\"');\n if (wbPr.saveExternalLinkValues === false) wbPrAttrs.push('saveExternalLinkValues=\"0\"');\n if (wbPr.updateLinks) wbPrAttrs.push(`updateLinks=\"${escapeXml(wbPr.updateLinks)}\"`);\n if (wbPr.showPivotChartFilter) wbPrAttrs.push('showPivotChartFilter=\"1\"');\n if (wbPr.publishItems) wbPrAttrs.push('publishItems=\"1\"');\n if (wbPr.checkCompatibility) wbPrAttrs.push('checkCompatibility=\"1\"');\n if (wbPr.autoCompressPictures === false) wbPrAttrs.push('autoCompressPictures=\"0\"');\n if (wbPr.refreshAllConnections) wbPrAttrs.push('refreshAllConnections=\"1\"');\n parts.push(`<workbookPr${wbPrAttrs.length > 0 ? ` ${wbPrAttrs.join(\" \")}` : \"\"}/>`);\n } else {\n parts.push(\"<workbookPr/>\");\n }\n\n // Workbook protection (after workbookPr, before bookViews per XSD sequence)\n if (this.protection) {\n const prot = this.protection;\n const protAttrs: string[] = [];\n if (prot.lockStructure) protAttrs.push('lockStructure=\"1\"');\n if (prot.lockWindows) protAttrs.push('lockWindows=\"1\"');\n if (prot.lockRevision) protAttrs.push('lockRevision=\"1\"');\n if (prot.workbookPassword) {\n protAttrs.push(`workbookPassword=\"${this.hashPassword(prot.workbookPassword)}\"`);\n // Auto-derive modern hash when workbookPassword provided without explicit workbookHashValue\n if (prot.workbookHashValue === undefined) {\n const wbDerived = derivePasswordHash(prot.workbookPassword);\n protAttrs.push(`workbookAlgorithmName=\"${escapeXml(wbDerived.algorithmName)}\"`);\n protAttrs.push(`workbookHashValue=\"${escapeXml(wbDerived.hashValue)}\"`);\n protAttrs.push(`workbookSaltValue=\"${escapeXml(wbDerived.saltValue)}\"`);\n protAttrs.push(`workbookSpinCount=\"${wbDerived.spinCount}\"`);\n }\n }\n if (prot.workbookAlgorithmName)\n protAttrs.push(`workbookAlgorithmName=\"${escapeXml(prot.workbookAlgorithmName)}\"`);\n if (prot.workbookHashValue)\n protAttrs.push(`workbookHashValue=\"${escapeXml(prot.workbookHashValue)}\"`);\n if (prot.workbookSaltValue)\n protAttrs.push(`workbookSaltValue=\"${escapeXml(prot.workbookSaltValue)}\"`);\n if (prot.workbookSpinCount !== undefined)\n protAttrs.push(`workbookSpinCount=\"${prot.workbookSpinCount}\"`);\n if (prot.revisionsPassword) {\n protAttrs.push(`revisionsPassword=\"${this.hashPassword(prot.revisionsPassword)}\"`);\n // Auto-derive modern hash when revisionsPassword provided without explicit revisionsHashValue\n if (prot.revisionsHashValue === undefined) {\n const revDerived = derivePasswordHash(prot.revisionsPassword);\n protAttrs.push(`revisionsAlgorithmName=\"${escapeXml(revDerived.algorithmName)}\"`);\n protAttrs.push(`revisionsHashValue=\"${escapeXml(revDerived.hashValue)}\"`);\n protAttrs.push(`revisionsSaltValue=\"${escapeXml(revDerived.saltValue)}\"`);\n protAttrs.push(`revisionsSpinCount=\"${revDerived.spinCount}\"`);\n }\n }\n if (prot.revisionsAlgorithmName)\n protAttrs.push(`revisionsAlgorithmName=\"${escapeXml(prot.revisionsAlgorithmName)}\"`);\n if (prot.revisionsHashValue)\n protAttrs.push(`revisionsHashValue=\"${escapeXml(prot.revisionsHashValue)}\"`);\n if (prot.revisionsSaltValue)\n protAttrs.push(`revisionsSaltValue=\"${escapeXml(prot.revisionsSaltValue)}\"`);\n if (prot.revisionsSpinCount !== undefined)\n protAttrs.push(`revisionsSpinCount=\"${prot.revisionsSpinCount}\"`);\n if (protAttrs.length > 0) {\n parts.push(`<workbookProtection ${protAttrs.join(\" \")}/>`);\n }\n }\n\n // Book views\n if (this.bookView) {\n const bv = this.bookView;\n const bvAttrs: string[] = [];\n if (bv.xWindow !== undefined) bvAttrs.push(`xWindow=\"${bv.xWindow}\"`);\n else bvAttrs.push('xWindow=\"0\"');\n if (bv.yWindow !== undefined) bvAttrs.push(`yWindow=\"${bv.yWindow}\"`);\n else bvAttrs.push('yWindow=\"0\"');\n if (bv.windowWidth !== undefined) bvAttrs.push(`windowWidth=\"${bv.windowWidth}\"`);\n else bvAttrs.push('windowWidth=\"28800\"');\n if (bv.windowHeight !== undefined) bvAttrs.push(`windowHeight=\"${bv.windowHeight}\"`);\n else bvAttrs.push('windowHeight=\"12300\"');\n if (bv.activeTab !== undefined) bvAttrs.push(`activeTab=\"${bv.activeTab}\"`);\n if (bv.autoFilterDateGrouping === false) bvAttrs.push('autoFilterDateGrouping=\"0\"');\n if (bv.firstSheet !== undefined) bvAttrs.push(`firstSheet=\"${bv.firstSheet}\"`);\n if (bv.showHorizontalScroll === false) bvAttrs.push('showHorizontalScroll=\"0\"');\n if (bv.showSheetTabs === false) bvAttrs.push('showSheetTabs=\"0\"');\n if (bv.showVerticalScroll === false) bvAttrs.push('showVerticalScroll=\"0\"');\n if (bv.tabRatio !== undefined) bvAttrs.push(`tabRatio=\"${bv.tabRatio}\"`);\n parts.push(`<bookViews><workbookView ${bvAttrs.join(\" \")}/></bookViews>`);\n } else {\n parts.push(\n '<bookViews><workbookView xWindow=\"0\" yWindow=\"0\" windowWidth=\"28800\" windowHeight=\"12300\"/></bookViews>',\n );\n }\n parts.push(\"<sheets>\");\n for (const s of this.sheets) {\n const stateAttr = s.state && s.state !== \"visible\" ? ` state=\"${s.state}\"` : \"\";\n parts.push(\n `<sheet name=\"${escapeXml(s.name)}\" sheetId=\"${s.sheetId}\" r:id=\"${s.rId}\"${stateAttr}/>`,\n );\n }\n parts.push(\"</sheets>\");\n\n // Function groups (after sheets, before externalReferences per XSD)\n if (this.functionGroupNames.length > 0) {\n const functionGroupParts: string[] = [`<functionGroups builtInGroupCount=\"16\">`];\n for (const name of this.functionGroupNames) {\n functionGroupParts.push(`<functionGroup name=\"${escapeXml(name)}\"/>`);\n }\n functionGroupParts.push(\"</functionGroups>\");\n parts.push(functionGroupParts.join(\"\"));\n }\n\n // externalReferences placeholder — compiler injects the XML here if needed\n parts.push(\"<!--EXTERNAL_REFS-->\");\n\n // Calculation properties\n if (this.calcPr) {\n const cp = this.calcPr;\n const cpAttrs: string[] = [];\n cpAttrs.push(`calcId=\"${cp.calcId ?? 162913}\"`);\n if (cp.calcMode) cpAttrs.push(`calcMode=\"${escapeXml(cp.calcMode)}\"`);\n if (cp.fullCalcOnLoad) cpAttrs.push('fullCalcOnLoad=\"1\"');\n if (cp.calcOnSave === false) cpAttrs.push('calcOnSave=\"0\"');\n if (cp.forceFullCalc) cpAttrs.push('forceFullCalc=\"1\"');\n if (cp.concurrentCalc === false) cpAttrs.push('concurrentCalc=\"0\"');\n if (cp.concurrentManualCount !== undefined)\n cpAttrs.push(`concurrentManualCount=\"${cp.concurrentManualCount}\"`);\n if (cp.iterate) cpAttrs.push('iterate=\"1\"');\n if (cp.iterateCount !== undefined) cpAttrs.push(`iterateCount=\"${cp.iterateCount}\"`);\n if (cp.iterateDelta !== undefined) cpAttrs.push(`iterateDelta=\"${cp.iterateDelta}\"`);\n if (cp.refMode) cpAttrs.push(`refMode=\"${escapeXml(cp.refMode)}\"`);\n if (cp.fullPrecision === false) cpAttrs.push('fullPrecision=\"0\"');\n if (cp.calcCompleted) cpAttrs.push('calcCompleted=\"1\"');\n parts.push(`<calcPr ${cpAttrs.join(\" \")}/>`);\n } else {\n parts.push('<calcPr calcId=\"162913\"/>');\n }\n\n // Custom workbook views (after calcPr, before pivotCaches per XSD)\n if (this.customViews && this.customViews.length > 0) {\n parts.push(\"<customWorkbookViews>\");\n for (const v of this.customViews) {\n const vAttrs: string[] = [\n `name=\"${escapeXml(v.name)}\"`,\n `guid=\"${escapeXml(v.guid)}\"`,\n `windowWidth=\"${v.windowWidth}\"`,\n `windowHeight=\"${v.windowHeight}\"`,\n `activeSheetId=\"${v.activeSheetId}\"`,\n ];\n if (v.xWindow !== undefined) vAttrs.push(`xWindow=\"${v.xWindow}\"`);\n if (v.yWindow !== undefined) vAttrs.push(`yWindow=\"${v.yWindow}\"`);\n if (v.showFormulaBar === false) vAttrs.push('showFormulaBar=\"0\"');\n if (v.showStatusbar === false) vAttrs.push('showStatusbar=\"0\"');\n if (v.showHorizontalScroll === false) vAttrs.push('showHorizontalScroll=\"0\"');\n if (v.showVerticalScroll === false) vAttrs.push('showVerticalScroll=\"0\"');\n if (v.showSheetTabs === false) vAttrs.push('showSheetTabs=\"0\"');\n if (v.tabRatio !== undefined) vAttrs.push(`tabRatio=\"${v.tabRatio}\"`);\n if (v.includeHiddenRowCol === false) vAttrs.push('includeHiddenRowCol=\"0\"');\n if (v.includePrintSettings === false) vAttrs.push('includePrintSettings=\"0\"');\n if (v.personalView) vAttrs.push('personalView=\"1\"');\n if (v.maximized) vAttrs.push('maximized=\"1\"');\n if (v.minimized) vAttrs.push('minimized=\"1\"');\n if (v.autoUpdate) vAttrs.push('autoUpdate=\"1\"');\n if (v.mergeInterval !== undefined) vAttrs.push(`mergeInterval=\"${v.mergeInterval}\"`);\n if (v.changesSavedWin) vAttrs.push('changesSavedWin=\"1\"');\n if (v.onlySync) vAttrs.push('onlySync=\"1\"');\n if (v.showComments) vAttrs.push(`showComments=\"${escapeXml(v.showComments)}\"`);\n parts.push(`<customWorkbookView ${vAttrs.join(\" \")}/>`);\n }\n parts.push(\"</customWorkbookViews>\");\n }\n\n if (this.pivotCaches.length > 0) {\n parts.push(\"<pivotCaches>\");\n for (const pc of this.pivotCaches) {\n parts.push(`<pivotCache cacheId=\"${pc.cacheId}\" r:id=\"${pc.rId}\"/>`);\n }\n parts.push(\"</pivotCaches>\");\n }\n\n // Web publishing (after pivotCaches, before fileRecoveryPr per XSD sequence)\n if (this.webPublishing) {\n const webPublishing = this.webPublishing;\n const wpAttrs: string[] = [];\n if (webPublishing.css === false) wpAttrs.push('css=\"0\"');\n if (webPublishing.thicket === false) wpAttrs.push('thicket=\"0\"');\n if (webPublishing.longFileNames === false) wpAttrs.push('longFileNames=\"0\"');\n if (webPublishing.vml) wpAttrs.push('vml=\"1\"');\n if (webPublishing.allowPng) wpAttrs.push('allowPng=\"1\"');\n if (webPublishing.targetScreenSize && webPublishing.targetScreenSize !== \"800x600\")\n wpAttrs.push(`targetScreenSize=\"${webPublishing.targetScreenSize}\"`);\n if (webPublishing.dpi !== undefined && webPublishing.dpi !== 96)\n wpAttrs.push(`dpi=\"${webPublishing.dpi}\"`);\n if (webPublishing.codePage !== undefined)\n wpAttrs.push(`codePage=\"${webPublishing.codePage}\"`);\n if (webPublishing.characterSet)\n wpAttrs.push(`characterSet=\"${escapeXml(webPublishing.characterSet)}\"`);\n parts.push(`<webPublishing ${wpAttrs.join(\" \")}/>`);\n }\n\n // File recovery properties (after webPublishing per XSD sequence)\n if (this.fileRecoveryPr) {\n const fileRecovery = this.fileRecoveryPr;\n const frpAttrs: string[] = [];\n if (fileRecovery.autoRecover === false) frpAttrs.push('autoRecover=\"0\"');\n if (fileRecovery.crashSave) frpAttrs.push('crashSave=\"1\"');\n if (fileRecovery.dataExtractLoad) frpAttrs.push('dataExtractLoad=\"1\"');\n if (fileRecovery.repairLoad) frpAttrs.push('repairLoad=\"1\"');\n if (frpAttrs.length > 0) {\n parts.push(`<fileRecoveryPr ${frpAttrs.join(\" \")}/>`);\n }\n }\n\n // Web publish objects (after fileRecoveryPr per XSD sequence)\n if (this.webPublishObjects && this.webPublishObjects.length > 0) {\n const wpoParts: string[] = [`<webPublishObjects count=\"${this.webPublishObjects.length}\">`];\n for (const wpo of this.webPublishObjects) {\n const wpoAttrs: string[] = [`r:id=\"${escapeXml(wpo.rId)}\"`];\n if (wpo.destinationFile)\n wpoAttrs.push(`destinationFile=\"${escapeXml(wpo.destinationFile)}\"`);\n if (wpo.autoRepublish) wpoAttrs.push('autoRepublish=\"1\"');\n if (wpo.title) wpoAttrs.push(`title=\"${escapeXml(wpo.title)}\"`);\n if (wpo.sourceObject) wpoAttrs.push(`sourceObject=\"${escapeXml(wpo.sourceObject)}\"`);\n wpoParts.push(`<webPublishObject ${wpoAttrs.join(\" \")}/>`);\n }\n wpoParts.push(\"</webPublishObjects>\");\n parts.push(wpoParts.join(\"\"));\n }\n\n // Volatile dependencies (volTypes)\n if (this.volTypes && this.volTypes.length > 0) {\n const vtParts: string[] = [`<volTypes count=\"${this.volTypes.length}\">`];\n for (const vt of this.volTypes) {\n const vtType = vt.type ?? \"realTimeData\";\n const mains = vt.mains ?? [];\n if (mains.length > 0) {\n const mainParts: string[] = [];\n for (const m of mains) {\n const tpParts: string[] = [];\n for (const topic of m.topics ?? []) {\n let tpInner = `<v>${escapeXml(topic.value)}</v>`;\n for (const stp of topic.stringTopics ?? []) {\n tpInner += `<stp>${escapeXml(stp)}</stp>`;\n }\n for (const tr of topic.refs ?? []) {\n tpInner += `<tr r=\"${escapeXml(tr.reference)}\" s=\"${tr.sheetIndex}\"/>`;\n }\n const tpAttr =\n topic.valueType && topic.valueType !== \"n\"\n ? ` t=\"${escapeXml(topic.valueType)}\"`\n : \"\";\n tpParts.push(`<tp${tpAttr}>${tpInner}</tp>`);\n }\n mainParts.push(`<main first=\"${escapeXml(m.first)}\">${tpParts.join(\"\")}</main>`);\n }\n vtParts.push(`<volType type=\"${vtType}\">${mainParts.join(\"\")}</volType>`);\n } else {\n vtParts.push(`<volType type=\"${vtType}\"/>`);\n }\n }\n vtParts.push(\"</volTypes>\");\n parts.push(vtParts.join(\"\"));\n }\n\n parts.push(\"</workbook>\");\n return parts.join(\"\");\n }\n\n /**\n * Generate tableParts XML fragment for embedding in a worksheet.\n * This is called by the compiler to insert table references into the worksheet XML.\n */\n public static buildTablePartsXml(tableParts: readonly TablePartReference[]): string {\n if (tableParts.length === 0) return \"\";\n const parts: string[] = [`<tableParts count=\"${tableParts.length}\">`];\n for (const tp of tableParts) {\n parts.push(`<tablePart r:id=\"${tp.rId}\"/>`);\n }\n parts.push(\"</tableParts>\");\n return parts.join(\"\");\n }\n\n /**\n * Generate externalReferences XML fragment for embedding in the workbook.\n * This is called by the compiler to insert external reference entries.\n */\n public static buildExternalReferencesXml(refs: readonly { rId: string }[]): string {\n if (refs.length === 0) return \"\";\n const parts: string[] = [\"<externalReferences>\"];\n for (const ref of refs) {\n parts.push(`<externalReference r:id=\"${ref.rId}\"/>`);\n }\n parts.push(\"</externalReferences>\");\n return parts.join(\"\");\n }\n\n /** Legacy Excel password hash (XOR-based) */\n private hashPassword(password: string): string {\n let hash = 0;\n for (let i = 0; i < password.length; i++) {\n const c = password.charCodeAt(i);\n hash = ((hash >> 14) & 1) + ((hash << 1) & 0x7fff);\n hash ^= c;\n hash = hash & 0x4000 ? hash ^ 0x1 : hash;\n }\n hash = ((hash >> 14) & 1) + ((hash << 1) & 0x7fff);\n hash = ((hash >> 14) & 1) + ((hash << 1) & 0x7fff);\n hash ^= password.length;\n return hash.toString(16).toUpperCase().padStart(4, \"0\");\n }\n}\n","import type { SharedStrings } from \"@file/shared-strings\";\nimport { buildRstXml } from \"@file/shared-strings\";\nimport type { Styles, StyleOptions } from \"@file/styles\";\n/**\n * Worksheet component — generates xl/worksheets/sheet{n}.xml.\n *\n * @module\n */\nimport { IgnoreIfEmptyXmlComponent } from \"@file/xml-components\";\nimport type { Context } from \"@file/xml-components\";\nimport type { ChartSpaceOptions } from \"@office-open/core\";\nimport { derivePasswordHash } from \"@office-open/core\";\nimport { attrs, escapeXml, selfCloseElement } from \"@office-open/xml\";\n\nimport type { PivotTableOptions } from \"./pivot\";\nimport type { TableOptions } from \"./table\";\n\nexport interface ColumnOptions {\n readonly min: number;\n readonly max: number;\n readonly width?: number;\n readonly hidden?: boolean;\n readonly customWidth?: boolean;\n readonly outlineLevel?: number;\n readonly collapsed?: boolean;\n /** Best-fit column width (CT_Col @bestFit) */\n readonly bestFit?: boolean;\n /** Phonetic text for CJK (CT_Col @phonetic) */\n readonly phonetic?: boolean;\n}\n\nexport interface RowOptions {\n readonly cells?: readonly CellOptions[];\n readonly height?: number;\n readonly hidden?: boolean;\n readonly rowNumber?: number;\n /** Spans for the row, e.g. \"1:15\" (CT_Row @spans) */\n readonly spans?: string;\n /** Custom format applied (CT_Row @customFormat) */\n readonly customFormat?: boolean;\n /** Thick top border (CT_Row @thickTop) */\n readonly thickTop?: boolean;\n /** Thick bottom border (CT_Row @thickBot) */\n readonly thickBot?: boolean;\n /** Phonetic text (CT_Row @ph) */\n readonly ph?: boolean;\n}\n\n/** Rich text run properties (CT_RPrElt). */\nexport interface RichTextRunPrOptions {\n /** Font name (CT_FontName → rFont) */\n readonly font?: string;\n /** Character set (CT_IntProperty) */\n readonly charset?: number;\n /** Font family (CT_IntProperty) */\n readonly family?: number;\n /** Bold */\n readonly bold?: boolean;\n /** Italic */\n readonly italic?: boolean;\n /** Strikethrough */\n readonly strike?: boolean;\n /** Outline */\n readonly outline?: boolean;\n /** Shadow */\n readonly shadow?: boolean;\n /** Condense */\n readonly condense?: boolean;\n /** Extend */\n readonly extend?: boolean;\n /** Font color (hex RGB, e.g. \"FF0000\") */\n readonly color?: string;\n /** Font size in points */\n readonly size?: number;\n /** Underline type */\n readonly underline?: \"single\" | \"double\" | \"singleAccounting\" | \"doubleAccounting\" | \"none\";\n /** Vertical alignment */\n readonly vertAlign?: \"superscript\" | \"subscript\" | \"baseline\";\n /** Font scheme */\n readonly scheme?: \"major\" | \"minor\" | \"none\";\n}\n\n/** A single rich text run (CT_RElt). */\nexport interface RichTextRunOptions {\n /** Run properties (optional = inherits from parent) */\n readonly properties?: RichTextRunPrOptions;\n /** Run text content */\n readonly text: string;\n}\n\n/** Phonetics run for CJK (CT_PhoneticRun → rPh). */\nexport interface PhoneticRunOptions {\n /** Start byte offset in base text */\n readonly sb: number;\n /** End byte offset in base text */\n readonly eb: number;\n /** Phonetic text */\n readonly text: string;\n}\n\n/** Rich text content (CT_Rst). Either plain text or rich runs. */\nexport interface RichTextOptions {\n /** Plain text (mutually exclusive with runs) */\n readonly text?: string;\n /** Rich text runs (mutually exclusive with text) */\n readonly runs?: readonly RichTextRunOptions[];\n /** Phonetic runs for CJK (CT_PhoneticRun) */\n readonly phonetics?: readonly PhoneticRunOptions[];\n}\n\nexport interface CellOptions {\n readonly value?: string | number | boolean | Date | RichTextOptions | null;\n readonly reference?: string;\n /** Direct style index (for pre-resolved styles) */\n readonly styleIndex?: number;\n /** Style options (resolved to index at compile time) */\n readonly style?: StyleOptions;\n /** Formula options. When set, value becomes the cached result. */\n readonly formula?: FormulaOptions;\n}\n\n/** Cell formula type (maps to ST_CellFormulaType). */\nexport const FormulaType = {\n NORMAL: \"normal\",\n ARRAY: \"array\",\n SHARED: \"shared\",\n} as const;\n\nexport type FormulaType = (typeof FormulaType)[keyof typeof FormulaType];\n\n/** Options for a cell formula (maps to CT_CellFormula). */\nexport interface FormulaOptions {\n /** Formula expression, e.g. \"SUM(A1:B1)\" */\n readonly formula: string;\n /** Formula type (default: \"normal\") */\n readonly type?: FormulaType;\n /** Reference range for array/shared formulas, e.g. \"C1:C10\" */\n readonly reference?: string;\n /** Shared formula group index (required for shared formulas) */\n readonly sharedIndex?: number;\n /** Always calculate array (CT_CellFormula @aca) */\n readonly aca?: boolean;\n /** 2-D data table (CT_CellFormula @dt2D) */\n readonly dt2D?: boolean;\n /** Data table row (CT_CellFormula @dtr) */\n readonly dtr?: boolean;\n /** Delete input cell 1 (CT_CellFormula @del1) */\n readonly del1?: boolean;\n /** Delete input cell 2 (CT_CellFormula @del2) */\n readonly del2?: boolean;\n /** Input cell 1 reference (CT_CellFormula @r1) */\n readonly r1?: string;\n /** Input cell 2 reference (CT_CellFormula @r2) */\n readonly r2?: string;\n /** Calculate cell (CT_CellFormula @ca) */\n readonly ca?: boolean;\n /** Array formula context (CT_CellFormula @bx) */\n readonly bx?: boolean;\n}\n\n/** Input cell for a what-if scenario (maps to CT_InputCells). */\nexport interface ScenarioCellOptions {\n /** Cell reference, e.g. \"B2\" */\n readonly r: string;\n /** Cell value for this scenario */\n readonly val: string | number;\n /** Whether the value is deleted */\n readonly deleted?: boolean;\n}\n\n/** A single what-if scenario (maps to CT_Scenario). */\nexport interface ScenarioDefinition {\n /** Scenario name */\n readonly name: string;\n /** Input cells with their values for this scenario */\n readonly inputCells: readonly ScenarioCellOptions[];\n /** Sort/order count */\n readonly count?: number;\n /** Creator user name */\n readonly user?: string;\n /** Comment */\n readonly comment?: string;\n /** Whether the scenario is hidden */\n readonly hidden?: boolean;\n /** Whether the scenario is locked */\n readonly locked?: boolean;\n}\n\n/** Scenarios for what-if analysis (maps to CT_Scenarios). */\nexport interface ScenarioOptions {\n /** Named scenarios */\n readonly scenarios: readonly ScenarioDefinition[];\n /** Current scenario index (0-based) */\n readonly current?: number;\n /** Show scenario index (0-based) */\n readonly show?: number;\n}\n\nexport interface MergeCellOptions {\n readonly from: { readonly row: number; readonly col: number };\n readonly to: { readonly row: number; readonly col: number };\n}\n\nexport interface SheetProtectionOptions {\n /** Plain-text password — legacy Excel hash is computed automatically */\n readonly password?: string;\n /** Modern encryption: algorithm name (e.g. \"SHA-512\") */\n readonly algorithmName?: string;\n /** Modern encryption: base64-encoded hash value */\n readonly hashValue?: string;\n /** Modern encryption: base64-encoded salt value */\n readonly saltValue?: string;\n /** Modern encryption: spin count for hash iteration */\n readonly spinCount?: number;\n /** Set true to enable sheet protection (required for protection flags to take effect) */\n readonly sheet?: boolean;\n readonly objects?: boolean;\n readonly scenarios?: boolean;\n readonly formatCells?: boolean;\n readonly formatColumns?: boolean;\n readonly formatRows?: boolean;\n readonly insertColumns?: boolean;\n readonly insertRows?: boolean;\n readonly insertHyperlinks?: boolean;\n readonly deleteColumns?: boolean;\n readonly deleteRows?: boolean;\n readonly selectLockedCells?: boolean;\n readonly sort?: boolean;\n readonly autoFilter?: boolean;\n readonly pivotTables?: boolean;\n readonly selectUnlockedCells?: boolean;\n}\n\n/** A named protected range within a sheet (CT_ProtectedRange) */\nexport interface ProtectedRangeOptions {\n /** Range reference (required), e.g. \"A1:C10\" */\n readonly sqref: string;\n /** Range name (required) */\n readonly name: string;\n /** Plain-text password — legacy hash computed automatically */\n readonly password?: string;\n /** Modern encryption: algorithm name */\n readonly algorithmName?: string;\n /** Modern encryption: base64-encoded hash value */\n readonly hashValue?: string;\n /** Modern encryption: base64-encoded salt value */\n readonly saltValue?: string;\n /** Modern encryption: spin count */\n readonly spinCount?: number;\n /** Security descriptor (SID string) */\n readonly securityDescriptor?: string;\n}\n\nexport interface FreezePaneOptions {\n /** Row split position (1-based, freezes rows above) */\n readonly row?: number;\n /** Column split position (1-based, freezes columns to the left) */\n readonly col?: number;\n}\n\nexport interface WorksheetImageOptions {\n readonly data: Uint8Array;\n readonly type: \"png\" | \"jpeg\" | \"jpg\";\n readonly col: number;\n readonly row: number;\n}\n\nexport interface WorksheetChartOptions extends ChartSpaceOptions {\n /** 1-based column position for the chart */\n readonly col: number;\n /** 1-based row position for the chart */\n readonly row: number;\n}\n\nexport interface SheetViewOptions {\n readonly showGridLines?: boolean;\n readonly showRowColHeaders?: boolean;\n readonly showZeros?: boolean;\n readonly zoomScale?: number;\n readonly tabSelected?: boolean;\n readonly rightToLeft?: boolean;\n /** Window protection (CT_SheetView @windowProtection) */\n readonly windowProtection?: boolean;\n /** Show formulas instead of values (CT_SheetView @showFormulas) */\n readonly showFormulas?: boolean;\n /** Show ruler (CT_SheetView @showRuler) */\n readonly showRuler?: boolean;\n /** Show outline symbols (CT_SheetView @showOutlineSymbols) */\n readonly showOutlineSymbols?: boolean;\n /** Default grid color (CT_SheetView @defaultGridColor) */\n readonly defaultGridColor?: boolean;\n /** Show white space (CT_SheetView @showWhiteSpace) */\n readonly showWhiteSpace?: boolean;\n /** View type (CT_SheetView @view) */\n readonly view?: \"normal\" | \"pageBreakPreview\" | \"pageLayout\";\n /** Tab color ID (CT_SheetView @colorId) */\n readonly colorId?: number;\n /** Zoom scale for normal view (CT_SheetView @zoomScaleNormal) */\n readonly zoomScaleNormal?: number;\n /** Zoom scale for sheet layout view (CT_SheetView @zoomScaleSheetLayoutView) */\n readonly zoomScaleSheetLayoutView?: number;\n /** Zoom scale for page layout view (CT_SheetView @zoomScalePageLayoutView) */\n readonly zoomScalePageLayoutView?: number;\n /** Pivot selections (CT_PivotSelection) */\n readonly pivotSelections?: readonly PivotSelectionOptions[];\n}\n\n/** Pivot selection in sheet view (CT_PivotSelection) */\nexport interface PivotSelectionOptions {\n /** Pane (default: \"topLeft\") */\n readonly pane?: \"bottomRight\" | \"topRight\" | \"bottomLeft\" | \"topLeft\";\n /** Show header (default: false) */\n readonly showHeader?: boolean;\n /** Label selected (default: false) */\n readonly label?: boolean;\n /** Data selected (default: false) */\n readonly data?: boolean;\n /** Extendable (default: false) */\n readonly extendable?: boolean;\n /** Selection count */\n readonly count?: number;\n /** Axis */\n readonly axis?: \"axisRow\" | \"axisCol\" | \"axisPage\" | \"axisValues\";\n /** Dimension */\n readonly dimension?: number;\n /** Start index */\n readonly start?: number;\n /** Min index */\n readonly min?: number;\n /** Max index */\n readonly max?: number;\n /** Active row */\n readonly activeRow?: number;\n /** Active column */\n readonly activeCol?: number;\n /** Previous row */\n readonly previousRow?: number;\n /** Previous column */\n readonly previousCol?: number;\n /** Clicked row */\n readonly click?: number;\n /** Relationship ID (maps to r:id in XML) */\n readonly rId?: string;\n}\n\nexport type HyperlinkTarget =\n | { readonly type: \"external\"; readonly url: string }\n | { readonly type: \"internal\"; readonly location: string };\n\nexport interface HyperlinkOptions {\n /** Cell reference, e.g. \"A1\" */\n readonly cell: string;\n /** Hyperlink target */\n readonly target: HyperlinkTarget;\n /** Tooltip text */\n readonly tooltip?: string;\n /** Display text */\n readonly display?: string;\n}\n\nexport interface HeaderFooterOptions {\n readonly oddHeader?: string;\n readonly oddFooter?: string;\n readonly evenHeader?: string;\n readonly evenFooter?: string;\n readonly firstHeader?: string;\n readonly firstFooter?: string;\n readonly differentOddEven?: boolean;\n readonly differentFirst?: boolean;\n /** Scale header/footer with document (CT_HeaderFooter @scaleWithDoc) */\n readonly scaleWithDoc?: boolean;\n /** Align with page margins (CT_HeaderFooter @alignWithMargins) */\n readonly alignWithMargins?: boolean;\n}\n\nexport type PageOrientation = \"default\" | \"portrait\" | \"landscape\";\n\nexport interface PageSetupOptions {\n readonly paperSize?: number;\n readonly orientation?: PageOrientation;\n readonly scale?: number;\n readonly fitToWidth?: number;\n readonly fitToHeight?: number;\n readonly pageOrder?: \"downThenOver\" | \"overThenDown\";\n readonly useFirstPageNumber?: boolean;\n readonly firstPageNumber?: number;\n /** Paper height (CT_PageSetup @paperHeight) */\n readonly paperHeight?: number;\n /** Paper width (CT_PageSetup @paperWidth) */\n readonly paperWidth?: number;\n /** Use printer defaults (CT_PageSetup @usePrinterDefaults) */\n readonly usePrinterDefaults?: boolean;\n /** Black and white printing (CT_PageSetup @blackAndWhite) */\n readonly blackAndWhite?: boolean;\n /** Draft quality printing (CT_PageSetup @draft) */\n readonly draft?: boolean;\n /** Print cell comments mode (CT_PageSetup @cellComments) */\n readonly cellComments?: \"none\" | \"asDisplayed\" | \"atEnd\";\n /** Print error display mode (CT_PageSetup @errors) */\n readonly errors?: \"displayed\" | \"blank\" | \"dash\" | \"NA\";\n}\n\nexport interface TabColorOptions {\n /** RGB color string, e.g. \"FF0000\" */\n readonly rgb?: string;\n /** Theme color index (0-based) */\n readonly theme?: number;\n /** Tint value (-1.0 to 1.0) */\n readonly tint?: number;\n}\n\n/** Object anchor (CT_ObjectAnchor). */\nexport interface ObjectAnchorOptions {\n /** Move with cells (default: false) */\n readonly moveWithCells?: boolean;\n /** Size with cells (default: false) */\n readonly sizeWithCells?: boolean;\n}\n\n/** Comment property (CT_CommentPr). */\nexport interface CommentPrOptions {\n /** Locked */\n readonly locked?: boolean;\n /** Default size */\n readonly defaultSize?: boolean;\n /** Print */\n readonly print?: boolean;\n /** Disabled */\n readonly disabled?: boolean;\n /** Auto fill */\n readonly autoFill?: boolean;\n /** Auto line */\n readonly autoLine?: boolean;\n /** Alt text */\n readonly altText?: string;\n /** Text horizontal alignment */\n readonly textHAlign?: \"left\" | \"center\" | \"right\" | \"justify\" | \"distributed\";\n /** Text vertical alignment */\n readonly textVAlign?: \"top\" | \"center\" | \"bottom\" | \"justify\" | \"distributed\";\n /** Lock text */\n readonly lockText?: boolean;\n /** Justify last line */\n readonly justLastX?: boolean;\n /** Auto scale */\n readonly autoScale?: boolean;\n /** Object anchor position */\n readonly anchor?: ObjectAnchorOptions;\n}\n\nexport interface CommentOptions {\n /** Cell reference, e.g. \"A1\" */\n readonly cell: string;\n /** Author name */\n readonly author: string;\n /** Comment text (plain string or rich text) */\n readonly text: string | RichTextOptions;\n /** Comment properties (CT_CommentPr) */\n readonly commentPr?: CommentPrOptions;\n}\n\nexport type DataValidationType =\n | \"none\"\n | \"whole\"\n | \"decimal\"\n | \"list\"\n | \"date\"\n | \"time\"\n | \"textLength\"\n | \"custom\";\nexport type DataValidationOperator =\n | \"between\"\n | \"notBetween\"\n | \"equal\"\n | \"notEqual\"\n | \"greaterThan\"\n | \"lessThan\"\n | \"greaterThanOrEqual\"\n | \"lessThanOrEqual\";\n\nexport interface DataValidationOptions {\n /** Cell range, e.g. \"A1:A10\" */\n readonly sqref: string;\n readonly type?: DataValidationType;\n readonly operator?: DataValidationOperator;\n readonly formula1?: string;\n readonly formula2?: string;\n readonly allowBlank?: boolean;\n readonly showErrorMessage?: boolean;\n readonly errorTitle?: string;\n readonly error?: string;\n readonly showInputMessage?: boolean;\n readonly promptTitle?: string;\n readonly prompt?: string;\n /** Error style (CT_DataValidation @errorStyle) */\n readonly errorStyle?: \"stop\" | \"warning\" | \"information\";\n /** IME mode (CT_DataValidation @imeMode) */\n readonly imeMode?:\n | \"noControl\"\n | \"on\"\n | \"off\"\n | \"disabled\"\n | \"hiragana\"\n | \"fullKatakana\"\n | \"halfKatakana\"\n | \"fullAlpha\"\n | \"halfAlpha\"\n | \"fullHangul\"\n | \"halfHangul\";\n /** Show drop-down (CT_DataValidation @showDropDown — note inverted semantics in OOXML) */\n readonly showDropDown?: boolean;\n}\n\nexport type ConditionalFormatType =\n | \"cellIs\"\n | \"containsText\"\n | \"expression\"\n | \"top10\"\n | \"aboveAverage\"\n | \"colorScale\"\n | \"dataBar\"\n | \"iconSet\";\nexport type ConditionalFormatOperator =\n | \"lessThan\"\n | \"lessThanOrEqual\"\n | \"equal\"\n | \"notEqual\"\n | \"greaterThanOrEqual\"\n | \"greaterThan\"\n | \"between\"\n | \"notBetween\"\n | \"containsText\"\n | \"notContains\"\n | \"beginsWith\"\n | \"endsWith\";\n\n/** Conditional format value object type (ST_CfvoType) */\nexport type CfvoType = \"num\" | \"percent\" | \"max\" | \"min\" | \"formula\" | \"percentile\";\n\n/** Conditional format value object */\nexport interface CfvoOptions {\n readonly type: CfvoType;\n readonly val?: string | number;\n /** Greater than or equal (default: true) */\n readonly gte?: boolean;\n}\n\n/** Icon set type (ST_IconSetType) */\nexport type IconSetType =\n | \"3Arrows\"\n | \"3ArrowsGray\"\n | \"3Flags\"\n | \"3TrafficLights1\"\n | \"3TrafficLights2\"\n | \"3Signs\"\n | \"3Symbols\"\n | \"3Symbols2\"\n | \"4Arrows\"\n | \"4ArrowsGray\"\n | \"4RedToBlack\"\n | \"4Rating\"\n | \"4TrafficLights\"\n | \"5Arrows\"\n | \"5ArrowsGray\"\n | \"5Rating\"\n | \"5Quarters\";\n\n/** Color scale rule configuration */\nexport interface ColorScaleOptions {\n /** Conditional format values (minimum 2, typically 2 or 3) */\n readonly cfvo: readonly CfvoOptions[];\n /** Colors for each value (same count as cfvo) — RGB hex without alpha, e.g. \"FF0000\" */\n readonly colors: readonly string[];\n}\n\n/** Data bar rule configuration */\nexport interface DataBarOptions {\n /** Minimum and maximum value objects (exactly 2) */\n readonly cfvo: readonly [CfvoOptions, CfvoOptions];\n /** Bar color — RGB hex without alpha, e.g. \"638EC6\" */\n readonly color: string;\n /** Minimum bar length as percentage (default: 10) */\n readonly minLength?: number;\n /** Maximum bar length as percentage (default: 90) */\n readonly maxLength?: number;\n /** Whether to show cell values (default: true) */\n readonly showValue?: boolean;\n}\n\n/** Icon set rule configuration */\nexport interface IconSetOptions {\n /** Conditional format values (minimum 2) */\n readonly cfvo: readonly CfvoOptions[];\n /** Icon set type (default: \"3TrafficLights1\") */\n readonly iconSet?: IconSetType;\n /** Whether to show cell values (default: true) */\n readonly showValue?: boolean;\n /** Whether values are percentages (default: true) */\n readonly percent?: boolean;\n /** Whether to reverse icon order (default: false) */\n readonly reverse?: boolean;\n}\n\nexport interface ConditionalFormatRule {\n readonly type: ConditionalFormatType;\n readonly operator?: ConditionalFormatOperator;\n /** Formula(s) — up to 3 */\n readonly formulas?: readonly string[];\n readonly priority?: number;\n /** Reference to a dxf (differential format) in the styles table */\n readonly dxfId?: number;\n /** Color scale configuration (when type is \"colorScale\") */\n readonly colorScale?: ColorScaleOptions;\n /** Data bar configuration (when type is \"dataBar\") */\n readonly dataBar?: DataBarOptions;\n /** Icon set configuration (when type is \"iconSet\") */\n readonly iconSet?: IconSetOptions;\n /** Stop if true — skip remaining rules (CT_CfRule @stopIfTrue) */\n readonly stopIfTrue?: boolean;\n /** Time period for date-based highlighting (CT_CfRule @timePeriod) */\n readonly timePeriod?:\n | \"today\"\n | \"yesterday\"\n | \"tomorrow\"\n | \"last7Days\"\n | \"thisMonth\"\n | \"lastMonth\"\n | \"nextMonth\"\n | \"thisWeek\"\n | \"lastWeek\"\n | \"nextWeek\";\n /** Rank for top/bottom rules (CT_CfRule @rank) */\n readonly rank?: number;\n /** Equal average flag (CT_CfRule @equalAverage) */\n readonly equalAverage?: boolean;\n}\n\nexport interface ConditionalFormatOptions {\n /** Cell range, e.g. \"A1:A10\" */\n readonly sqref: string;\n readonly rules: readonly ConditionalFormatRule[];\n}\n\nexport interface Top10FilterOptions {\n readonly colId: number;\n readonly top?: boolean;\n readonly percent?: boolean;\n readonly val: number;\n}\n\nexport interface CustomFilterOptions {\n readonly colId: number;\n readonly operator?:\n | \"equal\"\n | \"notEqual\"\n | \"greaterThan\"\n | \"greaterThanOrEqual\"\n | \"lessThan\"\n | \"lessThanOrEqual\";\n readonly val?: string;\n readonly and?: boolean;\n readonly val2?: string;\n}\n\nexport interface SortCondition {\n /** Cell reference for the sort column, e.g. \"B1\" */\n readonly ref: string;\n readonly descending?: boolean;\n /** Sort by (CT_SortCondition @sortBy) */\n readonly sortBy?: \"value\" | \"cellColor\" | \"fontColor\" | \"icon\";\n /** Custom sort list (CT_SortCondition @customList) */\n readonly customList?: string;\n /** Icon set index (CT_SortCondition @iconId) */\n readonly iconId?: number;\n}\n\nexport interface AutoFilterOptions {\n /** Range, e.g. \"A1:D10\" */\n readonly ref: string;\n readonly top10?: readonly Top10FilterOptions[];\n readonly customFilters?: readonly CustomFilterOptions[];\n readonly sort?: readonly SortCondition[];\n /** Sort state options */\n readonly sortState?: SortStateOptions;\n /** Color filters (CT_ColorFilter) */\n readonly colorFilters?: readonly ColorFilterOptions[];\n /** Icon filters (CT_IconFilter) */\n readonly iconFilters?: readonly IconFilterOptions[];\n /** Dynamic filters (CT_DynamicFilter) */\n readonly dynamicFilters?: readonly DynamicFilterOptions[];\n /** Date group items in filters (CT_DateGroupItem) */\n readonly dateGroupItems?: readonly DateGroupFilterOptions[];\n}\n\n/** Color filter (CT_ColorFilter) */\nexport interface ColorFilterOptions {\n /** Column ID */\n readonly colId: number;\n /** Cell color RGB (dxfId used if not set) */\n readonly dxfId?: number;\n /** Filter by cell color (CT_ColorFilter @cellColor) */\n readonly cellColor?: boolean;\n}\n\n/** Icon filter (CT_IconFilter) */\nexport interface IconFilterOptions {\n /** Column ID */\n readonly colId: number;\n /** Icon set index (CT_IconFilter @iconSet) */\n readonly iconSet: number;\n /** Icon ID within set (CT_IconFilter @iconId) */\n readonly iconId?: number;\n}\n\n/** Dynamic filter (CT_DynamicFilter) */\nexport interface DynamicFilterOptions {\n /** Column ID */\n readonly colId: number;\n /** Dynamic filter type (CT_DynamicFilter @type) */\n readonly type:\n | \"null\"\n | \"aboveAverage\"\n | \"belowAverage\"\n | \"tomorrow\"\n | \"today\"\n | \"yesterday\"\n | \"nextWeek\"\n | \"thisWeek\"\n | \"lastWeek\"\n | \"nextMonth\"\n | \"thisMonth\"\n | \"lastMonth\"\n | \"nextQuarter\"\n | \"thisQuarter\"\n | \"lastQuarter\"\n | \"nextYear\"\n | \"thisYear\"\n | \"lastYear\"\n | \"yearToDate\"\n | \"Q1\"\n | \"Q2\"\n | \"Q3\"\n | \"Q4\"\n | \"M1\"\n | \"M2\"\n | \"M3\"\n | \"M4\"\n | \"M5\"\n | \"M6\"\n | \"M7\"\n | \"M8\"\n | \"M9\"\n | \"M10\"\n | \"M11\"\n | \"M12\";\n /** Max value (CT_DynamicFilter @val) */\n readonly val?: number;\n /** Max value as date ISO string (CT_DynamicFilter @maxVal) */\n readonly maxVal?: number;\n}\n\n/** Date group filter item (CT_DateGroupItem) */\nexport interface DateGroupFilterOptions {\n /** Column ID */\n readonly colId: number;\n /** Date grouping level (CT_DateGroupItem @dateTimeGrouping) */\n readonly dateTimeGrouping: \"year\" | \"month\" | \"day\" | \"hour\" | \"minute\" | \"second\";\n /** Year (CT_DateGroupItem @year) */\n readonly year?: number;\n /** Month (1-12, CT_DateGroupItem @month) */\n readonly month?: number;\n /** Day (1-31, CT_DateGroupItem @day) */\n readonly day?: number;\n /** Hour (0-23, CT_DateGroupItem @hour) */\n readonly hour?: number;\n /** Minute (0-59, CT_DateGroupItem @minute) */\n readonly minute?: number;\n /** Second (0-59, CT_DateGroupItem @second) */\n readonly second?: number;\n}\n\n/** Sort state configuration (CT_SortState) */\nexport interface SortStateOptions {\n /** Column sort mode (CT_SortState @columnSort) */\n readonly columnSort?: boolean;\n /** Case sensitive sorting (CT_SortState @caseSensitive) */\n readonly caseSensitive?: boolean;\n /** Sort method (CT_SortState @sortMethod) */\n readonly sortMethod?: \"pinYin\" | \"stroke\";\n}\n\n/** Print options (CT_PrintOptions) */\nexport interface PrintOptions {\n /** Center horizontally on page */\n readonly horizontalCentered?: boolean;\n /** Center vertically on page */\n readonly verticalCentered?: boolean;\n /** Print row/column headings */\n readonly headings?: boolean;\n /** Print grid lines */\n readonly gridLines?: boolean;\n /** Grid lines set flag */\n readonly gridLinesSet?: boolean;\n}\n\n/** Sheet format properties (CT_SheetFormatPr) */\nexport interface SheetFormatPrOptions {\n /** Base column width (CT_SheetFormatPr @baseColWidth) */\n readonly baseColWidth?: number;\n /** Default column width (CT_SheetFormatPr @defaultColWidth) */\n readonly defaultColWidth?: number;\n /** Default row height */\n readonly defaultRowHeight?: number;\n /** Zero height rows hidden (CT_SheetFormatPr @zeroHeight) */\n readonly zeroHeight?: boolean;\n /** Thick top borders (CT_SheetFormatPr @thickTop) */\n readonly thickTop?: boolean;\n /** Thick bottom borders (CT_SheetFormatPr @thickBottom) */\n readonly thickBottom?: boolean;\n /** Outline level row (CT_SheetFormatPr @outlineLevelRow) */\n readonly outlineLevelRow?: number;\n /** Outline level column (CT_SheetFormatPr @outlineLevelCol) */\n readonly outlineLevelCol?: number;\n}\n\n/** Sheet properties extended options (CT_SheetPr attributes) */\nexport interface SheetPrOptions {\n /** Sync horizontal scroll (CT_SheetPr @syncHorizontal) */\n readonly syncHorizontal?: boolean;\n /** Sync vertical scroll (CT_SheetPr @syncVertical) */\n readonly syncVertical?: boolean;\n /** Sync reference (CT_SheetPr @syncRef) */\n readonly syncRef?: string;\n /** Transition evaluation mode (CT_SheetPr @transitionEvaluation) */\n readonly transitionEvaluation?: boolean;\n /** Transition entry mode (CT_SheetPr @transitionEntry) */\n readonly transitionEntry?: boolean;\n /** Published to server (CT_SheetPr @published) */\n readonly published?: boolean;\n /** Filter mode (CT_SheetPr @filterMode) */\n readonly filterMode?: boolean;\n /** Enable format conditions calculation (CT_SheetPr @enableFormatConditionsCalculation) */\n readonly enableFormatConditionsCalculation?: boolean;\n /** Outline apply styles (CT_OutlinePr @applyStyles) */\n readonly outlineApplyStyles?: boolean;\n /** Outline show symbols (CT_OutlinePr @showOutlineSymbols) */\n readonly outlineShowSymbols?: boolean;\n}\n\n/** An ignored error entry — suppresses specific Excel error checks for a range. */\nexport interface IgnoredErrorOptions {\n /** Cell range, e.g. \"A1:A10\" (required) */\n readonly sqref: string;\n readonly evalError?: boolean;\n readonly twoDigitTextYear?: boolean;\n readonly numberStoredAsText?: boolean;\n readonly formula?: boolean;\n readonly formulaRange?: boolean;\n readonly unlockedFormula?: boolean;\n readonly emptyCellReference?: boolean;\n readonly listDataValidation?: boolean;\n readonly calculatedColumn?: boolean;\n}\n\n/** Phonetic properties for CJK text (CT_PhoneticPr) */\nexport interface PhoneticPrOptions {\n /** Font ID from the styles table (required) */\n readonly fontId: number;\n /** Phonetic type (default: \"fullwidthKatakana\") */\n readonly type?: \"fullwidthKatakana\" | \"halfwidthKatakana\" | \"Hiragana\" | \"noConversion\";\n /** Alignment (default: \"left\") */\n readonly alignment?: \"left\" | \"center\" | \"distributed\";\n}\n\n/** Background image for a worksheet */\nexport interface SheetBackgroundImageOptions {\n readonly data: Uint8Array;\n readonly type: \"png\" | \"jpeg\" | \"jpg\";\n}\n\n/** Page break entry (CT_Break) */\nexport interface PageBreakOptions {\n /** Row or column ID (1-based) */\n readonly id: number;\n /** Min value (CT_Break @min) */\n readonly min?: number;\n /** Max value (CT_Break @max) */\n readonly max?: number;\n /** Manual break (CT_Break @man) */\n readonly manual?: boolean;\n /** Pivot break (CT_Break @pt) */\n readonly pivot?: boolean;\n}\n\n/** Selection in sheet view (CT_Selection) */\nexport interface SelectionOptions {\n /** Pane (CT_Selection @pane) */\n readonly pane?: \"bottomRight\" | \"topRight\" | \"bottomLeft\" | \"topLeft\";\n /** Active cell (CT_Selection @activeCell) */\n readonly activeCell?: string;\n /** Active cell index (CT_Selection @activeCellId) */\n readonly activeCellId?: number;\n /** Selected range (CT_Selection @sqref) */\n readonly sqref?: string;\n}\n\n/** Custom sheet view (CT_CustomSheetView) */\nexport interface CustomSheetViewOptions {\n /** GUID identifier (required, CT_CustomSheetView @guid) */\n readonly guid: string;\n /** Zoom scale (CT_CustomSheetView @scale) */\n readonly scale?: number;\n /** Show page breaks (CT_CustomSheetView @showPageBreaks) */\n readonly showPageBreaks?: boolean;\n /** Show formulas (CT_CustomSheetView @showFormulas) */\n readonly showFormulas?: boolean;\n /** Show grid lines (CT_CustomSheetView @showGridLines) */\n readonly showGridLines?: boolean;\n /** Show row/column headers (CT_CustomSheetView @showRowCol) */\n readonly showRowColHeaders?: boolean;\n /** Show outline symbols (CT_CustomSheetView @outlineSymbols) */\n readonly outlineSymbols?: boolean;\n /** Show zero values (CT_CustomSheetView @zeroValues) */\n readonly zeroValues?: boolean;\n /** Fit to page (CT_CustomSheetView @fitToPage) */\n readonly fitToPage?: boolean;\n /** Print area (CT_CustomSheetView @printArea) */\n readonly printArea?: boolean;\n /** Filter applied (CT_CustomSheetView @filter) */\n readonly filter?: boolean;\n /** Show auto filter (CT_CustomSheetView @showAutoFilter) */\n readonly showAutoFilter?: boolean;\n /** Hidden rows (CT_CustomSheetView @hiddenRows) */\n readonly hiddenRows?: boolean;\n /** Hidden columns (CT_CustomSheetView @hiddenColumns) */\n readonly hiddenColumns?: boolean;\n /** Sheet state (CT_CustomSheetView @state) */\n readonly state?: \"visible\" | \"hidden\" | \"veryHidden\";\n /** Filter unique (CT_CustomSheetView @filterUnique) */\n readonly filterUnique?: boolean;\n /** View type (CT_CustomSheetView @view) */\n readonly view?: \"normal\" | \"pageBreakPreview\" | \"pageLayout\";\n}\n\n/** Cell watch entry (CT_CellWatch) */\nexport interface CellWatchOptions {\n /** Cell reference, e.g. \"A1\" */\n readonly r: string;\n}\n\n/** Data consolidation (CT_DataConsolidate) */\nexport interface DataConsolidateOptions {\n /** Consolidation function (CT_DataConsolidate @function) */\n readonly function?:\n | \"average\"\n | \"count\"\n | \"countNums\"\n | \"max\"\n | \"min\"\n | \"product\"\n | \"stdDev\"\n | \"stdDevp\"\n | \"sum\"\n | \"var\"\n | \"varp\";\n /** Use top row labels (CT_DataConsolidate @startLabels) */\n readonly topLabels?: boolean;\n /** Use left column labels (CT_DataConsolidate @leftLabels) */\n readonly leftLabels?: boolean;\n /** Use labels in first row (CT_DataConsolidate @startLabels alias) */\n readonly startLabels?: boolean;\n /** Link to source data (CT_DataConsolidate @link) */\n readonly link?: boolean;\n /** Source data references */\n readonly refs?: readonly string[];\n}\n\n/** Drawing in header/footer (CT_DrawingHF) */\nexport interface DrawingHfOptions {\n /** Relationship ID for the drawing (required) */\n readonly rId: string;\n /** Left header odd (CT_DrawingHF @lho) */\n readonly lho?: number;\n /** Left header even (CT_DrawingHF @lhe) */\n readonly lhe?: number;\n /** Left header first (CT_DrawingHF @lhf) */\n readonly lhf?: number;\n /** Center header odd (CT_DrawingHF @cho) */\n readonly cho?: number;\n /** Center header even (CT_DrawingHF @che) */\n readonly che?: number;\n /** Center header first (CT_DrawingHF @chf) */\n readonly chf?: number;\n /** Right header odd (CT_DrawingHF @rho) */\n readonly rho?: number;\n /** Right header even (CT_DrawingHF @rhe) */\n readonly rhe?: number;\n /** Right header first (CT_DrawingHF @rhf) */\n readonly rhf?: number;\n /** Left footer odd (CT_DrawingHF @lfo) */\n readonly lfo?: number;\n /** Left footer even (CT_DrawingHF @lfe) */\n readonly lfe?: number;\n /** Left footer first (CT_DrawingHF @lff) */\n readonly lff?: number;\n /** Center footer odd (CT_DrawingHF @cfo) */\n readonly cfo?: number;\n /** Center footer even (CT_DrawingHF @cfe) */\n readonly cfe?: number;\n /** Center footer first (CT_DrawingHF @cff) */\n readonly cff?: number;\n /** Right footer odd (CT_DrawingHF @rfo) */\n readonly rfo?: number;\n /** Right footer even (CT_DrawingHF @rfe) */\n readonly rfe?: number;\n /** Right footer first (CT_DrawingHF @rff) */\n readonly rff?: number;\n}\n\nexport interface WorksheetOptions {\n readonly name?: string;\n readonly rows?: readonly RowOptions[];\n readonly columns?: readonly ColumnOptions[];\n readonly mergeCells?: readonly MergeCellOptions[];\n readonly freezePanes?: FreezePaneOptions;\n readonly protection?: SheetProtectionOptions;\n /** Named protected ranges within this sheet */\n readonly protectedRanges?: readonly ProtectedRangeOptions[];\n /** What-if scenarios */\n readonly scenarios?: ScenarioOptions;\n /** Auto-filter configuration */\n readonly autoFilter?: string | AutoFilterOptions;\n readonly images?: readonly WorksheetImageOptions[];\n readonly charts?: readonly WorksheetChartOptions[];\n readonly dataValidations?: readonly DataValidationOptions[];\n readonly conditionalFormats?: readonly ConditionalFormatOptions[];\n readonly hyperlinks?: readonly HyperlinkOptions[];\n readonly comments?: readonly CommentOptions[];\n readonly headerFooter?: HeaderFooterOptions;\n readonly pageSetup?: PageSetupOptions;\n readonly tabColor?: TabColorOptions;\n readonly sheetView?: SheetViewOptions;\n readonly pivotTables?: readonly PivotTableOptions[];\n /** Tables (list objects) for this worksheet */\n readonly tables?: readonly TableOptions[];\n /** Ignored errors — suppress specific Excel error checks for cell ranges */\n readonly ignoredErrors?: readonly IgnoredErrorOptions[];\n /** Phonetic properties for CJK text */\n readonly phoneticPr?: PhoneticPrOptions;\n /** Background image for the worksheet */\n readonly backgroundImage?: SheetBackgroundImageOptions;\n /** Print options (CT_PrintOptions) */\n readonly printOptions?: PrintOptions;\n /** Sheet format properties (CT_SheetFormatPr) */\n readonly sheetFormatPr?: SheetFormatPrOptions;\n /** Sheet extended properties (CT_SheetPr attributes) */\n readonly sheetPr?: SheetPrOptions;\n /** Row page breaks (CT_PageBreaks) */\n readonly rowBreaks?: readonly PageBreakOptions[];\n /** Column page breaks (CT_PageBreaks) */\n readonly colBreaks?: readonly PageBreakOptions[];\n /** Custom sheet views (CT_CustomSheetViews) */\n readonly customSheetViews?: readonly CustomSheetViewOptions[];\n /** Cell watches (CT_CellWatches) */\n readonly cellWatches?: readonly CellWatchOptions[];\n /** Data consolidation (CT_DataConsolidate) */\n readonly dataConsolidate?: DataConsolidateOptions;\n /** OLE embedded range (CT_OleSize) */\n readonly oleSize?: string;\n /** Drawing in header/footer (CT_DrawingHF) */\n readonly drawingHF?: DrawingHfOptions;\n /** Legacy drawing for header/footer r:id (CT_LegacyDrawingHF) */\n readonly legacyDrawingHF?: string;\n /** Selection in sheet view (CT_Selection) */\n readonly selection?: SelectionOptions;\n /** Sheet calc properties (CT_SheetCalcPr) */\n readonly sheetCalcPr?: SheetCalcPrOptions;\n /** Extension list (extLst) */\n readonly ext?: string;\n /** Control objects (CT_Controls) */\n readonly controls?: readonly ControlOptions[];\n /** Custom sheet properties (CT_CustomProperties) */\n readonly customProperties?: readonly CustomPropertyOptions[];\n /** OLE objects (CT_OleObjects) */\n readonly oleObjects?: readonly OleObjectOptions[];\n /** Web publish items (CT_WebPublishItems) */\n readonly webPublishItems?: readonly WebPublishItemOptions[];\n}\n\n/** Sheet calc properties (CT_SheetCalcPr) */\nexport interface SheetCalcPrOptions {\n /** Full calc on load (CT_SheetCalcPr @fullCalcOnLoad) */\n readonly fullCalcOnLoad?: boolean;\n}\n\n/** Form control object (CT_Control) */\nexport interface ControlOptions {\n /** Shape ID (CT_Control @shapeId) */\n readonly shapeId: number;\n /** Control r:id (CT_ControlPr @r:id) */\n readonly rId: string;\n /** Control name (CT_ControlPr @name) */\n readonly name?: string;\n /** Locked (CT_ControlPr @locked) */\n readonly locked?: boolean;\n /** UI-locked (CT_ControlPr @uiObject) */\n readonly uiObject?: boolean;\n}\n\n/** Custom property (CT_CustomProperty) */\nexport interface CustomPropertyOptions {\n /** Property name */\n readonly name: string;\n /** Relationship ID to binary data */\n readonly rId: string;\n}\n\n/** OLE object (CT_OleObject) */\nexport interface OleObjectOptions {\n /** Program ID (CT_OleObject @progId) */\n readonly progId?: string;\n /** Display aspect (CT_OleObject @dvAspect) */\n readonly dvAspect?: \"DVASPECT_CONTENT\" | \"DVASPECT_ICON\";\n /** Linked source (CT_OleObject @link) */\n readonly link?: string;\n /** OLE update mode (CT_OleObject @oleUpdate) */\n readonly oleUpdate?: \"OLEUPDATE_ALWAYS\" | \"OLEUPDATE_ONCALL\";\n /** Auto load (CT_OleObject @autoLoad) */\n readonly autoLoad?: boolean;\n /** Shape ID (CT_OleObject @shapeId) */\n readonly shapeId: number;\n /** Relationship ID (CT_OleObject @r:id) */\n readonly rId?: string;\n /** Object properties (CT_ObjectPr) */\n readonly objectPr?: OleObjectPrOptions;\n}\n\n/** OLE object properties (CT_ObjectPr) */\nexport interface OleObjectPrOptions {\n /** Locked */\n readonly locked?: boolean;\n /** Default size */\n readonly defaultSize?: boolean;\n /** Print */\n readonly print?: boolean;\n /** Disabled */\n readonly disabled?: boolean;\n /** UI object */\n readonly uiObject?: boolean;\n /** Auto fill */\n readonly autoFill?: boolean;\n /** Auto line */\n readonly autoLine?: boolean;\n /** Auto picture */\n readonly autoPict?: boolean;\n /** Macro */\n readonly macro?: string;\n /** Alt text */\n readonly altText?: string;\n /** DDE */\n readonly dde?: boolean;\n /** Relationship ID */\n readonly rId?: string;\n}\n\n/** Web publish item (CT_WebPublishItem) */\nexport interface WebPublishItemOptions {\n /** Item ID */\n readonly id: number;\n /** HTML div ID */\n readonly divId: string;\n /** Source type */\n readonly sourceType:\n | \"sheet\"\n | \"printArea\"\n | \"autoFilter\"\n | \"range\"\n | \"chart\"\n | \"pivotTable\"\n | \"query\"\n | \"label\";\n /** Source cell reference */\n readonly sourceRef?: string;\n /** Source object name */\n readonly sourceObject?: string;\n /** Destination file path */\n readonly destinationFile: string;\n /** Title */\n readonly title?: string;\n /** Auto republish */\n readonly autoRepublish?: boolean;\n}\n\nexport class Worksheet extends IgnoreIfEmptyXmlComponent {\n private readonly rows: readonly RowOptions[];\n private readonly columns: readonly ColumnOptions[];\n private readonly mergeCells: readonly MergeCellOptions[];\n private readonly freezePanes?: FreezePaneOptions;\n private readonly protection?: SheetProtectionOptions;\n private readonly protectedRanges: readonly ProtectedRangeOptions[];\n private readonly scenarioOpts?: ScenarioOptions;\n private readonly autoFilter?: string | AutoFilterOptions;\n private readonly images: readonly WorksheetImageOptions[];\n private readonly chartOptions: readonly WorksheetChartOptions[];\n private readonly dataValidations: readonly DataValidationOptions[];\n private readonly conditionalFormats: readonly ConditionalFormatOptions[];\n private readonly hyperlinks: readonly HyperlinkOptions[];\n private readonly comments: readonly CommentOptions[];\n private readonly headerFooter?: HeaderFooterOptions;\n private readonly pageSetup?: PageSetupOptions;\n private readonly tabColor?: TabColorOptions;\n private readonly sheetView?: SheetViewOptions;\n private readonly pivotTableOptions: readonly PivotTableOptions[];\n private readonly tableOptions: readonly TableOptions[];\n private readonly ignoredErrors: readonly IgnoredErrorOptions[];\n private readonly phoneticPr?: PhoneticPrOptions;\n private readonly backgroundImage?: SheetBackgroundImageOptions;\n private readonly printOptions?: PrintOptions;\n private readonly sheetFormatPr?: SheetFormatPrOptions;\n private readonly sheetPr?: SheetPrOptions;\n private readonly rowBreaks: readonly PageBreakOptions[];\n private readonly colBreaks: readonly PageBreakOptions[];\n private readonly customSheetViews: readonly CustomSheetViewOptions[];\n private readonly cellWatches: readonly CellWatchOptions[];\n private readonly dataConsolidate?: DataConsolidateOptions;\n private readonly oleSize?: string;\n private readonly drawingHF?: DrawingHfOptions;\n private readonly legacyDrawingHF?: string;\n private readonly selection?: SelectionOptions;\n private readonly sheetCalcPr?: SheetCalcPrOptions;\n private readonly ext?: string;\n private readonly controls: readonly ControlOptions[];\n private readonly customProperties: readonly CustomPropertyOptions[];\n private readonly oleObjects: readonly OleObjectOptions[];\n private readonly webPublishItems: readonly WebPublishItemOptions[];\n\n public constructor(options: WorksheetOptions) {\n super(\"worksheet\");\n this.rows = options.rows ?? [];\n this.columns = options.columns ?? [];\n this.mergeCells = options.mergeCells ?? [];\n this.freezePanes = options.freezePanes;\n this.protection = options.protection;\n this.protectedRanges = options.protectedRanges ?? [];\n this.scenarioOpts = options.scenarios;\n this.autoFilter = options.autoFilter;\n this.images = options.images ?? [];\n this.chartOptions = options.charts ?? [];\n this.dataValidations = options.dataValidations ?? [];\n this.conditionalFormats = options.conditionalFormats ?? [];\n this.hyperlinks = options.hyperlinks ?? [];\n this.comments = options.comments ?? [];\n this.headerFooter = options.headerFooter;\n this.pageSetup = options.pageSetup;\n this.tabColor = options.tabColor;\n this.sheetView = options.sheetView;\n this.pivotTableOptions = options.pivotTables ?? [];\n this.tableOptions = options.tables ?? [];\n this.ignoredErrors = options.ignoredErrors ?? [];\n this.phoneticPr = options.phoneticPr;\n this.backgroundImage = options.backgroundImage;\n this.printOptions = options.printOptions;\n this.sheetFormatPr = options.sheetFormatPr;\n this.sheetPr = options.sheetPr;\n this.rowBreaks = options.rowBreaks ?? [];\n this.colBreaks = options.colBreaks ?? [];\n this.customSheetViews = options.customSheetViews ?? [];\n this.cellWatches = options.cellWatches ?? [];\n this.dataConsolidate = options.dataConsolidate;\n this.oleSize = options.oleSize;\n this.drawingHF = options.drawingHF;\n this.legacyDrawingHF = options.legacyDrawingHF;\n this.selection = options.selection;\n this.sheetCalcPr = options.sheetCalcPr;\n this.ext = options.ext;\n this.controls = options.controls ?? [];\n this.customProperties = options.customProperties ?? [];\n this.oleObjects = options.oleObjects ?? [];\n this.webPublishItems = options.webPublishItems ?? [];\n }\n\n public get imageOptions(): readonly WorksheetImageOptions[] {\n return this.images;\n }\n\n public get charts(): readonly WorksheetChartOptions[] {\n return this.chartOptions;\n }\n\n public get hyperlinkOptions(): readonly HyperlinkOptions[] {\n return this.hyperlinks;\n }\n\n public get worksheetRows(): readonly RowOptions[] {\n return this.rows;\n }\n\n public get commentOptions(): readonly CommentOptions[] {\n return this.comments;\n }\n\n public get pivotTables(): readonly PivotTableOptions[] {\n return this.pivotTableOptions;\n }\n\n public get tables(): readonly TableOptions[] {\n return this.tableOptions;\n }\n\n public get background(): SheetBackgroundImageOptions | undefined {\n return this.backgroundImage;\n }\n\n /**\n * Zero-allocation fast path: directly concatenate XML string.\n * Bypasses the IXmlableObject intermediate tree entirely.\n */\n public override toXml(context: Context): string {\n const fileData = context.fileData as\n | { sharedStrings?: SharedStrings; styles?: Styles }\n | undefined;\n const sharedStrings = fileData?.sharedStrings;\n const styles = fileData?.styles;\n\n const p: string[] = [\n '<worksheet xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\"' +\n ' xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\"' +\n ' xmlns:mc=\"http://schemas.openxmlformats.org/markup-compatibility/2006\"' +\n ' mc:Ignorable=\"x14ac xr xr2 xr3\"' +\n ' xmlns:x14ac=\"http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac\"' +\n ' xmlns:xr=\"http://schemas.microsoft.com/office/spreadsheetml/2014/revision\"' +\n ' xmlns:xr2=\"http://schemas.microsoft.com/office/spreadsheetml/2015/revision2\"' +\n ' xmlns:xr3=\"http://schemas.microsoft.com/office/spreadsheetml/2016/revision3\">',\n ];\n\n // Sheet properties (tabColor, outlinePr go here)\n const hasTabColor = !!this.tabColor;\n const hasOutline = this.columns.some((c) => c.outlineLevel !== undefined);\n const sp = this.sheetPr;\n const hasSheetPrAttrs =\n sp &&\n (sp.syncHorizontal ||\n sp.syncVertical ||\n sp.syncRef ||\n sp.transitionEvaluation ||\n sp.transitionEntry ||\n sp.published ||\n sp.filterMode ||\n sp.enableFormatConditionsCalculation);\n if (hasTabColor || hasOutline || hasSheetPrAttrs) {\n const prParts: string[] = [];\n const prAttrs: Record<string, string | number | boolean | undefined> = {};\n if (sp?.syncHorizontal) prAttrs.syncHorizontal = 1;\n if (sp?.syncVertical) prAttrs.syncVertical = 1;\n if (sp?.syncRef) prAttrs.syncRef = sp.syncRef;\n if (sp?.transitionEvaluation) prAttrs.transitionEvaluation = 1;\n if (sp?.transitionEntry) prAttrs.transitionEntry = 1;\n if (sp?.published) prAttrs.published = 1;\n if (sp?.filterMode) prAttrs.filterMode = 1;\n if (sp?.enableFormatConditionsCalculation) prAttrs.enableFormatConditionsCalculation = 1;\n if (this.tabColor) {\n const tc = this.tabColor;\n const tcAttrs: Record<string, string | number | boolean | undefined> = {};\n if (tc.rgb) tcAttrs.rgb = tc.rgb;\n if (tc.theme !== undefined) tcAttrs.theme = tc.theme;\n if (tc.tint !== undefined) tcAttrs.tint = tc.tint;\n prParts.push(`<tabColor${attrs(tcAttrs)}/>`);\n }\n if (hasOutline) {\n const outAttrs: Record<string, string | number | boolean | undefined> = {\n summaryBelow: 1,\n summaryRight: 1,\n };\n if (sp?.outlineApplyStyles) outAttrs.applyStyles = 1;\n if (sp?.outlineShowSymbols === false) outAttrs.showOutlineSymbols = 0;\n prParts.push(`<outlinePr${attrs(outAttrs)}/>`);\n }\n // pageSetUpPr (inside sheetPr when fitToPage or autoPageBreaks needed)\n if (this.pageSetup?.fitToWidth || this.pageSetup?.fitToHeight) {\n prParts.push('<pageSetUpPr fitToPage=\"1\"/>');\n }\n const prAttrStr = Object.keys(prAttrs).length > 0 ? attrs(prAttrs) : \"\";\n p.push(`<sheetPr${prAttrStr}>${prParts.join(\"\")}</sheetPr>`);\n }\n\n // Dimension — defines the used range of the sheet\n const maxRow = this.rows.length;\n let maxCol = 0;\n for (const row of this.rows) {\n if (row.cells && row.cells.length > maxCol) maxCol = row.cells.length;\n }\n if (maxRow > 0 && maxCol > 0) {\n const dimRef = `A1:${this.defaultCellRef(maxRow, maxCol)}`;\n p.push(`<dimension ref=\"${dimRef}\"/>`);\n }\n\n // Sheet views\n const pivotSelXml = this.sheetView?.pivotSelections\n ? this.sheetView.pivotSelections.map((ps) => this.buildPivotSelectionXml(ps)).join(\"\")\n : \"\";\n if (this.freezePanes) {\n const fp = this.freezePanes;\n const ySplit = fp.row ? fp.row : 0;\n const xSplit = fp.col ? fp.col : 0;\n const topRow = fp.row ? fp.row + 1 : 1;\n const leftCol = fp.col ? fp.col + 1 : 1;\n const topLeftCell = this.defaultCellRef(topRow, leftCol);\n const activePane =\n ySplit > 0 && xSplit > 0 ? \"bottomRight\" : ySplit > 0 ? \"bottomLeft\" : \"topRight\";\n const svAttrs = this.buildSheetViewAttrs();\n p.push(\n `<sheetViews><sheetView${svAttrs}>`,\n `<pane ySplit=\"${ySplit}\" xSplit=\"${xSplit}\" topLeftCell=\"${topLeftCell}\" activePane=\"${activePane}\" state=\"frozen\"/>`,\n this.selection ? this.buildSelectionXml(this.selection) : \"\",\n pivotSelXml,\n \"</sheetView></sheetViews>\",\n );\n } else {\n const svAttrs = this.buildSheetViewAttrs();\n const innerXml = (this.selection ? this.buildSelectionXml(this.selection) : \"\") + pivotSelXml;\n if (innerXml) {\n p.push(`<sheetViews><sheetView${svAttrs}>${innerXml}</sheetView></sheetViews>`);\n } else {\n p.push(`<sheetViews><sheetView${svAttrs}/></sheetViews>`);\n }\n }\n\n // Sheet format — default row height\n if (this.sheetFormatPr) {\n const sfp = this.sheetFormatPr;\n const sfpAttrs: Record<string, string | number | boolean | undefined> = {};\n if (sfp.baseColWidth !== undefined) sfpAttrs.baseColWidth = sfp.baseColWidth;\n if (sfp.defaultColWidth !== undefined) sfpAttrs.defaultColWidth = sfp.defaultColWidth;\n sfpAttrs.defaultRowHeight = sfp.defaultRowHeight ?? 15;\n if (sfp.zeroHeight) sfpAttrs.zeroHeight = 1;\n if (sfp.thickTop) sfpAttrs.thickTop = 1;\n if (sfp.thickBottom) sfpAttrs.thickBottom = 1;\n if (sfp.outlineLevelRow !== undefined) sfpAttrs.outlineLevelRow = sfp.outlineLevelRow;\n if (sfp.outlineLevelCol !== undefined) sfpAttrs.outlineLevelCol = sfp.outlineLevelCol;\n p.push(`<sheetFormatPr${attrs(sfpAttrs)}/>`);\n } else {\n p.push('<sheetFormatPr defaultRowHeight=\"15\"/>');\n }\n\n // Column definitions\n if (this.columns.length > 0) {\n p.push(\"<cols>\");\n for (const col of this.columns) {\n const colAttrs: Record<string, string | number | boolean | undefined> = {\n min: col.min,\n max: col.max,\n };\n if (col.width !== undefined) {\n colAttrs.width = col.width;\n colAttrs.customWidth = 1;\n }\n if (col.hidden) {\n colAttrs.hidden = 1;\n }\n if (col.outlineLevel !== undefined) {\n colAttrs.outlineLevel = col.outlineLevel;\n }\n if (col.collapsed) {\n colAttrs.collapsed = 1;\n }\n if (col.bestFit) {\n colAttrs.bestFit = 1;\n }\n if (col.phonetic) {\n colAttrs.phonetic = 1;\n }\n p.push(selfCloseElement(\"col\", attrs(colAttrs)));\n }\n p.push(\"</cols>\");\n }\n\n // Sheet data (rows + cells) — the hot path\n p.push(\"<sheetData>\");\n for (let i = 0; i < this.rows.length; i++) {\n const rowOpts = this.rows[i];\n const rowNumber = rowOpts.rowNumber ?? i + 1;\n const rowAttrs: Record<string, string | number | boolean | undefined> = { r: rowNumber };\n if (rowOpts.height !== undefined) {\n rowAttrs.ht = rowOpts.height;\n rowAttrs.customHeight = 1;\n }\n if (rowOpts.hidden) {\n rowAttrs.hidden = 1;\n }\n if (rowOpts.spans) rowAttrs.spans = rowOpts.spans;\n if (rowOpts.customFormat) rowAttrs.customFormat = 1;\n if (rowOpts.thickTop) rowAttrs.thickTop = 1;\n if (rowOpts.thickBot) rowAttrs.thickBot = 1;\n if (rowOpts.ph) rowAttrs.ph = 1;\n\n if (rowOpts.cells) {\n const rowParts: string[] = [];\n for (let j = 0; j < rowOpts.cells.length; j++) {\n const cell = rowOpts.cells[j];\n const ref = cell.reference ?? this.defaultCellRef(rowNumber, j + 1);\n const cellStr = this.buildCellString(ref, cell, sharedStrings, styles);\n if (cellStr) rowParts.push(cellStr);\n }\n p.push(`<row${attrs(rowAttrs)}>`, ...rowParts, \"</row>\");\n } else {\n p.push(`<row${attrs(rowAttrs)}/>`);\n }\n }\n p.push(\"</sheetData>\");\n\n // Sheet calc properties (after sheetData per XSD sequence)\n if (this.sheetCalcPr) {\n const scAttrs: string[] = [];\n if (this.sheetCalcPr.fullCalcOnLoad) scAttrs.push('fullCalcOnLoad=\"1\"');\n p.push(`<sheetCalcPr${scAttrs.length ? \" \" + scAttrs.join(\" \") : \"\"}/>`);\n }\n\n // Row breaks (after sheetCalcPr per XSD sequence)\n if (this.rowBreaks.length > 0) {\n const brkParts = this.rowBreaks.map((b) => {\n const bAttrs: Record<string, string | number | boolean | undefined> = { id: b.id };\n if (b.min !== undefined) bAttrs.min = b.min;\n if (b.max !== undefined) bAttrs.max = b.max;\n if (b.manual) bAttrs.man = 1;\n if (b.pivot) bAttrs.pt = 1;\n return `<brk${attrs(bAttrs)}/>`;\n });\n p.push(\n `<rowBreaks count=\"${this.rowBreaks.length}\" manualBreakCount=\"${this.rowBreaks.filter((b) => b.manual).length}\">${brkParts.join(\"\")}</rowBreaks>`,\n );\n }\n\n // Column breaks\n if (this.colBreaks.length > 0) {\n const brkParts = this.colBreaks.map((b) => {\n const bAttrs: Record<string, string | number | boolean | undefined> = { id: b.id };\n if (b.min !== undefined) bAttrs.min = b.min;\n if (b.max !== undefined) bAttrs.max = b.max;\n if (b.manual) bAttrs.man = 1;\n if (b.pivot) bAttrs.pt = 1;\n return `<brk${attrs(bAttrs)}/>`;\n });\n p.push(\n `<colBreaks count=\"${this.colBreaks.length}\" manualBreakCount=\"${this.colBreaks.filter((b) => b.manual).length}\">${brkParts.join(\"\")}</colBreaks>`,\n );\n }\n\n // Custom properties (CT_CustomProperties, after colBreaks per XSD sequence)\n if (this.customProperties.length > 0) {\n const cpParts: string[] = [\"<customProperties>\"];\n for (const cp of this.customProperties) {\n cpParts.push(`<customPr name=\"${escapeXml(cp.name)}\" r:id=\"${escapeXml(cp.rId)}\"/>`);\n }\n cpParts.push(\"</customProperties>\");\n p.push(cpParts.join(\"\"));\n }\n\n // OLE size\n if (this.oleSize) {\n p.push(`<oleSize ref=\"${escapeXml(this.oleSize)}\"/>`);\n }\n\n // Custom sheet views (after oleSize per XSD sequence)\n if (this.customSheetViews.length > 0) {\n p.push(\"<customSheetViews>\");\n for (const csv of this.customSheetViews) {\n const csvAttrs: Record<string, string | number | boolean | undefined> = { guid: csv.guid };\n if (csv.scale !== undefined) csvAttrs.scale = csv.scale;\n if (csv.showPageBreaks) csvAttrs.showPageBreaks = 1;\n if (csv.showFormulas) csvAttrs.showFormulas = 1;\n if (csv.showGridLines === false) csvAttrs.showGridLines = 0;\n if (csv.showRowColHeaders === false) csvAttrs.showRowCol = 0;\n if (csv.outlineSymbols === false) csvAttrs.outlineSymbols = 0;\n if (csv.zeroValues === false) csvAttrs.zeroValues = 0;\n if (csv.fitToPage) csvAttrs.fitToPage = 1;\n if (csv.printArea) csvAttrs.printArea = 1;\n if (csv.filter) csvAttrs.filter = 1;\n if (csv.showAutoFilter) csvAttrs.showAutoFilter = 1;\n if (csv.hiddenRows) csvAttrs.hiddenRows = 1;\n if (csv.hiddenColumns) csvAttrs.hiddenColumns = 1;\n if (csv.state && csv.state !== \"visible\") csvAttrs.state = csv.state;\n if (csv.filterUnique) csvAttrs.filterUnique = 1;\n if (csv.view && csv.view !== \"normal\") csvAttrs.view = csv.view;\n p.push(`<customSheetView${attrs(csvAttrs)}/>`);\n }\n p.push(\"</customSheetViews>\");\n }\n\n // Cell watches\n if (this.cellWatches.length > 0) {\n p.push(\"<cellWatches>\");\n for (const cw of this.cellWatches) {\n p.push(`<cellWatch r=\"${escapeXml(cw.r)}\"/>`);\n }\n p.push(\"</cellWatches>\");\n }\n\n // Data consolidation\n if (this.dataConsolidate) {\n const dc = this.dataConsolidate;\n const dcAttrs: Record<string, string | number | boolean | undefined> = {};\n if (dc.function && dc.function !== \"sum\") dcAttrs.function = dc.function;\n if (dc.topLabels) dcAttrs.topLabels = 1;\n if (dc.leftLabels) dcAttrs.leftLabels = 1;\n if (dc.startLabels) dcAttrs.startLabels = 1;\n if (dc.link) dcAttrs.link = 1;\n const refsInner = dc.refs?.map((r) => `<dataRef ref=\"${escapeXml(r)}\"/>`).join(\"\") ?? \"\";\n const refsXml = refsInner ? `<dataRefs>${refsInner}</dataRefs>` : \"\";\n if (refsXml || Object.keys(dcAttrs).length > 0) {\n p.push(`<dataConsolidate${attrs(dcAttrs)}>${refsXml}</dataConsolidate>`);\n }\n }\n\n // Sheet protection (after sheetData, before protectedRanges per XSD sequence)\n if (this.protection) {\n const prot = this.protection;\n const protAttrs: Record<string, string | number | boolean | undefined> = {};\n if (prot.password) protAttrs.password = this.hashPassword(prot.password);\n // Auto-derive modern hash when password provided without explicit hashValue\n let derived: ReturnType<typeof derivePasswordHash> | undefined;\n if (prot.password !== undefined && prot.hashValue === undefined) {\n derived = derivePasswordHash(prot.password);\n }\n protAttrs.algorithmName = prot.algorithmName ?? derived?.algorithmName;\n protAttrs.hashValue = prot.hashValue ?? derived?.hashValue;\n protAttrs.saltValue = prot.saltValue ?? derived?.saltValue;\n if (prot.spinCount !== undefined) protAttrs.spinCount = prot.spinCount;\n else if (derived) protAttrs.spinCount = derived.spinCount;\n if (prot.sheet) protAttrs.sheet = 1;\n if (prot.objects) protAttrs.objects = 1;\n if (prot.scenarios) protAttrs.scenarios = 1;\n if (prot.formatCells === false) protAttrs.formatCells = 0;\n if (prot.formatColumns === false) protAttrs.formatColumns = 0;\n if (prot.formatRows === false) protAttrs.formatRows = 0;\n if (prot.insertColumns === false) protAttrs.insertColumns = 0;\n if (prot.insertRows === false) protAttrs.insertRows = 0;\n if (prot.insertHyperlinks === false) protAttrs.insertHyperlinks = 0;\n if (prot.deleteColumns === false) protAttrs.deleteColumns = 0;\n if (prot.deleteRows === false) protAttrs.deleteRows = 0;\n if (prot.selectLockedCells) protAttrs.selectLockedCells = 1;\n if (prot.sort === false) protAttrs.sort = 0;\n if (prot.autoFilter === false) protAttrs.autoFilter = 0;\n if (prot.pivotTables === false) protAttrs.pivotTables = 0;\n if (prot.selectUnlockedCells) protAttrs.selectUnlockedCells = 1;\n p.push(selfCloseElement(\"sheetProtection\", attrs(protAttrs)));\n }\n\n // Protected ranges (after sheetProtection per XSD sequence)\n if (this.protectedRanges.length > 0) {\n const prParts: string[] = [\"<protectedRanges>\"];\n for (const pr of this.protectedRanges) {\n const prAttrs: Record<string, string | number | boolean | undefined> = {\n name: pr.name,\n sqref: pr.sqref,\n };\n if (pr.password) prAttrs.password = this.hashPassword(pr.password);\n // Auto-derive modern hash when password provided without explicit hashValue\n let prDerived: ReturnType<typeof derivePasswordHash> | undefined;\n if (pr.password !== undefined && pr.hashValue === undefined) {\n prDerived = derivePasswordHash(pr.password);\n }\n prAttrs.algorithmName = pr.algorithmName ?? prDerived?.algorithmName;\n prAttrs.hashValue = pr.hashValue ?? prDerived?.hashValue;\n prAttrs.saltValue = pr.saltValue ?? prDerived?.saltValue;\n if (pr.spinCount !== undefined) prAttrs.spinCount = pr.spinCount;\n else if (prDerived) prAttrs.spinCount = prDerived.spinCount;\n const hasSecurityDescriptor = !!pr.securityDescriptor;\n if (hasSecurityDescriptor) {\n prParts.push(\n `<protectedRange${attrs(prAttrs)}><securityDescriptor>${escapeXml(pr.securityDescriptor!)}</securityDescriptor></protectedRange>`,\n );\n } else {\n prParts.push(selfCloseElement(\"protectedRange\", attrs(prAttrs)));\n }\n }\n prParts.push(\"</protectedRanges>\");\n p.push(prParts.join(\"\"));\n }\n\n // Scenarios (what-if analysis)\n if (this.scenarioOpts) {\n const scParts: string[] = [\"<scenarios\"];\n const scAttrs: Record<string, string | number> = {};\n if (this.scenarioOpts.current !== undefined) scAttrs.current = this.scenarioOpts.current;\n if (this.scenarioOpts.show !== undefined) scAttrs.show = this.scenarioOpts.show;\n scParts[0] = `<scenarios${attrs(scAttrs)}>`;\n\n for (const scenario of this.scenarioOpts.scenarios) {\n const sAttrs: Record<string, string | number | boolean | undefined> = {\n name: scenario.name,\n };\n if (scenario.count !== undefined) sAttrs.count = scenario.count;\n if (scenario.user) sAttrs.user = scenario.user;\n if (scenario.comment) sAttrs.comment = scenario.comment;\n if (scenario.hidden) sAttrs.hidden = true;\n if (scenario.locked) sAttrs.locked = true;\n\n const sParts: string[] = [`<scenario${attrs(sAttrs)}>`];\n for (const cell of scenario.inputCells) {\n const icAttrs: Record<string, string | number | boolean | undefined> = {\n r: cell.r,\n val: String(cell.val),\n };\n if (cell.deleted) icAttrs.deleted = true;\n sParts.push(`<inputCells${attrs(icAttrs)}/>`);\n }\n sParts.push(\"</scenario>\");\n scParts.push(sParts.join(\"\"));\n }\n scParts.push(\"</scenarios>\");\n p.push(scParts.join(\"\"));\n }\n\n // Auto filter\n if (this.autoFilter) {\n if (typeof this.autoFilter === \"string\") {\n p.push(selfCloseElement(\"autoFilter\", attrs({ ref: this.autoFilter })));\n } else {\n const af = this.autoFilter;\n const inner: string[] = [];\n for (const t10 of af.top10 ?? []) {\n const t10Attrs: Record<string, string | number | boolean | undefined> = { val: t10.val };\n if (t10.top === false) t10Attrs.top = 0;\n if (t10.percent) t10Attrs.percent = 1;\n inner.push(\n `<filterColumn colId=\"${t10.colId}\"><top10${attrs(t10Attrs)}/></filterColumn>`,\n );\n }\n for (const cf of af.customFilters ?? []) {\n const cfAttrs: Record<string, string | number | boolean | undefined> = {};\n if (cf.and) cfAttrs.and = 1;\n const filters: string[] = [];\n if (cf.val !== undefined) {\n const fAttrs: Record<string, string | number | boolean | undefined> = { val: cf.val };\n if (cf.operator) fAttrs.operator = cf.operator;\n filters.push(selfCloseElement(\"customFilter\", attrs(fAttrs)));\n }\n if (cf.val2 !== undefined) {\n filters.push(selfCloseElement(\"customFilter\", attrs({ val: cf.val2 })));\n }\n if (filters.length > 0) {\n inner.push(\n `<filterColumn colId=\"${cf.colId}\"><customFilters${attrs(cfAttrs)}>${filters.join(\"\")}</customFilters></filterColumn>`,\n );\n }\n }\n if (af.sort && af.sort.length > 0) {\n const sortParts: string[] = [];\n for (const sc of af.sort) {\n const scAttrs: Record<string, string | number | boolean | undefined> = { ref: sc.ref };\n if (sc.descending) scAttrs.descending = 1;\n if (sc.sortBy) scAttrs.sortBy = sc.sortBy;\n if (sc.customList) scAttrs.customList = sc.customList;\n if (sc.iconId !== undefined) scAttrs.iconId = sc.iconId;\n sortParts.push(selfCloseElement(\"sortCondition\", attrs(scAttrs)));\n }\n const ssAttrs: Record<string, string | number | boolean | undefined> = { ref: af.ref };\n if (af.sortState?.columnSort) ssAttrs.columnSort = 1;\n if (af.sortState?.caseSensitive) ssAttrs.caseSensitive = 1;\n if (af.sortState?.sortMethod) ssAttrs.sortMethod = af.sortState.sortMethod;\n inner.push(`<sortState${attrs(ssAttrs)}>${sortParts.join(\"\")}</sortState>`);\n }\n // Color filters\n for (const cf of af.colorFilters ?? []) {\n const cfAttrs: Record<string, string | number | boolean | undefined> = {};\n if (cf.dxfId !== undefined) cfAttrs.dxfId = cf.dxfId;\n if (cf.cellColor === false) cfAttrs.cellColor = 0;\n inner.push(\n `<filterColumn colId=\"${cf.colId}\"><colorFilter${attrs(cfAttrs)}/></filterColumn>`,\n );\n }\n // Icon filters\n for (const if_ of af.iconFilters ?? []) {\n const ifAttrs: Record<string, string | number | boolean | undefined> = {\n iconSet: if_.iconSet,\n };\n if (if_.iconId !== undefined) ifAttrs.iconId = if_.iconId;\n inner.push(\n `<filterColumn colId=\"${if_.colId}\"><iconFilter${attrs(ifAttrs)}/></filterColumn>`,\n );\n }\n // Dynamic filters\n for (const df of af.dynamicFilters ?? []) {\n const dfAttrs: Record<string, string | number | boolean | undefined> = { type: df.type };\n if (df.val !== undefined) dfAttrs.val = df.val;\n if (df.maxVal !== undefined) dfAttrs.maxVal = df.maxVal;\n inner.push(\n `<filterColumn colId=\"${df.colId}\"><dynamicFilter${attrs(dfAttrs)}/></filterColumn>`,\n );\n }\n // Date group filters\n for (const dg of af.dateGroupItems ?? []) {\n const dgAttrs: Record<string, string | number | boolean | undefined> = {\n dateTimeGrouping: dg.dateTimeGrouping,\n };\n if (dg.year !== undefined) dgAttrs.year = dg.year;\n if (dg.month !== undefined) dgAttrs.month = dg.month;\n if (dg.day !== undefined) dgAttrs.day = dg.day;\n if (dg.hour !== undefined) dgAttrs.hour = dg.hour;\n if (dg.minute !== undefined) dgAttrs.minute = dg.minute;\n if (dg.second !== undefined) dgAttrs.second = dg.second;\n inner.push(\n `<filterColumn colId=\"${dg.colId}\"><dateGroupItem${attrs(dgAttrs)}/></filterColumn>`,\n );\n }\n if (inner.length > 0) {\n p.push(`<autoFilter ref=\"${af.ref}\">`, ...inner, \"</autoFilter>\");\n } else {\n p.push(selfCloseElement(\"autoFilter\", attrs({ ref: af.ref })));\n }\n }\n }\n\n // Merge cells\n if (this.mergeCells.length > 0) {\n p.push(`<mergeCells count=\"${this.mergeCells.length}\">`);\n for (const mc of this.mergeCells) {\n const fromRef = this.defaultCellRef(mc.from.row, mc.from.col);\n const toRef = this.defaultCellRef(mc.to.row, mc.to.col);\n p.push(selfCloseElement(\"mergeCell\", attrs({ ref: `${fromRef}:${toRef}` })));\n }\n p.push(\"</mergeCells>\");\n }\n\n // Phonetic properties (after mergeCells per XSD sequence)\n if (this.phoneticPr) {\n const pp = this.phoneticPr;\n const ppAttrs: Record<string, string | number> = { fontId: pp.fontId };\n if (pp.type && pp.type !== \"fullwidthKatakana\") ppAttrs.type = pp.type;\n if (pp.alignment && pp.alignment !== \"left\") ppAttrs.alignment = pp.alignment;\n p.push(selfCloseElement(\"phoneticPr\", attrs(ppAttrs)));\n }\n\n // Conditional formatting\n if (this.conditionalFormats.length > 0) {\n for (const cf of this.conditionalFormats) {\n p.push(`<conditionalFormatting sqref=\"${cf.sqref}\">`);\n for (let ri = 0; ri < cf.rules.length; ri++) {\n const rule = cf.rules[ri];\n const ruleAttrs: Record<string, string | number | boolean | undefined> = {\n type: rule.type,\n priority: rule.priority ?? ri + 1,\n };\n if (rule.operator) ruleAttrs.operator = rule.operator;\n if (rule.dxfId !== undefined) ruleAttrs.dxfId = rule.dxfId;\n if (rule.stopIfTrue) ruleAttrs.stopIfTrue = 1;\n if (rule.timePeriod) ruleAttrs.timePeriod = rule.timePeriod;\n if (rule.rank !== undefined) ruleAttrs.rank = rule.rank;\n if (rule.equalAverage) ruleAttrs.equalAverage = 1;\n\n // Color scale\n if (rule.type === \"colorScale\" && rule.colorScale) {\n const cs = rule.colorScale;\n const inner: string[] = [];\n for (const v of cs.cfvo) {\n inner.push(this.buildCfvoXml(v));\n }\n for (const c of cs.colors) {\n inner.push(`<color rgb=\"FF${c}\"/>`);\n }\n p.push(\n `<cfRule${attrs(ruleAttrs)}><colorScale>${inner.join(\"\")}</colorScale></cfRule>`,\n );\n }\n // Data bar\n else if (rule.type === \"dataBar\" && rule.dataBar) {\n const db = rule.dataBar;\n const inner: string[] = [];\n for (const v of db.cfvo) {\n inner.push(this.buildCfvoXml(v));\n }\n inner.push(`<color rgb=\"FF${db.color}\"/>`);\n const dbAttrs: Record<string, string | number | boolean | undefined> = {};\n if (db.minLength !== undefined && db.minLength !== 10) dbAttrs.minLength = db.minLength;\n if (db.maxLength !== undefined && db.maxLength !== 90) dbAttrs.maxLength = db.maxLength;\n if (db.showValue === false) dbAttrs.showValue = 0;\n const attrStr = Object.keys(dbAttrs).length > 0 ? attrs(dbAttrs) : \"\";\n p.push(\n `<cfRule${attrs(ruleAttrs)}><dataBar${attrStr}>${inner.join(\"\")}</dataBar></cfRule>`,\n );\n }\n // Icon set\n else if (rule.type === \"iconSet\" && rule.iconSet) {\n const is = rule.iconSet;\n const inner: string[] = [];\n for (const v of is.cfvo) {\n inner.push(this.buildCfvoXml(v));\n }\n const isAttrs: Record<string, string | number | boolean | undefined> = {};\n if (is.iconSet !== undefined && is.iconSet !== \"3TrafficLights1\")\n isAttrs.iconSet = is.iconSet;\n if (is.showValue === false) isAttrs.showValue = 0;\n if (is.percent === false) isAttrs.percent = 0;\n if (is.reverse) isAttrs.reverse = 1;\n const attrStr = Object.keys(isAttrs).length > 0 ? attrs(isAttrs) : \"\";\n p.push(\n `<cfRule${attrs(ruleAttrs)}><iconSet${attrStr}>${inner.join(\"\")}</iconSet></cfRule>`,\n );\n }\n // Standard rules (cellIs, containsText, expression, top10, aboveAverage)\n else {\n if (rule.formulas && rule.formulas.length > 0) {\n const formulaParts = rule.formulas.map((f) => `<formula>${escapeXml(f)}</formula>`);\n p.push(`<cfRule${attrs(ruleAttrs)}>`, ...formulaParts, \"</cfRule>\");\n } else {\n p.push(selfCloseElement(\"cfRule\", attrs(ruleAttrs)));\n }\n }\n }\n p.push(\"</conditionalFormatting>\");\n }\n }\n\n // Data validations\n if (this.dataValidations.length > 0) {\n p.push(`<dataValidations count=\"${this.dataValidations.length}\">`);\n for (const dv of this.dataValidations) {\n const dvAttrs: Record<string, string | number | boolean | undefined> = { sqref: dv.sqref };\n if (dv.type && dv.type !== \"none\") dvAttrs.type = dv.type;\n if (dv.operator) dvAttrs.operator = dv.operator;\n if (dv.allowBlank) dvAttrs.allowBlank = 1;\n if (dv.showErrorMessage) dvAttrs.showErrorMessage = 1;\n if (dv.showInputMessage) dvAttrs.showInputMessage = 1;\n if (dv.errorTitle) dvAttrs.errorTitle = dv.errorTitle;\n if (dv.error) dvAttrs.error = dv.error;\n if (dv.promptTitle) dvAttrs.promptTitle = dv.promptTitle;\n if (dv.prompt) dvAttrs.prompt = dv.prompt;\n if (dv.errorStyle) dvAttrs.errorStyle = dv.errorStyle;\n if (dv.imeMode) dvAttrs.imeMode = dv.imeMode;\n if (dv.showDropDown) dvAttrs.showDropDown = 1;\n const inner: string[] = [];\n if (dv.formula1 !== undefined) inner.push(`<formula1>${escapeXml(dv.formula1)}</formula1>`);\n if (dv.formula2 !== undefined) inner.push(`<formula2>${escapeXml(dv.formula2)}</formula2>`);\n if (inner.length > 0) {\n p.push(`<dataValidation${attrs(dvAttrs)}>`, ...inner, \"</dataValidation>\");\n } else {\n p.push(selfCloseElement(\"dataValidation\", attrs(dvAttrs)));\n }\n }\n p.push(\"</dataValidations>\");\n }\n\n // Hyperlinks — r:id numbering must match worksheet rels order (compiler handles rels)\n if (this.hyperlinks.length > 0) {\n p.push(\"<hyperlinks>\");\n let hlIdx = 0;\n for (const hl of this.hyperlinks) {\n const hlAttrs: Record<string, string | number | boolean | undefined> = { ref: hl.cell };\n if (hl.target.type === \"external\") {\n hlIdx++;\n hlAttrs[\"r:id\"] = `rId${hlIdx}`;\n } else {\n hlAttrs.location = hl.target.location;\n }\n if (hl.tooltip) hlAttrs.tooltip = hl.tooltip;\n if (hl.display) hlAttrs.display = hl.display;\n p.push(selfCloseElement(\"hyperlink\", attrs(hlAttrs)));\n }\n p.push(\"</hyperlinks>\");\n }\n\n // Print options\n if (this.printOptions) {\n const po = this.printOptions;\n const poAttrs: Record<string, string | number | boolean | undefined> = {};\n if (po.horizontalCentered) poAttrs.horizontalCentered = 1;\n if (po.verticalCentered) poAttrs.verticalCentered = 1;\n if (po.headings) poAttrs.headings = 1;\n if (po.gridLines) poAttrs.gridLines = 1;\n if (po.gridLinesSet === false) poAttrs.gridLinesSet = 0;\n p.push(selfCloseElement(\"printOptions\", attrs(poAttrs)));\n }\n\n p.push('<pageMargins left=\"0.75\" right=\"0.75\" top=\"1\" bottom=\"1\" header=\"0.5\" footer=\"0.5\"/>');\n\n // Page setup\n if (this.pageSetup) {\n const ps = this.pageSetup;\n const psAttrs: Record<string, string | number | boolean | undefined> = {};\n if (ps.paperSize !== undefined) psAttrs.paperSize = ps.paperSize;\n if (ps.orientation && ps.orientation !== \"default\") psAttrs.orientation = ps.orientation;\n if (ps.scale !== undefined) psAttrs.scale = ps.scale;\n if (ps.fitToWidth !== undefined) psAttrs.fitToWidth = ps.fitToWidth;\n if (ps.fitToHeight !== undefined) psAttrs.fitToHeight = ps.fitToHeight;\n if (ps.pageOrder && ps.pageOrder !== \"downThenOver\") psAttrs.pageOrder = ps.pageOrder;\n if (ps.useFirstPageNumber) psAttrs.useFirstPageNumber = 1;\n if (ps.firstPageNumber !== undefined) psAttrs.firstPageNumber = ps.firstPageNumber;\n if (ps.paperHeight !== undefined) psAttrs.paperHeight = ps.paperHeight;\n if (ps.paperWidth !== undefined) psAttrs.paperWidth = ps.paperWidth;\n if (ps.usePrinterDefaults) psAttrs.usePrinterDefaults = 1;\n if (ps.blackAndWhite) psAttrs.blackAndWhite = 1;\n if (ps.draft) psAttrs.draft = 1;\n if (ps.cellComments && ps.cellComments !== \"none\") psAttrs.cellComments = ps.cellComments;\n if (ps.errors && ps.errors !== \"displayed\") psAttrs.errors = ps.errors;\n p.push(selfCloseElement(\"pageSetup\", attrs(psAttrs)));\n }\n\n // Header/footer\n if (this.headerFooter) {\n const hf = this.headerFooter;\n const hfAttrs: Record<string, string | number | boolean | undefined> = {};\n if (hf.differentOddEven) hfAttrs.differentOddEven = 1;\n if (hf.differentFirst) hfAttrs.differentFirst = 1;\n if (hf.scaleWithDoc === false) hfAttrs.scaleWithDoc = 0;\n if (hf.alignWithMargins === false) hfAttrs.alignWithMargins = 0;\n const inner: string[] = [];\n if (hf.oddHeader) inner.push(`<oddHeader>${escapeXml(hf.oddHeader)}</oddHeader>`);\n if (hf.oddFooter) inner.push(`<oddFooter>${escapeXml(hf.oddFooter)}</oddFooter>`);\n if (hf.evenHeader) inner.push(`<evenHeader>${escapeXml(hf.evenHeader)}</evenHeader>`);\n if (hf.evenFooter) inner.push(`<evenFooter>${escapeXml(hf.evenFooter)}</evenFooter>`);\n if (hf.firstHeader) inner.push(`<firstHeader>${escapeXml(hf.firstHeader)}</firstHeader>`);\n if (hf.firstFooter) inner.push(`<firstFooter>${escapeXml(hf.firstFooter)}</firstFooter>`);\n if (inner.length > 0) {\n p.push(`<headerFooter${attrs(hfAttrs)}>`, ...inner, \"</headerFooter>\");\n } else if (hfAttrs.differentOddEven || hfAttrs.differentFirst) {\n p.push(selfCloseElement(\"headerFooter\", attrs(hfAttrs)));\n }\n }\n\n // Drawing in header/footer (after headerFooter per XSD sequence)\n if (this.drawingHF) {\n const dhf = this.drawingHF;\n const dhfAttrs: Record<string, string | number | boolean | undefined> = { \"r:id\": dhf.rId };\n if (dhf.lho !== undefined) dhfAttrs.lho = dhf.lho;\n if (dhf.lhe !== undefined) dhfAttrs.lhe = dhf.lhe;\n if (dhf.lhf !== undefined) dhfAttrs.lhf = dhf.lhf;\n if (dhf.cho !== undefined) dhfAttrs.cho = dhf.cho;\n if (dhf.che !== undefined) dhfAttrs.che = dhf.che;\n if (dhf.chf !== undefined) dhfAttrs.chf = dhf.chf;\n if (dhf.rho !== undefined) dhfAttrs.rho = dhf.rho;\n if (dhf.rhe !== undefined) dhfAttrs.rhe = dhf.rhe;\n if (dhf.rhf !== undefined) dhfAttrs.rhf = dhf.rhf;\n if (dhf.lfo !== undefined) dhfAttrs.lfo = dhf.lfo;\n if (dhf.lfe !== undefined) dhfAttrs.lfe = dhf.lfe;\n if (dhf.lff !== undefined) dhfAttrs.lff = dhf.lff;\n if (dhf.cfo !== undefined) dhfAttrs.cfo = dhf.cfo;\n if (dhf.cfe !== undefined) dhfAttrs.cfe = dhf.cfe;\n if (dhf.cff !== undefined) dhfAttrs.cff = dhf.cff;\n if (dhf.rfo !== undefined) dhfAttrs.rfo = dhf.rfo;\n if (dhf.rfe !== undefined) dhfAttrs.rfe = dhf.rfe;\n if (dhf.rff !== undefined) dhfAttrs.rff = dhf.rff;\n p.push(selfCloseElement(\"drawingHF\", attrs(dhfAttrs)));\n }\n\n // Legacy drawing in header/footer\n if (this.legacyDrawingHF) {\n p.push(`<legacyDrawingHF r:id=\"${escapeXml(this.legacyDrawingHF)}\"/>`);\n }\n\n // Ignored errors (after headerFooter per XSD sequence)\n if (this.ignoredErrors.length > 0) {\n const ieParts: string[] = [\"<ignoredErrors>\"];\n for (const ie of this.ignoredErrors) {\n const ieAttrs: Record<string, string | number | boolean | undefined> = {\n sqref: ie.sqref,\n };\n if (ie.evalError) ieAttrs.evalError = 1;\n if (ie.twoDigitTextYear) ieAttrs.twoDigitTextYear = 1;\n if (ie.numberStoredAsText) ieAttrs.numberStoredAsText = 1;\n if (ie.formula) ieAttrs.formula = 1;\n if (ie.formulaRange) ieAttrs.formulaRange = 1;\n if (ie.unlockedFormula) ieAttrs.unlockedFormula = 1;\n if (ie.emptyCellReference) ieAttrs.emptyCellReference = 1;\n if (ie.listDataValidation) ieAttrs.listDataValidation = 1;\n if (ie.calculatedColumn) ieAttrs.calculatedColumn = 1;\n ieParts.push(selfCloseElement(\"ignoredError\", attrs(ieAttrs)));\n }\n ieParts.push(\"</ignoredErrors>\");\n p.push(ieParts.join(\"\"));\n }\n\n // Background picture placeholder — compiler replaces with <picture r:id=\"rIdN\"/>\n if (this.backgroundImage) {\n p.push(\"<!--BACKGROUND_PICTURE-->\");\n }\n\n // OLE objects (CT_OleObjects, after picture per XSD sequence)\n if (this.oleObjects.length > 0) {\n const oleParts: string[] = [\"<oleObjects>\"];\n for (const ole of this.oleObjects) {\n const oleAttrs: string[] = [`shapeId=\"${ole.shapeId}\"`];\n if (ole.progId) oleAttrs.push(`progId=\"${escapeXml(ole.progId)}\"`);\n if (ole.dvAspect && ole.dvAspect !== \"DVASPECT_CONTENT\")\n oleAttrs.push(`dvAspect=\"${ole.dvAspect}\"`);\n if (ole.link) oleAttrs.push(`link=\"${escapeXml(ole.link)}\"`);\n if (ole.oleUpdate) oleAttrs.push(`oleUpdate=\"${ole.oleUpdate}\"`);\n if (ole.autoLoad) oleAttrs.push('autoLoad=\"1\"');\n if (ole.rId) oleAttrs.push(`r:id=\"${escapeXml(ole.rId)}\"`);\n // objectPr (CT_ObjectPr, optional child)\n if (ole.objectPr) {\n const opr = ole.objectPr;\n const oprAttrs: string[] = [];\n if (opr.locked === false) oprAttrs.push('locked=\"0\"');\n if (opr.defaultSize === false) oprAttrs.push('defaultSize=\"0\"');\n if (opr.print === false) oprAttrs.push('print=\"0\"');\n if (opr.disabled) oprAttrs.push('disabled=\"1\"');\n if (opr.uiObject) oprAttrs.push('uiObject=\"1\"');\n if (opr.autoFill === false) oprAttrs.push('autoFill=\"0\"');\n if (opr.autoLine === false) oprAttrs.push('autoLine=\"0\"');\n if (opr.autoPict === false) oprAttrs.push('autoPict=\"0\"');\n if (opr.macro) oprAttrs.push(`macro=\"${escapeXml(opr.macro)}\"`);\n if (opr.altText) oprAttrs.push(`altText=\"${escapeXml(opr.altText)}\"`);\n if (opr.dde) oprAttrs.push('dde=\"1\"');\n if (opr.rId) oprAttrs.push(`r:id=\"${escapeXml(opr.rId)}\"`);\n oleParts.push(\n `<oleObject ${oleAttrs.join(\" \")}><objectPr${oprAttrs.length ? \" \" + oprAttrs.join(\" \") : \"\"}/></oleObject>`,\n );\n } else {\n oleParts.push(`<oleObject ${oleAttrs.join(\" \")}/>`);\n }\n }\n oleParts.push(\"</oleObjects>\");\n p.push(oleParts.join(\"\"));\n }\n\n // Controls (CT_Controls, after oleObjects per XSD sequence)\n if (this.controls.length > 0) {\n const ctrlParts: string[] = [\"<controls>\"];\n for (const c of this.controls) {\n const cAttrs: string[] = [`shapeId=\"${c.shapeId}\"`, `r:id=\"${escapeXml(c.rId)}\"`];\n if (c.name) cAttrs.push(`name=\"${escapeXml(c.name)}\"`);\n // controlPr (optional)\n const prAttrs: string[] = [];\n if (c.locked === false) prAttrs.push('locked=\"0\"');\n if (c.uiObject) prAttrs.push('uiObject=\"1\"');\n if (prAttrs.length > 0) {\n ctrlParts.push(\n `<control ${cAttrs.join(\" \")}><controlPr${prAttrs.length ? \" \" + prAttrs.join(\" \") : \"\"}/></control>`,\n );\n } else {\n ctrlParts.push(`<control ${cAttrs.join(\" \")}/>`);\n }\n }\n ctrlParts.push(\"</controls>\");\n p.push(ctrlParts.join(\"\"));\n }\n\n // Web publish items (CT_WebPublishItems, after controls per XSD sequence)\n if (this.webPublishItems.length > 0) {\n const wpParts: string[] = [`<webPublishItems count=\"${this.webPublishItems.length}\">`];\n for (const wpi of this.webPublishItems) {\n const wpiAttrs: string[] = [\n `id=\"${wpi.id}\"`,\n `divId=\"${escapeXml(wpi.divId)}\"`,\n `sourceType=\"${wpi.sourceType}\"`,\n `destinationFile=\"${escapeXml(wpi.destinationFile)}\"`,\n ];\n if (wpi.sourceRef) wpiAttrs.push(`sourceRef=\"${escapeXml(wpi.sourceRef)}\"`);\n if (wpi.sourceObject) wpiAttrs.push(`sourceObject=\"${escapeXml(wpi.sourceObject)}\"`);\n if (wpi.title) wpiAttrs.push(`title=\"${escapeXml(wpi.title)}\"`);\n if (wpi.autoRepublish) wpiAttrs.push('autoRepublish=\"1\"');\n wpParts.push(`<webPublishItem ${wpiAttrs.join(\" \")}/>`);\n }\n wpParts.push(\"</webPublishItems>\");\n p.push(wpParts.join(\"\"));\n }\n\n // Extension list (extLst, last per XSD sequence)\n if (this.ext) {\n p.push(`<extLst>${this.ext}</extLst>`);\n }\n\n p.push(\"</worksheet>\");\n return p.join(\"\");\n }\n\n /**\n * Build a <cfvo> element string for conditional formatting.\n */\n private buildCfvoXml(cfvo: CfvoOptions): string {\n const a: Record<string, string | number | boolean | undefined> = { type: cfvo.type };\n if (cfvo.val !== undefined) a.val = cfvo.val;\n if (cfvo.gte === false) a.gte = 0;\n return `<cfvo${attrs(a)}/>`;\n }\n\n private buildSheetViewAttrs(): string {\n const sv = this.sheetView;\n const svMap: Record<string, string | number | boolean | undefined> = {\n workbookViewId: 0,\n };\n if (sv?.tabSelected !== undefined) svMap.tabSelected = sv.tabSelected ? 1 : 0;\n else svMap.tabSelected = 1;\n if (sv?.showGridLines === false) svMap.showGridLines = 0;\n if (sv?.showRowColHeaders === false) svMap.showRowColHeaders = 0;\n if (sv?.showZeros === false) svMap.showZeros = 0;\n if (sv?.zoomScale !== undefined) svMap.zoomScale = sv.zoomScale;\n if (sv?.rightToLeft) svMap.rightToLeft = 1;\n if (sv?.windowProtection) svMap.windowProtection = 1;\n if (sv?.showFormulas) svMap.showFormulas = 1;\n if (sv?.showRuler === false) svMap.showRuler = 0;\n if (sv?.showOutlineSymbols === false) svMap.showOutlineSymbols = 0;\n if (sv?.defaultGridColor === false) svMap.defaultGridColor = 0;\n if (sv?.showWhiteSpace === false) svMap.showWhiteSpace = 0;\n if (sv?.view) svMap.view = sv.view;\n if (sv?.colorId !== undefined) svMap.colorId = sv.colorId;\n if (sv?.zoomScaleNormal !== undefined) svMap.zoomScaleNormal = sv.zoomScaleNormal;\n if (sv?.zoomScaleSheetLayoutView !== undefined)\n svMap.zoomScaleSheetLayoutView = sv.zoomScaleSheetLayoutView;\n if (sv?.zoomScalePageLayoutView !== undefined)\n svMap.zoomScalePageLayoutView = sv.zoomScalePageLayoutView;\n return attrs(svMap);\n }\n\n private buildSelectionXml(sel: SelectionOptions): string {\n const selAttrs: Record<string, string | number | boolean | undefined> = {};\n if (sel.pane) selAttrs.pane = sel.pane;\n if (sel.activeCell) selAttrs.activeCell = sel.activeCell;\n if (sel.activeCellId !== undefined) selAttrs.activeCellId = sel.activeCellId;\n if (sel.sqref) selAttrs.sqref = sel.sqref;\n return `<selection${attrs(selAttrs)}/>`;\n }\n\n private buildPivotSelectionXml(ps: PivotSelectionOptions): string {\n const psAttrs: Record<string, string | number | boolean | undefined> = {};\n if (ps.pane) psAttrs.pane = ps.pane;\n if (ps.showHeader) psAttrs.showHeader = 1;\n if (ps.label) psAttrs.label = 1;\n if (ps.data) psAttrs.data = 1;\n if (ps.extendable) psAttrs.extendable = 1;\n if (ps.count !== undefined) psAttrs.count = ps.count;\n if (ps.axis) psAttrs.axis = ps.axis;\n if (ps.dimension !== undefined) psAttrs.dimension = ps.dimension;\n if (ps.start !== undefined) psAttrs.start = ps.start;\n if (ps.min !== undefined) psAttrs.min = ps.min;\n if (ps.max !== undefined) psAttrs.max = ps.max;\n if (ps.activeRow !== undefined) psAttrs.activeRow = ps.activeRow;\n if (ps.activeCol !== undefined) psAttrs.activeCol = ps.activeCol;\n if (ps.previousRow !== undefined) psAttrs.previousRow = ps.previousRow;\n if (ps.previousCol !== undefined) psAttrs.previousCol = ps.previousCol;\n if (ps.click !== undefined) psAttrs.click = ps.click;\n if (ps.rId) psAttrs[\"r:id\"] = ps.rId;\n // CT_PivotSelection requires a pivotArea child\n return `<pivotSelection${attrs(psAttrs)}><pivotArea/></pivotSelection>`;\n }\n\n /**\n * Excel legacy password hash (16-bit, little-endian hex).\n * Matches the algorithm used by ECMA-376 Part 1, §18.2.27.\n */\n private hashPassword(password: string): string {\n let hash = 0;\n for (let i = 0; i < password.length; i++) {\n const c = password.charCodeAt(i);\n hash = ((hash >> 14) & 1) + ((hash << 1) & 0x7fff);\n hash ^= c;\n hash = hash & 0x4000 ? hash ^ 0x1 : hash;\n }\n hash = ((hash >> 14) & 1) + ((hash << 1) & 0x7fff);\n hash = ((hash >> 14) & 1) + ((hash << 1) & 0x7fff);\n hash ^= password.length;\n return hash.toString(16).toUpperCase().padStart(4, \"0\");\n }\n\n /**\n * Build the <f> element string for a cell formula.\n */\n private buildFormulaString(fOpts: FormulaOptions): string {\n const fAttrs: Record<string, string | number | boolean | undefined> = {};\n if (fOpts.type && fOpts.type !== FormulaType.NORMAL) fAttrs.t = fOpts.type;\n if (fOpts.reference) fAttrs.ref = fOpts.reference;\n if (fOpts.sharedIndex !== undefined) fAttrs.si = fOpts.sharedIndex;\n if (fOpts.aca) fAttrs.aca = 1;\n if (fOpts.dt2D) fAttrs.dt2D = 1;\n if (fOpts.dtr) fAttrs.dtr = 1;\n if (fOpts.del1) fAttrs.del1 = 1;\n if (fOpts.del2) fAttrs.del2 = 1;\n if (fOpts.r1) fAttrs.r1 = fOpts.r1;\n if (fOpts.r2) fAttrs.r2 = fOpts.r2;\n if (fOpts.ca) fAttrs.ca = 1;\n if (fOpts.bx) fAttrs.bx = 1;\n\n const hasContent = fOpts.formula !== undefined && fOpts.formula !== \"\";\n\n if (hasContent) {\n return `<f${attrs(fAttrs)}>${escapeXml(fOpts.formula)}</f>`;\n }\n if (Object.keys(fAttrs).length > 0) {\n return selfCloseElement(\"f\", attrs(fAttrs));\n }\n return \"\";\n }\n\n /**\n * Direct string serialization of a single cell — zero intermediate objects.\n */\n private buildCellString(\n ref: string,\n cell: CellOptions,\n sharedStrings?: SharedStrings,\n styles?: Styles,\n ): string {\n const cellAttrs: Record<string, string | number | boolean | undefined> = { r: ref };\n\n // Resolve style\n if (cell.style !== undefined && styles) {\n cellAttrs.s = styles.register(cell.style);\n } else if (cell.styleIndex !== undefined) {\n cellAttrs.s = cell.styleIndex;\n }\n\n const value = cell.value;\n\n // Formula path — formula takes precedence; value is the cached result.\n if (cell.formula) {\n const fStr = this.buildFormulaString(cell.formula);\n let vStr = \"\";\n if (value === null || value === undefined) {\n return `<c${attrs(cellAttrs)}>${fStr}</c>`;\n }\n if (typeof value === \"number\") {\n vStr = `<v>${value}</v>`;\n } else if (typeof value === \"boolean\") {\n cellAttrs.t = \"b\";\n vStr = `<v>${value ? 1 : 0}</v>`;\n } else if (typeof value === \"string\") {\n cellAttrs.t = \"str\";\n vStr = `<v>${escapeXml(value)}</v>`;\n } else if (value instanceof Date) {\n vStr = `<v>${this.dateToSerialNumber(value)}</v>`;\n }\n if (vStr) {\n return `<c${attrs(cellAttrs)}>${fStr}${vStr}</c>`;\n }\n return `<c${attrs(cellAttrs)}>${fStr}</c>`;\n }\n\n if (value === null || value === undefined) {\n if (cell.styleIndex !== undefined) {\n return selfCloseElement(\"c\", attrs(cellAttrs));\n }\n return \"\";\n }\n\n // Rich text value (RichTextOptions)\n if (typeof value === \"object\" && !(value instanceof Date)) {\n if (sharedStrings) {\n cellAttrs.t = \"s\";\n const idx = sharedStrings.registerRich(value);\n return `<c${attrs(cellAttrs)}><v>${idx}</v></c>`;\n }\n cellAttrs.t = \"inlineStr\";\n return `<c${attrs(cellAttrs)}><is>${buildRstXml(value)}</is></c>`;\n }\n\n if (typeof value === \"string\") {\n if (sharedStrings) {\n cellAttrs.t = \"s\";\n const idx = sharedStrings.register(value);\n return `<c${attrs(cellAttrs)}><v>${idx}</v></c>`;\n }\n cellAttrs.t = \"inlineStr\";\n return `<c${attrs(cellAttrs)}><is><t>${escapeXml(value)}</t></is></c>`;\n }\n\n if (typeof value === \"number\") {\n return `<c${attrs(cellAttrs)}><v>${value}</v></c>`;\n }\n\n if (typeof value === \"boolean\") {\n cellAttrs.t = \"b\";\n return `<c${attrs(cellAttrs)}><v>${value ? 1 : 0}</v></c>`;\n }\n\n if (value instanceof Date) {\n const serial = this.dateToSerialNumber(value);\n return `<c${attrs(cellAttrs)}><v>${serial}</v></c>`;\n }\n\n return \"\";\n }\n\n private defaultCellRef(row: number, col: number): string {\n return this.columnToLetter(col) + row;\n }\n\n private columnToLetter(col: number): string {\n let result = \"\";\n let n = col;\n while (n > 0) {\n const remainder = (n - 1) % 26;\n result = String.fromCharCode(65 + remainder) + result;\n n = Math.floor((n - 1) / 26);\n }\n return result;\n }\n\n private dateToSerialNumber(date: Date): number {\n const epoch = new Date(1899, 11, 30);\n const msPerDay = 86400000;\n return (date.getTime() - epoch.getTime()) / msPerDay;\n }\n}\n","import { ContentTypes } from \"@file/content-types\";\nimport { CoreProperties, type CorePropertiesOptions } from \"@file/core-properties\";\nimport { Media } from \"@file/media/media\";\nimport { SharedStrings } from \"@file/shared-strings\";\nimport { Styles } from \"@file/styles\";\nimport type { DxfOptions } from \"@file/styles\";\nimport { DefaultTheme } from \"@file/theme\";\nimport {\n WorkbookXml,\n type SheetDefinition,\n type PivotCacheReference,\n type WorkbookProtectionOptions,\n type FileRecoveryPrOptions,\n type WebPublishingOptions,\n type FileSharingOptions,\n} from \"@file/workbook\";\nimport { Worksheet, type WorksheetOptions } from \"@file/worksheet\";\n/**\n * File class (exported as Workbook) — the top-level container for XLSX documents.\n *\n * @module\n */\nimport { AppProperties, ChartCollection, Relationships } from \"@office-open/core\";\n\nimport type { ChartsheetOptions } from \"./chartsheet\";\nimport type { ExternalLinkOptions } from \"./external-link\";\n\nexport interface WorkbookOptions extends CorePropertiesOptions {\n readonly worksheets?: readonly WorksheetOptions[];\n /** Chart-only sheets (no cells, just a chart) */\n readonly chartsheets?: readonly ChartsheetOptions[];\n /** Pre-defined differential formats for conditional formatting */\n readonly dxfs?: readonly DxfOptions[];\n /** Workbook-level protection */\n readonly workbookProtection?: WorkbookProtectionOptions;\n /** External link definitions */\n readonly externalLinks?: readonly ExternalLinkOptions[];\n /** Custom workbook views */\n readonly customWorkbookViews?: readonly import(\"./workbook\").CustomWorkbookViewOptions[];\n /** File recovery properties */\n readonly fileRecoveryPr?: FileRecoveryPrOptions;\n /** Custom VBA function group names */\n readonly functionGroups?: readonly string[];\n /** Web publishing properties */\n readonly webPublishing?: WebPublishingOptions;\n /** File sharing / read-only recommendation */\n readonly fileSharing?: FileSharingOptions;\n /** Volatile dependencies (CT_VolTypes) */\n readonly volTypes?: readonly import(\"./workbook\").VolTypeOptions[];\n /** Web publish objects (CT_WebPublishItems) */\n readonly webPublishObjects?: readonly import(\"./workbook\").WebPublishObjectOptions[];\n}\n\nexport class File {\n private readonly worksheetOptions: readonly WorksheetOptions[];\n private readonly chartsheetOptions: readonly ChartsheetOptions[];\n private readonly corePropsOptions: CorePropertiesOptions;\n private readonly dxfOptions: readonly DxfOptions[];\n private readonly protectionOptions?: WorkbookProtectionOptions;\n private readonly externalLinkOptions: readonly ExternalLinkOptions[];\n private readonly customViewOptions?: readonly import(\"./workbook\").CustomWorkbookViewOptions[];\n private readonly fileRecoveryPrOpts?: FileRecoveryPrOptions;\n private readonly functionGroupOpts?: readonly string[];\n private readonly webPublishingOpts?: WebPublishingOptions;\n private readonly fileSharingOpts?: FileSharingOptions;\n private readonly volTypeOpts?: readonly import(\"./workbook\").VolTypeOptions[];\n private readonly webPublishObjectOpts?: readonly import(\"./workbook\").WebPublishObjectOptions[];\n\n // Lazy components\n private _coreProperties?: CoreProperties;\n private _appProperties?: AppProperties;\n private _contentTypes?: ContentTypes;\n private _styles?: Styles;\n private _theme?: DefaultTheme;\n private _workbookXml?: WorkbookXml;\n private _worksheets?: Worksheet[];\n private _sharedStrings?: SharedStrings;\n private _media?: Media;\n private _fileRels?: Relationships;\n private _workbookRels?: Relationships;\n private _charts?: ChartCollection;\n private _pivotCacheRefs: PivotCacheReference[] = [];\n\n public constructor(options: WorkbookOptions) {\n this.worksheetOptions = options.worksheets ?? [];\n this.chartsheetOptions = options.chartsheets ?? [];\n this.corePropsOptions = options;\n this.dxfOptions = options.dxfs ?? [];\n this.protectionOptions = options.workbookProtection;\n this.externalLinkOptions = options.externalLinks ?? [];\n this.customViewOptions = options.customWorkbookViews;\n this.fileRecoveryPrOpts = options.fileRecoveryPr;\n this.functionGroupOpts = options.functionGroups;\n this.webPublishingOpts = options.webPublishing;\n this.fileSharingOpts = options.fileSharing;\n this.volTypeOpts = options.volTypes;\n this.webPublishObjectOpts = options.webPublishObjects;\n }\n\n // ── Lazy getters ──\n\n public get coreProperties(): CoreProperties {\n return (this._coreProperties ??= new CoreProperties(this.corePropsOptions));\n }\n\n public get appProperties(): AppProperties {\n return (this._appProperties ??= new AppProperties());\n }\n\n public get contentTypes(): ContentTypes {\n if (!this._contentTypes) {\n this._contentTypes = new ContentTypes();\n for (let i = 0; i < this.worksheetOptions.length; i++) {\n this._contentTypes.addWorksheet(i + 1);\n }\n this._contentTypes.addStyles();\n this._contentTypes.addSharedStrings();\n this._contentTypes.addTheme();\n }\n return this._contentTypes;\n }\n\n public get styles(): Styles {\n return (this._styles ??= new Styles());\n }\n\n /**\n * Register a differential format and return its dxfId.\n * Call this before generating XML to use the ID in conditional formatting rules.\n */\n public registerDxf(opts: DxfOptions): number {\n return this.styles.registerDxf(opts);\n }\n\n public get theme(): DefaultTheme {\n return (this._theme ??= new DefaultTheme());\n }\n\n public get workbookXml(): WorkbookXml {\n if (!this._workbookXml) {\n const sheets: SheetDefinition[] = [];\n let sheetId = 1;\n let rId = 1;\n for (const ws of this.worksheetOptions) {\n sheets.push({\n name: ws.name ?? `Sheet${sheetId}`,\n sheetId: sheetId++,\n rId: `rId${rId++}`,\n });\n }\n for (const cs of this.chartsheetOptions) {\n sheets.push({\n name: cs.name ?? `Chart${sheetId}`,\n sheetId: sheetId++,\n rId: `rId${rId++}`,\n });\n }\n this._workbookXml = new WorkbookXml(\n sheets,\n this._pivotCacheRefs,\n this.protectionOptions,\n this.customViewOptions,\n this.fileRecoveryPrOpts,\n this.functionGroupOpts,\n this.webPublishingOpts,\n this.fileSharingOpts,\n undefined, // workbookPr\n undefined, // calcPr\n undefined, // bookView\n this.volTypeOpts,\n this.webPublishObjectOpts,\n );\n }\n return this._workbookXml;\n }\n\n public get sharedStrings(): SharedStrings {\n return (this._sharedStrings ??= new SharedStrings());\n }\n\n public get media(): Media {\n return (this._media ??= new Media());\n }\n\n public get charts(): ChartCollection {\n return (this._charts ??= new ChartCollection());\n }\n\n public get dxfEntries(): readonly DxfOptions[] {\n return this.dxfOptions;\n }\n\n public get pivotCacheRefs(): readonly PivotCacheReference[] {\n return this._pivotCacheRefs;\n }\n\n public registerPivotCache(cacheId: number, rId: string): void {\n this._pivotCacheRefs.push({ cacheId, rId });\n }\n\n public get externalLinks(): readonly ExternalLinkOptions[] {\n return this.externalLinkOptions;\n }\n\n public get worksheetConfigs(): readonly WorksheetOptions[] {\n return this.worksheetOptions;\n }\n\n public get chartsheetConfigs(): readonly ChartsheetOptions[] {\n return this.chartsheetOptions;\n }\n\n public get worksheets(): readonly Worksheet[] {\n if (!this._worksheets) {\n this._worksheets = this.worksheetOptions.map((ws) => new Worksheet(ws));\n }\n return this._worksheets;\n }\n\n public get fileRelationships(): Relationships {\n if (!this._fileRels) {\n this._fileRels = new Relationships();\n this._fileRels.addRelationship(\n 1,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument\",\n \"xl/workbook.xml\",\n );\n this._fileRels.addRelationship(\n 2,\n \"http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties\",\n \"docProps/core.xml\",\n );\n this._fileRels.addRelationship(\n 3,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties\",\n \"docProps/app.xml\",\n );\n }\n return this._fileRels;\n }\n\n public get workbookRelationships(): Relationships {\n if (!this._workbookRels) {\n this._workbookRels = new Relationships();\n let rid = 1;\n for (let i = 0; i < this.worksheetOptions.length; i++) {\n this._workbookRels.addRelationship(\n rid++,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet\",\n `worksheets/sheet${i + 1}.xml`,\n );\n }\n for (let i = 0; i < this.chartsheetOptions.length; i++) {\n this._workbookRels.addRelationship(\n rid++,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/chartsheet\",\n `chartsheets/sheet${i + 1}.xml`,\n );\n }\n this._workbookRels.addRelationship(\n rid++,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles\",\n \"styles.xml\",\n );\n this._workbookRels.addRelationship(\n rid++,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme\",\n \"theme/theme1.xml\",\n );\n this._workbookRels.addRelationship(\n rid++,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings\",\n \"sharedStrings.xml\",\n );\n }\n return this._workbookRels;\n }\n}\n","/**\n * Pivot table utility types and helper functions.\n *\n * @module\n */\n\n/** Aggregation function for data fields (maps to ST_DataConsolidateFunction). */\nexport const ConsolidateFunction = {\n SUM: \"sum\",\n COUNT: \"count\",\n AVERAGE: \"average\",\n MAX: \"max\",\n MIN: \"min\",\n PRODUCT: \"product\",\n COUNT_NUMS: \"countNums\",\n STD_DEV: \"stdDev\",\n STD_DEV_P: \"stdDevp\",\n VAR: \"var\",\n VAR_P: \"varp\",\n} as const;\n\nexport type ConsolidateFunction = (typeof ConsolidateFunction)[keyof typeof ConsolidateFunction];\n\n/** A data field definition for pivot table aggregation. */\nexport interface PivotDataField {\n /** Source column name to aggregate */\n readonly field: string;\n /** Aggregation function (default: \"sum\") */\n readonly summarize?: ConsolidateFunction;\n /** Custom name for the data field (default: \"Sum of {field}\") */\n readonly name?: string;\n /** Show data as (CT_DataField @showDataAs) */\n readonly showDataAs?: string;\n /** Base field index for \"show data as\" calculations */\n readonly baseField?: number;\n /** Base item index for \"show data as\" calculations */\n readonly baseItem?: number;\n /** Sort by tuple items (CT_Tuples in sortByTuple) */\n readonly sortByTupleItems?: readonly number[];\n}\n\n/** Pivot filter type (ST_PivotFilterType) */\nexport const PivotFilterType = {\n UNKNOWN: \"unknown\",\n COUNT: \"count\",\n PERCENT: \"percent\",\n SUM: \"sum\",\n CAPTION_EQUAL: \"captionEqual\",\n CAPTION_NOT_EQUAL: \"captionNotEqual\",\n CAPTION_BEGINS_WITH: \"captionBeginsWith\",\n CAPTION_NOT_BEGINS_WITH: \"captionNotBeginsWith\",\n CAPTION_ENDS_WITH: \"captionEndsWith\",\n CAPTION_NOT_ENDS_WITH: \"captionNotEndsWith\",\n CAPTION_CONTAINS: \"captionContains\",\n CAPTION_NOT_CONTAINS: \"captionNotContains\",\n CAPTION_GREATER_THAN: \"captionGreaterThan\",\n CAPTION_GREATER_THAN_OR_EQUAL: \"captionGreaterThanOrEqual\",\n CAPTION_LESS_THAN: \"captionLessThan\",\n CAPTION_LESS_THAN_OR_EQUAL: \"captionLessThanOrEqual\",\n CAPTION_BETWEEN: \"captionBetween\",\n CAPTION_NOT_BETWEEN: \"captionNotBetween\",\n VALUE_EQUAL: \"valueEqual\",\n VALUE_NOT_EQUAL: \"valueNotEqual\",\n VALUE_GREATER_THAN: \"valueGreaterThan\",\n VALUE_GREATER_THAN_OR_EQUAL: \"valueGreaterThanOrEqual\",\n VALUE_LESS_THAN: \"valueLessThan\",\n VALUE_LESS_THAN_OR_EQUAL: \"valueLessThanOrEqual\",\n VALUE_BETWEEN: \"valueBetween\",\n VALUE_NOT_BETWEEN: \"valueNotBetween\",\n DATE_EQUAL: \"dateEqual\",\n DATE_NOT_EQUAL: \"dateNotEqual\",\n DATE_OLDER_THAN: \"dateOlderThan\",\n DATE_OLDER_THAN_OR_EQUAL: \"dateOlderThanOrEqual\",\n DATE_NEWER_THAN: \"dateNewerThan\",\n DATE_NEWER_THAN_OR_EQUAL: \"dateNewerThanOrEqual\",\n DATE_BETWEEN: \"dateBetween\",\n DATE_NOT_BETWEEN: \"dateNotBetween\",\n TOMORROW: \"tomorrow\",\n TODAY: \"today\",\n YESTERDAY: \"yesterday\",\n NEXT_WEEK: \"nextWeek\",\n THIS_WEEK: \"thisWeek\",\n LAST_WEEK: \"lastWeek\",\n NEXT_MONTH: \"nextMonth\",\n THIS_MONTH: \"thisMonth\",\n LAST_MONTH: \"lastMonth\",\n NEXT_QUARTER: \"nextQuarter\",\n THIS_QUARTER: \"thisQuarter\",\n LAST_QUARTER: \"lastQuarter\",\n NEXT_YEAR: \"nextYear\",\n THIS_YEAR: \"thisYear\",\n LAST_YEAR: \"lastYear\",\n YEAR_TO_DATE: \"yearToDate\",\n Q1: \"Q1\",\n Q2: \"Q2\",\n Q3: \"Q3\",\n Q4: \"Q4\",\n M1: \"M1\",\n M2: \"M2\",\n M3: \"M3\",\n M4: \"M4\",\n M5: \"M5\",\n M6: \"M6\",\n M7: \"M7\",\n M8: \"M8\",\n M9: \"M9\",\n M10: \"M10\",\n M11: \"M11\",\n M12: \"M12\",\n} as const;\n\nexport type PivotFilterType = (typeof PivotFilterType)[keyof typeof PivotFilterType];\n\n/** A single pivot filter (CT_PivotFilter) */\nexport interface PivotFilterOptions {\n /** Field index to filter on (required) */\n readonly fld: number;\n /** Filter type (required) */\n readonly type: PivotFilterType;\n /** Filter ID — unique within this pivot table (required) */\n readonly id: number;\n /** Measure field index for OLAP filters */\n readonly mpFld?: number;\n /** Evaluation order */\n readonly evalOrder?: number;\n /** Measure hierarchy */\n readonly iMeasureHier?: number;\n /** Measure field */\n readonly iMeasureFld?: number;\n /** Filter name */\n readonly name?: string;\n /** Filter description */\n readonly description?: string;\n /** First string value for caption/date filters */\n readonly stringValue1?: string;\n /** Second string value for between filters */\n readonly stringValue2?: string;\n}\n\n/** Options for a single pivot table on a worksheet. */\nexport interface PivotTableOptions {\n /** Pivot table name (default: \"PivotTable{N}\") */\n readonly name?: string;\n /** Source data range, e.g. \"A1:D11\" — must be on the same or a different sheet */\n readonly source: string;\n /** Source sheet name (default: current sheet) */\n readonly sourceSheet?: string;\n /** Target cell for the pivot table output (default: \"A3\") */\n readonly location?: string;\n /** Field names to use as row labels */\n readonly rows: readonly string[];\n /** Field names to use as column labels */\n readonly columns?: readonly string[];\n /** Data fields with aggregation settings */\n readonly data: readonly PivotDataField[];\n /** Pivot style name (default: \"PivotStyleLight16\") */\n readonly style?: string;\n /** Pivot filters (CT_PivotFilters) */\n readonly filters?: readonly PivotFilterOptions[];\n /** Field names to use as page/report filters */\n readonly pages?: readonly string[];\n /** Data fields on rows instead of columns (CT_PivotTableDefinition @dataOnRows) */\n readonly dataOnRows?: boolean;\n /** Grand total caption text */\n readonly grandTotalCaption?: string;\n /** Error caption text */\n readonly errorCaption?: string;\n /** Show error messages */\n readonly showError?: boolean;\n /** Missing caption text */\n readonly missingCaption?: string;\n /** Show missing items */\n readonly showMissing?: boolean;\n /** Custom page style name */\n readonly pageStyle?: string;\n /** Custom pivot table style name */\n readonly pivotTableStyle?: string;\n /** Tag string */\n readonly tag?: string;\n /** Show items with no data */\n readonly showItems?: boolean;\n /** Edit data in-place */\n readonly editData?: boolean;\n /** Disable field list */\n readonly disableFieldList?: boolean;\n /** Show calculated members */\n readonly showCalcMbrs?: boolean;\n /** Visual totals */\n readonly visualTotals?: boolean;\n /** Show multiple labels */\n readonly showMultipleLabel?: boolean;\n /** Show data drop-down */\n readonly showDataDropDown?: boolean;\n /** Show drill indicators */\n readonly showDrill?: boolean;\n /** Print drill indicators */\n readonly printDrill?: boolean;\n /** Show member property tips */\n readonly showMemberPropertyTips?: boolean;\n /** Show data tips */\n readonly showDataTips?: boolean;\n /** Enable layout wizard */\n readonly enableWizard?: boolean;\n /** Enable drill-down */\n readonly enableDrill?: boolean;\n /** Enable field properties */\n readonly enableFieldProperties?: boolean;\n /** Number of page fields per row/column */\n readonly pageWrap?: number;\n /** Page layout over then down */\n readonly pageOverThenDown?: boolean;\n /** Subtotal hidden items */\n readonly subtotalHiddenItems?: boolean;\n /** Field print titles */\n readonly fieldPrintTitles?: boolean;\n /** Merge item labels */\n readonly mergeItem?: boolean;\n /** Show drop zones */\n readonly showDropZones?: boolean;\n /** Show empty row */\n readonly showEmptyRow?: boolean;\n /** Show empty column */\n readonly showEmptyCol?: boolean;\n /** Show headers */\n readonly showHeaders?: boolean;\n /** Published to server */\n readonly published?: boolean;\n /** Grid drop zones */\n readonly gridDropZones?: boolean;\n /** Multiple field filters */\n readonly multipleFieldFilters?: boolean;\n /** Row header caption */\n readonly rowHeaderCaption?: string;\n /** Column header caption */\n readonly colHeaderCaption?: string;\n /** Sort field list ascending */\n readonly fieldListSortAscending?: boolean;\n /** MDX subqueries enabled */\n readonly mdxSubqueries?: boolean;\n /** Custom list sort */\n readonly customListSort?: boolean;\n /** Calculated items (CT_CalculatedItems) */\n readonly calculatedItems?: readonly CalculatedItemOptions[];\n /** Calculated members (CT_CalculatedMembers) */\n readonly calculatedMembers?: readonly CalculatedMemberOptions[];\n /** Pivot hierarchies (CT_PivotHierarchies) */\n readonly pivotHierarchies?: readonly PivotHierarchyOptions[];\n /** Conditional formats (CT_ConditionalFormats for pivot) */\n readonly pivotConditionalFormats?: readonly PivotConditionalFormatOptions[];\n /** Chart formats (CT_ChartFormats) */\n readonly chartFormats?: readonly ChartFormatOptions[];\n /** Auto sort scope (CT_AutoSortScope) */\n readonly autoSortScope?: PivotAreaOptions;\n /** Member properties per field (CT_MemberProperties → mps/mp) */\n readonly memberProperties?: readonly MemberPropertyOptions[];\n /** Pivot format areas (CT_Formats → format) */\n readonly formats?: readonly PivotFormatOptions[];\n /** Row hierarchy usage (CT_RowHierarchiesUsage) */\n readonly rowHierarchiesUsage?: readonly HierarchyUsageOptions[];\n /** Column hierarchy usage (CT_ColHierarchiesUsage) */\n readonly colHierarchiesUsage?: readonly HierarchyUsageOptions[];\n}\n\n/** Pivot format (CT_Format). */\nexport interface PivotFormatOptions {\n /** Action type (default: \"formatting\") */\n readonly action?: \"formatting\" | \"drill\" | \"formula\" | \"blank\" | \"subtotal\" | \"report\";\n /** Differential format index */\n readonly dxfId?: number;\n /** Pivot area */\n readonly pivotArea: PivotAreaOptions;\n}\n\n/** Calculated item in a pivot table (CT_CalculatedItem) */\nexport interface CalculatedItemOptions {\n /** Field index */\n readonly field?: number;\n /** Formula */\n readonly formula?: string;\n /** Pivot area reference */\n readonly pivotArea?: PivotAreaOptions;\n}\n\n/** Calculated member in a pivot table (CT_CalculatedMember) */\nexport interface CalculatedMemberOptions {\n /** Name (required) */\n readonly name: string;\n /** MDX expression (required) */\n readonly mdx: string;\n /** Member name */\n readonly memberName?: string;\n /** Hierarchy */\n readonly hierarchy?: string;\n /** Parent member */\n readonly parent?: string;\n /** Solve order (default: 0) */\n readonly solveOrder?: number;\n /** Is a set (default: false) */\n readonly set?: boolean;\n}\n\n/** Pivot hierarchy (CT_PivotHierarchy) */\nexport interface PivotHierarchyOptions {\n /** Outline mode (default: false) */\n readonly outline?: boolean;\n /** Allow multiple item selection (default: false) */\n readonly multipleItemSelectionAllowed?: boolean;\n /** Subtotal on top (default: false) */\n readonly subtotalTop?: boolean;\n /** Show in field list (default: true) */\n readonly showInFieldList?: boolean;\n /** Drag to row (default: true) */\n readonly dragToRow?: boolean;\n /** Drag to column (default: true) */\n readonly dragToCol?: boolean;\n /** Drag to page (default: true) */\n readonly dragToPage?: boolean;\n /** Drag to data (default: false) */\n readonly dragToData?: boolean;\n /** Drag off (default: true) */\n readonly dragOff?: boolean;\n /** Include new items in filter (default: false) */\n readonly includeNewItemsInFilter?: boolean;\n /** Caption */\n readonly caption?: string;\n /** Members */\n readonly members?: readonly MemberOptions[];\n /** Member properties (CT_MemberProperties → mps/mp) */\n readonly memberProperties?: readonly MemberPropertyOptions[];\n}\n\n/** Member in pivot hierarchy (CT_Member) */\nexport interface MemberOptions {\n /** Member name (required) */\n readonly name: string;\n}\n\n/** Member property (CT_MemberProperty) */\nexport interface MemberPropertyOptions {\n /** Field index */\n readonly field: number;\n /** Property name */\n readonly name?: string;\n /** Show cell? */\n readonly showCell?: boolean;\n /** Show tip? */\n readonly showTip?: boolean;\n}\n\n/** Pivot area for conditional formats, chart formats, etc. (CT_PivotArea) */\nexport interface PivotAreaOptions {\n /** Field index */\n readonly field?: number;\n /** Area type (default: \"normal\") */\n readonly type?: \"none\" | \"normal\" | \"data\" | \"all\" | \"origin\" | \"button\" | \"topEnd\" | \"topRight\";\n /** Data only (default: true) */\n readonly dataOnly?: boolean;\n /** Label only (default: false) */\n readonly labelOnly?: boolean;\n /** Grand row (default: false) */\n readonly grandRow?: boolean;\n /** Grand column (default: false) */\n readonly grandCol?: boolean;\n /** Cache index (default: false) */\n readonly cacheIndex?: boolean;\n /** Outline (default: true) */\n readonly outline?: boolean;\n /** Offset reference */\n readonly offset?: string;\n /** Collapsed levels are subtotals (default: false) */\n readonly collapsedLevelsAreSubtotals?: boolean;\n /** Axis */\n readonly axis?: \"axisRow\" | \"axisCol\" | \"axisPage\" | \"axisValues\";\n /** Field position */\n readonly fieldPosition?: number;\n /** References */\n readonly references?: readonly PivotAreaReferenceOptions[];\n}\n\n/** Pivot area reference (CT_PivotAreaReference) */\nexport interface PivotAreaReferenceOptions {\n /** Field index */\n readonly field?: number;\n /** Count */\n readonly count?: number;\n /** Selected (default: true) */\n readonly selected?: boolean;\n /** By position (default: false) */\n readonly byPosition?: boolean;\n /** Relative (default: false) */\n readonly relative?: boolean;\n /** Default subtotal */\n readonly defaultSubtotal?: boolean;\n /** Sum subtotal */\n readonly sumSubtotal?: boolean;\n /** CountA subtotal */\n readonly countASubtotal?: boolean;\n /** Average subtotal */\n readonly avgSubtotal?: boolean;\n /** Max subtotal */\n readonly maxSubtotal?: boolean;\n /** Min subtotal */\n readonly minSubtotal?: boolean;\n /** X indices */\n readonly x?: readonly number[];\n}\n\n/** Pivot conditional format (CT_ConditionalFormat for pivot) */\nexport interface PivotConditionalFormatOptions {\n /** Scope (default: \"selection\") */\n readonly scope?: \"selection\" | \"data\" | \"field\";\n /** Type (default: \"none\") */\n readonly type?: \"none\" | \"all\" | \"row\" | \"column\";\n /** Priority (required) */\n readonly priority: number;\n /** Pivot areas */\n readonly pivotAreas?: readonly PivotAreaOptions[];\n}\n\n/** Chart format for pivot table (CT_ChartFormat) */\nexport interface ChartFormatOptions {\n /** Chart index (required) */\n readonly chart: number;\n /** Format index (required) */\n readonly format: number;\n /** Is series (default: false) */\n readonly series?: boolean;\n /** Pivot area */\n readonly pivotArea?: PivotAreaOptions;\n}\n\n/** Cache hierarchy for OLAP pivot caches (CT_CacheHierarchy) */\nexport interface CacheHierarchyOptions {\n /** Unique name (required) */\n readonly uniqueName: string;\n /** Caption */\n readonly caption?: string;\n /** Is measure (default: false) */\n readonly measure?: boolean;\n /** Is set (default: false) */\n readonly set?: boolean;\n /** Parent set index */\n readonly parentSet?: number;\n /** Icon set (default: 0) */\n readonly iconSet?: number;\n /** Is attribute (default: false) */\n readonly attribute?: boolean;\n /** Is time dimension (default: false) */\n readonly time?: boolean;\n /** Key attribute (default: false) */\n readonly keyAttribute?: boolean;\n /** Default member unique name */\n readonly defaultMemberUniqueName?: string;\n /** All unique name */\n readonly allUniqueName?: string;\n /** All caption */\n readonly allCaption?: string;\n /** Dimension unique name */\n readonly dimensionUniqueName?: string;\n /** Display folder */\n readonly displayFolder?: string;\n /** Measure group */\n readonly measureGroup?: string;\n /** Is measures (default: false) */\n readonly measures?: boolean;\n /** Count (required) */\n readonly count: number;\n /** One field (default: false) */\n readonly oneField?: boolean;\n /** Hidden (default: false) */\n readonly hidden?: boolean;\n /** Group levels (CT_GroupLevels) */\n readonly groupLevels?: readonly GroupLevelOptions[];\n /** Fields usage (CT_FieldsUsage) */\n readonly fieldsUsage?: readonly FieldUsageOptions[];\n}\n\n/** KPI definition for pivot cache (CT_PCDKPI) */\nexport interface KpiOptions {\n /** Unique name (required) */\n readonly uniqueName: string;\n /** Caption */\n readonly caption?: string;\n /** Display folder */\n readonly displayFolder?: string;\n /** Measure group */\n readonly measureGroup?: string;\n /** Parent */\n readonly parent?: string;\n /** Value expression (required) */\n readonly value: string;\n /** Goal expression */\n readonly goal?: string;\n /** Status expression */\n readonly status?: string;\n /** Trend expression */\n readonly trend?: string;\n /** Weight expression */\n readonly weight?: string;\n /** Time expression */\n readonly time?: string;\n}\n\n/** Measure group (CT_MeasureGroup) */\nexport interface MeasureGroupOptions {\n /** Name (required) */\n readonly name: string;\n /** Caption (required) */\n readonly caption: string;\n}\n\n/** Set definition (CT_Set) */\nexport interface SetOptions {\n /** Count */\n readonly count?: number;\n /** Max rank (required) */\n readonly maxRank: number;\n /** Set definition MDX (required) */\n readonly setDefinition: string;\n /** Sort type (default: \"none\") */\n readonly sortType?:\n | \"none\"\n | \"ascending\"\n | \"descending\"\n | \"ascendingAlpha\"\n | \"descendingAlpha\"\n | \"ascendingNatural\"\n | \"descendingNatural\";\n /** Query failed (default: false) */\n readonly queryFailed?: boolean;\n}\n\n/** Server format (CT_ServerFormat) */\nexport interface ServerFormatOptions {\n /** Culture */\n readonly culture?: string;\n /** Format string */\n readonly format?: string;\n}\n\n/** Field group for pivot cache (CT_FieldGroup) */\nexport interface FieldGroupOptions {\n /** Parent field index */\n readonly parent?: number;\n /** Base field index */\n readonly base?: number;\n /** Range properties */\n readonly rangePr?: RangePrOptions;\n /** Discrete properties */\n readonly discretePr?: readonly number[];\n /** Group items names */\n readonly groupItems?: readonly string[];\n}\n\n/** Range properties for field grouping (CT_RangePr) */\nexport interface RangePrOptions {\n /** Auto start (default: true) */\n readonly autoStart?: boolean;\n /** Auto end (default: true) */\n readonly autoEnd?: boolean;\n /** Group by (default: \"range\") */\n readonly groupBy?:\n | \"range\"\n | \"seconds\"\n | \"minutes\"\n | \"hours\"\n | \"days\"\n | \"months\"\n | \"quarters\"\n | \"years\";\n /** Start number */\n readonly startNum?: number;\n /** End number */\n readonly endNum?: number;\n /** Start date ISO string */\n readonly startDate?: string;\n /** End date ISO string */\n readonly endDate?: string;\n /** Group interval (default: 1) */\n readonly groupInterval?: number;\n}\n\n/** Pivot dimension (CT_PivotDimension) */\nexport interface PivotDimensionOptions {\n /** Is measure (default: false) */\n readonly measure?: boolean;\n /** Name (required) */\n readonly name: string;\n /** Unique name (required) */\n readonly uniqueName: string;\n /** Caption (required) */\n readonly caption: string;\n}\n\n/** Range set for consolidation source (CT_RangeSet) */\nexport interface RangeSetOptions {\n /** Index for page field 1 */\n readonly i1?: number;\n /** Index for page field 2 */\n readonly i2?: number;\n /** Index for page field 3 */\n readonly i3?: number;\n /** Index for page field 4 */\n readonly i4?: number;\n /** Cell reference */\n readonly ref?: string;\n /** Named range */\n readonly name?: string;\n /** Sheet name */\n readonly sheet?: string;\n /** Relationship ID to external workbook */\n readonly rId?: string;\n}\n\n/** Page item for consolidation (CT_PageItem) */\nexport interface ConsolidationPageItemOptions {\n /** Page item name */\n readonly name: string;\n}\n\n/** Page for consolidation (CT_PCDSCPage) */\nexport interface ConsolidationPageOptions {\n /** Page items */\n readonly items?: readonly ConsolidationPageItemOptions[];\n}\n\n/** Consolidation source (CT_Consolidation) */\nexport interface ConsolidationOptions {\n /** Auto page (default: true) */\n readonly autoPage?: boolean;\n /** Pages (max 4) */\n readonly pages?: readonly ConsolidationPageOptions[];\n /** Range sets (required) */\n readonly rangeSets: readonly RangeSetOptions[];\n}\n\n/** Tuple cache entry (CT_PCDSDTCEntries choice: m/n/e/s) */\nexport interface TupleCacheEntryOptions {\n /** Entry type */\n readonly type: \"m\" | \"n\" | \"e\" | \"s\";\n /** Value (required for n/s, optional for e) */\n readonly value?: number | string;\n}\n\n/** Deleted field (CT_DeletedField) */\nexport interface DeletedFieldOptions {\n /** Field name */\n readonly name: string;\n}\n\n/** Group member (CT_GroupMember) */\nexport interface GroupMemberOptions {\n /** Unique name (required) */\n readonly uniqueName: string;\n /** Is group */\n readonly group?: boolean;\n}\n\n/** Level group (CT_LevelGroup) */\nexport interface LevelGroupOptions {\n /** Name (required) */\n readonly name: string;\n /** Unique name (required) */\n readonly uniqueName: string;\n /** Caption (required) */\n readonly caption: string;\n /** Unique parent */\n readonly uniqueParent?: string;\n /** Group ID */\n readonly id?: number;\n /** Members */\n readonly members: readonly GroupMemberOptions[];\n}\n\n/** Group level (CT_GroupLevel) */\nexport interface GroupLevelOptions {\n /** Unique name (required) */\n readonly uniqueName: string;\n /** Caption (required) */\n readonly caption: string;\n /** User-defined */\n readonly user?: boolean;\n /** Custom roll-up */\n readonly customRollUp?: boolean;\n /** Groups */\n readonly groups?: readonly LevelGroupOptions[];\n}\n\n/** Field usage (CT_FieldUsage) */\nexport interface FieldUsageOptions {\n /** Field index */\n readonly value: number;\n}\n\n/** Hierarchy usage (CT_HierarchyUsage) */\nexport interface HierarchyUsageOptions {\n /** Hierarchy usage value (required) */\n readonly hierarchyUsage: number;\n}\n\n/** Query cache entry (CT_Query) */\nexport interface QueryCacheEntryOptions {\n /** MDX query string (required) */\n readonly mdx: string;\n /** Tuples */\n readonly tpls?: readonly TupleOptions[];\n}\n\n/** Tuple (CT_Tuple) */\nexport interface TupleOptions {\n /** Tuple items (field indices) */\n readonly items?: readonly number[];\n}\n\n/** Member property map (CT_X, used as mpMap child) */\nexport interface MpMapOptions {\n /** Field index */\n readonly x: number;\n}\n\n/** Measure dimension map (CT_MeasureDimensionMap) */\nexport interface MeasureDimensionMapOptions {\n /** Measure group index */\n readonly measureGroup?: number;\n /** Dimension index */\n readonly dimension?: number;\n}\n\n/** OLAP properties for pivot cache (CT_OlapPr) */\nexport interface OlapPrOptions {\n /** Local cube connection string */\n readonly local?: string;\n /** Local connection string */\n readonly localConnection?: string;\n /** Send locale info to OLAP server */\n readonly sendLocale?: boolean;\n /** Row dimensions */\n readonly rowDrillCount?: number;\n /** Column dimensions */\n readonly colDrillCount?: number;\n /** Local refresh (CT_OlapPr @localRefresh) */\n readonly localRefresh?: boolean;\n /** Use server fill formatting */\n readonly serverFill?: boolean;\n /** Use server number formatting */\n readonly serverNumberFormat?: boolean;\n /** Use server font formatting */\n readonly serverFont?: boolean;\n /** Use server font color */\n readonly serverFontColor?: boolean;\n}\n\n/** Parsed source data for pivot cache generation. */\nexport interface PivotSourceData {\n readonly fieldNames: readonly string[];\n readonly records: readonly (string | number | null | Date)[][];\n}\n\n/**\n * Extract unique values from source data for a given field index.\n */\nexport function collectUniqueValues(\n records: readonly (string | number | null | Date)[][],\n fieldIdx: number,\n): (string | number | null | Date)[] {\n const seen = new Set<string>();\n const result: (string | number | null | Date)[] = [];\n for (const row of records) {\n const val = row[fieldIdx];\n const key = val instanceof Date ? val.toISOString() : String(val);\n if (!seen.has(key)) {\n seen.add(key);\n result.push(val);\n }\n }\n return result;\n}\n\n/**\n * Check if a field is numeric (all non-empty values are numbers).\n */\nexport function isNumericField(\n records: readonly (string | number | null | Date)[][],\n fieldIdx: number,\n): boolean {\n for (const row of records) {\n const val = row[fieldIdx];\n if (typeof val === \"string\" && val !== \"\") return false;\n }\n return true;\n}\n\n/**\n * Aggregate values using the specified function.\n */\nexport function aggregate(values: readonly number[], func: ConsolidateFunction): number {\n if (values.length === 0) return 0;\n switch (func) {\n case \"sum\":\n return values.reduce((a, b) => a + b, 0);\n case \"count\":\n case \"countNums\":\n return values.length;\n case \"average\":\n return values.reduce((a, b) => a + b, 0) / values.length;\n case \"max\":\n return Math.max(...values);\n case \"min\":\n return Math.min(...values);\n case \"product\":\n return values.reduce((a, b) => a * b, 1);\n case \"var\":\n return sampleVariance(values);\n case \"varp\":\n return populationVariance(values);\n case \"stdDev\":\n return Math.sqrt(sampleVariance(values));\n case \"stdDevp\":\n return Math.sqrt(populationVariance(values));\n default:\n return values.reduce((a, b) => a + b, 0);\n }\n}\n\nfunction populationVariance(values: readonly number[]): number {\n const mean = values.reduce((a, b) => a + b, 0) / values.length;\n return values.reduce((sum, v) => sum + (v - mean) ** 2, 0) / values.length;\n}\n\nfunction sampleVariance(values: readonly number[]): number {\n if (values.length < 2) return 0;\n const mean = values.reduce((a, b) => a + b, 0) / values.length;\n return values.reduce((sum, v) => sum + (v - mean) ** 2, 0) / (values.length - 1);\n}\n","/**\n * PivotCacheDefinition XML generator.\n *\n * Generates xl/pivotCache/pivotCacheDefinition{N}.xml.\n * Follows CT_PivotCacheDefinition from sml.xsd.\n *\n * @module\n */\nimport { BaseXmlComponent } from \"@file/xml-components\";\nimport type { Context } from \"@file/xml-components\";\nimport { escapeXml } from \"@office-open/xml\";\n\nimport type {\n PivotSourceData,\n OlapPrOptions,\n CacheHierarchyOptions,\n KpiOptions,\n MeasureGroupOptions,\n SetOptions,\n ServerFormatOptions,\n PivotDimensionOptions,\n FieldGroupOptions,\n ConsolidationOptions,\n TupleCacheEntryOptions,\n QueryCacheEntryOptions,\n MpMapOptions,\n MeasureDimensionMapOptions,\n} from \"./pivot-utils\";\nimport { collectUniqueValues, isNumericField } from \"./pivot-utils\";\n\nexport interface PivotCacheDefinitionOptions {\n /** Cache is invalid (CT_PivotCacheDefinition @invalid) */\n readonly invalid?: boolean;\n /** Save data with cache (CT_PivotCacheDefinition @saveData) */\n readonly saveData?: boolean;\n /** Optimize memory usage (CT_PivotCacheDefinition @optimizeMemory) */\n readonly optimizeMemory?: boolean;\n /** Enable refresh (CT_PivotCacheDefinition @enableRefresh) */\n readonly enableRefresh?: boolean;\n /** User who last refreshed */\n readonly refreshedBy?: string;\n /** Date of last refresh (decimal) */\n readonly refreshedDate?: number;\n /** Date of last refresh (ISO 8601) */\n readonly refreshedDateIso?: string;\n /** Background query (CT_PivotCacheDefinition @backgroundQuery) */\n readonly backgroundQuery?: boolean;\n /** Missing items limit */\n readonly missingItemsLimit?: number;\n /** Upgrade on refresh */\n readonly upgradeOnRefresh?: boolean;\n /** Support subquery */\n readonly supportSubquery?: boolean;\n /** Support advanced drill */\n readonly supportAdvancedDrill?: boolean;\n /** Cache hierarchies (CT_CacheHierarchies) */\n readonly cacheHierarchies?: readonly CacheHierarchyOptions[];\n /** KPIs (CT_PCDKPIs) */\n readonly kpis?: readonly KpiOptions[];\n /** Measure groups (CT_MeasureGroups) */\n readonly measureGroups?: readonly MeasureGroupOptions[];\n /** Dimensions (CT_Dimensions) */\n readonly dimensions?: readonly PivotDimensionOptions[];\n /** Sets (CT_Sets in tupleCache) */\n readonly sets?: readonly SetOptions[];\n /** Server formats (CT_ServerFormats) */\n readonly serverFormats?: readonly ServerFormatOptions[];\n /** Field groups per field index (CT_FieldGroup inside cacheField) */\n readonly fieldGroups?: ReadonlyMap<number, FieldGroupOptions>;\n /** Consolidation source (alternative to worksheetSource) */\n readonly consolidation?: ConsolidationOptions;\n /** Tuple cache entries (CT_PCDSDTCEntries) */\n readonly entries?: readonly TupleCacheEntryOptions[];\n /** Query cache (CT_QueryCache in tupleCache) */\n readonly queryCache?: readonly QueryCacheEntryOptions[];\n /** Member property map per cache field (mpMap) */\n readonly mpMaps?: readonly MpMapOptions[];\n /** Measure dimension maps (CT_MeasureDimensionMaps) */\n readonly measureDimensionMaps?: readonly MeasureDimensionMapOptions[];\n}\n\nexport class PivotCacheDefinitionXml extends BaseXmlComponent {\n private readonly sourceRef: string;\n private readonly sourceSheet: string;\n private readonly sourceData: PivotSourceData;\n private readonly recordsRid: string;\n private readonly olapPr?: OlapPrOptions;\n private readonly cacheDefOpts?: PivotCacheDefinitionOptions;\n\n public constructor(\n _cacheIdx: number,\n sourceRef: string,\n sourceSheet: string,\n sourceData: PivotSourceData,\n recordsRid: string,\n olapPr?: OlapPrOptions,\n cacheDefOpts?: PivotCacheDefinitionOptions,\n ) {\n super(\"pivotCacheDefinition\");\n this.sourceRef = sourceRef;\n this.sourceSheet = sourceSheet;\n this.sourceData = sourceData;\n this.recordsRid = recordsRid;\n this.olapPr = olapPr;\n this.cacheDefOpts = cacheDefOpts;\n }\n\n public override toXml(_context: Context): string {\n const p: string[] = [];\n\n // Root element attributes\n const rootAttrs: string[] = [\n 'xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\"',\n 'xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\"',\n `r:id=\"${escapeXml(this.recordsRid)}\"`,\n `recordCount=\"${this.sourceData.records.length}\"`,\n 'createdVersion=\"6\"',\n 'refreshedVersion=\"6\"',\n 'minRefreshableVersion=\"3\"',\n ];\n\n // Optional cache definition attributes on root element\n if (this.cacheDefOpts) {\n const cd = this.cacheDefOpts;\n if (cd.invalid) rootAttrs.push('invalid=\"1\"');\n if (cd.saveData === false) rootAttrs.push('saveData=\"0\"');\n if (cd.optimizeMemory) rootAttrs.push('optimizeMemory=\"1\"');\n if (cd.enableRefresh === false) rootAttrs.push('enableRefresh=\"0\"');\n if (cd.refreshedBy) rootAttrs.push(`refreshedBy=\"${escapeXml(cd.refreshedBy)}\"`);\n if (cd.refreshedDate !== undefined) rootAttrs.push(`refreshedDate=\"${cd.refreshedDate}\"`);\n if (cd.refreshedDateIso)\n rootAttrs.push(`refreshedDateIso=\"${escapeXml(cd.refreshedDateIso)}\"`);\n if (cd.backgroundQuery) rootAttrs.push('backgroundQuery=\"1\"');\n if (cd.missingItemsLimit !== undefined)\n rootAttrs.push(`missingItemsLimit=\"${cd.missingItemsLimit}\"`);\n if (cd.upgradeOnRefresh) rootAttrs.push('upgradeOnRefresh=\"1\"');\n if (cd.supportSubquery) rootAttrs.push('supportSubquery=\"1\"');\n if (cd.supportAdvancedDrill) rootAttrs.push('supportAdvancedDrill=\"1\"');\n }\n\n p.push(`<pivotCacheDefinition ${rootAttrs.join(\" \")}>`);\n\n // cacheSource (worksheetSource or consolidation)\n if (this.cacheDefOpts?.consolidation) {\n const con = this.cacheDefOpts.consolidation;\n const conParts: string[] = ['<cacheSource type=\"consolidation\"><consolidation'];\n if (con.autoPage === false) conParts.push(' autoPage=\"0\"');\n conParts.push(\">\");\n // pages (optional, max 4)\n if (con.pages && con.pages.length > 0) {\n conParts.push(`<pages count=\"${con.pages.length}\">`);\n for (const pg of con.pages) {\n const pgItems = pg.items ?? [];\n conParts.push(`<page${pgItems.length ? ` count=\"${pgItems.length}\"` : \"\"}>`);\n for (const pi of pgItems) {\n conParts.push(`<pageItem name=\"${escapeXml(pi.name)}\"/>`);\n }\n conParts.push(\"</page>\");\n }\n conParts.push(\"</pages>\");\n }\n // rangeSets (required)\n conParts.push(`<rangeSets count=\"${con.rangeSets.length}\">`);\n for (const rs of con.rangeSets) {\n const rsAttrs: string[] = [];\n if (rs.i1 !== undefined) rsAttrs.push(`i1=\"${rs.i1}\"`);\n if (rs.i2 !== undefined) rsAttrs.push(`i2=\"${rs.i2}\"`);\n if (rs.i3 !== undefined) rsAttrs.push(`i3=\"${rs.i3}\"`);\n if (rs.i4 !== undefined) rsAttrs.push(`i4=\"${rs.i4}\"`);\n if (rs.ref) rsAttrs.push(`ref=\"${escapeXml(rs.ref)}\"`);\n if (rs.name) rsAttrs.push(`name=\"${escapeXml(rs.name)}\"`);\n if (rs.sheet) rsAttrs.push(`sheet=\"${escapeXml(rs.sheet)}\"`);\n if (rs.rId) rsAttrs.push(`r:id=\"${escapeXml(rs.rId)}\"`);\n conParts.push(`<rangeSet ${rsAttrs.join(\" \")}/>`);\n }\n conParts.push(\"</rangeSets></consolidation></cacheSource>\");\n p.push(conParts.join(\"\"));\n } else {\n p.push(\n `<cacheSource type=\"worksheet\">` +\n `<worksheetSource ref=\"${escapeXml(this.sourceRef)}\" sheet=\"${escapeXml(this.sourceSheet)}\"/>` +\n `</cacheSource>`,\n );\n }\n\n // cacheFields\n const fields = this.sourceData.fieldNames;\n p.push(`<cacheFields count=\"${fields.length}\">`);\n\n for (let i = 0; i < fields.length; i++) {\n const fieldName = fields[i];\n const numeric = isNumericField(this.sourceData.records, i);\n const uniqueVals = collectUniqueValues(this.sourceData.records, i);\n\n if (numeric) {\n // Numeric field: sharedItems with type metadata only, no inline values\n let min = Infinity;\n let max = -Infinity;\n for (const row of this.sourceData.records) {\n const v = row[i];\n if (typeof v === \"number\") {\n if (v < min) min = v;\n if (v > max) max = v;\n }\n }\n if (!isFinite(min)) {\n min = 0;\n max = 0;\n }\n const allInteger = this.sourceData.records.every(\n (row) => typeof row[i] === \"number\" && Number.isInteger(row[i]),\n );\n p.push(\n `<cacheField name=\"${escapeXml(fieldName)}\" numFmtId=\"0\">` +\n `<sharedItems containsSemiMixedTypes=\"0\" containsString=\"0\"` +\n ` containsNumber=\"1\" containsInteger=\"${allInteger ? \"1\" : \"0\"}\"` +\n ` minValue=\"${min}\" maxValue=\"${max}\" count=\"${uniqueVals.length}\"/>` +\n `</cacheField>`,\n );\n } else {\n // String/categorical/mixed field: list unique values in sharedItems\n // Detect if field contains dates or nulls for correct metadata attributes\n let hasDate = false;\n let hasMissing = false;\n for (const v of uniqueVals) {\n if (v instanceof Date) hasDate = true;\n if (v === null) hasMissing = true;\n }\n const siAttrs: string[] = [`count=\"${uniqueVals.length}\"`];\n if (hasDate) siAttrs.push('containsDate=\"1\"');\n if (hasMissing) siAttrs.push('containsBlank=\"1\"');\n\n p.push(\n `<cacheField name=\"${escapeXml(fieldName)}\" numFmtId=\"0\"><sharedItems ${siAttrs.join(\" \")}>`,\n );\n for (const v of uniqueVals) {\n if (v === null) {\n p.push(\"<m/>\");\n } else if (v instanceof Date) {\n p.push(`<d v=\"${v.toISOString().replace(/\\.\\d{3}Z$/, \"Z\")}\"/>`);\n } else {\n p.push(`<s v=\"${escapeXml(String(v))}\"/>`);\n }\n }\n p.push(\"</sharedItems>\");\n\n // fieldGroup (CT_FieldGroup, after sharedItems per XSD sequence)\n const fg = this.cacheDefOpts?.fieldGroups?.get(i);\n if (fg) {\n const fgParts: string[] = [\"<fieldGroup\"];\n if (fg.parent !== undefined) fgParts.push(` par=\"${fg.parent}\"`);\n if (fg.base !== undefined) fgParts.push(` base=\"${fg.base}\"`);\n fgParts.push(\">\");\n // rangePr (CT_RangePr)\n if (fg.rangePr) {\n const rp = fg.rangePr;\n const rpAttrs: string[] = [];\n if (rp.autoStart === false) rpAttrs.push('autoStart=\"0\"');\n if (rp.autoEnd === false) rpAttrs.push('autoEnd=\"0\"');\n if (rp.groupBy && rp.groupBy !== \"range\") rpAttrs.push(`groupBy=\"${rp.groupBy}\"`);\n if (rp.startNum !== undefined) rpAttrs.push(`startNum=\"${rp.startNum}\"`);\n if (rp.endNum !== undefined) rpAttrs.push(`endNum=\"${rp.endNum}\"`);\n if (rp.startDate) rpAttrs.push(`startDate=\"${escapeXml(rp.startDate)}\"`);\n if (rp.endDate) rpAttrs.push(`endDate=\"${escapeXml(rp.endDate)}\"`);\n if (rp.groupInterval !== undefined) rpAttrs.push(`groupInterval=\"${rp.groupInterval}\"`);\n fgParts.push(`<rangePr${rpAttrs.length ? \" \" + rpAttrs.join(\" \") : \"\"}/>`);\n }\n // discretePr (CT_DiscretePr)\n if (fg.discretePr && fg.discretePr.length > 0) {\n fgParts.push(`<discretePr count=\"${fg.discretePr.length}\">`);\n for (const idx of fg.discretePr) {\n fgParts.push(`<x v=\"${idx}\"/>`);\n }\n fgParts.push(\"</discretePr>\");\n }\n // groupItems (CT_GroupItems)\n if (fg.groupItems && fg.groupItems.length > 0) {\n fgParts.push(`<groupItems count=\"${fg.groupItems.length}\">`);\n for (const gi of fg.groupItems) {\n fgParts.push(`<s v=\"${escapeXml(gi)}\"/>`);\n }\n fgParts.push(\"</groupItems>\");\n }\n fgParts.push(\"</fieldGroup>\");\n p.push(fgParts.join(\"\"));\n }\n\n p.push(\"</cacheField>\");\n }\n }\n\n p.push(\"</cacheFields>\");\n\n // mpMap elements — rendered once outside cacheFields (CT_PivotCacheDefinition sequence)\n if (this.cacheDefOpts?.mpMaps) {\n for (const mp of this.cacheDefOpts.mpMaps) {\n p.push(`<mpMap x=\"${mp.x}\"/>`);\n }\n }\n\n // olapPr (optional)\n if (this.olapPr) {\n const olAttrs: string[] = [];\n if (this.olapPr.local) olAttrs.push(` local=\"${escapeXml(this.olapPr.local)}\"`);\n if (this.olapPr.localConnection)\n olAttrs.push(` localConnection=\"${escapeXml(this.olapPr.localConnection)}\"`);\n if (this.olapPr.sendLocale) olAttrs.push(` sendLocale=\"1\"`);\n if (this.olapPr.rowDrillCount !== undefined)\n olAttrs.push(` rowDrillCount=\"${this.olapPr.rowDrillCount}\"`);\n if (this.olapPr.colDrillCount !== undefined)\n olAttrs.push(` colDrillCount=\"${this.olapPr.colDrillCount}\"`);\n if (this.olapPr.localRefresh) olAttrs.push(' localRefresh=\"1\"');\n if (this.olapPr.serverFill === false) olAttrs.push(' serverFill=\"0\"');\n if (this.olapPr.serverNumberFormat === false) olAttrs.push(' serverNumberFormat=\"0\"');\n if (this.olapPr.serverFont === false) olAttrs.push(' serverFont=\"0\"');\n if (this.olapPr.serverFontColor === false) olAttrs.push(' serverFontColor=\"0\"');\n if (olAttrs.length > 0) {\n p.push(`<olapPr${olAttrs.join(\"\")}/>`);\n }\n }\n\n // cacheHierarchies (optional)\n if (this.cacheDefOpts?.cacheHierarchies && this.cacheDefOpts.cacheHierarchies.length > 0) {\n const chs = this.cacheDefOpts.cacheHierarchies;\n p.push(`<cacheHierarchies count=\"${chs.length}\">`);\n for (const ch of chs) {\n const chAttrs: string[] = [\n `uniqueName=\"${escapeXml(ch.uniqueName)}\"`,\n `count=\"${ch.count}\"`,\n ];\n if (ch.caption) chAttrs.push(`caption=\"${escapeXml(ch.caption)}\"`);\n if (ch.measure) chAttrs.push('measure=\"1\"');\n if (ch.set) chAttrs.push('set=\"1\"');\n if (ch.parentSet !== undefined) chAttrs.push(`parentSet=\"${ch.parentSet}\"`);\n if (ch.iconSet !== undefined && ch.iconSet !== 0) chAttrs.push(`iconSet=\"${ch.iconSet}\"`);\n if (ch.attribute) chAttrs.push('attribute=\"1\"');\n if (ch.time) chAttrs.push('time=\"1\"');\n if (ch.keyAttribute) chAttrs.push('keyAttribute=\"1\"');\n if (ch.defaultMemberUniqueName)\n chAttrs.push(`defaultMemberUniqueName=\"${escapeXml(ch.defaultMemberUniqueName)}\"`);\n if (ch.allUniqueName) chAttrs.push(`allUniqueName=\"${escapeXml(ch.allUniqueName)}\"`);\n if (ch.allCaption) chAttrs.push(`allCaption=\"${escapeXml(ch.allCaption)}\"`);\n if (ch.dimensionUniqueName)\n chAttrs.push(`dimensionUniqueName=\"${escapeXml(ch.dimensionUniqueName)}\"`);\n if (ch.displayFolder) chAttrs.push(`displayFolder=\"${escapeXml(ch.displayFolder)}\"`);\n if (ch.measureGroup) chAttrs.push(`measureGroup=\"${escapeXml(ch.measureGroup)}\"`);\n if (ch.measures) chAttrs.push('measures=\"1\"');\n if (ch.oneField) chAttrs.push('oneField=\"1\"');\n if (ch.hidden) chAttrs.push('hidden=\"1\"');\n\n // groupLevels and fieldsUsage (optional children)\n const hasGroupLevels = ch.groupLevels && ch.groupLevels.length > 0;\n const hasFieldsUsage = ch.fieldsUsage && ch.fieldsUsage.length > 0;\n\n if (hasGroupLevels || hasFieldsUsage) {\n p.push(`<cacheHierarchy ${chAttrs.join(\" \")}>`);\n // fieldsUsage (CT_FieldsUsage)\n if (hasFieldsUsage) {\n const fuParts = [`<fieldsUsage count=\"${ch.fieldsUsage!.length}\">`];\n for (const fu of ch.fieldsUsage!) {\n fuParts.push(`<fieldUsage v=\"${fu.value}\"/>`);\n }\n fuParts.push(\"</fieldsUsage>\");\n p.push(fuParts.join(\"\"));\n }\n // groupLevels (CT_GroupLevels)\n if (hasGroupLevels) {\n const glParts = [`<groupLevels count=\"${ch.groupLevels!.length}\">`];\n for (const gl of ch.groupLevels!) {\n const glAttrs = [\n `uniqueName=\"${escapeXml(gl.uniqueName)}\"`,\n `caption=\"${escapeXml(gl.caption)}\"`,\n ];\n if (gl.user) glAttrs.push('user=\"1\"');\n if (gl.customRollUp) glAttrs.push('customRollUp=\"1\"');\n if (gl.groups && gl.groups.length > 0) {\n glParts.push(\n `<groupLevel ${glAttrs.join(\" \")}><groups count=\"${gl.groups.length}\">`,\n );\n for (const lg of gl.groups) {\n const lgAttrs = [\n `name=\"${escapeXml(lg.name)}\"`,\n `uniqueName=\"${escapeXml(lg.uniqueName)}\"`,\n `caption=\"${escapeXml(lg.caption)}\"`,\n ];\n if (lg.uniqueParent) lgAttrs.push(`uniqueParent=\"${escapeXml(lg.uniqueParent)}\"`);\n if (lg.id !== undefined) lgAttrs.push(`id=\"${lg.id}\"`);\n glParts.push(\n `<group ${lgAttrs.join(\" \")}><groupMembers count=\"${lg.members.length}\">`,\n );\n for (const gm of lg.members) {\n const gmAttrs = [`uniqueName=\"${escapeXml(gm.uniqueName)}\"`];\n if (gm.group) gmAttrs.push('group=\"1\"');\n glParts.push(`<groupMember ${gmAttrs.join(\" \")}/>`);\n }\n glParts.push(\"</groupMembers></group>\");\n }\n glParts.push(\"</groups></groupLevel>\");\n } else {\n glParts.push(`<groupLevel ${glAttrs.join(\" \")}/>`);\n }\n }\n glParts.push(\"</groupLevels>\");\n p.push(glParts.join(\"\"));\n }\n p.push(\"</cacheHierarchy>\");\n } else {\n p.push(`<cacheHierarchy ${chAttrs.join(\" \")}/>`);\n }\n }\n p.push(\"</cacheHierarchies>\");\n }\n\n // kpis (optional)\n if (this.cacheDefOpts?.kpis && this.cacheDefOpts.kpis.length > 0) {\n const kpis = this.cacheDefOpts.kpis;\n p.push(`<kpis count=\"${kpis.length}\">`);\n for (const k of kpis) {\n const kAttrs: string[] = [\n `uniqueName=\"${escapeXml(k.uniqueName)}\"`,\n `value=\"${escapeXml(k.value)}\"`,\n ];\n if (k.caption) kAttrs.push(`caption=\"${escapeXml(k.caption)}\"`);\n if (k.displayFolder) kAttrs.push(`displayFolder=\"${escapeXml(k.displayFolder)}\"`);\n if (k.measureGroup) kAttrs.push(`measureGroup=\"${escapeXml(k.measureGroup)}\"`);\n if (k.parent) kAttrs.push(`parent=\"${escapeXml(k.parent)}\"`);\n if (k.goal) kAttrs.push(`goal=\"${escapeXml(k.goal)}\"`);\n if (k.status) kAttrs.push(`status=\"${escapeXml(k.status)}\"`);\n if (k.trend) kAttrs.push(`trend=\"${escapeXml(k.trend)}\"`);\n if (k.weight) kAttrs.push(`weight=\"${escapeXml(k.weight)}\"`);\n if (k.time) kAttrs.push(`time=\"${escapeXml(k.time)}\"`);\n p.push(`<kpi ${kAttrs.join(\" \")}/>`);\n }\n p.push(\"</kpis>\");\n }\n\n // measureGroups (optional)\n if (this.cacheDefOpts?.measureGroups && this.cacheDefOpts.measureGroups.length > 0) {\n const mgs = this.cacheDefOpts.measureGroups;\n p.push(`<measureGroups count=\"${mgs.length}\">`);\n for (const mg of mgs) {\n p.push(`<measureGroup name=\"${escapeXml(mg.name)}\" caption=\"${escapeXml(mg.caption)}\"/>`);\n }\n p.push(\"</measureGroups>\");\n }\n\n // maps (CT_MeasureDimensionMaps, after measureGroups per XSD)\n if (\n this.cacheDefOpts?.measureDimensionMaps &&\n this.cacheDefOpts.measureDimensionMaps.length > 0\n ) {\n const mdm = this.cacheDefOpts.measureDimensionMaps;\n p.push(`<maps count=\"${mdm.length}\">`);\n for (const m of mdm) {\n const mAttrs: string[] = [];\n if (m.measureGroup !== undefined) mAttrs.push(`measureGroup=\"${m.measureGroup}\"`);\n if (m.dimension !== undefined) mAttrs.push(`dimension=\"${m.dimension}\"`);\n p.push(`<map ${mAttrs.join(\" \")}/>`);\n }\n p.push(\"</maps>\");\n }\n\n // dimensions (optional)\n if (this.cacheDefOpts?.dimensions && this.cacheDefOpts.dimensions.length > 0) {\n const dims = this.cacheDefOpts.dimensions;\n p.push(`<dimensions count=\"${dims.length}\">`);\n for (const d of dims) {\n const dAttrs: string[] = [\n `name=\"${escapeXml(d.name)}\"`,\n `uniqueName=\"${escapeXml(d.uniqueName)}\"`,\n `caption=\"${escapeXml(d.caption)}\"`,\n ];\n if (d.measure) dAttrs.push('measure=\"1\"');\n p.push(`<dimension ${dAttrs.join(\" \")}/>`); // XSD uses \"dimension\" not \"dimensions\" for individual items\n }\n p.push(\"</dimensions>\");\n }\n\n // tupleCache with entries, sets and serverFormats (optional)\n const cd = this.cacheDefOpts;\n const hasEntries = cd?.entries && cd.entries.length > 0;\n const hasSets = cd?.sets && cd.sets.length > 0;\n const hasServerFormats = cd?.serverFormats && cd.serverFormats.length > 0;\n const hasQueryCache = cd?.queryCache && cd.queryCache.length > 0;\n if (hasEntries || hasSets || hasServerFormats || hasQueryCache) {\n p.push(\"<tupleCache>\");\n // entries (CT_PCDSDTCEntries)\n if (hasEntries) {\n const entParts: string[] = [`<entries count=\"${cd!.entries!.length}\">`];\n for (const ent of cd!.entries!) {\n if (ent.type === \"m\") {\n entParts.push(\"<m/>\");\n } else if (ent.type === \"e\" && ent.value !== undefined) {\n entParts.push(`<e v=\"${ent.value}\"/>`);\n } else if (ent.value !== undefined) {\n entParts.push(`<${ent.type} v=\"${ent.value}\"/>`);\n }\n }\n entParts.push(\"</entries>\");\n p.push(entParts.join(\"\"));\n }\n if (hasSets) {\n p.push(`<sets count=\"${cd!.sets!.length}\">`);\n for (const s of cd!.sets!) {\n const sAttrs: string[] = [\n `maxRank=\"${s.maxRank}\"`,\n `setDefinition=\"${escapeXml(s.setDefinition)}\"`,\n ];\n if (s.count !== undefined) sAttrs.push(`count=\"${s.count}\"`);\n if (s.sortType && s.sortType !== \"none\") sAttrs.push(`sortType=\"${s.sortType}\"`);\n if (s.queryFailed) sAttrs.push('queryFailed=\"1\"');\n p.push(`<set ${sAttrs.join(\" \")}/>`);\n }\n p.push(\"</sets>\");\n }\n if (hasServerFormats) {\n p.push(`<serverFormats count=\"${cd!.serverFormats!.length}\">`);\n for (const sf of cd!.serverFormats!) {\n const sfAttrs: string[] = [];\n if (sf.culture) sfAttrs.push(`culture=\"${escapeXml(sf.culture)}\"`);\n if (sf.format) sfAttrs.push(`format=\"${escapeXml(sf.format)}\"`);\n p.push(`<serverFormat ${sfAttrs.join(\" \")}/>`);\n }\n p.push(\"</serverFormats>\");\n }\n // queryCache (CT_QueryCache)\n if (hasQueryCache) {\n const qc = cd!.queryCache!;\n p.push(`<queryCache count=\"${qc.length}\">`);\n for (const q of qc) {\n let qInner = \"\";\n if (q.tpls && q.tpls.length > 0) {\n qInner = `<tpls count=\"${q.tpls.length}\">`;\n for (const tpl of q.tpls) {\n if (tpl.items && tpl.items.length > 0) {\n qInner += `<tpl>${tpl.items.map((i) => `<x v=\"${i}\"/>`).join(\"\")}</tpl>`;\n } else {\n qInner += \"<tpl/>\";\n }\n }\n qInner += \"</tpls>\";\n }\n if (qInner) {\n p.push(`<query mdx=\"${escapeXml(q.mdx)}\">${qInner}</query>`);\n } else {\n p.push(`<query mdx=\"${escapeXml(q.mdx)}\"/>`);\n }\n }\n p.push(\"</queryCache>\");\n }\n\n p.push(\"</tupleCache>\");\n }\n\n p.push(\"</pivotCacheDefinition>\");\n\n return p.join(\"\");\n }\n}\n","/**\n * PivotCacheRecords XML generator.\n *\n * Generates xl/pivotCache/pivotCacheRecords{N}.xml.\n * Follows CT_PivotCacheRecords from sml.xsd.\n *\n * @module\n */\nimport { BaseXmlComponent } from \"@file/xml-components\";\nimport type { Context } from \"@file/xml-components\";\n\nimport type { PivotSourceData } from \"./pivot-utils\";\nimport { collectUniqueValues, isNumericField } from \"./pivot-utils\";\n\nexport class PivotCacheRecordsXml extends BaseXmlComponent {\n private readonly sourceData: PivotSourceData;\n private readonly numericFields: readonly boolean[];\n /** For string fields: value → sharedItems index */\n private readonly fieldIndexMaps: readonly Map<string, number>[];\n\n public constructor(sourceData: PivotSourceData) {\n super(\"pivotCacheRecords\");\n this.sourceData = sourceData;\n this.numericFields = sourceData.fieldNames.map((_, i) => isNumericField(sourceData.records, i));\n this.fieldIndexMaps = sourceData.fieldNames.map((_, i) => {\n if (this.numericFields[i]) return new Map<string, number>();\n const unique = collectUniqueValues(sourceData.records, i);\n const map = new Map<string, number>();\n for (let j = 0; j < unique.length; j++) {\n map.set(String(unique[j]), j);\n }\n return map;\n });\n }\n\n public override toXml(_context: Context): string {\n const p: string[] = [];\n\n p.push(\n '<pivotCacheRecords xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\"' +\n ` count=\"${this.sourceData.records.length}\">`,\n );\n\n for (const row of this.sourceData.records) {\n p.push(\"<r>\");\n for (let i = 0; i < row.length; i++) {\n const val = row[i];\n if (val === null) {\n p.push(\"<m/>\");\n } else if (val instanceof Date) {\n p.push(`<d v=\"${val.toISOString().replace(/\\.\\d{3}Z$/, \"Z\")}\"/>`);\n } else if (this.numericFields[i]) {\n p.push(`<n v=\"${val}\"/>`);\n } else {\n const idx = this.fieldIndexMaps[i].get(String(val)) ?? 0;\n p.push(`<x v=\"${idx}\"/>`);\n }\n }\n p.push(\"</r>\");\n }\n\n p.push(\"</pivotCacheRecords>\");\n return p.join(\"\");\n }\n}\n","/**\n * PivotTableDefinition XML generator.\n *\n * Generates xl/pivotTables/pivotTable{N}.xml.\n * Follows CT_pivotTableDefinition from sml.xsd.\n *\n * @module\n */\nimport { BaseXmlComponent } from \"@file/xml-components\";\nimport type { Context } from \"@file/xml-components\";\nimport { attrs, escapeXml } from \"@office-open/xml\";\n\nimport type { PivotSourceData } from \"./pivot-utils\";\nimport type {\n PivotTableOptions,\n PivotDataField,\n PivotFilterOptions,\n CalculatedItemOptions,\n CalculatedMemberOptions,\n PivotHierarchyOptions,\n PivotConditionalFormatOptions,\n ChartFormatOptions,\n PivotAreaOptions,\n} from \"./pivot-utils\";\nimport { collectUniqueValues } from \"./pivot-utils\";\n\nexport class PivotTableXml extends BaseXmlComponent {\n private readonly options: PivotTableOptions;\n private readonly sourceData: PivotSourceData;\n private readonly cacheId: number;\n\n public constructor(options: PivotTableOptions, sourceData: PivotSourceData, cacheId: number) {\n super(\"pivotTableDefinition\");\n this.options = options;\n this.sourceData = sourceData;\n this.cacheId = cacheId;\n }\n\n public override toXml(_context: Context): string {\n const o = this.options;\n const sd = this.sourceData;\n const fields = sd.fieldNames;\n const rowFieldNames = o.rows;\n const colFieldNames = o.columns ?? [];\n const dataFields = o.data;\n const style = o.style ?? \"PivotStyleLight16\";\n const location = o.location ?? \"A3\";\n const name = o.name ?? \"PivotTable1\";\n\n // Compute field indices\n const rowFieldIndices = rowFieldNames.map((n) => fields.indexOf(n));\n const colFieldIndices = colFieldNames.map((n) => fields.indexOf(n));\n const dataFieldIndices = dataFields.map((df) => fields.indexOf(df.field));\n const pageFieldNames = o.pages ?? [];\n const pageFieldIndices = pageFieldNames.map((n) => fields.indexOf(n));\n\n // Build pivotFields\n const pivotFieldsXml = this.buildPivotFields(\n rowFieldIndices,\n colFieldIndices,\n dataFieldIndices,\n pageFieldIndices,\n );\n\n // Build pageFields (if any)\n const pageFieldsXml = this.buildPageFields(pageFieldIndices);\n\n // Build rowFields + rowItems\n const rowFieldsXml = this.buildRowFields(rowFieldIndices);\n const rowItemsXml = this.buildRowItems(rowFieldIndices);\n\n // Build colFields + colItems\n const colFieldsXml = this.buildColFields(colFieldIndices);\n const colItemsXml = this.buildColItems(colFieldIndices, dataFields);\n\n // Build dataFields\n const dataFieldsXml = this.buildDataFields(dataFields, dataFieldIndices);\n\n // Compute location ref\n const locationRef = this.computeLocationRef(\n location,\n rowFieldIndices,\n colFieldIndices,\n dataFields,\n );\n\n const p: string[] = [];\n const defAttrs: string[] = [\n `name=\"${escapeXml(name)}\"`,\n `cacheId=\"${this.cacheId}\"`,\n 'dataCaption=\"Values\"',\n 'updatedVersion=\"6\"',\n 'minRefreshableVersion=\"3\"',\n 'createdVersion=\"6\"',\n 'applyNumberFormats=\"0\"',\n 'applyBorderFormats=\"0\"',\n 'applyFontFormats=\"0\"',\n 'applyPatternFormats=\"0\"',\n 'applyAlignmentFormats=\"0\"',\n 'applyWidthHeightFormats=\"1\"',\n 'autoFormatId=\"0\"',\n 'useAutoFormatting=\"1\"',\n 'itemPrintTitles=\"1\"',\n 'indent=\"0\"',\n 'outline=\"1\"',\n 'outlineData=\"1\"',\n 'compact=\"1\"',\n 'compactData=\"1\"',\n 'rowGrandTotals=\"1\"',\n 'colGrandTotals=\"1\"',\n ];\n // Optional pivot table definition attributes\n if (o.dataOnRows) defAttrs.push('dataOnRows=\"1\"');\n if (o.grandTotalCaption) defAttrs.push(`grandTotalCaption=\"${escapeXml(o.grandTotalCaption)}\"`);\n if (o.errorCaption) defAttrs.push(`errorCaption=\"${escapeXml(o.errorCaption)}\"`);\n if (o.showError) defAttrs.push('showError=\"1\"');\n if (o.missingCaption) defAttrs.push(`missingCaption=\"${escapeXml(o.missingCaption)}\"`);\n if (o.showMissing === false) defAttrs.push('showMissing=\"0\"');\n if (o.pageStyle) defAttrs.push(`pageStyle=\"${escapeXml(o.pageStyle)}\"`);\n if (o.pivotTableStyle) defAttrs.push(`pivotTableStyle=\"${escapeXml(o.pivotTableStyle)}\"`);\n if (o.tag) defAttrs.push(`tag=\"${escapeXml(o.tag)}\"`);\n if (o.showItems === false) defAttrs.push('showItems=\"0\"');\n if (o.editData) defAttrs.push('editData=\"1\"');\n if (o.disableFieldList) defAttrs.push('disableFieldList=\"1\"');\n if (o.showCalcMbrs === false) defAttrs.push('showCalcMbrs=\"0\"');\n if (o.visualTotals) defAttrs.push('visualTotals=\"1\"');\n if (o.showMultipleLabel === false) defAttrs.push('showMultipleLabel=\"0\"');\n if (o.showDataDropDown === false) defAttrs.push('showDataDropDown=\"0\"');\n if (o.showDrill === false) defAttrs.push('showDrill=\"0\"');\n if (o.printDrill) defAttrs.push('printDrill=\"1\"');\n if (o.showMemberPropertyTips) defAttrs.push('showMemberPropertyTips=\"1\"');\n if (o.showDataTips === false) defAttrs.push('showDataTips=\"0\"');\n if (o.enableWizard === false) defAttrs.push('enableWizard=\"0\"');\n if (o.enableDrill === false) defAttrs.push('enableDrill=\"0\"');\n if (o.enableFieldProperties === false) defAttrs.push('enableFieldProperties=\"0\"');\n if (o.pageWrap !== undefined) defAttrs.push(`pageWrap=\"${o.pageWrap}\"`);\n if (o.pageOverThenDown) defAttrs.push('pageOverThenDown=\"1\"');\n if (o.subtotalHiddenItems) defAttrs.push('subtotalHiddenItems=\"1\"');\n if (o.fieldPrintTitles) defAttrs.push('fieldPrintTitles=\"1\"');\n if (o.mergeItem) defAttrs.push('mergeItem=\"1\"');\n if (o.showDropZones === false) defAttrs.push('showDropZones=\"0\"');\n if (o.showEmptyRow) defAttrs.push('showEmptyRow=\"1\"');\n if (o.showEmptyCol) defAttrs.push('showEmptyCol=\"1\"');\n if (o.showHeaders === false) defAttrs.push('showHeaders=\"0\"');\n if (o.published) defAttrs.push('published=\"1\"');\n if (o.gridDropZones === false) defAttrs.push('gridDropZones=\"0\"');\n if (o.multipleFieldFilters === false) defAttrs.push('multipleFieldFilters=\"0\"');\n if (o.rowHeaderCaption) defAttrs.push(`rowHeaderCaption=\"${escapeXml(o.rowHeaderCaption)}\"`);\n if (o.colHeaderCaption) defAttrs.push(`colHeaderCaption=\"${escapeXml(o.colHeaderCaption)}\"`);\n if (o.fieldListSortAscending) defAttrs.push('fieldListSortAscending=\"1\"');\n if (o.mdxSubqueries) defAttrs.push('mdxSubqueries=\"1\"');\n if (o.customListSort === false) defAttrs.push('customListSort=\"0\"');\n\n p.push(\n `<pivotTableDefinition xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\" ${defAttrs.join(\" \")}>`,\n );\n\n // location\n p.push(\n `<location ref=\"${escapeXml(locationRef)}\" firstHeaderRow=\"1\" firstDataRow=\"${colFieldIndices.length + 1}\" firstDataCol=\"${rowFieldIndices.length}\"/>`,\n );\n\n // pivotFields\n p.push(pivotFieldsXml);\n\n // pivotHierarchies (after pivotFields per XSD sequence)\n if (o.pivotHierarchies && o.pivotHierarchies.length > 0) {\n p.push(this.buildPivotHierarchies(o.pivotHierarchies));\n }\n\n // pageFields (before rowFields per XSD sequence)\n if (pageFieldIndices.length > 0) {\n p.push(pageFieldsXml);\n }\n\n // rowFields\n p.push(rowFieldsXml);\n\n // rowItems\n p.push(rowItemsXml);\n\n // colFields (only when column fields exist)\n if (colFieldIndices.length > 0) {\n p.push(colFieldsXml);\n }\n\n // colItems (always present)\n p.push(colItemsXml);\n\n // dataFields\n if (dataFields.length > 0) {\n p.push(dataFieldsXml);\n }\n\n // style\n p.push(\n `<pivotTableStyleInfo name=\"${escapeXml(style)}\" showRowHeaders=\"1\" showColHeaders=\"1\" showRowStripes=\"0\" showColStripes=\"0\" showLastColumn=\"1\"/>`,\n );\n\n // filters (after pivotTableStyleInfo per XSD sequence)\n if (o.filters && o.filters.length > 0) {\n p.push(this.buildFilters(o.filters));\n }\n\n // calculatedItems (after filters per XSD sequence)\n if (o.calculatedItems && o.calculatedItems.length > 0) {\n p.push(this.buildCalculatedItems(o.calculatedItems));\n }\n\n // calculatedMembers\n if (o.calculatedMembers && o.calculatedMembers.length > 0) {\n p.push(this.buildCalculatedMembers(o.calculatedMembers));\n }\n\n // formats (CT_Formats, after dataFields per XSD sequence)\n if (o.formats && o.formats.length > 0) {\n const fmtParts: string[] = [`<formats count=\"${o.formats.length}\">`];\n for (const fmt of o.formats) {\n const fmtAttrs: string[] = [];\n if (fmt.action && fmt.action !== \"formatting\") fmtAttrs.push(`action=\"${fmt.action}\"`);\n if (fmt.dxfId !== undefined) fmtAttrs.push(`dxfId=\"${fmt.dxfId}\"`);\n fmtParts.push(\n `<format${fmtAttrs.length ? \" \" + fmtAttrs.join(\" \") : \"\"}>${this.buildPivotAreaXml(fmt.pivotArea)}</format>`,\n );\n }\n fmtParts.push(\"</formats>\");\n p.push(fmtParts.join(\"\"));\n }\n\n // conditionalFormats (pivot-specific)\n if (o.pivotConditionalFormats && o.pivotConditionalFormats.length > 0) {\n p.push(this.buildPivotConditionalFormats(o.pivotConditionalFormats));\n }\n\n // chartFormats\n if (o.chartFormats && o.chartFormats.length > 0) {\n p.push(this.buildChartFormats(o.chartFormats));\n }\n\n // rowHierarchiesUsage (CT_RowHierarchiesUsage)\n if (o.rowHierarchiesUsage && o.rowHierarchiesUsage.length > 0) {\n const rhu = o.rowHierarchiesUsage;\n p.push(\n `<rowHierarchiesUsage count=\"${rhu.length}\">${rhu.map((h) => `<rowHierarchyUsage hierarchyUsage=\"${h.hierarchyUsage}\"/>`).join(\"\")}</rowHierarchiesUsage>`,\n );\n }\n\n // colHierarchiesUsage (CT_ColHierarchiesUsage)\n if (o.colHierarchiesUsage && o.colHierarchiesUsage.length > 0) {\n const chu = o.colHierarchiesUsage;\n p.push(\n `<colHierarchiesUsage count=\"${chu.length}\">${chu.map((h) => `<colHierarchyUsage hierarchyUsage=\"${h.hierarchyUsage}\"/>`).join(\"\")}</colHierarchiesUsage>`,\n );\n }\n\n p.push(\"</pivotTableDefinition>\");\n return p.join(\"\");\n }\n\n private buildPivotFields(\n rowIndices: readonly number[],\n colIndices: readonly number[],\n dataIndices: readonly number[],\n pageIndices: readonly number[],\n ): string {\n const fields = this.sourceData.fieldNames;\n const o = this.options;\n const parts: string[] = [`<pivotFields count=\"${fields.length}\">`];\n\n for (let i = 0; i < fields.length; i++) {\n const isRow = rowIndices.includes(i);\n const isCol = colIndices.includes(i);\n const isData = dataIndices.includes(i);\n const isPage = pageIndices.includes(i);\n\n if (isData) {\n const dataFieldIdx = dataIndices.indexOf(i);\n const df = o.data[dataFieldIdx];\n const dfAttrs: string[] = ['dataField=\"1\"', 'showAll=\"0\"'];\n if (df?.showDataAs) dfAttrs.push(`showDataAs=\"${df.showDataAs}\"`);\n if (df?.baseField !== undefined) dfAttrs.push(`baseField=\"${df.baseField}\"`);\n if (df?.baseItem !== undefined) dfAttrs.push(`baseItem=\"${df.baseItem}\"`);\n // autoSortScope for data fields\n if (o.autoSortScope || (df?.sortByTupleItems && df.sortByTupleItems.length > 0)) {\n const scopeChildren: string[] = [];\n if (o.autoSortScope) {\n scopeChildren.push(this.buildPivotAreaXml(o.autoSortScope));\n }\n if (df?.sortByTupleItems && df.sortByTupleItems.length > 0) {\n const tplXml = df.sortByTupleItems.map((v) => `<tpl><x v=\"${v}\"/></tpl>`).join(\"\");\n scopeChildren.push(`<sortByTuple>${tplXml}</sortByTuple>`);\n }\n parts.push(\n `<pivotField ${dfAttrs.join(\" \")}><autoSortScope>${scopeChildren.join(\"\")}</autoSortScope></pivotField>`,\n );\n } else {\n parts.push(`<pivotField ${dfAttrs.join(\" \")}/>`);\n }\n } else if (isRow) {\n const uniqueVals = collectUniqueValues(this.sourceData.records, i);\n parts.push(`<pivotField axis=\"axisRow\" showAll=\"0\">`);\n parts.push(`<items count=\"${uniqueVals.length + 1}\">`);\n for (let j = 0; j < uniqueVals.length; j++) {\n parts.push(`<item x=\"${j}\"/>`);\n }\n parts.push(`<item t=\"default\"/>`);\n parts.push(\"</items></pivotField>\");\n } else if (isCol) {\n const uniqueVals = collectUniqueValues(this.sourceData.records, i);\n parts.push(`<pivotField axis=\"axisCol\" showAll=\"0\">`);\n parts.push(`<items count=\"${uniqueVals.length + 1}\">`);\n for (let j = 0; j < uniqueVals.length; j++) {\n parts.push(`<item x=\"${j}\"/>`);\n }\n parts.push(`<item t=\"default\"/>`);\n parts.push(\"</items></pivotField>\");\n } else if (isPage) {\n const uniqueVals = collectUniqueValues(this.sourceData.records, i);\n parts.push(`<pivotField axis=\"axisPage\" showAll=\"0\">`);\n parts.push(`<items count=\"${uniqueVals.length + 1}\">`);\n for (let j = 0; j < uniqueVals.length; j++) {\n parts.push(`<item x=\"${j}\"/>`);\n }\n parts.push(`<item t=\"default\"/>`);\n parts.push(\"</items></pivotField>\");\n } else {\n parts.push(`<pivotField showAll=\"0\"/>`);\n }\n }\n\n parts.push(\"</pivotFields>\");\n return parts.join(\"\");\n }\n\n private buildPageFields(pageIndices: readonly number[]): string {\n if (pageIndices.length === 0) return \"\";\n const parts: string[] = [`<pageFields count=\"${pageIndices.length}\">`];\n for (let i = 0; i < pageIndices.length; i++) {\n parts.push(`<pageField fld=\"${pageIndices[i]}\" hier=\"${i}\"/>`);\n }\n parts.push(\"</pageFields>\");\n return parts.join(\"\");\n }\n\n private buildRowFields(rowIndices: readonly number[]): string {\n if (rowIndices.length === 0) return '<rowFields count=\"0\"/>';\n const parts: string[] = [`<rowFields count=\"${rowIndices.length}\">`];\n for (const idx of rowIndices) {\n parts.push(`<field x=\"${idx}\"/>`);\n }\n parts.push(\"</rowFields>\");\n return parts.join(\"\");\n }\n\n private buildRowItems(rowIndices: readonly number[]): string {\n if (rowIndices.length === 0) return '<rowItems count=\"1\"><i/></rowItems>';\n\n const allUniqueCounts: number[] = [];\n for (const idx of rowIndices) {\n const vals = collectUniqueValues(this.sourceData.records, idx);\n allUniqueCounts.push(vals.length);\n }\n\n // Simple case: single row field\n if (rowIndices.length === 1) {\n const count = allUniqueCounts[0];\n const parts: string[] = [`<rowItems count=\"${count + 1}\">`];\n for (let i = 0; i < count; i++) {\n parts.push(`<i><x v=\"${i}\"/></i>`);\n }\n parts.push(`<i t=\"grand\"><x/></i>`);\n parts.push(\"</rowItems>\");\n return parts.join(\"\");\n }\n\n // Multi-field: build cartesian product indices\n const combos = cartesianOfCounts(allUniqueCounts);\n const rowItems: string[] = [];\n for (const combo of combos) {\n const xParts = combo.map((v) => `<x v=\"${v}\"/>`).join(\"\");\n rowItems.push(`<i>${xParts}</i>`);\n }\n // Grand total\n rowItems.push(`<i t=\"grand\">${rowIndices.map(() => \"<x/>\").join(\"\")}</i>`);\n\n return `<rowItems count=\"${rowItems.length}\">${rowItems.join(\"\")}</rowItems>`;\n }\n\n private buildColFields(colIndices: readonly number[]): string {\n if (colIndices.length === 0) return '<colFields count=\"0\"/>';\n const parts: string[] = [`<colFields count=\"${colIndices.length}\">`];\n for (const idx of colIndices) {\n parts.push(`<field x=\"${idx}\"/>`);\n }\n parts.push(\"</colFields>\");\n return parts.join(\"\");\n }\n\n private buildColItems(\n colIndices: readonly number[],\n dataFields: readonly PivotDataField[],\n ): string {\n if (colIndices.length > 0) {\n const allUniqueCounts: number[] = [];\n for (const idx of colIndices) {\n const vals = collectUniqueValues(this.sourceData.records, idx);\n allUniqueCounts.push(vals.length);\n }\n\n const combos = cartesianOfCounts(allUniqueCounts);\n const items: string[] = [];\n for (const combo of combos) {\n const xParts = combo.map((v) => `<x v=\"${v}\"/>`).join(\"\");\n items.push(`<i>${xParts}</i>`);\n }\n items.push(`<i t=\"grand\">${colIndices.map(() => \"<x/>\").join(\"\")}</i>`);\n return `<colItems count=\"${items.length}\">${items.join(\"\")}</colItems>`;\n }\n\n // No column fields: if multiple data fields, each becomes a column\n if (dataFields.length > 1) {\n const items = dataFields.map((_, i) => `<i><x v=\"${i}\"/></i>`);\n return `<colItems count=\"${items.length}\">${items.join(\"\")}</colItems>`;\n }\n\n // Single or no data fields, no column fields\n return '<colItems count=\"1\"><i/></colItems>';\n }\n\n private buildDataFields(\n dataFields: readonly PivotDataField[],\n dataFieldIndices: readonly number[],\n ): string {\n if (dataFields.length === 0) return '<dataFields count=\"0\"/>';\n const parts: string[] = [`<dataFields count=\"${dataFields.length}\">`];\n for (let i = 0; i < dataFields.length; i++) {\n const df = dataFields[i];\n const subtotal = df.summarize ?? \"sum\";\n const name = df.name ?? `${subtotal === \"sum\" ? \"Sum\" : subtotal} of ${df.field}`;\n const dfAttrs: string[] = [\n `name=\"${escapeXml(name)}\"`,\n `fld=\"${dataFieldIndices[i]}\"`,\n `subtotal=\"${subtotal}\"`,\n ];\n if (df.showDataAs) dfAttrs.push(`showDataAs=\"${df.showDataAs}\"`);\n if (df.baseField !== undefined) dfAttrs.push(`baseField=\"${df.baseField}\"`);\n if (df.baseItem !== undefined) dfAttrs.push(`baseItem=\"${df.baseItem}\"`);\n parts.push(`<dataField ${dfAttrs.join(\" \")}/>`);\n }\n parts.push(\"</dataFields>\");\n return parts.join(\"\");\n }\n\n private computeLocationRef(\n location: string,\n rowFieldIndices: readonly number[],\n colFieldIndices: readonly number[],\n dataFields: readonly PivotDataField[],\n ): string {\n const startCell = location.split(\":\")[0];\n const match = startCell.match(/^([A-Z]+)(\\d+)$/);\n if (!match) return location;\n\n const startCol = match[1];\n const startRow = parseInt(match[2], 10);\n\n // Count rows: unique row values + header + grand total\n let rowCount = 1; // header\n if (rowFieldIndices.length > 0) {\n rowCount += collectUniqueValues(this.sourceData.records, rowFieldIndices[0]).length;\n }\n rowCount += 1; // grand total\n\n // Count columns: row fields + column values or data fields\n let colCount = Math.max(rowFieldIndices.length, 1);\n if (colFieldIndices.length > 0) {\n colCount += collectUniqueValues(this.sourceData.records, colFieldIndices[0]).length;\n } else if (dataFields.length > 1) {\n colCount += dataFields.length - 1;\n }\n colCount += 1; // grand total column\n\n const endCol = colIndexToLetter(letterToColIndex(startCol) + colCount - 1);\n const endRow = startRow + rowCount - 1;\n\n return `${startCol}${startRow}:${endCol}${endRow}`;\n }\n\n private buildFilters(filters: readonly PivotFilterOptions[]): string {\n const parts: string[] = [`<filters count=\"${filters.length}\">`];\n for (const f of filters) {\n const fAttrs: Record<string, string | number | boolean | undefined> = {\n fld: f.fld,\n type: f.type,\n id: f.id,\n };\n if (f.mpFld !== undefined) fAttrs.mpFld = f.mpFld;\n if (f.evalOrder !== undefined) fAttrs.evalOrder = f.evalOrder;\n if (f.iMeasureHier !== undefined) fAttrs.iMeasureHier = f.iMeasureHier;\n if (f.iMeasureFld !== undefined) fAttrs.iMeasureFld = f.iMeasureFld;\n if (f.name !== undefined) fAttrs.name = f.name;\n if (f.description !== undefined) fAttrs.description = f.description;\n if (f.stringValue1 !== undefined) fAttrs.stringValue1 = f.stringValue1;\n if (f.stringValue2 !== undefined) fAttrs.stringValue2 = f.stringValue2;\n parts.push(`<filter${attrs(fAttrs)}><autoFilter/></filter>`);\n }\n parts.push(\"</filters>\");\n return parts.join(\"\");\n }\n\n private buildPivotHierarchies(hierarchies: readonly PivotHierarchyOptions[]): string {\n const parts: string[] = [`<pivotHierarchies count=\"${hierarchies.length}\">`];\n for (const h of hierarchies) {\n const hAttrs: string[] = [];\n if (h.outline) hAttrs.push('outline=\"1\"');\n if (h.multipleItemSelectionAllowed) hAttrs.push('multipleItemSelectionAllowed=\"1\"');\n if (h.subtotalTop) hAttrs.push('subtotalTop=\"1\"');\n if (h.showInFieldList === false) hAttrs.push('showInFieldList=\"0\"');\n if (h.dragToRow === false) hAttrs.push('dragToRow=\"0\"');\n if (h.dragToCol === false) hAttrs.push('dragToCol=\"0\"');\n if (h.dragToPage === false) hAttrs.push('dragToPage=\"0\"');\n if (h.dragToData) hAttrs.push('dragToData=\"1\"');\n if (h.dragOff === false) hAttrs.push('dragOff=\"0\"');\n if (h.includeNewItemsInFilter) hAttrs.push('includeNewItemsInFilter=\"1\"');\n if (h.caption) hAttrs.push(`caption=\"${escapeXml(h.caption)}\"`);\n const mpsXml = h.memberProperties\n ? `<mps count=\"${h.memberProperties.length}\">${h.memberProperties\n .map((mp) => {\n const mpAttrs: string[] = [`field=\"${mp.field}\"`];\n if (mp.name !== undefined) mpAttrs.push(`name=\"${escapeXml(mp.name)}\"`);\n if (mp.showCell) mpAttrs.push('showCell=\"1\"');\n if (mp.showTip) mpAttrs.push('showTip=\"1\"');\n return `<mp ${mpAttrs.join(\" \")}/>`;\n })\n .join(\"\")}</mps>`\n : \"\";\n const membersXml = h.members\n ? `<members count=\"${h.members.length}\">${h.members.map((m) => `<member name=\"${escapeXml(m.name)}\"/>`).join(\"\")}</members>`\n : \"\";\n const inner = mpsXml + membersXml;\n if (inner) {\n parts.push(`<pivotHierarchy ${hAttrs.join(\" \")}>${inner}</pivotHierarchy>`);\n } else {\n parts.push(`<pivotHierarchy ${hAttrs.join(\" \")}/>`);\n }\n }\n parts.push(\"</pivotHierarchies>\");\n return parts.join(\"\");\n }\n\n private buildCalculatedItems(items: readonly CalculatedItemOptions[]): string {\n const parts: string[] = [`<calculatedItems count=\"${items.length}\">`];\n for (const item of items) {\n const ciAttrs: string[] = [];\n if (item.field !== undefined) ciAttrs.push(`field=\"${item.field}\"`);\n if (item.formula) ciAttrs.push(`formula=\"${escapeXml(item.formula)}\"`);\n const inner = item.pivotArea ? this.buildPivotAreaXml(item.pivotArea) : \"\";\n if (inner) {\n parts.push(`<calculatedItem ${ciAttrs.join(\" \")}>${inner}</calculatedItem>`);\n } else {\n parts.push(`<calculatedItem ${ciAttrs.join(\" \")}/>`);\n }\n }\n parts.push(\"</calculatedItems>\");\n return parts.join(\"\");\n }\n\n private buildCalculatedMembers(members: readonly CalculatedMemberOptions[]): string {\n const parts: string[] = [`<calculatedMembers count=\"${members.length}\">`];\n for (const m of members) {\n const mAttrs: string[] = [`name=\"${escapeXml(m.name)}\"`, `mdx=\"${escapeXml(m.mdx)}\"`];\n if (m.memberName) mAttrs.push(`memberName=\"${escapeXml(m.memberName)}\"`);\n if (m.hierarchy) mAttrs.push(`hierarchy=\"${escapeXml(m.hierarchy)}\"`);\n if (m.parent) mAttrs.push(`parent=\"${escapeXml(m.parent)}\"`);\n if (m.solveOrder !== undefined) mAttrs.push(`solveOrder=\"${m.solveOrder}\"`);\n if (m.set) mAttrs.push('set=\"1\"');\n parts.push(`<calculatedMember ${mAttrs.join(\" \")}/>`);\n }\n parts.push(\"</calculatedMembers>\");\n return parts.join(\"\");\n }\n\n private buildPivotConditionalFormats(formats: readonly PivotConditionalFormatOptions[]): string {\n const parts: string[] = [`<conditionalFormats count=\"${formats.length}\">`];\n for (const cf of formats) {\n const cfAttrs: string[] = [`priority=\"${cf.priority}\"`];\n if (cf.scope && cf.scope !== \"selection\") cfAttrs.push(`scope=\"${cf.scope}\"`);\n if (cf.type && cf.type !== \"none\") cfAttrs.push(`type=\"${cf.type}\"`);\n const areasXml = cf.pivotAreas?.map((a) => this.buildPivotAreaXml(a)).join(\"\") ?? \"\";\n const pivotAreasXml = areasXml ? `<pivotAreas>${areasXml}</pivotAreas>` : \"\";\n parts.push(`<conditionalFormat ${cfAttrs.join(\" \")}>${pivotAreasXml}</conditionalFormat>`);\n }\n parts.push(\"</conditionalFormats>\");\n return parts.join(\"\");\n }\n\n private buildChartFormats(formats: readonly ChartFormatOptions[]): string {\n const parts: string[] = [`<chartFormats count=\"${formats.length}\">`];\n for (const cf of formats) {\n const cfAttrs: string[] = [`chart=\"${cf.chart}\"`, `format=\"${cf.format}\"`];\n if (cf.series) cfAttrs.push('series=\"1\"');\n const areaXml = cf.pivotArea ? this.buildPivotAreaXml(cf.pivotArea) : \"\";\n if (areaXml) {\n parts.push(`<chartFormat ${cfAttrs.join(\" \")}>${areaXml}</chartFormat>`);\n } else {\n parts.push(`<chartFormat ${cfAttrs.join(\" \")}/>`);\n }\n }\n parts.push(\"</chartFormats>\");\n return parts.join(\"\");\n }\n\n private buildPivotAreaXml(area: PivotAreaOptions): string {\n const aAttrs: string[] = [];\n if (area.field !== undefined) aAttrs.push(`field=\"${area.field}\"`);\n if (area.type) aAttrs.push(`type=\"${area.type}\"`);\n if (area.dataOnly === false) aAttrs.push('dataOnly=\"0\"');\n if (area.labelOnly) aAttrs.push('labelOnly=\"1\"');\n if (area.grandRow) aAttrs.push('grandRow=\"1\"');\n if (area.grandCol) aAttrs.push('grandCol=\"1\"');\n if (area.cacheIndex) aAttrs.push('cacheIndex=\"1\"');\n if (area.outline === false) aAttrs.push('outline=\"0\"');\n if (area.offset) aAttrs.push(`offset=\"${escapeXml(area.offset)}\"`);\n if (area.collapsedLevelsAreSubtotals) aAttrs.push('collapsedLevelsAreSubtotals=\"1\"');\n if (area.axis) aAttrs.push(`axis=\"${area.axis}\"`);\n if (area.fieldPosition !== undefined) aAttrs.push(`fieldPosition=\"${area.fieldPosition}\"`);\n const refsXml = area.references ? this.buildPivotAreaReferences(area.references) : \"\";\n if (refsXml) {\n return `<pivotArea ${aAttrs.join(\" \")}>${refsXml}</pivotArea>`;\n }\n return `<pivotArea ${aAttrs.join(\" \")}/>`;\n }\n\n private buildPivotAreaReferences(\n refs: readonly import(\"./pivot-utils\").PivotAreaReferenceOptions[],\n ): string {\n const parts: string[] = [`<references count=\"${refs.length}\">`];\n for (const ref of refs) {\n const rAttrs: string[] = [];\n if (ref.field !== undefined) rAttrs.push(`field=\"${ref.field}\"`);\n if (ref.count !== undefined) rAttrs.push(`count=\"${ref.count}\"`);\n if (ref.selected === false) rAttrs.push('selected=\"0\"');\n if (ref.byPosition) rAttrs.push('byPosition=\"1\"');\n if (ref.relative) rAttrs.push('relative=\"1\"');\n if (ref.defaultSubtotal) rAttrs.push('defaultSubtotal=\"1\"');\n if (ref.sumSubtotal) rAttrs.push('sumSubtotal=\"1\"');\n if (ref.countASubtotal) rAttrs.push('countASubtotal=\"1\"');\n if (ref.avgSubtotal) rAttrs.push('avgSubtotal=\"1\"');\n if (ref.maxSubtotal) rAttrs.push('maxSubtotal=\"1\"');\n if (ref.minSubtotal) rAttrs.push('minSubtotal=\"1\"');\n const xXml = ref.x ? ref.x.map((v) => `<x v=\"${v}\"/>`).join(\"\") : \"\";\n if (xXml) {\n parts.push(`<reference ${rAttrs.join(\" \")}>${xXml}</reference>`);\n } else {\n parts.push(`<reference ${rAttrs.join(\" \")}/>`);\n }\n }\n parts.push(\"</references>\");\n return parts.join(\"\");\n }\n}\n\nfunction letterToColIndex(letters: string): number {\n let col = 0;\n for (let i = 0; i < letters.length; i++) {\n col = col * 26 + (letters.charCodeAt(i) - 64);\n }\n return col;\n}\n\nfunction colIndexToLetter(col: number): string {\n let result = \"\";\n let n = col;\n while (n > 0) {\n n--;\n result = String.fromCharCode(65 + (n % 26)) + result;\n n = Math.floor(n / 26);\n }\n return result;\n}\n\n/** Cartesian product from counts: e.g. [2, 3] → [[0,0],[0,1],[0,2],[1,0],[1,1],[1,2]] */\nfunction cartesianOfCounts(counts: readonly number[]): number[][] {\n if (counts.length === 0) return [[]];\n let result: number[][] = [[]];\n for (const count of counts) {\n const next: number[][] = [];\n for (const prefix of result) {\n for (let i = 0; i < count; i++) {\n next.push([...prefix, i]);\n }\n }\n result = next;\n }\n return result;\n}\n","/**\n * Table XML generator — generates xl/tables/table{n}.xml.\n *\n * Implements CT_Table from sml.xsd (transitional schema).\n *\n * @module\n */\nimport { BaseXmlComponent } from \"@file/xml-components\";\nimport type { Context } from \"@file/xml-components\";\nimport { escapeXml } from \"@office-open/xml\";\n\n// ── Totals row function (ST_TotalsRowFunction) ──\n\nexport const TotalsRowFunction = {\n NONE: \"none\",\n SUM: \"sum\",\n MIN: \"min\",\n MAX: \"max\",\n AVERAGE: \"average\",\n COUNT: \"count\",\n COUNT_NUMS: \"countNums\",\n STD_DEV: \"stdDev\",\n VAR: \"var\",\n CUSTOM: \"custom\",\n} as const;\n\nexport type TotalsRowFunction = (typeof TotalsRowFunction)[keyof typeof TotalsRowFunction];\n\n// ── Table type (ST_TableType) ──\n\nexport const TableType = {\n WORKSHEET: \"worksheet\",\n XML: \"xml\",\n QUERY_TABLE: \"queryTable\",\n} as const;\n\nexport type TableType = (typeof TableType)[keyof typeof TableType];\n\n// ── Options interfaces ──\n\nexport interface TableStyleInfoOptions {\n /** Table style name, e.g. \"TableStyleMedium9\" */\n readonly name?: string;\n readonly showFirstColumn?: boolean;\n readonly showLastColumn?: boolean;\n readonly showRowStripes?: boolean;\n readonly showColumnStripes?: boolean;\n}\n\nexport interface TableColumnOptions {\n /** Column name (used in header row) */\n readonly name: string;\n /** Totals row function */\n readonly totalsRowFunction?: TotalsRowFunction;\n /** Totals row label (used when totalsRowFunction is \"none\" or \"custom\") */\n readonly totalsRowLabel?: string;\n /** Calculated column formula */\n readonly calculatedColumnFormula?: string;\n /** Totals row formula (CT_TableColumn/totalsRowFormula, used when totalsRowFunction is \"custom\") */\n readonly totalsRowFormula?: string;\n /** Whether totals row formula is array (CT_TableFormula @array) */\n readonly totalsRowFormulaArray?: boolean;\n /** Whether calculated column formula is array (CT_TableFormula @array) */\n readonly calculatedColumnFormulaArray?: boolean;\n /** Unique column name for structured references (CT_TableColumn @uniqueName) */\n readonly uniqueName?: string;\n /** Query table field ID (CT_TableColumn @queryTableFieldId) */\n readonly queryTableFieldId?: number;\n /** Header row differential format index */\n readonly headerRowDxfId?: number;\n /** Data differential format index */\n readonly dataDxfId?: number;\n /** Totals row differential format index */\n readonly totalsRowDxfId?: number;\n /** Header row cell style name */\n readonly headerRowCellStyle?: string;\n /** Data cell style name */\n readonly dataCellStyle?: string;\n /** Totals row cell style name */\n readonly totalsRowCellStyle?: string;\n}\n\nexport interface TableOptions {\n /** Unique table id (1-based, must be unique across the workbook) */\n readonly id: number;\n /** Table name (used in structured references) */\n readonly name?: string;\n /** Display name (required by XSD, defaults to name if not set) */\n readonly displayName: string;\n /** Data range, e.g. \"A1:D10\" */\n readonly ref: string;\n /** Column definitions */\n readonly columns: readonly TableColumnOptions[];\n /** Number of header rows (default: 1) */\n readonly headerRowCount?: number;\n /** Number of totals rows (default: 0) */\n readonly totalsRowCount?: number;\n /** Whether to show totals row (default: true when totalsRowCount > 0) */\n readonly totalsRowShown?: boolean;\n /** Table type (default: \"worksheet\") */\n readonly tableType?: TableType;\n /** Table style */\n readonly style?: TableStyleInfoOptions;\n /** Auto-filter reference (defaults to ref) */\n readonly autoFilter?: string;\n /** Insert row shifts existing rows (CT_Table @insertRowShift) */\n readonly insertRowShift?: boolean;\n /** Published to server (CT_Table @published) */\n readonly published?: boolean;\n /** Header row differential format index */\n readonly headerRowDxfId?: number;\n /** Data differential format index */\n readonly dataDxfId?: number;\n /** Totals row differential format index */\n readonly totalsRowDxfId?: number;\n /** Header row border differential format index */\n readonly headerRowBorderDxfId?: number;\n /** Table border differential format index */\n readonly tableBorderDxfId?: number;\n /** Totals row border differential format index */\n readonly totalsRowBorderDxfId?: number;\n /** Header row cell style name */\n readonly headerRowCellStyle?: string;\n /** Data cell style name */\n readonly dataCellStyle?: string;\n /** Totals row cell style name */\n readonly totalsRowCellStyle?: string;\n}\n\n/**\n * Table XML component — generates xl/tables/table{n}.xml.\n *\n * Follows the zero-allocation string concatenation pattern used by other\n * XLSX components.\n */\nexport class TableXml extends BaseXmlComponent {\n private readonly opts: TableOptions;\n\n public constructor(options: TableOptions) {\n super(\"table\");\n this.opts = options;\n }\n\n public override toXml(_context: Context): string {\n const o = this.opts;\n const p: string[] = [];\n\n // Root element with attributes\n const rootAttrs: Record<string, string | number | boolean | undefined> = {\n id: o.id,\n name: o.name ?? o.displayName,\n displayName: o.displayName,\n ref: o.ref,\n };\n if (o.tableType && o.tableType !== \"worksheet\") {\n rootAttrs.tableType = o.tableType;\n }\n if (o.headerRowCount !== undefined && o.headerRowCount !== 1) {\n rootAttrs.headerRowCount = o.headerRowCount;\n }\n if (o.totalsRowCount !== undefined && o.totalsRowCount > 0) {\n rootAttrs.totalsRowCount = o.totalsRowCount;\n }\n if (o.totalsRowShown === false) {\n rootAttrs.totalsRowShown = 0;\n }\n if (o.insertRowShift) rootAttrs.insertRowShift = 1;\n if (o.published) rootAttrs.published = 1;\n if (o.headerRowDxfId !== undefined) rootAttrs.headerRowDxfId = o.headerRowDxfId;\n if (o.dataDxfId !== undefined) rootAttrs.dataDxfId = o.dataDxfId;\n if (o.totalsRowDxfId !== undefined) rootAttrs.totalsRowDxfId = o.totalsRowDxfId;\n if (o.headerRowBorderDxfId !== undefined)\n rootAttrs.headerRowBorderDxfId = o.headerRowBorderDxfId;\n if (o.tableBorderDxfId !== undefined) rootAttrs.tableBorderDxfId = o.tableBorderDxfId;\n if (o.totalsRowBorderDxfId !== undefined)\n rootAttrs.totalsRowBorderDxfId = o.totalsRowBorderDxfId;\n if (o.headerRowCellStyle) rootAttrs.headerRowCellStyle = o.headerRowCellStyle;\n if (o.dataCellStyle) rootAttrs.dataCellStyle = o.dataCellStyle;\n if (o.totalsRowCellStyle) rootAttrs.totalsRowCellStyle = o.totalsRowCellStyle;\n\n p.push(\n `<table xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\"` +\n ` xmlns:mc=\"http://schemas.openxmlformats.org/markup-compatibility/2006\"` +\n ` mc:Ignorable=\"xr xr2\"` +\n ` xmlns:xr=\"http://schemas.microsoft.com/office/spreadsheetml/2014/revision\"` +\n ` xmlns:xr2=\"http://schemas.microsoft.com/office/spreadsheetml/2015/revision2\"${this.buildAttrs(rootAttrs)}>`,\n );\n\n // autoFilter (optional, before tableColumns per XSD sequence)\n if (o.autoFilter !== undefined) {\n p.push(`<autoFilter ref=\"${escapeXml(o.autoFilter)}\"/>`);\n }\n\n // tableColumns (required)\n p.push(`<tableColumns count=\"${o.columns.length}\">`);\n for (let i = 0; i < o.columns.length; i++) {\n const col = o.columns[i];\n const colAttrs: Record<string, string | number | boolean | undefined> = {\n id: i + 1,\n name: col.name,\n };\n\n const inner: string[] = [];\n\n // calculatedColumnFormula\n if (col.calculatedColumnFormula !== undefined) {\n const fAttrs = col.calculatedColumnFormulaArray ? ' array=\"1\"' : \"\";\n inner.push(\n `<calculatedColumnFormula${fAttrs}>${escapeXml(col.calculatedColumnFormula)}</calculatedColumnFormula>`,\n );\n }\n\n // totalsRowFormula (when totalsRowFunction is \"custom\")\n if (col.totalsRowFormula !== undefined) {\n const fAttrs = col.totalsRowFormulaArray ? ' array=\"1\"' : \"\";\n inner.push(\n `<totalsRowFormula${fAttrs}>${escapeXml(col.totalsRowFormula)}</totalsRowFormula>`,\n );\n }\n\n // totalsRowFormula (only when totalsRowFunction is \"custom\")\n if (col.totalsRowFunction === TotalsRowFunction.CUSTOM && col.totalsRowLabel) {\n // Use totalsRowLabel for custom display\n }\n\n if (col.totalsRowFunction !== undefined && col.totalsRowFunction !== TotalsRowFunction.NONE) {\n colAttrs.totalsRowFunction = col.totalsRowFunction;\n }\n if (col.totalsRowLabel !== undefined) {\n colAttrs.totalsRowLabel = col.totalsRowLabel;\n }\n if (col.uniqueName) colAttrs.uniqueName = col.uniqueName;\n if (col.queryTableFieldId !== undefined) colAttrs.queryTableFieldId = col.queryTableFieldId;\n if (col.headerRowDxfId !== undefined) colAttrs.headerRowDxfId = col.headerRowDxfId;\n if (col.dataDxfId !== undefined) colAttrs.dataDxfId = col.dataDxfId;\n if (col.totalsRowDxfId !== undefined) colAttrs.totalsRowDxfId = col.totalsRowDxfId;\n if (col.headerRowCellStyle) colAttrs.headerRowCellStyle = col.headerRowCellStyle;\n if (col.dataCellStyle) colAttrs.dataCellStyle = col.dataCellStyle;\n if (col.totalsRowCellStyle) colAttrs.totalsRowCellStyle = col.totalsRowCellStyle;\n\n if (inner.length > 0) {\n p.push(`<tableColumn${this.buildAttrs(colAttrs)}>${inner.join(\"\")}</tableColumn>`);\n } else {\n p.push(`<tableColumn${this.buildAttrs(colAttrs)}/>`);\n }\n }\n p.push(\"</tableColumns>\");\n\n // tableStyleInfo (optional)\n if (o.style) {\n const s = o.style;\n const styleAttrs: Record<string, string | number | boolean | undefined> = {};\n if (s.name !== undefined) styleAttrs.name = s.name;\n if (s.showFirstColumn) styleAttrs.showFirstColumn = 1;\n if (s.showLastColumn) styleAttrs.showLastColumn = 1;\n if (s.showRowStripes !== false) styleAttrs.showRowStripes = 1;\n if (s.showColumnStripes) styleAttrs.showColumnStripes = 1;\n p.push(`<tableStyleInfo${this.buildAttrs(styleAttrs)}/>`);\n } else {\n // Default style\n p.push(\n '<tableStyleInfo name=\"TableStyleMedium9\" showFirstColumn=\"0\" showLastColumn=\"0\" showRowStripes=\"1\" showColumnStripes=\"0\"/>',\n );\n }\n\n p.push(\"</table>\");\n return p.join(\"\");\n }\n\n private buildAttrs(attrs: Record<string, string | number | boolean | undefined>): string {\n const parts: string[] = [];\n for (const [k, v] of Object.entries(attrs)) {\n if (v === undefined) continue;\n parts.push(` ${k}=\"${typeof v === \"string\" ? escapeXml(v) : String(v)}\"`);\n }\n return parts.join(\"\");\n }\n}\n","/**\n * Dialogsheet XML generator — produces xl/dialogsheets/sheetN.xml.\n *\n * A dialogsheet is a legacy Excel 5.0 dialog sheet (no cell data).\n *\n * Reference: OOXML transitional, sml.xsd, CT_Dialogsheet\n *\n * @module\n */\nimport { BaseXmlComponent } from \"@file/xml-components\";\nimport type { Context } from \"@file/xml-components\";\nimport { attrs } from \"@office-open/xml\";\n\n// ── Options ──\n\nexport interface DialogsheetPageMargins {\n readonly left?: number;\n readonly right?: number;\n readonly top?: number;\n readonly bottom?: number;\n readonly header?: number;\n readonly footer?: number;\n}\n\nexport interface DialogsheetPageSetup {\n readonly paperSize?: number;\n readonly orientation?: string;\n readonly horizontalDpi?: number;\n readonly verticalDpi?: number;\n readonly copies?: number;\n}\n\nexport interface DialogsheetProtectionOptions {\n readonly content?: boolean;\n readonly objects?: boolean;\n readonly scenarios?: boolean;\n}\n\nexport interface DialogsheetOptions {\n /** Sheet name */\n readonly name?: string;\n /** Tab color (hex ARGB) */\n readonly tabColor?: string;\n /** Page margins */\n readonly pageMargins?: DialogsheetPageMargins;\n /** Page setup */\n readonly pageSetup?: DialogsheetPageSetup;\n /** Sheet protection */\n readonly sheetProtection?: DialogsheetProtectionOptions;\n}\n\n// ── Component ──\n\nexport class Dialogsheet extends BaseXmlComponent {\n private readonly opts: DialogsheetOptions;\n\n public constructor(options: DialogsheetOptions) {\n super(\"dialogsheet\");\n this.opts = options;\n }\n\n public override toXml(_context: Context): string {\n const p: string[] = [\n '<dialogsheet xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\"' +\n ' xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\">',\n ];\n\n // sheetPr (optional)\n if (this.opts.tabColor) {\n p.push(`<sheetPr><tabColor${attrs({ rgb: this.opts.tabColor })}/></sheetPr>`);\n }\n\n // sheetViews (required for most implementations)\n p.push('<sheetViews><sheetView workbookViewId=\"0\"/></sheetViews>');\n\n // sheetProtection (optional)\n if (this.opts.sheetProtection) {\n const sp = this.opts.sheetProtection;\n const spAttrs: Record<string, string | number | undefined> = {};\n if (sp.content) spAttrs.sheet = \"1\";\n if (sp.objects) spAttrs.objects = \"1\";\n if (sp.scenarios) spAttrs.scenarios = \"1\";\n if (Object.keys(spAttrs).length > 0) {\n p.push(`<sheetProtection${attrs(spAttrs)}/>`);\n }\n }\n\n // pageMargins (optional)\n if (this.opts.pageMargins) {\n const pm = this.opts.pageMargins;\n p.push(\n `<pageMargins${attrs({\n left: pm.left ?? 0.7,\n right: pm.right ?? 0.7,\n top: pm.top ?? 0.75,\n bottom: pm.bottom ?? 0.75,\n header: pm.header ?? 0.3,\n footer: pm.footer ?? 0.3,\n })}/>`,\n );\n }\n\n // pageSetup (optional)\n if (this.opts.pageSetup) {\n const ps = this.opts.pageSetup;\n p.push(\n `<pageSetup${attrs({\n paperSize: ps.paperSize,\n orientation: ps.orientation,\n horizontalDpi: ps.horizontalDpi,\n verticalDpi: ps.verticalDpi,\n copies: ps.copies,\n })}/>`,\n );\n }\n\n p.push(\"</dialogsheet>\");\n return p.join(\"\");\n }\n}\n","/**\n * QueryTable XML generator — produces xl/queryTables/queryTable{n}.xml.\n *\n * A query table represents data retrieved from an external data source.\n *\n * Reference: OOXML transitional, sml.xsd, CT_QueryTable\n *\n * @module\n */\nimport { BaseXmlComponent } from \"@file/xml-components\";\nimport type { Context } from \"@file/xml-components\";\nimport { attrs, escapeXml } from \"@office-open/xml\";\n\n// ── Options ──\n\nexport interface QueryTableDeletedFieldOptions {\n /** Field name that was deleted (required) */\n readonly name: string;\n}\n\nexport interface QueryTableFieldOptions {\n /** Field ID (required, 1-based) */\n readonly id: number;\n /** Field name */\n readonly name?: string;\n /** Table column index (1-based) */\n readonly tableColumnId?: number;\n /** Row number (for data layout) */\n readonly row?: number;\n /** Fill formatting */\n readonly fillFormatting?: boolean;\n /** Text formatting */\n readonly textFormatting?: boolean;\n /** Number formatting */\n readonly numberFormatting?: boolean;\n /** Border formatting */\n readonly borderFormatting?: boolean;\n /** Width */\n readonly width?: number;\n /** CLipped */\n readonly clipped?: boolean;\n}\n\nexport interface QueryTableRefreshOptions {\n /** Next unique ID for new rows */\n readonly nextId?: number;\n /** Minimum refresh version */\n readonly minimumVersion?: number;\n /** Preserve column sort/filter/layout on refresh */\n readonly preserveFormatting?: boolean;\n /** Adjust column width on refresh */\n readonly adjustColumnWidth?: boolean;\n /** Refresh data on load */\n readonly refreshOnLoad?: boolean;\n /** Background refresh */\n readonly backgroundRefresh?: boolean;\n /** Deleted fields */\n readonly deletedFields?: readonly QueryTableDeletedFieldOptions[];\n /** Query table fields */\n readonly queryTableFields?: readonly QueryTableFieldOptions[];\n /** Row count */\n readonly rowCount?: number;\n}\n\nexport interface QueryTableOptions {\n /** Query table name */\n readonly name?: string;\n /** Connection ID referencing the workbook connection */\n readonly connectionId: number;\n /** Auto-refresh on open */\n readonly autoFormat?: boolean;\n /** Preserve column sort/filter/layout on refresh */\n readonly preserveFormatting?: boolean;\n /** Adjust column width on refresh */\n readonly adjustColumnWidth?: boolean;\n /** Refresh data on load */\n readonly refreshOnLoad?: boolean;\n /** Background refresh */\n readonly backgroundRefresh?: boolean;\n /** Show row numbers (CT_QueryTable @rowNumbers) */\n readonly rowNumbers?: boolean;\n /** Disable refresh (CT_QueryTable @disableRefresh) */\n readonly disableRefresh?: boolean;\n /** First background refresh (CT_QueryTable @firstBackgroundRefresh) */\n readonly firstBackgroundRefresh?: boolean;\n /** Grow/shrink type (CT_QueryTable @growShrinkType) */\n readonly growShrinkType?: boolean;\n /** Fill formulas on refresh (CT_QueryTable @fillFormulas) */\n readonly fillFormulas?: boolean;\n /** Remove data on save (CT_QueryTable @removeDataOnSave) */\n readonly removeDataOnSave?: boolean;\n /** Disable edit (CT_QueryTable @disableEdit) */\n readonly disableEdit?: boolean;\n /** Intermediate (CT_QueryTable @intermediate) */\n readonly intermediate?: boolean;\n /** Query table refresh info (CT_QueryTableRefresh) */\n readonly queryTableRefresh?: QueryTableRefreshOptions;\n}\n\n// ── Component ──\n\nexport class QueryTableXml extends BaseXmlComponent {\n private readonly opts: QueryTableOptions;\n\n public constructor(options: QueryTableOptions) {\n super(\"queryTable\");\n this.opts = options;\n }\n\n public override toXml(_context: Context): string {\n const o = this.opts;\n const a: Record<string, string | number | boolean | undefined> = {\n name: o.name ?? \"QueryTable1\",\n connectionId: o.connectionId,\n autoFormat: o.autoFormat ? 1 : undefined,\n preserveFormatting: o.preserveFormatting ? 1 : undefined,\n adjustColumnWidth: o.adjustColumnWidth !== false ? 1 : 0,\n refreshOnLoad: o.refreshOnLoad ? 1 : undefined,\n backgroundRefresh: o.backgroundRefresh ? 1 : undefined,\n rowNumbers: o.rowNumbers ? 1 : undefined,\n disableRefresh: o.disableRefresh ? 1 : undefined,\n firstBackgroundRefresh: o.firstBackgroundRefresh ? 1 : undefined,\n growShrinkType: o.growShrinkType ? 1 : undefined,\n fillFormulas: o.fillFormulas ? 1 : undefined,\n removeDataOnSave: o.removeDataOnSave ? 1 : undefined,\n disableEdit: o.disableEdit ? 1 : undefined,\n intermediate: o.intermediate ? 1 : undefined,\n };\n\n const children: string[] = [];\n\n // queryTableRefresh\n if (o.queryTableRefresh) {\n children.push(buildQueryTableRefresh(o.queryTableRefresh));\n }\n\n if (children.length > 0) {\n return `<queryTable xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\"${attrs(a)}>${children.join(\"\")}</queryTable>`;\n }\n return `<queryTable xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\"${attrs(a)}/>`;\n }\n}\n\nfunction buildQueryTableRefresh(opts: QueryTableRefreshOptions): string {\n const a: Record<string, string | number | boolean | undefined> = {};\n if (opts.nextId !== undefined) a.nextId = opts.nextId;\n if (opts.minimumVersion !== undefined) a.minimumVersion = opts.minimumVersion;\n if (opts.preserveFormatting) a.preserveFormatting = 1;\n if (opts.adjustColumnWidth !== undefined) a.adjustColumnWidth = opts.adjustColumnWidth ? 1 : 0;\n if (opts.refreshOnLoad) a.refreshOnLoad = 1;\n if (opts.backgroundRefresh) a.backgroundRefresh = 1;\n if (opts.rowCount !== undefined) a.rowCount = opts.rowCount;\n\n const children: string[] = [];\n\n // queryTableDeletedFields\n if (opts.deletedFields && opts.deletedFields.length > 0) {\n const dfParts = opts.deletedFields.map((df) => `<deletedField name=\"${escapeXml(df.name)}\"/>`);\n children.push(\n `<queryTableDeletedFields count=\"${opts.deletedFields.length}\">${dfParts.join(\"\")}</queryTableDeletedFields>`,\n );\n }\n\n // queryTableFields\n if (opts.queryTableFields && opts.queryTableFields.length > 0) {\n const fParts: string[] = [`<queryTableFields count=\"${opts.queryTableFields.length}\">`];\n for (const f of opts.queryTableFields) {\n const fAttrs: Record<string, string | number | boolean | undefined> = { id: f.id };\n if (f.name !== undefined) fAttrs.name = f.name;\n if (f.tableColumnId !== undefined) fAttrs.tableColumnId = f.tableColumnId;\n if (f.row !== undefined) fAttrs.row = f.row;\n if (f.fillFormatting) fAttrs.fillFormatting = 1;\n if (f.textFormatting) fAttrs.textFormatting = 1;\n if (f.numberFormatting) fAttrs.numberFormatting = 1;\n if (f.borderFormatting) fAttrs.borderFormatting = 1;\n if (f.width !== undefined) fAttrs.width = f.width;\n if (f.clipped) fAttrs.clipped = 1;\n fParts.push(`<queryTableField${attrs(fAttrs)}/>`);\n }\n fParts.push(\"</queryTableFields>\");\n children.push(fParts.join(\"\"));\n }\n\n // Sort-by-row column (tr — CT_TableRefresh)\n if (children.length > 0) {\n return `<queryTableRefresh${attrs(a)}>${children.join(\"\")}</queryTableRefresh>`;\n }\n return `<queryTableRefresh${attrs(a)}/>`;\n}\n","/**\n * Metadata XML generator — produces xl/metadata.xml.\n *\n * Contains cell metadata and value metadata for rich data types.\n *\n * Reference: OOXML transitional, sml.xsd, CT_Metadata\n *\n * @module\n */\nimport { BaseXmlComponent } from \"@file/xml-components\";\nimport type { Context } from \"@file/xml-components\";\nimport { attrs, escapeXml } from \"@office-open/xml\";\n\n// ── Options ──\n\nexport interface MetadataTypeOptions {\n /** Metadata type name */\n readonly name: string;\n /** Minimum version */\n readonly minVersion?: number;\n /** Minimum supported version (CT_MetadataType @minSupportedVersion) */\n readonly minSupportedVersion?: number;\n /** Ghost row flag */\n readonly ghostRow?: boolean;\n /** Ghost column flag */\n readonly ghostCol?: boolean;\n /** Edit flag */\n readonly edit?: boolean;\n /** Delete flag */\n readonly delete?: boolean;\n /** Copy flag */\n readonly copy?: boolean;\n /** Paste flag */\n readonly paste?: boolean;\n /** Paste all (CT_MetadataType @pasteAll) */\n readonly pasteAll?: boolean;\n /** Paste formulas */\n readonly pasteFormulas?: boolean;\n /** Paste values */\n readonly pasteValues?: boolean;\n /** Paste formats */\n readonly pasteFormats?: boolean;\n /** Paste comments */\n readonly pasteComments?: boolean;\n /** Paste data validation */\n readonly pasteDataValidation?: boolean;\n /** Paste borders */\n readonly pasteBorders?: boolean;\n /** Paste column widths */\n readonly pasteColWidths?: boolean;\n /** Paste number formats */\n readonly pasteNumberFormats?: boolean;\n /** Merge cells */\n readonly merge?: boolean;\n /** Split first */\n readonly splitFirst?: boolean;\n /** Split all */\n readonly splitAll?: boolean;\n /** Row/column shift */\n readonly rowColShift?: boolean;\n /** Clear all */\n readonly clearAll?: boolean;\n /** Clear formats */\n readonly clearFormats?: boolean;\n /** Clear contents */\n readonly clearContents?: boolean;\n /** Clear comments */\n readonly clearComments?: boolean;\n /** Assign */\n readonly assign?: boolean;\n /** Coerce */\n readonly coerce?: boolean;\n /** Adjust */\n readonly adjust?: boolean;\n /** Cell metadata */\n readonly cellMeta?: boolean;\n}\n\nexport interface MetadataStringOptions {\n /** String value */\n readonly value: string;\n}\n\nexport interface FutureMetadataOptions {\n /** Future metadata type name */\n readonly name: string;\n /** Future metadata type */\n readonly type: string;\n}\n\nexport interface MetadataRecordOptions {\n /** Metadata type index (required) */\n readonly t: number;\n /** Metadata value index (required) */\n readonly v: number;\n}\n\nexport interface MetadataBlockOptions {\n /** Metadata records */\n readonly records?: readonly MetadataRecordOptions[];\n}\n\nexport interface MetadataOptions {\n /** Metadata types */\n readonly types?: readonly MetadataTypeOptions[];\n /** Metadata strings */\n readonly strings?: readonly MetadataStringOptions[];\n /** Future metadata */\n readonly futureMetadata?: readonly FutureMetadataOptions[];\n /** MDX metadata (CT_MdxMetadata) */\n readonly mdxMetadata?: readonly MdxOptions[];\n /** Cell metadata blocks */\n readonly cellMetadataBlocks?: readonly MetadataBlockOptions[];\n /** Value metadata blocks */\n readonly valueMetadataBlocks?: readonly MetadataBlockOptions[];\n}\n\n/** MDX query entry (CT_Mdx) */\nexport interface MdxOptions {\n /** MDX function type: \"m\"|\"v\"|\"s\"|\"c\"|\"r\"|\"p\"|\"k\" */\n readonly f: string;\n /** Name index (required) */\n readonly n: number;\n /** MDX tuple */\n readonly tuple?: MdxTupleOptions;\n /** MDX set */\n readonly set?: MdxSetOptions;\n /** MDX member property */\n readonly memberProp?: MdxMemberPropOptions;\n /** MDX KPI */\n readonly kpi?: MdxKpiOptions;\n}\n\nexport interface MdxTupleOptions {\n /** Tuple count */\n readonly c?: number;\n}\n\nexport interface MdxSetOptions {\n /** Namespace count (required) */\n readonly ns: number;\n}\n\nexport interface MdxMemberPropOptions {\n /** Name index (required) */\n readonly n: number;\n /** Name pair index (required) */\n readonly np: number;\n}\n\nexport interface MdxKpiOptions {\n /** Name index (required) */\n readonly n: number;\n /** Name pair index (required) */\n readonly np: number;\n /** KPI property (required) */\n readonly p: string;\n}\n\n// ── Component ──\n\nexport class MetadataXml extends BaseXmlComponent {\n private readonly opts: MetadataOptions;\n\n public constructor(options: MetadataOptions) {\n super(\"metadata\");\n this.opts = options;\n }\n\n public override toXml(_context: Context): string {\n const p: string[] = [\n '<metadata xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\">',\n ];\n\n // metadataTypes\n const types = this.opts.types ?? [];\n p.push(`<metadataTypes count=\"${types.length}\">`);\n for (const t of types) {\n p.push(\n `<metadataType${attrs({\n name: t.name,\n minVersion: t.minVersion,\n minSupportedVersion: t.minSupportedVersion,\n ghostRow: t.ghostRow ? 1 : undefined,\n ghostCol: t.ghostCol ? 1 : undefined,\n edit: t.edit ? 1 : undefined,\n delete: t.delete ? 1 : undefined,\n copy: t.copy ? 1 : undefined,\n paste: t.paste ? 1 : undefined,\n pasteAll: t.pasteAll ? 1 : undefined,\n pasteFormulas: t.pasteFormulas ? 1 : undefined,\n pasteValues: t.pasteValues ? 1 : undefined,\n pasteFormats: t.pasteFormats ? 1 : undefined,\n pasteComments: t.pasteComments ? 1 : undefined,\n pasteDataValidation: t.pasteDataValidation ? 1 : undefined,\n pasteBorders: t.pasteBorders ? 1 : undefined,\n pasteColWidths: t.pasteColWidths ? 1 : undefined,\n pasteNumberFormats: t.pasteNumberFormats ? 1 : undefined,\n merge: t.merge ? 1 : undefined,\n splitFirst: t.splitFirst ? 1 : undefined,\n splitAll: t.splitAll ? 1 : undefined,\n rowColShift: t.rowColShift ? 1 : undefined,\n clearAll: t.clearAll ? 1 : undefined,\n clearFormats: t.clearFormats ? 1 : undefined,\n clearContents: t.clearContents ? 1 : undefined,\n clearComments: t.clearComments ? 1 : undefined,\n assign: t.assign ? 1 : undefined,\n coerce: t.coerce ? 1 : undefined,\n adjust: t.adjust ? 1 : undefined,\n cellMeta: t.cellMeta ? 1 : undefined,\n })}/>`,\n );\n }\n p.push(\"</metadataTypes>\");\n\n // metadataStrings\n const strings = this.opts.strings ?? [];\n if (strings.length > 0) {\n p.push(`<metadataStrings count=\"${strings.length}\">`);\n for (const s of strings) {\n p.push(`<s v=\"${s.value}\"/>`);\n }\n p.push(\"</metadataStrings>\");\n }\n\n // futureMetadata\n const future = this.opts.futureMetadata ?? [];\n if (future.length > 0) {\n for (const f of future) {\n p.push(`<futureMetadata name=\"${f.name}\" type=\"${f.type}\"><bk/>`);\n p.push(\"</futureMetadata>\");\n }\n }\n\n // cellMetadata\n const cmBlocks = this.opts.cellMetadataBlocks ?? [];\n if (cmBlocks.length > 0) {\n p.push(`<cellMetadata count=\"${cmBlocks.length}\">`);\n for (const blk of cmBlocks) {\n const records = blk.records ?? [];\n if (records.length > 0) {\n const rcParts = records.map((r) => `<rc t=\"${r.t}\" v=\"${r.v}\"/>`);\n p.push(`<bk>${rcParts.join(\"\")}</bk>`);\n } else {\n p.push(\"<bk/>\");\n }\n }\n p.push(\"</cellMetadata>\");\n } else {\n p.push('<cellMetadata count=\"0\"/>');\n }\n\n // valueMetadata\n const vmBlocks = this.opts.valueMetadataBlocks ?? [];\n if (vmBlocks.length > 0) {\n p.push(`<valueMetadata count=\"${vmBlocks.length}\">`);\n for (const blk of vmBlocks) {\n const records = blk.records ?? [];\n if (records.length > 0) {\n const rcParts = records.map((r) => `<rc t=\"${r.t}\" v=\"${r.v}\"/>`);\n p.push(`<bk>${rcParts.join(\"\")}</bk>`);\n } else {\n p.push(\"<bk/>\");\n }\n }\n p.push(\"</valueMetadata>\");\n } else {\n p.push('<valueMetadata count=\"0\"/>');\n }\n\n // mdxMetadata (CT_MdxMetadata)\n const mdxMeta = this.opts.mdxMetadata;\n if (mdxMeta && mdxMeta.length > 0) {\n p.push(`<mdxMetadata count=\"${mdxMeta.length}\">`);\n for (const m of mdxMeta) {\n const mAttrs: Record<string, string | number | undefined> = {\n n: m.n,\n f: m.f,\n };\n let child = \"\";\n if (m.tuple) {\n const tAttrs: Record<string, string | number | undefined> = {};\n if (m.tuple.c !== undefined) tAttrs.c = m.tuple.c;\n child = `<t${attrs(tAttrs)}/>`;\n } else if (m.set) {\n child = `<ms ns=\"${m.set.ns}\"/>`;\n } else if (m.memberProp) {\n child = `<p n=\"${m.memberProp.n}\" np=\"${m.memberProp.np}\"/>`;\n } else if (m.kpi) {\n child = `<k n=\"${m.kpi.n}\" np=\"${m.kpi.np}\" p=\"${escapeXml(m.kpi.p)}\"/>`;\n }\n if (child) {\n p.push(`<mdx${attrs(mAttrs)}>${child}</mdx>`);\n } else {\n p.push(`<mdx${attrs(mAttrs)}/>`);\n }\n }\n p.push(\"</mdxMetadata>\");\n }\n\n p.push(\"</metadata>\");\n return p.join(\"\");\n }\n}\n","/**\n * Revision Headers XML generator — produces xl/revisionHeaders.xml.\n *\n * Reference: OOXML transitional, sml.xsd, CT_RevisionHeaders\n *\n * @module\n */\nimport { BaseXmlComponent } from \"@file/xml-components\";\nimport type { Context } from \"@file/xml-components\";\nimport { attrs, escapeXml } from \"@office-open/xml\";\n\nimport type { RevisionHeadersOptions, UsersOptions } from \"./revision-types\";\n\n// ── Component ──\n\nexport class RevisionHeadersXml extends BaseXmlComponent {\n private readonly opts: RevisionHeadersOptions;\n private readonly users?: UsersOptions;\n\n public constructor(options: RevisionHeadersOptions, users?: UsersOptions) {\n super(\"headers\");\n this.opts = options;\n this.users = users;\n }\n\n public override toXml(_context: Context): string {\n const p: string[] = [\n '<headers xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\"' +\n ' xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\"',\n ];\n\n // Root attributes\n const rootAttrs: Record<string, string | number | boolean | undefined> = {\n guid: this.opts.guid,\n lastGuid: this.opts.lastGuid,\n shared: this.opts.shared,\n history: this.opts.history,\n trackRevisions: this.opts.trackRevisions,\n revisionId: this.opts.revisionId,\n version: this.opts.version,\n keepChangeHistory: this.opts.keepChangeHistory,\n protected: this.opts.protected,\n preserveHistory: this.opts.preserveHistory,\n };\n p.push(`${attrs(rootAttrs)}>`);\n\n // header entries\n for (const h of this.opts.headers) {\n const headerAttrs: Record<string, string | number | undefined> = {\n guid: h.guid,\n dateTime: h.dateTime,\n maxSheetId: h.maxSheetId,\n userName: h.userName,\n };\n\n // Build header content\n const content: string[] = [];\n\n // sheetIdMap\n if (h.sheetIds && h.sheetIds.length > 0) {\n const idParts: string[] = [];\n for (const sid of h.sheetIds) {\n idParts.push(`<sheetId val=\"${sid.id}\"/>`);\n }\n content.push(\n `<sheetIdMap${attrs({ count: h.sheetIds.length })}>${idParts.join(\"\")}</sheetIdMap>`,\n );\n }\n\n p.push(\n `<header${attrs(headerAttrs)} r:id=\"${escapeXml(h.rId)}\">${content.join(\"\")}</header>`,\n );\n }\n\n p.push(\"</headers>\");\n return p.join(\"\");\n }\n\n /** Build users XML (CT_Users) — separate file xl/users.xml */\n public buildUsersXml(): string {\n if (!this.users?.users || this.users.users.length === 0) return \"\";\n const u = this.users.users;\n const parts: string[] = [\n '<users xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\"',\n ` count=\"${u.length}\">`,\n ];\n for (const user of u) {\n const uAttrs: Record<string, string | number | undefined> = {\n guid: user.guid,\n name: user.name,\n id: user.id,\n dateTime: user.dateTime,\n };\n parts.push(`<userInfo${attrs(uAttrs)}/>`);\n }\n parts.push(\"</users>\");\n return parts.join(\"\");\n }\n}\n","/**\n * Revision Log XML generator — produces xl/revisions/revisionN.xml.\n *\n * Reference: OOXML transitional, sml.xsd, CT_Revisions\n *\n * @module\n */\nimport { BaseXmlComponent } from \"@file/xml-components\";\nimport type { Context } from \"@file/xml-components\";\nimport { attrs, escapeXml } from \"@office-open/xml\";\n\nimport type {\n RevisionEntry,\n RevisionRowColumnOptions,\n RevisionCellChangeOptions,\n RevisionMoveOptions,\n RevisionFormattingOptions,\n RevisionInsertSheetOptions,\n RevisionCommentOptions,\n RevisionDefinedNameOptions,\n RevisionAutoFormattingOptions,\n RevisionCustomViewOptions,\n RevisionSheetRenameOptions,\n RevisionQueryTableFieldOptions,\n RevisionConflictOptions,\n} from \"./revision-types\";\n\n// ── Helpers ──\n\nfunction buildRowColumn(opts: RevisionRowColumnOptions): string {\n const actionMap: Record<string, string> = {\n insertRow: \"ir\",\n insertCol: \"ic\",\n deleteRow: \"dr\",\n deleteCol: \"dc\",\n };\n const a: Record<string, string | number | boolean | undefined> = {\n rId: opts.rId,\n action: actionMap[opts.action],\n sId: opts.sheetIndex,\n edge: opts.edge ? 1 : undefined,\n };\n if (opts.action.includes(\"Row\")) {\n a.row = opts.row;\n } else {\n a.col = opts.col;\n }\n return `<rrc${attrs(a)}/>`;\n}\n\nfunction buildCellChange(opts: RevisionCellChangeOptions): string {\n const a: Record<string, string | number | boolean | undefined> = {\n rId: opts.rId,\n sId: opts.sheetIndex,\n quotePrefix: opts.quotePrefix ? 1 : undefined,\n oldQuotePrefix: opts.oldQuotePrefix ? 1 : undefined,\n ph: opts.ph ? 1 : undefined,\n oldPh: opts.oldPh ? 1 : undefined,\n };\n\n const children: string[] = [];\n\n // Old value\n if (opts.oldValue !== undefined) {\n const oldType = opts.oldType ?? (typeof opts.oldValue === \"number\" ? \"n\" : \"s\");\n if (opts.formula) {\n children.push(`<f>${escapeXml(opts.formula)}</f>`);\n }\n children.push(\n `<oc${attrs({ t: oldType, vm: opts.numFmtId })}>` +\n `<v>${escapeXml(String(opts.oldValue))}</v></oc>`,\n );\n }\n\n // New value\n if (opts.newValue !== undefined) {\n const newType = opts.newType ?? (typeof opts.newValue === \"number\" ? \"n\" : \"s\");\n children.push(`<nc${attrs({ t: newType })}><v>${escapeXml(String(opts.newValue))}</v></nc>`);\n }\n\n // ndxf/odxf — differential format (CT_Dxf placeholder)\n if (opts.xfDxf !== undefined) {\n children.push(`<ndxf><font/><numFmt/><fill/><border/><protection/></ndxf>`);\n children.push(`<odxf><font/><numFmt/><fill/><border/><protection/></odxf>`);\n }\n\n return `<rcc${attrs({ ref: opts.ref, ...a })}>${children.join(\"\")}</rcc>`;\n}\n\nfunction buildMove(opts: RevisionMoveOptions): string {\n const a: Record<string, string | number | undefined> = {\n rId: opts.rId,\n sId: opts.sheetIndex,\n source: opts.source,\n destination: opts.destination,\n sourceSheetId: opts.sourceSheetId,\n };\n return `<rm${attrs(a)}/>`;\n}\n\nfunction buildFormatting(opts: RevisionFormattingOptions): string {\n const a: Record<string, string | number | undefined> = {\n rId: opts.rId,\n sId: opts.sheetIndex,\n ref: opts.ref,\n s: opts.s,\n xfDxf: opts.xfDxf,\n };\n return `<rfmt${attrs(a)}/>`;\n}\n\nfunction buildInsertSheet(opts: RevisionInsertSheetOptions): string {\n const a: Record<string, string | number | undefined> = {\n rId: opts.rId,\n sId: opts.sheetIndex,\n name: opts.name,\n sheetPosition: opts.sheetPosition,\n };\n return `<ris${attrs(a)}/>`;\n}\n\nfunction buildComment(opts: RevisionCommentOptions): string {\n const a: Record<string, string | number | boolean | undefined> = {\n rId: opts.rId,\n sId: opts.sheetIndex,\n ref: opts.ref,\n alwaysShow: opts.alwaysShow ? 1 : undefined,\n old: opts.old ? 1 : undefined,\n hiddenRow: opts.hiddenRow ? 1 : undefined,\n hiddenColumn: opts.hiddenColumn ? 1 : undefined,\n oldLength: opts.oldLength,\n newLength: opts.newLength,\n };\n const children: string[] = [];\n if (opts.text) {\n children.push(`<t>${escapeXml(opts.text)}</t>`);\n }\n if (opts.author) {\n children.push(`<author>${escapeXml(opts.author)}</author>`);\n }\n if (children.length > 0) {\n return `<rcmt${attrs(a)}>${children.join(\"\")}</rcmt>`;\n }\n return `<rcmt${attrs(a)}/>`;\n}\n\nfunction buildDefinedName(opts: RevisionDefinedNameOptions): string {\n const a: Record<string, string | number | boolean | undefined> = {\n rId: opts.rId,\n name: opts.name,\n localSheetId: opts.localSheetId,\n customView: opts.customView ? 1 : undefined,\n function: opts[\"function\"] ? 1 : undefined,\n oldFunction: opts.oldFunction ? 1 : undefined,\n functionGroupId: opts.functionGroupId,\n oldFunctionGroupId: opts.oldFunctionGroupId,\n shortcutKey: opts.shortcutKey,\n oldShortcutKey: opts.oldShortcutKey,\n oldHidden: opts.oldHidden ? 1 : undefined,\n customMenu: opts.customMenu,\n oldCustomMenu: opts.oldCustomMenu,\n oldDescription: opts.oldDescription,\n help: opts.help,\n oldHelp: opts.oldHelp,\n statusBar: opts.statusBar,\n oldStatusBar: opts.oldStatusBar,\n };\n const children: string[] = [];\n if (opts.value) {\n children.push(`<formula>${escapeXml(opts.value)}</formula>`);\n }\n if (opts.oldComment) {\n children.push(`<oldFormula>${escapeXml(opts.oldComment)}</oldFormula>`);\n }\n return `<rdn${attrs(a)}>${children.join(\"\")}</rdn>`;\n}\n\nfunction buildAutoFormatting(opts: RevisionAutoFormattingOptions): string {\n const a: Record<string, string | number | undefined> = {\n rId: opts.rId,\n sId: opts.sheetIndex,\n ref: opts.ref,\n };\n return `<raf${attrs(a)}/>`;\n}\n\nfunction buildCustomView(opts: RevisionCustomViewOptions): string {\n const a: Record<string, string | number | undefined> = {\n rId: opts.rId,\n guid: opts.guid,\n };\n return `<rcv${attrs(a)}/>`;\n}\n\nfunction buildSheetRename(opts: RevisionSheetRenameOptions): string {\n const a: Record<string, string | number | undefined> = {\n rId: opts.rId,\n sId: opts.sheetIndex,\n oldName: opts.oldName,\n newName: opts.newName,\n };\n return `<rsnm${attrs(a)}/>`;\n}\n\nfunction buildQueryTableField(opts: RevisionQueryTableFieldOptions): string {\n const a: Record<string, string | number | undefined> = {\n rId: opts.rId,\n sId: opts.sheetIndex,\n fieldId: opts.fieldId,\n };\n return `<rqt${attrs(a)}/>`;\n}\n\nfunction buildConflict(opts: RevisionConflictOptions): string {\n const a: Record<string, string | number | undefined> = {\n rId: opts.rId,\n sId: opts.sheetIndex,\n };\n return `<rcft${attrs(a)}/>`;\n}\n\n// ── Component ──\n\nexport class RevisionLogXml extends BaseXmlComponent {\n private readonly entries: readonly RevisionEntry[];\n\n public constructor(entries: readonly RevisionEntry[]) {\n super(\"revisions\");\n this.entries = entries;\n }\n\n public override toXml(_context: Context): string {\n const p: string[] = [\n '<revisions xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\"' +\n ' xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\">',\n ];\n\n const localReviewedList: string[] = [];\n\n for (const entry of this.entries) {\n switch (entry.type) {\n case \"rowColumn\":\n p.push(buildRowColumn(entry.data));\n break;\n case \"cellChange\":\n p.push(buildCellChange(entry.data));\n break;\n case \"move\":\n p.push(buildMove(entry.data));\n break;\n case \"formatting\":\n p.push(buildFormatting(entry.data));\n break;\n case \"insertSheet\":\n p.push(buildInsertSheet(entry.data));\n break;\n case \"comment\":\n p.push(buildComment(entry.data));\n break;\n case \"definedName\":\n p.push(buildDefinedName(entry.data));\n break;\n case \"reviewed\":\n localReviewedList.push(`<reviewed rId=\"${entry.data.rId}\"/>`);\n p.push(`<reviewed rId=\"${entry.data.rId}\"/>`);\n break;\n case \"undo\":\n p.push(`<undo rId=\"${entry.data.rId}\"/>`);\n break;\n case \"autoFormatting\":\n p.push(buildAutoFormatting(entry.data));\n break;\n case \"customView\":\n p.push(buildCustomView(entry.data));\n break;\n case \"sheetRename\":\n p.push(buildSheetRename(entry.data));\n break;\n case \"queryTableField\":\n p.push(buildQueryTableField(entry.data));\n break;\n case \"conflict\":\n p.push(buildConflict(entry.data));\n break;\n }\n }\n\n // reviewedList — container for all reviewed entries (CT_ReviewedList)\n if (localReviewedList.length > 0) {\n p.push(`<reviewedList>${localReviewedList.join(\"\")}</reviewedList>`);\n }\n\n p.push(\"</revisions>\");\n return p.join(\"\");\n }\n}\n","/**\n * Connection XML generator — produces xl/connections.xml.\n *\n * Reference: OOXML transitional, sml.xsd, CT_Connections\n *\n * @module\n */\nimport { BaseXmlComponent } from \"@file/xml-components\";\nimport type { Context } from \"@file/xml-components\";\nimport { attrs, escapeXml } from \"@office-open/xml\";\n\n// ── Options ──\n\nexport interface DbPrOptions {\n /** OLE DB connection string (required) */\n readonly connection: string;\n /** Command text */\n readonly command?: string;\n /** Command type: \"1\"=cube, \"2\"=SQL, \"3\"=table, \"4\"=default */\n readonly commandType?: number;\n /** Server formatting */\n readonly serverCommand?: string;\n}\n\nexport interface WebPrOptions {\n /** URL (required) */\n readonly url: string;\n /** Source data from: \"csv\" | \"html\" | ... */\n readonly sourceData?: boolean;\n /** HTML formatting: \"all\" | \"rtf\" | \"none\" */\n readonly htmlFormat?: string;\n /** HTML tables (1-based indices) */\n readonly htmlTables?: readonly string[];\n /** Consecutive property */\n readonly consecutive?: boolean;\n /** First row header */\n readonly firstRowHeader?: boolean;\n /** Parse PRE tags */\n readonly parsePre?: boolean;\n /** Same row dates */\n readonly xl2000?: boolean;\n /** Text fields configuration */\n readonly textFields?: readonly TextFieldOptions[];\n}\n\nexport interface TextPrOptions {\n /** Text fields */\n readonly textFields?: readonly TextFieldOptions[];\n /** Code page */\n readonly codePage?: number;\n /** Character set */\n readonly characterSet?: string;\n /** Source file */\n readonly sourceFile?: string;\n /** Delimited */\n readonly delimited?: boolean;\n /** Tab delimiter */\n readonly tab?: boolean;\n /** Space delimiter */\n readonly space?: boolean;\n /** Comma delimiter */\n readonly comma?: boolean;\n /** Semicolon delimiter */\n readonly semicolon?: boolean;\n /** Custom delimiter character */\n readonly custom?: string;\n /** Decimal character */\n readonly decimal?: string;\n /** Thousands separator */\n readonly thousands?: string;\n /** Trailing minus */\n readonly trailingMinus?: boolean;\n}\n\nexport interface TextFieldOptions {\n /** Column index (1-based) */\n readonly type: number;\n /** Field data type: \"auto\" | \"text\" | \"MDY\" | \"DMY\" | \"YMD\" | \"MYD\" | \"DYM\" | \"YDM\" | \"skip\" | \"ELAPSED\" | \"SYS_DATE\" | ... */\n readonly dataType?: string;\n}\n\nexport interface ParameterOptions {\n /** Parameter name (required) */\n readonly name: string;\n /** SQL data type */\n readonly sqlType?: number;\n /** Character set */\n readonly characterSet?: string;\n /** String value */\n readonly stringValue?: string;\n /** Integer value */\n readonly integerValue?: number;\n /** Boolean value */\n readonly booleanValue?: boolean;\n /** Refresh on load */\n readonly refreshOnChange?: boolean;\n /** Prompt user */\n readonly prompt?: boolean;\n /** Cell reference for parameter value */\n readonly reference?: string;\n /** Parameter type: \"prompt\" | \"value\" | \"cell\" */\n readonly parameterType?: string;\n}\n\nexport interface ConnectionOptions {\n /** Unique connection ID (required) */\n readonly id: number;\n /** Connection name */\n readonly name?: string;\n /** Connection type: 1=ODBC, 2=DAO, 3=OLE DB, 4=web, 5=text, 6=ADO, 7=DSP */\n readonly type?: number;\n /** Refresh on load */\n readonly refreshOnLoad?: boolean;\n /** Refreshed version */\n readonly refreshedVersion?: number;\n /** Background refresh */\n readonly backgroundRefresh?: boolean;\n /** Save data */\n readonly saveData?: boolean;\n /** Save password */\n readonly savePassword?: boolean;\n /** Connection description */\n readonly description?: string;\n /** Credentials method: \"integrated\" | \"none\" | \"stored\" | \"prompt\" */\n readonly credentials?: string;\n /** OLE DB properties */\n readonly dbPr?: DbPrOptions;\n /** Web query properties */\n readonly webPr?: WebPrOptions;\n /** Text import properties */\n readonly textPr?: TextPrOptions;\n /** Parameters */\n readonly parameters?: readonly ParameterOptions[];\n}\n\n// ── Component ──\n\nexport class ConnectionsXml extends BaseXmlComponent {\n private readonly connections: readonly ConnectionOptions[];\n\n public constructor(connections: readonly ConnectionOptions[]) {\n super(\"connections\");\n this.connections = connections;\n }\n\n public override toXml(_context: Context): string {\n const p: string[] = [\n '<connections xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\">',\n ];\n\n for (const c of this.connections) {\n const cAttrs: Record<string, string | number | boolean | undefined> = {\n id: c.id,\n };\n if (c.name !== undefined) cAttrs.name = c.name;\n if (c.type !== undefined) cAttrs.type = c.type;\n if (c.refreshOnLoad) cAttrs.refreshOnLoad = 1;\n if (c.refreshedVersion !== undefined) cAttrs.refreshedVersion = c.refreshedVersion;\n else cAttrs.refreshedVersion = 6;\n if (c.backgroundRefresh) cAttrs.backgroundRefresh = 1;\n if (c.saveData === false) cAttrs.saveData = 0;\n if (c.savePassword) cAttrs.savePassword = 1;\n if (c.description !== undefined) cAttrs.description = c.description;\n if (c.credentials !== undefined) cAttrs.credentials = c.credentials;\n\n const children: string[] = [];\n\n // dbPr\n if (c.dbPr) {\n const dbAttrs: Record<string, string | number | undefined> = {\n connection: c.dbPr.connection,\n };\n if (c.dbPr.command !== undefined) dbAttrs.command = c.dbPr.command;\n if (c.dbPr.commandType !== undefined) dbAttrs.commandType = c.dbPr.commandType;\n if (c.dbPr.serverCommand !== undefined) dbAttrs.serverCommand = c.dbPr.serverCommand;\n children.push(`<dbPr${attrs(dbAttrs)}/>`);\n }\n\n // webPr\n if (c.webPr) {\n const wpAttrs: Record<string, string | number | boolean | undefined> = {\n url: c.webPr.url,\n };\n if (c.webPr.sourceData) wpAttrs.sourceData = 1;\n if (c.webPr.htmlFormat !== undefined) wpAttrs.htmlFormat = c.webPr.htmlFormat;\n if (c.webPr.consecutive) wpAttrs.consecutive = 1;\n if (c.webPr.firstRowHeader) wpAttrs.firstRowHeader = 1;\n if (c.webPr.parsePre) wpAttrs.parsePre = 1;\n if (c.webPr.xl2000) wpAttrs.xl2000 = 1;\n\n const wpChildren: string[] = [];\n if (c.webPr.htmlTables && c.webPr.htmlTables.length > 0) {\n wpChildren.push(\n `<tables>${c.webPr.htmlTables.map((t) => `<x v=\"${escapeXml(t)}\"/>`).join(\"\")}</tables>`,\n );\n }\n if (c.webPr.textFields && c.webPr.textFields.length > 0) {\n wpChildren.push(buildTextFields(c.webPr.textFields));\n }\n if (wpChildren.length > 0) {\n children.push(`<webPr${attrs(wpAttrs)}>${wpChildren.join(\"\")}</webPr>`);\n } else {\n children.push(`<webPr${attrs(wpAttrs)}/>`);\n }\n }\n\n // textPr\n if (c.textPr) {\n const tpAttrs: Record<string, string | number | boolean | undefined> = {};\n if (c.textPr.codePage !== undefined) tpAttrs.codePage = c.textPr.codePage;\n if (c.textPr.characterSet !== undefined) tpAttrs.characterSet = c.textPr.characterSet;\n if (c.textPr.sourceFile !== undefined) tpAttrs.sourceFile = c.textPr.sourceFile;\n if (c.textPr.delimited !== undefined) tpAttrs.delimited = c.textPr.delimited ? 1 : 0;\n if (c.textPr.tab !== undefined) tpAttrs.tab = c.textPr.tab ? 1 : 0;\n if (c.textPr.space !== undefined) tpAttrs.space = c.textPr.space ? 1 : 0;\n if (c.textPr.comma !== undefined) tpAttrs.comma = c.textPr.comma ? 1 : 0;\n if (c.textPr.semicolon !== undefined) tpAttrs.semicolon = c.textPr.semicolon ? 1 : 0;\n if (c.textPr.custom !== undefined) tpAttrs.custom = c.textPr.custom;\n if (c.textPr.decimal !== undefined) tpAttrs.decimal = c.textPr.decimal;\n if (c.textPr.thousands !== undefined) tpAttrs.thousands = c.textPr.thousands;\n if (c.textPr.trailingMinus !== undefined)\n tpAttrs.trailingMinus = c.textPr.trailingMinus ? 1 : 0;\n\n const tpChildren: string[] = [];\n if (c.textPr.textFields && c.textPr.textFields.length > 0) {\n tpChildren.push(buildTextFields(c.textPr.textFields));\n }\n if (tpChildren.length > 0) {\n children.push(`<textPr${attrs(tpAttrs)}>${tpChildren.join(\"\")}</textPr>`);\n } else {\n children.push(`<textPr${attrs(tpAttrs)}/>`);\n }\n }\n\n // parameters\n if (c.parameters && c.parameters.length > 0) {\n const paramParts: string[] = [`<parameters count=\"${c.parameters.length}\">`];\n for (const param of c.parameters) {\n const paramAttrs: Record<string, string | number | boolean | undefined> = {\n name: param.name,\n };\n if (param.sqlType !== undefined) paramAttrs.sqlType = param.sqlType;\n if (param.characterSet !== undefined) paramAttrs.characterSet = param.characterSet;\n if (param.stringValue !== undefined) paramAttrs.stringValue = param.stringValue;\n if (param.integerValue !== undefined) paramAttrs.integerValue = param.integerValue;\n if (param.booleanValue !== undefined)\n paramAttrs.booleanValue = param.booleanValue ? 1 : 0;\n if (param.refreshOnChange) paramAttrs.refreshOnChange = 1;\n if (param.prompt) paramAttrs.prompt = 1;\n if (param.reference !== undefined) paramAttrs.reference = param.reference;\n if (param.parameterType !== undefined) paramAttrs.parameterType = param.parameterType;\n paramParts.push(`<parameter${attrs(paramAttrs)}/>`);\n }\n paramParts.push(\"</parameters>\");\n children.push(paramParts.join(\"\"));\n }\n\n if (children.length > 0) {\n p.push(`<connection${attrs(cAttrs)}>${children.join(\"\")}</connection>`);\n } else {\n p.push(`<connection${attrs(cAttrs)}/>`);\n }\n }\n\n p.push(\"</connections>\");\n return p.join(\"\");\n }\n}\n\nfunction buildTextFields(fields: readonly TextFieldOptions[]): string {\n const parts: string[] = [`<textFields count=\"${fields.length}\">`];\n for (const f of fields) {\n const fAttrs: Record<string, string | number | undefined> = { type: f.type };\n if (f.dataType !== undefined) fAttrs.dataType = f.dataType;\n parts.push(`<textField${attrs(fAttrs)}/>`);\n }\n parts.push(\"</textFields>\");\n return parts.join(\"\");\n}\n","/**\n * XML Mapping elements — produces XML spreadsheet mapping elements.\n *\n * Reference: OOXML transitional, sml.xsd\n * CT_MapInfo, CT_Schema, CT_Map, CT_DataBinding,\n * CT_SingleXmlCells, CT_SingleXmlCell, CT_XmlCellPr, CT_XmlColumnPr, CT_XmlPr\n *\n * @module\n */\nimport { BaseXmlComponent } from \"@file/xml-components\";\nimport type { Context } from \"@file/xml-components\";\nimport { attrs } from \"@office-open/xml\";\n\n// ── Options ──\n\nexport interface SchemaOptions {\n /** Unique schema ID (required) */\n readonly id: string;\n /** Schema reference */\n readonly schemaRef?: string;\n /** Namespace URI */\n readonly namespace?: string;\n /** Schema language */\n readonly schemaLanguage?: string;\n /** Schema ID */\n readonly schemaID?: string;\n /** Element form default */\n readonly elementFormDefault?: string;\n /** Attribute form default */\n readonly attributeFormDefault?: string;\n}\n\nexport interface DataBindingOptions {\n /** Data binding name */\n readonly dataBindingName?: string;\n /** Whether this is a file binding */\n readonly fileBinding?: boolean;\n /** File binding name */\n readonly fileBindingName?: string;\n /** Connection ID */\n readonly connectionID?: number;\n /** Data binding load mode */\n readonly dataBindingLoadMode?: number;\n}\n\nexport interface MapOptions {\n /** Unique map ID (required) */\n readonly id: number;\n /** Map name (required) */\n readonly name: string;\n /** Root element name (required) */\n readonly rootElement: string;\n /** Associated schema ID (required) */\n readonly schemaID: string;\n /** Show import/export validation errors */\n readonly showImportExportValidationErrors?: boolean;\n /** Append data */\n readonly append?: boolean;\n /** Data binding load mode (on Map level) */\n readonly dataBindingLoadMode?: number;\n /** Auto-fit columns */\n readonly autoFit?: boolean;\n /** Whether this is a file binding (on Map level) */\n readonly fileBinding?: boolean;\n /** File binding name (on Map level) */\n readonly fileBindingName?: string;\n /** Preserve formatting */\n readonly preserveFormat?: boolean;\n /** Preserve sort/autofilter layout */\n readonly preserveSortAFLayout?: boolean;\n /** Data binding (child element) */\n readonly dataBinding?: DataBindingOptions;\n}\n\nexport interface MapInfoOptions {\n /** Selection namespaces (required) */\n readonly selectionNamespaces: string;\n /** Schema definitions */\n readonly schemas: readonly SchemaOptions[];\n /** XML maps */\n readonly maps: readonly MapOptions[];\n}\n\nexport interface XmlPrOptions {\n /** XML element name */\n readonly xmlElement?: string;\n /** Associated map ID (required) */\n readonly mapId: number;\n /** XPath expression (required) */\n readonly xpath: string;\n /** XML data type (required) */\n readonly xmlDataType: string;\n}\n\nexport interface XmlCellPrOptions {\n /** Cell ID (required) */\n readonly id: number;\n /** Unique name */\n readonly uniqueName?: string;\n /** XML properties */\n readonly xmlPr: XmlPrOptions;\n}\n\nexport interface SingleXmlCellOptions {\n /** XML cell ID (required) */\n readonly id: number;\n /** Cell reference, e.g. \"A1\" (required) */\n readonly r: string;\n /** Connection ID (required) */\n readonly connectionId: number;\n /** XML cell properties */\n readonly xmlCellPr: XmlCellPrOptions;\n}\n\nexport interface XmlColumnPrOptions {\n /** XPath expression (required) */\n readonly xpath: string;\n /** XML data type (required) */\n readonly xmlDataType: string;\n /** Associated map ID (required) */\n readonly mapId: number;\n}\n\n// ── Helper functions ──\n\nfunction schemaToXml(s: SchemaOptions): string {\n const a: Record<string, string | number | boolean | undefined> = {\n ID: s.id,\n };\n if (s.schemaRef !== undefined) a.SchemaRef = s.schemaRef;\n if (s.namespace !== undefined) a.Namespace = s.namespace;\n if (s.schemaLanguage !== undefined) a.SchemaLanguage = s.schemaLanguage;\n if (s.schemaID !== undefined) a.SchemaID = s.schemaID;\n if (s.elementFormDefault !== undefined) a.ElementFormDefault = s.elementFormDefault;\n if (s.attributeFormDefault !== undefined) a.AttributeFormDefault = s.attributeFormDefault;\n return `<Schema${attrs(a)}/>`;\n}\n\nfunction dataBindingToXml(db: DataBindingOptions): string {\n const a: Record<string, string | number | boolean | undefined> = {};\n if (db.dataBindingName !== undefined) a.DataBindingName = db.dataBindingName;\n if (db.fileBinding !== undefined) a.FileBinding = db.fileBinding ? 1 : 0;\n if (db.fileBindingName !== undefined) a.FileBindingName = db.fileBindingName;\n if (db.connectionID !== undefined) a.ConnectionID = db.connectionID;\n if (db.dataBindingLoadMode !== undefined) a.DataBindingLoadMode = db.dataBindingLoadMode;\n return `<DataBinding${attrs(a)}/>`;\n}\n\nfunction mapToXml(m: MapOptions): string {\n const a: Record<string, string | number | boolean | undefined> = {\n ID: m.id,\n Name: m.name,\n RootElement: m.rootElement,\n SchemaID: m.schemaID,\n };\n if (m.showImportExportValidationErrors !== undefined)\n a.ShowImportExportValidationErrors = m.showImportExportValidationErrors ? 1 : 0;\n if (m.append !== undefined) a.Append = m.append ? 1 : 0;\n if (m.dataBindingLoadMode !== undefined) a.DataBindingLoadMode = m.dataBindingLoadMode;\n if (m.autoFit !== undefined) a.AutoFit = m.autoFit ? 1 : 0;\n if (m.fileBinding !== undefined) a.FileBinding = m.fileBinding ? 1 : 0;\n if (m.fileBindingName !== undefined) a.FileBindingName = m.fileBindingName;\n if (m.preserveFormat !== undefined) a.PreserveFormat = m.preserveFormat ? 1 : 0;\n if (m.preserveSortAFLayout !== undefined) a.PreserveSortAFLayout = m.preserveSortAFLayout ? 1 : 0;\n\n const children: string[] = [];\n if (m.dataBinding) {\n children.push(dataBindingToXml(m.dataBinding));\n }\n\n if (children.length > 0) {\n return `<Map${attrs(a)}>${children.join(\"\")}</Map>`;\n }\n return `<Map${attrs(a)}/>`;\n}\n\nfunction xmlPrToXml(xp: XmlPrOptions): string {\n const a: Record<string, string | number | boolean | undefined> = {\n mapId: xp.mapId,\n xpath: xp.xpath,\n xmlDataType: xp.xmlDataType,\n };\n if (xp.xmlElement !== undefined) a.xmlElement = xp.xmlElement;\n return `<xmlPr${attrs(a)}/>`;\n}\n\nfunction xmlCellPrToXml(xcp: XmlCellPrOptions): string {\n const a: Record<string, string | number | boolean | undefined> = {\n id: xcp.id,\n };\n if (xcp.uniqueName !== undefined) a.uniqueName = xcp.uniqueName;\n return `<xmlCellPr${attrs(a)}>${xmlPrToXml(xcp.xmlPr)}</xmlCellPr>`;\n}\n\nfunction singleXmlCellToXml(sxc: SingleXmlCellOptions): string {\n const a: Record<string, string | number | boolean | undefined> = {\n id: sxc.id,\n r: sxc.r,\n connectionId: sxc.connectionId,\n };\n return `<singleXmlCell${attrs(a)}>${xmlCellPrToXml(sxc.xmlCellPr)}</singleXmlCell>`;\n}\n\n// ── Components ──\n\nexport class MapInfoXml extends BaseXmlComponent {\n private readonly options: MapInfoOptions;\n\n public constructor(options: MapInfoOptions) {\n super(\"MapInfo\");\n this.options = options;\n }\n\n public override toXml(_context: Context): string {\n const p: string[] = [\n '<MapInfo xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\"',\n ];\n p.push(` SelectionNamespaces=\"${this.options.selectionNamespaces}\">`);\n\n for (const s of this.options.schemas) {\n p.push(schemaToXml(s));\n }\n for (const m of this.options.maps) {\n p.push(mapToXml(m));\n }\n\n p.push(\"</MapInfo>\");\n return p.join(\"\");\n }\n}\n\nexport class SingleXmlCellsXml extends BaseXmlComponent {\n private readonly cells: readonly SingleXmlCellOptions[];\n\n public constructor(cells: readonly SingleXmlCellOptions[]) {\n super(\"singleXmlCells\");\n this.cells = cells;\n }\n\n public override toXml(_context: Context): string {\n const p: string[] = [\n '<singleXmlCells xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\">',\n ];\n\n for (const cell of this.cells) {\n p.push(singleXmlCellToXml(cell));\n }\n\n p.push(\"</singleXmlCells>\");\n return p.join(\"\");\n }\n}\n\nexport class XmlColumnPrXml extends BaseXmlComponent {\n private readonly options: XmlColumnPrOptions;\n\n public constructor(options: XmlColumnPrOptions) {\n super(\"xmlColumnPr\");\n this.options = options;\n }\n\n public override toXml(_context: Context): string {\n const a: Record<string, string | number | boolean | undefined> = {\n xpath: this.options.xpath,\n xmlDataType: this.options.xmlDataType,\n mapId: this.options.mapId,\n };\n return `<xmlColumnPr${attrs(a)}/>`;\n }\n}\n","/**\n * Calculation Chain — generates xl/calcChain.xml.\n *\n * The calculation chain lists formula cells in calculation order,\n * enabling faster recalculation in spreadsheet applications.\n *\n * Reference: OOXML transitional, sml.xsd, CT_CalcChain / CT_CalcCell\n *\n * @module\n */\nimport { BaseXmlComponent } from \"@file/xml-components\";\nimport type { Context } from \"@file/xml-components\";\nimport { attrs } from \"@office-open/xml\";\n\nexport interface CalcCell {\n /** Cell reference, e.g. \"A1\" */\n readonly reference: string;\n /** Sheet index (1-based) */\n readonly sheetIndex: number;\n /** Array formula */\n readonly array?: boolean;\n}\n\nexport class CalcChain extends BaseXmlComponent {\n private readonly cells: CalcCell[] = [];\n\n public constructor() {\n super(\"calcChain\");\n }\n\n public addCell(cell: CalcCell): void {\n this.cells.push(cell);\n }\n\n public get count(): number {\n return this.cells.length;\n }\n\n public override toXml(_context: Context): string {\n const parts: string[] = [\n '<calcChain xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\">',\n ];\n for (const cell of this.cells) {\n const cellAttrs: Record<string, string | number | boolean> = {\n r: cell.reference,\n i: cell.sheetIndex,\n };\n if (cell.array) cellAttrs.a = true;\n parts.push(`<c${attrs(cellAttrs)}/>`);\n }\n parts.push(\"</calcChain>\");\n return parts.join(\"\");\n }\n}\n","/**\n * Chartsheet XML generator — produces xl/chartsheets/sheetN.xml.\n *\n * A chartsheet is a worksheet that contains only a chart (no cells).\n *\n * Reference: OOXML transitional, sml.xsd, CT_Chartsheet\n *\n * @module\n */\nimport { BaseXmlComponent } from \"@file/xml-components\";\nimport type { Context } from \"@file/xml-components\";\nimport { attrs, escapeXml } from \"@office-open/xml\";\n\n// ── Options ──\n\nexport interface ChartsheetPageMargins {\n readonly left?: number;\n readonly right?: number;\n readonly top?: number;\n readonly bottom?: number;\n readonly header?: number;\n readonly footer?: number;\n}\n\nexport interface ChartsheetPageSetup {\n /** Paper size (1=Letter, 9=A4, etc.) */\n readonly paperSize?: number;\n /** Orientation (\"default\" | \"portrait\" | \"landscape\") */\n readonly orientation?: string;\n /** Horizontal DPI */\n readonly horizontalDpi?: number;\n /** Vertical DPI */\n readonly verticalDpi?: number;\n /** Copies to print */\n readonly copies?: number;\n}\n\nexport interface ChartsheetProtectionOptions {\n /** Content is protected */\n readonly content?: boolean;\n /** Objects are protected */\n readonly objects?: boolean;\n}\n\nexport interface ChartsheetHeaderFooterOptions {\n /** Different first page header/footer */\n readonly differentFirst?: boolean;\n /** Different odd/even page headers/footers */\n readonly differentOddEven?: boolean;\n /** Odd page header */\n readonly oddHeader?: string;\n /** Odd page footer */\n readonly oddFooter?: string;\n}\n\nexport interface ChartsheetOptions {\n /** Sheet name */\n readonly name?: string;\n /** Tab color (hex ARGB, e.g. \"FF4472C4\") */\n readonly tabColor?: string;\n /** Page margins */\n readonly pageMargins?: ChartsheetPageMargins;\n /** Page setup */\n readonly pageSetup?: ChartsheetPageSetup;\n /** Header/footer */\n readonly headerFooter?: ChartsheetHeaderFooterOptions;\n /** Sheet protection */\n readonly sheetProtection?: ChartsheetProtectionOptions;\n /** Published to server (CT_ChartsheetPr @published) */\n readonly published?: boolean;\n /** Zoom to fit (CT_ChartsheetView @zoomToFit) */\n readonly zoomToFit?: boolean;\n /** Chart definition (type, title, series, etc.) */\n readonly chart: {\n readonly type: string;\n readonly title?: string;\n readonly categories?: readonly string[];\n readonly series: readonly {\n readonly name: string;\n readonly values: readonly number[];\n }[];\n };\n}\n\n// ── Component ──\n\nexport class Chartsheet extends BaseXmlComponent {\n private readonly opts: ChartsheetOptions;\n private drawingRId: string = \"rId1\";\n\n public constructor(options: ChartsheetOptions) {\n super(\"chartsheet\");\n this.opts = options;\n }\n\n public setDrawingRId(rId: string): void {\n this.drawingRId = rId;\n }\n\n public override toXml(_context: Context): string {\n const p: string[] = [\n '<chartsheet xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\"' +\n ' xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\">',\n ];\n\n // sheetPr (optional)\n if (this.opts.tabColor || this.opts.published) {\n const prAttrs: string[] = [];\n if (this.opts.tabColor) prAttrs.push(`<tabColor${attrs({ rgb: this.opts.tabColor })}/>`);\n const spAttr = this.opts.published ? ' published=\"1\"' : \"\";\n p.push(`<sheetPr${spAttr}>${prAttrs.join(\"\")}</sheetPr>`);\n }\n\n // sheetViews (required)\n const svAttrs: string[] = ['workbookViewId=\"0\"'];\n if (this.opts.zoomToFit) svAttrs.push('zoomToFit=\"1\"');\n p.push(`<sheetViews><sheetView ${svAttrs.join(\" \")}/></sheetViews>`);\n\n // sheetProtection (optional, XSD: after sheetViews, before pageMargins)\n if (this.opts.sheetProtection) {\n const sp = this.opts.sheetProtection;\n const spAttrs: string[] = [];\n if (sp.content) spAttrs.push(` content=\"1\"`);\n if (sp.objects) spAttrs.push(` objects=\"1\"`);\n if (spAttrs.length > 0) {\n p.push(`<sheetProtection${spAttrs.join(\"\")}/>`);\n }\n }\n\n // pageMargins (optional)\n if (this.opts.pageMargins) {\n const pm = this.opts.pageMargins;\n p.push(\n `<pageMargins${attrs({\n left: pm.left ?? 0.7,\n right: pm.right ?? 0.7,\n top: pm.top ?? 0.75,\n bottom: pm.bottom ?? 0.75,\n header: pm.header ?? 0.3,\n footer: pm.footer ?? 0.3,\n })}/>`,\n );\n }\n\n // pageSetup (optional)\n if (this.opts.pageSetup) {\n const ps = this.opts.pageSetup;\n p.push(\n `<pageSetup${attrs({\n paperSize: ps.paperSize,\n orientation: ps.orientation,\n horizontalDpi: ps.horizontalDpi,\n verticalDpi: ps.verticalDpi,\n copies: ps.copies,\n })}/>`,\n );\n }\n\n // headerFooter (optional)\n if (this.opts.headerFooter) {\n const hf = this.opts.headerFooter;\n const hfParts: string[] = [];\n if (hf.differentFirst) hfParts.push(` differentFirst=\"1\"`);\n if (hf.differentOddEven) hfParts.push(` differentOddEven=\"1\"`);\n const hfContent: string[] = [];\n if (hf.oddHeader) hfContent.push(`<oddHeader>${escapeXml(hf.oddHeader)}</oddHeader>`);\n if (hf.oddFooter) hfContent.push(`<oddFooter>${escapeXml(hf.oddFooter)}</oddFooter>`);\n p.push(`<headerFooter${hfParts.join(\"\")}>${hfContent.join(\"\")}</headerFooter>`);\n }\n\n // drawing (required)\n p.push(`<drawing r:id=\"${escapeXml(this.drawingRId)}\"/>`);\n\n p.push(\"</chartsheet>\");\n return p.join(\"\");\n }\n}\n","import { BaseXmlComponent } from \"@file/xml-components\";\nimport type { Context } from \"@file/xml-components\";\nimport { escapeXml } from \"@office-open/xml\";\n\nimport { buildRstXml } from \"./shared-strings\";\nimport type { CommentOptions } from \"./worksheet\";\n\n/**\n * Generates xl/comments{n}.xml — cell comment data.\n *\n * @module\n */\nexport class Comments extends BaseXmlComponent {\n public constructor(private readonly entries: readonly CommentOptions[]) {\n super(\"comments\");\n }\n\n public override toXml(_context: Context): string {\n const authors = this.collectAuthors();\n const p: string[] = [\n '<comments xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\">',\n `<authors>`,\n ];\n\n for (const author of authors) {\n p.push(`<author>${escapeXml(author)}</author>`);\n }\n\n p.push(\"</authors><commentList>\");\n\n for (const entry of this.entries) {\n const authorId = authors.indexOf(entry.author);\n const textXml =\n typeof entry.text === \"string\"\n ? `<t>${escapeXml(entry.text)}</t>`\n : buildRstXml(entry.text);\n // commentPr (CT_CommentPr, optional)\n let commentPrXml = \"\";\n if (entry.commentPr) {\n const cp = entry.commentPr;\n const cpAttrs: string[] = [];\n if (cp.locked === false) cpAttrs.push('locked=\"0\"');\n if (cp.defaultSize === false) cpAttrs.push('defaultSize=\"0\"');\n if (cp.print === false) cpAttrs.push('print=\"0\"');\n if (cp.disabled) cpAttrs.push('disabled=\"1\"');\n if (cp.autoFill === false) cpAttrs.push('autoFill=\"0\"');\n if (cp.autoLine === false) cpAttrs.push('autoLine=\"0\"');\n if (cp.altText) cpAttrs.push(`altText=\"${escapeXml(cp.altText)}\"`);\n if (cp.textHAlign && cp.textHAlign !== \"left\")\n cpAttrs.push(`textHAlign=\"${cp.textHAlign}\"`);\n if (cp.textVAlign && cp.textVAlign !== \"top\") cpAttrs.push(`textVAlign=\"${cp.textVAlign}\"`);\n if (cp.lockText === false) cpAttrs.push('lockText=\"0\"');\n if (cp.justLastX) cpAttrs.push('justLastX=\"1\"');\n if (cp.autoScale) cpAttrs.push('autoScale=\"1\"');\n // anchor (CT_ObjectAnchor, required child of commentPr)\n const anchorAttrs: string[] = [];\n if (cp.anchor?.moveWithCells) anchorAttrs.push('moveWithCells=\"1\"');\n if (cp.anchor?.sizeWithCells) anchorAttrs.push('sizeWithCells=\"1\"');\n commentPrXml = `<commentPr${cpAttrs.length ? \" \" + cpAttrs.join(\" \") : \"\"}><anchor${anchorAttrs.length ? \" \" + anchorAttrs.join(\" \") : \"\"}/></commentPr>`;\n }\n p.push(\n `<comment ref=\"${entry.cell}\" authorId=\"${authorId}\"><text>${textXml}</text>${commentPrXml}</comment>`,\n );\n }\n\n p.push(\"</commentList></comments>\");\n return p.join(\"\");\n }\n\n private collectAuthors(): string[] {\n const seen = new Set<string>();\n const result: string[] = [];\n for (const entry of this.entries) {\n if (!seen.has(entry.author)) {\n seen.add(entry.author);\n result.push(entry.author);\n }\n }\n return result.length > 0 ? result : [\"\"];\n }\n}\n","/**\n * XLSX Drawing component — generates xl/drawings/drawing{n}.xml.\n *\n * Uses the spreadsheetDrawing namespace (default, no prefix) for anchoring\n * images and charts to worksheet cells.\n *\n * @module\n */\nimport { BaseXmlComponent } from \"@file/xml-components\";\nimport type { Context } from \"@file/xml-components\";\n\nexport interface ImageOptions {\n /** 1-based column */\n readonly col: number;\n /** Column offset in EMU (default 0) */\n readonly colOffset?: number;\n /** 1-based row */\n readonly row: number;\n /** Row offset in EMU (default 0) */\n readonly rowOffset?: number;\n /** Relationship ID for the image */\n readonly rId: string;\n /** Lock anchor with sheet (default true) */\n readonly locksWithSheet?: boolean;\n /** Print with sheet (default true) */\n readonly printsWithSheet?: boolean;\n}\n\nexport interface ChartAnchorOptions {\n /** 1-based column */\n readonly col: number;\n /** Column offset in EMU (default 0) */\n readonly colOffset?: number;\n /** 1-based row */\n readonly row: number;\n /** Row offset in EMU (default 0) */\n readonly rowOffset?: number;\n /** Relationship ID for the chart */\n readonly rId: string;\n /** Lock anchor with sheet (default true) */\n readonly locksWithSheet?: boolean;\n /** Print with sheet (default true) */\n readonly printsWithSheet?: boolean;\n}\n\nconst XDR_NS = \"http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing\";\nconst A_NS = \"http://schemas.openxmlformats.org/drawingml/2006/main\";\nconst R_NS = \"http://schemas.openxmlformats.org/officeDocument/2006/relationships\";\nconst C_URI = \"http://schemas.openxmlformats.org/drawingml/2006/chart\";\n\nexport class Drawing extends BaseXmlComponent {\n private readonly images: readonly ImageOptions[];\n private readonly charts: readonly ChartAnchorOptions[];\n\n public constructor(images: readonly ImageOptions[], charts: readonly ChartAnchorOptions[] = []) {\n super(\"wsDr\");\n this.images = images;\n this.charts = charts;\n }\n\n public override toXml(_context: Context): string {\n const p: string[] = [`<wsDr xmlns=\"${XDR_NS}\" xmlns:a=\"${A_NS}\" xmlns:r=\"${R_NS}\">`];\n let id = 1;\n for (const img of this.images) {\n p.push(\n `<twoCellAnchor editAs=\"oneCell\"><from><col>${img.col - 1}</col><colOff>${img.colOffset ?? 0}</colOff><row>${img.row - 1}</row><rowOff>${img.rowOffset ?? 0}</rowOff></from>`,\n `<to><col>${img.col}</col><colOff>0</colOff><row>${img.row}</row><rowOff>0</rowOff></to>`,\n `<pic><nvPicPr><cNvPr id=\"${id}\" name=\"Picture ${id}\"/><cNvPicPr preferRelativeResize=\"1\"/></nvPicPr>`,\n `<blipFill><a:blip r:embed=\"${img.rId}\"/><a:stretch><a:fillRect/></a:stretch></blipFill>`,\n `<spPr><a:xfrm><a:off x=\"0\" y=\"0\"/><a:ext cx=\"400000\" cy=\"300000\"/></a:xfrm><a:prstGeom prst=\"rect\"><a:avLst/></a:prstGeom></spPr></pic>`,\n `<clientData fLocksWithSheet=\"${img.locksWithSheet !== false ? 1 : 0}\" fPrintsWithSheet=\"${img.printsWithSheet !== false ? 1 : 0}\"/></twoCellAnchor>`,\n );\n id++;\n }\n for (const chart of this.charts) {\n p.push(\n `<twoCellAnchor editAs=\"oneCell\"><from><col>${chart.col - 1}</col><colOff>${chart.colOffset ?? 0}</colOff><row>${chart.row - 1}</row><rowOff>${chart.rowOffset ?? 0}</rowOff></from>`,\n `<to><col>${chart.col + 8}</col><colOff>0</colOff><row>${chart.row + 15}</row><rowOff>0</rowOff></to>`,\n `<graphicFrame><nvGraphicFramePr><cNvPr id=\"${id}\" name=\"Chart ${id}\"/><cNvGraphicFramePr><a:graphicFrameLocks noGrp=\"1\"/></cNvGraphicFramePr></nvGraphicFramePr>`,\n `<xfrm><a:off x=\"0\" y=\"0\"/><a:ext cx=\"0\" cy=\"0\"/></xfrm>`,\n `<a:graphic><a:graphicData uri=\"${C_URI}\"><c:chart xmlns:c=\"http://schemas.openxmlformats.org/drawingml/2006/chart\" xmlns:r=\"${R_NS}\" r:id=\"${chart.rId}\"/></a:graphicData></a:graphic></graphicFrame>`,\n `<clientData fLocksWithSheet=\"${chart.locksWithSheet !== false ? 1 : 0}\" fPrintsWithSheet=\"${chart.printsWithSheet !== false ? 1 : 0}\"/></twoCellAnchor>`,\n );\n id++;\n }\n p.push(\"</wsDr>\");\n return p.join(\"\");\n }\n}\n","/**\n * External Link XML generator — produces xl/externalLinks/externalLinkN.xml.\n *\n * Reference: OOXML transitional, sml.xsd, CT_ExternalLink\n *\n * @module\n */\nimport { BaseXmlComponent } from \"@file/xml-components\";\nimport type { Context } from \"@file/xml-components\";\nimport { attrs, escapeXml } from \"@office-open/xml\";\n\n// ── Options ──\n\nexport interface ExternalDefinedNameOptions {\n readonly name: string;\n readonly refersTo?: string;\n readonly sheetId?: number;\n}\n\nexport interface ExternalCellOptions {\n /** Cell reference, e.g. \"A1\" */\n readonly reference: string;\n /** Cell data type */\n readonly type?: string;\n /** Cell value */\n readonly value?: string;\n}\n\nexport interface ExternalBookOptions {\n /** Target path of the external workbook */\n readonly target?: string;\n /** Sheet names from the external workbook */\n readonly sheetNames?: readonly string[];\n /** Defined names from the external workbook */\n readonly definedNames?: readonly ExternalDefinedNameOptions[];\n /** Cached sheet data from the external workbook */\n readonly sheetDataSet?: readonly ExternalSheetDataOptions[];\n}\n\nexport interface ExternalRowOptions {\n /** Row number (1-based) */\n readonly rowNumber: number;\n readonly cells?: readonly ExternalCellOptions[];\n}\n\nexport interface ExternalSheetDataOptions {\n readonly sheetId: number;\n readonly refreshError?: boolean;\n readonly rows?: readonly ExternalRowOptions[];\n}\n\nexport interface ExternalLinkOptions {\n /** External book configuration */\n readonly externalBook?: ExternalBookOptions;\n /** Relationship ID for the external book (set by compiler) */\n readonly bookRId?: string;\n /** OLE link configuration (CT_OleLink) */\n readonly oleLink?: OleLinkOptions;\n /** Relationship ID for the OLE link (set by compiler) */\n readonly oleRId?: string;\n}\n\nexport interface OleItemOptions {\n /** OLE item name (required) */\n readonly name: string;\n /** Whether to advise events */\n readonly advise?: boolean;\n /** Whether preferred */\n readonly prefer?: boolean;\n}\n\nexport interface OleLinkOptions {\n /** OLE items */\n readonly oleItems?: readonly OleItemOptions[];\n}\n\n// ── Component ──\n\nexport class ExternalLinkXml extends BaseXmlComponent {\n private readonly opts: ExternalLinkOptions;\n\n public constructor(options: ExternalLinkOptions) {\n super(\"externalLink\");\n this.opts = options;\n }\n\n public override toXml(_context: Context): string {\n const p: string[] = [\n '<externalLink xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\"' +\n ' xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\">',\n ];\n\n if (this.opts.externalBook) {\n const book = this.opts.externalBook;\n // r:id is required on externalBook but will be set when the relationship is created\n // We use a placeholder that gets resolved by the compiler\n const bookParts: string[] = [];\n\n if (book.sheetNames && book.sheetNames.length > 0) {\n bookParts.push(\"<sheetNames>\");\n for (const name of book.sheetNames) {\n bookParts.push(`<sheetName val=\"${escapeXml(name)}\"/>`);\n }\n bookParts.push(\"</sheetNames>\");\n }\n\n if (book.definedNames && book.definedNames.length > 0) {\n bookParts.push(\"<definedNames>\");\n for (const dn of book.definedNames) {\n const dnAttrs: Record<string, string | number | undefined> = { name: dn.name };\n if (dn.refersTo !== undefined) dnAttrs.refersTo = dn.refersTo;\n if (dn.sheetId !== undefined) dnAttrs.sheetId = dn.sheetId;\n bookParts.push(`<definedName${attrs(dnAttrs)}/>`);\n }\n bookParts.push(\"</definedNames>\");\n }\n\n if (book.sheetDataSet && book.sheetDataSet.length > 0) {\n bookParts.push(\"<sheetDataSet>\");\n for (const sd of book.sheetDataSet) {\n const sdAttrs: Record<string, string | number | boolean | undefined> = {\n sheetId: sd.sheetId,\n };\n if (sd.refreshError) sdAttrs.refreshError = 1;\n bookParts.push(`<sheetData${attrs(sdAttrs)}>`);\n\n if (sd.rows) {\n for (const row of sd.rows) {\n bookParts.push(`<row r=\"${row.rowNumber}\">`);\n if (row.cells) {\n for (const cell of row.cells) {\n const cellAttrs: Record<string, string | number | undefined> = {\n r: cell.reference,\n };\n if (cell.type !== undefined) cellAttrs.t = cell.type;\n if (cell.value !== undefined) {\n bookParts.push(\n `<cell${attrs(cellAttrs)}><v>${escapeXml(cell.value)}</v></cell>`,\n );\n } else {\n bookParts.push(`<cell${attrs(cellAttrs)}/>`);\n }\n }\n }\n bookParts.push(\"</row>\");\n }\n }\n bookParts.push(\"</sheetData>\");\n }\n bookParts.push(\"</sheetDataSet>\");\n }\n\n const ridAttr = this.opts.bookRId ? ` r:id=\"${this.opts.bookRId}\"` : \"\";\n p.push(\n `<externalBook${ridAttr}${bookParts.length > 0 ? `>${bookParts.join(\"\")}</externalBook>` : \"/>\"}`,\n );\n }\n\n // oleLink (CT_OleLink)\n if (this.opts.oleLink) {\n const oleRId = this.opts.oleRId ? ` r:id=\"${escapeXml(this.opts.oleRId)}\"` : \"\";\n const oleChildren: string[] = [];\n if (this.opts.oleLink.oleItems && this.opts.oleLink.oleItems.length > 0) {\n const itemParts: string[] = [`<oleItems>`];\n for (const item of this.opts.oleLink.oleItems) {\n const itemAttrs: string[] = [`name=\"${escapeXml(item.name)}\"`];\n if (item.advise) itemAttrs.push('advise=\"1\"');\n if (item.prefer) itemAttrs.push('prefer=\"1\"');\n itemParts.push(`<oleItem ${itemAttrs.join(\" \")}/>`);\n }\n itemParts.push(\"</oleItems>\");\n oleChildren.push(itemParts.join(\"\"));\n }\n if (oleChildren.length > 0) {\n p.push(`<oleLink${oleRId}>${oleChildren.join(\"\")}</oleLink>`);\n } else {\n p.push(`<oleLink${oleRId}/>`);\n }\n }\n\n p.push(\"</externalLink>\");\n return p.join(\"\");\n }\n}\n","/**\n * VML Notes — generates legacy VML drawing for worksheet comments.\n *\n * Excel requires a VML drawing file (xl/drawings/vmlDrawing{N}.vml)\n * referenced by <legacyDrawing r:id=\"...\"/> in the worksheet XML.\n *\n * @module\n */\nimport type { CommentOptions } from \"@file/worksheet\";\n\nexport class VmlNotes {\n public constructor(private readonly comments: readonly CommentOptions[]) {}\n\n public toXml(): string {\n const p: string[] = [\n '<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>',\n '<xml xmlns:v=\"urn:schemas-microsoft-com:vml\" xmlns:o=\"urn:schemas-microsoft-com:office:office\" xmlns:x=\"urn:schemas-microsoft-com:office:excel\">',\n '<o:shapelayout v:ext=\"edit\"><o:idmap v:ext=\"edit\" data=\"1\"/></o:shapelayout>',\n '<v:shapetype id=\"_x0000_t202\" coordsize=\"21600,21600\" o:spt=\"202\" path=\"m,l,21600r21600,l21600,xe\">',\n '<v:stroke joinstyle=\"miter\"/>',\n '<v:path gradientshapeok=\"t\" o:connecttype=\"rect\"/>',\n \"</v:shapetype>\",\n ];\n\n for (let i = 0; i < this.comments.length; i++) {\n const c = this.comments[i];\n const col = c.cell.charCodeAt(0) - 65;\n const row = parseInt(c.cell.slice(1), 10) - 1;\n // 8-value anchor: fromCol, fromColOffset, fromRow, fromRowOffset, toCol, toColOffset, toRow, toRowOffset\n const anchor = `${col}, 0, ${row}, 0, ${col + 2}, 0, ${row + 2}, 0`;\n p.push(\n `<v:shape id=\"_x0000_s${1025 + i}\" type=\"#_x0000_t202\" ` +\n `style=\"position:absolute;margin-left:59.25pt;margin-top:1.5pt;width:108pt;height:59.25pt;` +\n `z-index:1;visibility:hidden\" fillcolor=\"infoBackground [80]\" strokecolor=\"none [81]\" o:insetmode=\"auto\">`,\n `<v:fill color2=\"infoBackground [80]\"/>`,\n `<v:shadow color=\"none [81]\" obscured=\"t\"/>`,\n `<v:path o:connecttype=\"none\"/>`,\n `<v:textbox style=\"mso-direction-alt:auto\"><div style=\"text-align:left\"/></v:textbox>`,\n `<x:ClientData ObjectType=\"Note\"><x:MoveWithCells/><x:SizeWithCells/>`,\n `<x:Anchor>${anchor}</x:Anchor>`,\n `<x:AutoFill>False</x:AutoFill>`,\n `<x:Row>${row}</x:Row>`,\n `<x:Column>${col}</x:Column>`,\n `</x:ClientData>`,\n `</v:shape>`,\n );\n }\n\n p.push(\"</xml>\");\n return p.join(\"\");\n }\n}\n","/**\n * XLSX Compiler — compiles a File object into a Zippable structure.\n *\n * @module\n */\nimport { Formatter } from \"@export/formatter\";\nimport { CalcChain } from \"@file/calc-chain\";\nimport { Chartsheet } from \"@file/chartsheet\";\nimport { Comments } from \"@file/comments\";\nimport { Drawing, type ImageOptions, type ChartAnchorOptions } from \"@file/drawing/drawing\";\nimport { ExternalLinkXml } from \"@file/external-link\";\nimport type { File } from \"@file/file\";\nimport {\n PivotCacheDefinitionXml,\n PivotCacheRecordsXml,\n PivotTableXml,\n aggregate,\n} from \"@file/pivot\";\nimport type { PivotSourceData, PivotTableOptions } from \"@file/pivot\";\nimport { TableXml } from \"@file/table\";\nimport { VmlNotes } from \"@file/vml-notes\";\nimport { WorkbookXml, type TablePartReference } from \"@file/workbook\";\nimport type { BaseXmlComponent, Context } from \"@file/xml-components\";\nimport {\n ChartSpace,\n Relationships,\n TargetModeType,\n compileMapping,\n type XmlifyedFile,\n type Zippable,\n} from \"@office-open/core\";\n\nexport class Compiler {\n private readonly formatter = new Formatter();\n\n public compile(\n file: File,\n overrides: readonly XmlifyedFile[] = [],\n mediaLevel: number = 0,\n ): Zippable {\n const context: Context = { fileData: file, stack: [] };\n const f = this.formatter;\n\n const mapping: Record<string, { data: string; path: string }> = {};\n\n const fmt = (component: BaseXmlComponent) => f.formatToXml(component, context);\n\n // Core properties\n mapping[\"Properties\"] = {\n data: fmt(file.coreProperties),\n path: \"docProps/core.xml\",\n };\n\n // App properties\n mapping[\"AppProperties\"] = {\n data: fmt(file.appProperties),\n path: \"docProps/app.xml\",\n };\n\n // File-level relationships (_rels/.rels)\n mapping[\"FileRelationships\"] = {\n data: fmt(file.fileRelationships),\n path: \"_rels/.rels\",\n };\n\n // Worksheets — formatted BEFORE SharedStrings so strings are registered\n const worksheets = file.worksheets;\n let globalMediaIdx = 0;\n let globalChartIdx = 0;\n let globalPivotIdx = 0;\n let globalPivotCacheIdx = 0;\n let globalTableIdx = 0;\n const pivotCacheDataMap = new Map<string, { cacheId: number; cacheIdx: number }>();\n const calcChain = new CalcChain();\n const allTableParts: TablePartReference[] = [];\n\n for (let i = 0; i < worksheets.length; i++) {\n const ws = worksheets[i];\n const imgOpts = ws.imageOptions;\n const chartOpts = ws.charts;\n const hlOpts = ws.hyperlinkOptions;\n const sheetName = file.worksheetConfigs[i]?.name ?? `Sheet${i + 1}`;\n\n // Worksheet uses toXml() fast path (zero-allocation string concat)\n let sheetXml = fmt(ws);\n\n // Collect formula cells for calcChain\n const sheetIdx = i + 1;\n const wsRows = ws.worksheetRows;\n for (let ri = 0; ri < wsRows.length; ri++) {\n const rowOpts = wsRows[ri];\n const rowNumber = rowOpts.rowNumber ?? ri + 1;\n if (!rowOpts.cells) continue;\n for (let ci = 0; ci < rowOpts.cells.length; ci++) {\n const cell = rowOpts.cells[ci];\n if (!cell.formula) continue;\n const ref = cell.reference ?? columnToLetter(ci + 1) + rowNumber;\n calcChain.addCell({\n reference: ref,\n sheetIndex: sheetIdx,\n array: cell.formula.type === \"array\",\n });\n }\n }\n\n const hasMedia = imgOpts.length > 0 || chartOpts.length > 0;\n const hasExternalHyperlinks = hlOpts.some((h) => h.target.type === \"external\");\n const commentOpts = ws.commentOptions;\n const hasComments = commentOpts.length > 0;\n const pivotOpts = ws.pivotTables;\n const hasPivots = pivotOpts.length > 0;\n const tableOpts = ws.tables;\n const hasTables = tableOpts.length > 0;\n const bgImg = ws.background;\n\n // Worksheet-level relationships\n let wsRels: Relationships | undefined;\n let nextRid = 0;\n\n if (hasMedia || hasExternalHyperlinks || hasComments || hasPivots || hasTables || bgImg) {\n wsRels = new Relationships();\n }\n\n if (hasExternalHyperlinks) {\n for (const hl of hlOpts) {\n if (hl.target.type !== \"external\") continue;\n const rid = ++nextRid;\n wsRels!.addRelationship(\n rid,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink\",\n hl.target.url,\n \"External\",\n );\n }\n }\n\n if (hasMedia) {\n const drawingImages: ImageOptions[] = [];\n const drawingCharts: ChartAnchorOptions[] = [];\n const drawingRels = new Relationships();\n let rid = 1;\n\n // Process images\n for (const img of imgOpts) {\n const mediaKey = `image_${globalMediaIdx}`;\n const ext = img.type === \"jpeg\" || img.type === \"jpg\" ? \"jpeg\" : \"png\";\n file.media.addImage(mediaKey, {\n fileName: `image${globalMediaIdx + 1}.${ext}`,\n type: ext,\n data: img.data,\n width: 0,\n height: 0,\n });\n\n drawingRels.addRelationship(\n rid,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/image\",\n `../media/image${globalMediaIdx + 1}.${ext}`,\n );\n\n drawingImages.push({\n col: img.col,\n row: img.row,\n rId: `rId${rid}`,\n });\n rid++;\n globalMediaIdx++;\n }\n\n // Process charts\n for (const chart of chartOpts) {\n const chartKey = `chart_${globalChartIdx}`;\n file.charts.addChart(chartKey, {\n key: chartKey,\n chartSpace: new ChartSpace(chart),\n });\n\n drawingRels.addRelationship(\n rid,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart\",\n `../charts/chart${globalChartIdx + 1}.xml`,\n );\n\n drawingCharts.push({\n col: chart.col,\n row: chart.row,\n rId: `rId${rid}`,\n });\n rid++;\n globalChartIdx++;\n }\n\n // Generate drawing XML\n const drawing = new Drawing(drawingImages, drawingCharts);\n const drawingIdx = i + 1;\n mapping[`Drawing${i}`] = {\n data: fmt(drawing),\n path: `xl/drawings/drawing${drawingIdx}.xml`,\n };\n\n // Drawing relationships\n mapping[`DrawingRels${i}`] = {\n data: fmt(drawingRels),\n path: `xl/drawings/_rels/drawing${drawingIdx}.xml.rels`,\n };\n\n // Insert drawing reference before the closing </worksheet> tag.\n const drawingRid = ++nextRid;\n const closingTag = \"</worksheet>\";\n sheetXml =\n sheetXml.slice(0, -closingTag.length) + `<drawing r:id=\"rId${drawingRid}\"/>` + closingTag;\n\n // Add drawing relationship to worksheet rels\n wsRels!.addRelationship(\n drawingRid,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing\",\n `../drawings/drawing${drawingIdx}.xml`,\n );\n\n file.contentTypes.addDrawing(drawingIdx);\n }\n\n // Comments\n if (hasComments) {\n const commentsIdx = i + 1;\n\n // Comments XML\n const commentsXml = new Comments(commentOpts);\n mapping[`Comments${i}`] = {\n data: fmt(commentsXml),\n path: `xl/comments${commentsIdx}.xml`,\n };\n\n // VML drawing (required by Excel for legacy comment rendering)\n const vmlNotes = new VmlNotes(commentOpts);\n mapping[`VmlDrawing${i}`] = {\n data: vmlNotes.toXml(),\n path: `xl/drawings/vmlDrawing${commentsIdx}.vml`,\n };\n\n // Worksheet rels: comments → comments XML, legacyDrawing → VML file\n const commentsRid = ++nextRid;\n wsRels!.addRelationship(\n commentsRid,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments\",\n `../comments${commentsIdx}.xml`,\n );\n\n const vmlRid = ++nextRid;\n wsRels!.addRelationship(\n vmlRid,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing\",\n `../drawings/vmlDrawing${commentsIdx}.vml`,\n );\n\n // Insert legacyDrawing reference before closing </worksheet>\n const closingTag = \"</worksheet>\";\n sheetXml =\n sheetXml.slice(0, -closingTag.length) +\n `<legacyDrawing r:id=\"rId${vmlRid}\"/>` +\n closingTag;\n\n // Register content types\n file.contentTypes.addComments(commentsIdx);\n file.contentTypes.addVmlDrawing();\n }\n\n // Background picture\n if (bgImg) {\n const ext = bgImg.type === \"jpg\" ? \"jpeg\" : bgImg.type;\n const mediaKey = `bg_${i}`;\n const mediaIdx = globalMediaIdx + 1;\n file.media.addImage(mediaKey, {\n fileName: `image${mediaIdx}.${ext}`,\n type: ext,\n data: bgImg.data,\n width: 0,\n height: 0,\n });\n globalMediaIdx++;\n const bgRid = ++nextRid;\n wsRels!.addRelationship(\n bgRid,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/image\",\n `../media/image${mediaIdx}.${ext}`,\n );\n sheetXml = sheetXml.replace(\"<!--BACKGROUND_PICTURE-->\", `<picture r:id=\"rId${bgRid}\"/>`);\n }\n\n // Pivot tables\n if (hasPivots) {\n for (const pt of pivotOpts) {\n globalPivotIdx++;\n const pivotIdx = globalPivotIdx;\n\n // Extract source data from source sheet\n const sourceSheet = pt.sourceSheet ?? sheetName;\n const sourceWsIdx = file.worksheetConfigs.findIndex(\n (ws) => (ws.name ?? `Sheet${file.worksheetConfigs.indexOf(ws) + 1}`) === sourceSheet,\n );\n if (sourceWsIdx === -1) continue;\n\n const sourceWs = worksheets[sourceWsIdx];\n const sourceData = extractPivotSourceData(sourceWs.worksheetRows, pt.source);\n\n // Deduplicate pivot caches by source reference\n const cacheKey = `${sourceSheet}:${pt.source}`;\n let cacheId: number;\n let cacheIdx: number;\n const existing = pivotCacheDataMap.get(cacheKey);\n if (existing) {\n cacheId = existing.cacheId;\n cacheIdx = existing.cacheIdx;\n } else {\n globalPivotCacheIdx++;\n cacheIdx = globalPivotCacheIdx;\n cacheId = cacheIdx - 1;\n pivotCacheDataMap.set(cacheKey, { cacheId, cacheIdx });\n\n // Generate pivotCacheDefinition\n const cacheDefRels = new Relationships();\n cacheDefRels.addRelationship(\n 1,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/pivotCacheRecords\",\n \"pivotCacheRecords1.xml\",\n );\n\n const cacheDef = new PivotCacheDefinitionXml(\n cacheIdx,\n pt.source.split(\":\")[0] ? pt.source : \"A1\",\n sourceSheet,\n sourceData,\n \"rId1\",\n );\n\n mapping[`PivotCacheDef${cacheIdx}`] = {\n data: fmt(cacheDef),\n path: `xl/pivotCache/pivotCacheDefinition${cacheIdx}.xml`,\n };\n mapping[`PivotCacheDefRels${cacheIdx}`] = {\n data: fmt(cacheDefRels),\n path: `xl/pivotCache/_rels/pivotCacheDefinition${cacheIdx}.xml.rels`,\n };\n\n // Generate pivotCacheRecords\n const cacheRecords = new PivotCacheRecordsXml(sourceData);\n mapping[`PivotCacheRecords${cacheIdx}`] = {\n data: fmt(cacheRecords),\n path: `xl/pivotCache/pivotCacheRecords${cacheIdx}.xml`,\n };\n\n // Content types\n file.contentTypes.addPivotCacheDefinition(cacheIdx);\n file.contentTypes.addPivotCacheRecords(cacheIdx);\n\n // Register in workbook\n const wbPivotRid = file.workbookRelationships.relationshipCount + 1;\n file.workbookRelationships.addRelationship(\n wbPivotRid,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/pivotCacheDefinition\",\n `pivotCache/pivotCacheDefinition${cacheIdx}.xml`,\n );\n file.registerPivotCache(cacheId, `rId${wbPivotRid}`);\n }\n\n // Generate pivotTable\n const pivotTable = new PivotTableXml(pt, sourceData, cacheId);\n mapping[`PivotTable${pivotIdx}`] = {\n data: fmt(pivotTable),\n path: `xl/pivotTables/pivotTable${pivotIdx}.xml`,\n };\n\n // pivotTable rels → cacheDefinition\n const ptRels = new Relationships();\n ptRels.addRelationship(\n 1,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/pivotCacheDefinition\",\n `../pivotCache/pivotCacheDefinition${cacheIdx}.xml`,\n );\n mapping[`PivotTableRels${pivotIdx}`] = {\n data: fmt(ptRels),\n path: `xl/pivotTables/_rels/pivotTable${pivotIdx}.xml.rels`,\n };\n\n // Worksheet rels → pivotTable\n const ptRid = ++nextRid;\n wsRels!.addRelationship(\n ptRid,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/pivotTable\",\n `../pivotTables/pivotTable${pivotIdx}.xml`,\n );\n\n file.contentTypes.addPivotTable(pivotIdx);\n }\n }\n\n // Tables (list objects)\n const wsTableParts: TablePartReference[] = [];\n if (hasTables) {\n for (const tbl of tableOpts) {\n globalTableIdx++;\n const tableIdx = globalTableIdx;\n\n // Generate table XML\n const tableXml = new TableXml({\n ...tbl,\n id: tbl.id ?? tableIdx,\n });\n mapping[`Table${tableIdx}`] = {\n data: fmt(tableXml),\n path: `xl/tables/table${tableIdx}.xml`,\n };\n\n // Worksheet rels → table\n const tblRid = ++nextRid;\n wsRels!.addRelationship(\n tblRid,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/table\",\n `../tables/table${tableIdx}.xml`,\n );\n\n wsTableParts.push({ rId: `rId${tblRid}` });\n allTableParts.push({ rId: `rId${tblRid}` });\n\n file.contentTypes.addTable(tableIdx);\n }\n }\n\n // Pre-render pivot table data into sheetData\n if (hasPivots) {\n const rendered = renderPivotSheetData(\n pivotOpts,\n worksheets,\n file.sharedStrings,\n file.worksheetConfigs,\n sheetName,\n );\n if (rendered.sheetData.length > 0) {\n // Replace empty <sheetData/> or <sheetData></sheetData> with rendered data\n sheetXml = sheetXml.replace(/<sheetData\\/>|<sheetData><\\/sheetData>/, rendered.sheetData);\n // Inject <dimension> before <sheetViews> (XSD sequence order: dimension before sheetViews)\n if (!sheetXml.includes(\"<dimension\")) {\n sheetXml = sheetXml.replace(\n \"<sheetViews\",\n `<dimension ref=\"${rendered.dimensionRef}\"/><sheetViews`,\n );\n }\n }\n }\n\n // Insert tableParts before closing </worksheet> tag\n if (wsTableParts.length > 0) {\n const tablePartsXml = WorkbookXml.buildTablePartsXml(wsTableParts);\n const closingTag = \"</worksheet>\";\n sheetXml = sheetXml.slice(0, -closingTag.length) + tablePartsXml + closingTag;\n }\n\n // Write worksheet rels if needed\n if (wsRels) {\n mapping[`WorksheetRels${i}`] = {\n data: fmt(wsRels),\n path: `xl/worksheets/_rels/sheet${i + 1}.xml.rels`,\n };\n }\n\n mapping[`Worksheet${i}`] = {\n data: sheetXml,\n path: `xl/worksheets/sheet${i + 1}.xml`,\n };\n }\n\n // Chartsheets — chart-only sheets\n const chartsheetConfigs = file.chartsheetConfigs;\n for (let i = 0; i < chartsheetConfigs.length; i++) {\n const csOpts = chartsheetConfigs[i];\n const chartsheet = new Chartsheet(csOpts);\n\n // Register chart in the charts collection\n const chartDef = csOpts.chart;\n const csChartGlobalIdx = file.charts.array.length;\n const csChartKey = `cs_chart_${csChartGlobalIdx}`;\n file.charts.addChart(csChartKey, {\n key: csChartKey,\n chartSpace: new ChartSpace({\n type: chartDef.type as\n | \"column\"\n | \"bar\"\n | \"line\"\n | \"pie\"\n | \"doughnut\"\n | \"area\"\n | \"scatter\"\n | \"bubble\",\n title: chartDef.title,\n categories: chartDef.categories,\n series: chartDef.series,\n }),\n });\n\n // Chartsheet relationships: drawing (required)\n const csRels = new Relationships();\n const csDrawingIdx = i + 1;\n csRels.addRelationship(\n 1,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing\",\n `../drawings/drawing${csDrawingIdx}.xml`,\n );\n chartsheet.setDrawingRId(\"rId1\");\n\n // Drawing rels: chart reference\n const csDrawingRels = new Relationships();\n csDrawingRels.addRelationship(\n 1,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart\",\n `../charts/chart${csChartGlobalIdx + 1}.xml`,\n );\n\n // Minimal drawing XML with chart anchor (XSD: absoluteAnchor → pos, ext, graphicFrame, clientData)\n const csDrawingXml =\n `<xdr:wsDr xmlns:xdr=\"http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing\" xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\">` +\n `<xdr:absoluteAnchor>` +\n `<xdr:pos x=\"0\" y=\"0\"/>` +\n `<xdr:ext cx=\"9308969\" cy=\"6096000\"/>` +\n `<xdr:graphicFrame>` +\n `<xdr:nvGraphicFramePr><xdr:cNvPr id=\"1\" name=\"Chart ${i + 1}\"/><xdr:cNvGraphicFramePr><a:graphicFrameLocks noGrp=\"1\"/></xdr:cNvGraphicFramePr></xdr:nvGraphicFramePr>` +\n `<xdr:xfrm><a:off x=\"0\" y=\"0\"/><a:ext cx=\"9308969\" cy=\"6096000\"/></xdr:xfrm>` +\n `<a:graphic><a:graphicData uri=\"http://schemas.openxmlformats.org/drawingml/2006/chart\"><c:chart xmlns:c=\"http://schemas.openxmlformats.org/drawingml/2006/chart\" r:id=\"rId1\"/></a:graphicData></a:graphic>` +\n `</xdr:graphicFrame>` +\n `<xdr:clientData/>` +\n `</xdr:absoluteAnchor>` +\n `</xdr:wsDr>`;\n\n mapping[`ChartsheetDrawing${i}`] = {\n data: csDrawingXml,\n path: `xl/drawings/drawing${csDrawingIdx}.xml`,\n };\n mapping[`ChartsheetDrawingRels${i}`] = {\n data: fmt(csDrawingRels),\n path: `xl/drawings/_rels/drawing${csDrawingIdx}.xml.rels`,\n };\n file.contentTypes.addDrawing(csDrawingIdx);\n\n mapping[`ChartsheetRels${i}`] = {\n data: fmt(csRels),\n path: `xl/chartsheets/_rels/sheet${i + 1}.xml.rels`,\n };\n mapping[`Chartsheet${i}`] = {\n data: chartsheet.toXml(context),\n path: `xl/chartsheets/sheet${i + 1}.xml`,\n };\n file.contentTypes.addChartsheet(i + 1);\n }\n\n // Workbook XML\n let workbookXml = fmt(file.workbookXml);\n\n // External links — generate XML files and inject externalReferences into workbook\n const extLinks = file.externalLinks;\n if (extLinks.length > 0) {\n const extRefs: { rId: string }[] = [];\n for (let ei = 0; ei < extLinks.length; ei++) {\n const elIdx = ei + 1;\n const elRid = file.workbookRelationships.relationshipCount + 1;\n file.workbookRelationships.addRelationship(\n elRid,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/externalLink\",\n `externalLinks/externalLink${elIdx}.xml`,\n );\n\n // Create the rels file for this external link (points to the external workbook)\n const elOpts = extLinks[ei];\n let bookRId: string | undefined;\n if (elOpts.externalBook?.target) {\n const elRels = new Relationships();\n elRels.addRelationship(\n 1,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/externalLinkPath\",\n elOpts.externalBook.target,\n TargetModeType.EXTERNAL,\n );\n bookRId = \"rId1\";\n mapping[`ExternalLinkRels${elIdx}`] = {\n data: fmt(elRels),\n path: `xl/externalLinks/_rels/externalLink${elIdx}.xml.rels`,\n };\n }\n\n // Generate the external link XML\n const elXml = new ExternalLinkXml({ ...elOpts, bookRId });\n mapping[`ExternalLink${elIdx}`] = {\n data: fmt(elXml),\n path: `xl/externalLinks/externalLink${elIdx}.xml`,\n };\n\n extRefs.push({ rId: `rId${elRid}` });\n file.contentTypes.addExternalLink(elIdx);\n }\n\n // Inject externalReferences into workbook XML (replace the placeholder)\n const extRefsXml = WorkbookXml.buildExternalReferencesXml(extRefs);\n workbookXml = workbookXml.replace(\"<!--EXTERNAL_REFS-->\", extRefsXml);\n } else {\n // Remove the placeholder if no external links\n workbookXml = workbookXml.replace(\"<!--EXTERNAL_REFS-->\", \"\");\n }\n\n mapping[\"Workbook\"] = {\n data: workbookXml,\n path: \"xl/workbook.xml\",\n };\n\n // Workbook relationships\n mapping[\"WorkbookRelationships\"] = {\n data: fmt(file.workbookRelationships),\n path: \"xl/_rels/workbook.xml.rels\",\n };\n\n // Shared Strings — AFTER worksheets so all strings are collected\n const sharedStrings = file.sharedStrings;\n if (sharedStrings.count > 0) {\n mapping[\"SharedStrings\"] = {\n data: fmt(sharedStrings),\n path: \"xl/sharedStrings.xml\",\n };\n }\n\n // Register predefined DXFs before styles XML is generated\n for (const dxf of file.dxfEntries) {\n file.registerDxf(dxf);\n }\n\n // Styles\n mapping[\"Styles\"] = {\n data: fmt(file.styles),\n path: \"xl/styles.xml\",\n };\n\n // Theme\n mapping[\"Theme\"] = {\n data: fmt(file.theme),\n path: \"xl/theme/theme1.xml\",\n };\n\n // Charts — AFTER worksheets so charts are registered\n for (let i = 0; i < file.charts.array.length; i++) {\n const chartData = file.charts.array[i];\n mapping[`Chart${i}`] = {\n data: fmt(chartData.chartSpace),\n path: `xl/charts/chart${i + 1}.xml`,\n };\n file.contentTypes.addChart(i + 1);\n }\n\n // Calculation chain — auto-generated from formula cells\n if (calcChain.count > 0) {\n mapping[\"CalcChain\"] = {\n data: calcChain.toXml(context),\n path: \"xl/calcChain.xml\",\n };\n file.contentTypes.addCalcChain();\n const calcChainRid = file.workbookRelationships.relationshipCount + 1;\n file.workbookRelationships.addRelationship(\n calcChainRid,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/calcChain\",\n \"calcChain.xml\",\n );\n }\n\n // Register image content types\n const imageExts = new Set<string>();\n for (const img of file.media.array) {\n const ext = img.fileName.endsWith(\".png\") ? \"png\" : \"jpeg\";\n if (!imageExts.has(ext)) {\n imageExts.add(ext);\n file.contentTypes.addImageType(ext as \"png\" | \"jpeg\");\n }\n }\n\n // Content Types — must be last\n mapping[\"ContentTypes\"] = {\n data: fmt(file.contentTypes),\n path: \"[Content_Types].xml\",\n };\n\n // Convert mapping to Zippable\n const mediaFiles: Array<{ data: Uint8Array; path: string }> = [];\n for (const img of file.media.array) {\n mediaFiles.push({ data: img.data, path: `xl/media/${img.fileName}` });\n }\n\n return compileMapping(mapping, overrides, mediaFiles, mediaLevel);\n }\n}\n\n/**\n * Extract source data from worksheet rows for pivot cache generation.\n */\nfunction extractPivotSourceData(\n rows: readonly import(\"@file/worksheet\").RowOptions[],\n sourceRef: string,\n): PivotSourceData {\n // Parse source range like \"A1:D11\"\n const parts = sourceRef.split(\":\");\n const startMatch = parts[0]?.match(/^([A-Z]+)(\\d+)$/);\n const endMatch = parts[1]?.match(/^([A-Z]+)(\\d+)$/);\n if (!startMatch) {\n return { fieldNames: [], records: [] };\n }\n\n const startRow = parseInt(startMatch[2], 10) - 1;\n const endRow = endMatch ? parseInt(endMatch[2], 10) - 1 : startRow;\n const startCol = colLetterToIndex(startMatch[1]);\n const endCol = endMatch ? colLetterToIndex(endMatch[1]) : startCol;\n const colCount = endCol - startCol + 1;\n\n // First row is headers\n const headerRow = rows[startRow];\n const fieldNames: string[] = [];\n if (headerRow?.cells) {\n for (let c = startCol; c <= endCol && c < headerRow.cells.length; c++) {\n const hv = headerRow.cells[c]?.value;\n fieldNames.push(\n typeof hv === \"string\"\n ? hv\n : typeof hv === \"number\" || typeof hv === \"boolean\"\n ? String(hv)\n : `Col${c}`,\n );\n }\n }\n\n // Remaining rows are data\n const records: (string | number)[][] = [];\n for (let r = startRow + 1; r <= endRow; r++) {\n const row = rows[r];\n if (!row?.cells) continue;\n const record: (string | number)[] = [];\n for (let c = startCol; c <= endCol; c++) {\n const val = row.cells[c]?.value;\n if (typeof val === \"number\") {\n record.push(val);\n } else if (val instanceof Date) {\n record.push(val.getTime());\n } else {\n record.push(typeof val === \"string\" ? val : typeof val === \"boolean\" ? String(val) : \"\");\n }\n }\n if (record.length === colCount) {\n records.push(record);\n }\n }\n\n return { fieldNames, records };\n}\n\nfunction colLetterToIndex(letters: string): number {\n let col = 0;\n for (let i = 0; i < letters.length; i++) {\n col = col * 26 + (letters.charCodeAt(i) - 64);\n }\n return col - 1;\n}\n\n/**\n * Pre-render pivot table output as sheetData cells.\n * Excel requires this so the pivot table is visible on open without manual refresh.\n */\nfunction renderPivotSheetData(\n pivotOpts: readonly PivotTableOptions[],\n worksheets: readonly import(\"@file/worksheet\").Worksheet[],\n sharedStrings: import(\"@file/shared-strings\").SharedStrings,\n worksheetConfigs: readonly import(\"@file/worksheet\").WorksheetOptions[],\n currentSheetName: string,\n): { sheetData: string; dimensionRef: string } {\n // Collect cells by row number to merge cells from different pivot tables on the same row\n const rowCells = new Map<number, string[]>();\n let maxRow = 0;\n let maxCol = 0;\n let minRow = Infinity;\n let minCol = Infinity;\n\n for (const pt of pivotOpts) {\n const location = pt.location ?? \"A3\";\n const locMatch = location.match(/^([A-Z]+)(\\d+)$/);\n if (!locMatch) continue;\n\n const startCol = colLetterToIndex(locMatch[1]);\n const startRow = parseInt(locMatch[2], 10);\n const rowFieldNames = pt.rows;\n const dataFields = pt.data;\n\n const sourceSheetName = pt.sourceSheet ?? currentSheetName;\n const sourceWsIdx = worksheetConfigs.findIndex(\n (ws) => (ws.name ?? `Sheet${worksheetConfigs.indexOf(ws) + 1}`) === sourceSheetName,\n );\n if (sourceWsIdx === -1) continue;\n\n const sourceRows = worksheets[sourceWsIdx]?.worksheetRows ?? [];\n const sourceData = extractPivotSourceData(sourceRows, pt.source);\n if (sourceData.fieldNames.length === 0) continue;\n\n const fields = sourceData.fieldNames;\n const rowFieldIndices = rowFieldNames.map((n) => fields.indexOf(n));\n const dataFieldIndices = dataFields.map((df) => fields.indexOf(df.field));\n\n if (rowFieldIndices.some((idx) => idx === -1)) continue;\n if (dataFieldIndices.some((idx) => idx === -1)) continue;\n\n // Group records by row field values\n const groupMap = new Map<string, { keys: (string | number)[]; values: number[][] }>();\n for (const record of sourceData.records) {\n const groupKey = rowFieldIndices.map((fi) => String(record[fi])).join(\"|\");\n let group = groupMap.get(groupKey);\n if (!group) {\n group = {\n keys: rowFieldIndices.map((fi) => {\n const v = record[fi];\n return typeof v === \"string\" || typeof v === \"number\" ? v : String(v ?? \"\");\n }),\n values: dataFieldIndices.map(() => []),\n };\n groupMap.set(groupKey, group);\n }\n for (let di = 0; di < dataFieldIndices.length; di++) {\n const val = record[dataFieldIndices[di]];\n if (typeof val === \"number\") {\n group.values[di].push(val);\n }\n }\n }\n\n const endCol = startCol + rowFieldNames.length + dataFields.length - 1;\n minCol = Math.min(minCol, startCol);\n maxCol = Math.max(maxCol, endCol);\n\n // Helper to add cells to a row\n const addCells = (rowIdx: number, cells: string[]) => {\n let arr = rowCells.get(rowIdx);\n if (!arr) {\n arr = [];\n rowCells.set(rowIdx, arr);\n }\n arr.push(...cells);\n minRow = Math.min(minRow, rowIdx);\n maxRow = Math.max(maxRow, rowIdx);\n };\n\n // Header row\n const headerCells: string[] = [];\n for (const rfName of rowFieldNames) {\n const cellRef = colIndexToLetterCompiler(startCol + headerCells.length) + startRow;\n const strIdx = sharedStrings.register(rfName);\n headerCells.push(`<c r=\"${cellRef}\" t=\"s\"><v>${strIdx}</v></c>`);\n }\n for (const df of dataFields) {\n const cellRef = colIndexToLetterCompiler(startCol + headerCells.length) + startRow;\n const subtotal = df.summarize ?? \"sum\";\n const dfName = df.name ?? `${subtotal === \"sum\" ? \"Sum\" : subtotal} of ${df.field}`;\n const strIdx = sharedStrings.register(dfName);\n headerCells.push(`<c r=\"${cellRef}\" t=\"s\"><v>${strIdx}</v></c>`);\n }\n addCells(startRow, headerCells);\n\n // Data rows\n let currentRow = startRow + 1;\n for (const [, group] of groupMap) {\n const cells: string[] = [];\n for (let ri = 0; ri < group.keys.length; ri++) {\n const cellRef = colIndexToLetterCompiler(startCol + ri) + currentRow;\n const strIdx = sharedStrings.register(String(group.keys[ri]));\n cells.push(`<c r=\"${cellRef}\" t=\"s\"><v>${strIdx}</v></c>`);\n }\n for (let di = 0; di < dataFields.length; di++) {\n const colOffset = rowFieldNames.length + di;\n const cellRef = colIndexToLetterCompiler(startCol + colOffset) + currentRow;\n const subtotal = dataFields[di].summarize ?? \"sum\";\n const result = aggregate(group.values[di], subtotal);\n cells.push(`<c r=\"${cellRef}\"><v>${result}</v></c>`);\n }\n addCells(currentRow, cells);\n currentRow++;\n }\n\n // Grand total row\n const gtCells: string[] = [];\n const gtStrIdx = sharedStrings.register(\"Grand Total\");\n gtCells.push(\n `<c r=\"${colIndexToLetterCompiler(startCol)}${currentRow}\" t=\"s\"><v>${gtStrIdx}</v></c>`,\n );\n for (let di = 0; di < dataFields.length; di++) {\n const colOffset = rowFieldNames.length + di;\n const cellRef = colIndexToLetterCompiler(startCol + colOffset) + currentRow;\n const subtotal = dataFields[di].summarize ?? \"sum\";\n const allValues = sourceData.records\n .map((r) => r[dataFieldIndices[di]])\n .filter((v): v is number => typeof v === \"number\");\n const result = aggregate(allValues, subtotal);\n gtCells.push(`<c r=\"${cellRef}\"><v>${result}</v></c>`);\n }\n addCells(currentRow, gtCells);\n }\n\n if (rowCells.size === 0) return { sheetData: \"\", dimensionRef: \"\" };\n\n // Build sheetData — rows must be sorted by row number\n const parts: string[] = [\"<sheetData>\"];\n const sortedRows = [...rowCells.entries()].sort((a, b) => a[0] - b[0]);\n for (const [rowIdx, cells] of sortedRows) {\n parts.push(`<row r=\"${rowIdx}\" x14ac:dyDescent=\"0.25\">`);\n parts.push(...cells);\n parts.push(\"</row>\");\n }\n parts.push(\"</sheetData>\");\n\n const dimStartCol = colIndexToLetterCompiler(minCol === Infinity ? 0 : minCol);\n const dimStartRow = minRow === Infinity ? 1 : minRow;\n const dimensionRef = `${dimStartCol}${dimStartRow}:${colIndexToLetterCompiler(maxCol)}${maxRow}`;\n return { sheetData: parts.join(\"\"), dimensionRef };\n}\n\nfunction colIndexToLetterCompiler(col: number): string {\n let result = \"\";\n let n = col + 1; // 0-indexed to 1-indexed\n while (n > 0) {\n n--;\n result = String.fromCharCode(65 + (n % 26)) + result;\n n = Math.floor(n / 26);\n }\n return result;\n}\n\nfunction columnToLetter(col: number): string {\n let result = \"\";\n let n = col;\n while (n > 0) {\n const remainder = (n - 1) % 26;\n result = String.fromCharCode(65 + remainder) + result;\n n = Math.floor((n - 1) / 26);\n }\n return result;\n}\n","import type { File } from \"@file/file\";\n/**\n * Packer module — export API for XLSX files.\n *\n * @module\n */\nimport { createPacker, OoxmlMimeType } from \"@office-open/core\";\n\nimport { Compiler } from \"./next-compiler\";\n\nconst compiler = new Compiler();\n\nexport const Packer = createPacker<File>({\n compile: (file, overrides, mediaLevel) => compiler.compile(file, overrides, mediaLevel),\n mimeType: OoxmlMimeType.XLSX,\n});\n","/**\n * Convert a 1-based column number to Excel column letter(s).\n * 1 → \"A\", 26 → \"Z\", 27 → \"AA\", 28 → \"AB\"\n */\nexport function columnToLetter(col: number): string {\n let result = \"\";\n let n = col;\n while (n > 0) {\n const remainder = (n - 1) % 26;\n result = String.fromCharCode(65 + remainder) + result;\n n = Math.floor((n - 1) / 26);\n }\n return result;\n}\n\n/**\n * Convert Excel column letter(s) to a 1-based column number.\n * \"A\" → 1, \"Z\" → 26, \"AA\" → 27\n */\nexport function letterToColumn(s: string): number {\n let result = 0;\n for (let i = 0; i < s.length; i++) {\n result = result * 26 + (s.charCodeAt(i) - 64);\n }\n return result;\n}\n\n/**\n * Convert a JavaScript Date to an Excel serial number.\n * Excel epoch: January 1, 1900 = 1 (with the 1900 leap year bug).\n */\nexport function dateToSerialNumber(date: Date): number {\n // Excel treats 1900 as a leap year (bug inherited from Lotus 1-2-3).\n // The epoch is effectively December 30, 1899 = 0.\n const epoch = new Date(1899, 11, 30);\n const msPerDay = 86400000;\n const diff = date.getTime() - epoch.getTime();\n return diff / msPerDay;\n}\n","/**\n * XLSX parsing — parse .xlsx files into structured data.\n *\n * @module\n */\nimport { parseArchive, parseCorePropsElement } from \"@office-open/core\";\nimport type { ParsedArchive } from \"@office-open/core\";\nimport { toUint8Array } from \"@office-open/core\";\nimport type { DataType } from \"@office-open/core\";\nimport type { Element } from \"@office-open/xml\";\nimport { attr, attrNum, findChild, textOf } from \"@office-open/xml\";\n\nimport type { WorkbookOptions } from \"./file/file\";\nimport type {\n WorksheetOptions,\n RowOptions,\n CellOptions,\n ColumnOptions,\n MergeCellOptions,\n} from \"./file/worksheet\";\nimport { letterToColumn } from \"./util\";\n\nexport { parseArchive };\n\n// ── Low-level parse result ──\n\nexport interface XlsxPartRefs {\n worksheets: string[];\n charts: string[];\n media: string[];\n drawings: string[];\n}\n\nexport interface XlsxDocument {\n doc: ParsedArchive;\n /** xl/workbook.xml root element */\n workbook?: Element;\n /** Worksheet paths (xl/worksheets/sheet{n}.xml) */\n worksheets: string[];\n /** xl/styles.xml root element */\n styles?: Element;\n /** xl/sharedStrings.xml root element */\n sharedStrings?: Element;\n partRefs: XlsxPartRefs;\n /** docProps/core.xml path */\n coreProps?: string;\n /** docProps/app.xml path */\n appProps?: string;\n}\n\nfunction sortByNumber(paths: string[]): string[] {\n return paths.sort((a, b) => {\n const numA = parseInt(a.match(/(\\d+)/)?.[1] ?? \"0\", 10);\n const numB = parseInt(b.match(/(\\d+)/)?.[1] ?? \"0\", 10);\n return numA - numB;\n });\n}\n\n/**\n * Parse raw .xlsx data into a low-level XlsxDocument.\n */\nexport function parseXlsx(data: DataType): XlsxDocument {\n const uint8 = toUint8Array(data);\n const doc = parseArchive(uint8);\n\n const workbook = doc.get(\"xl/workbook.xml\");\n const styles = doc.get(\"xl/styles.xml\");\n const sharedStrings = doc.get(\"xl/sharedStrings.xml\");\n\n // Resolve worksheet paths from workbook rels\n const worksheets: string[] = [];\n const charts: string[] = [];\n const drawings: string[] = [];\n const media: string[] = [];\n\n const wbRels = doc.get(\"xl/_rels/workbook.xml.rels\");\n if (wbRels) {\n for (const child of wbRels.elements ?? []) {\n if (child.name !== \"Relationship\") continue;\n const type = attr(child, \"Type\") ?? \"\";\n const target = attr(child, \"Target\") ?? \"\";\n if (!target) continue;\n\n if (type.includes(\"/worksheet\")) {\n worksheets.push(target.startsWith(\"/\") ? target.slice(1) : `xl/${target}`);\n }\n }\n }\n sortByNumber(worksheets);\n\n // Scan for drawings, charts, media\n drawings.push(...doc.keys(\"xl/drawings/\").filter((k) => k.endsWith(\".xml\")));\n charts.push(...doc.keys(\"xl/charts/\").filter((k) => k.endsWith(\".xml\")));\n media.push(...doc.keys(\"xl/media/\"));\n sortByNumber(drawings);\n sortByNumber(charts);\n\n // Root rels → core/app props\n let coreProps: string | undefined;\n let appProps: string | undefined;\n const rootRels = doc.get(\"_rels/.rels\");\n if (rootRels) {\n for (const child of rootRels.elements ?? []) {\n if (child.name !== \"Relationship\") continue;\n const type = attr(child, \"Type\") ?? \"\";\n const target = attr(child, \"Target\") ?? \"\";\n if (type.includes(\"/core-properties\")) coreProps = target;\n else if (type.includes(\"/extended-properties\")) appProps = target;\n }\n }\n\n return {\n doc,\n workbook,\n worksheets,\n styles,\n sharedStrings,\n partRefs: { worksheets, charts, media, drawings },\n coreProps,\n appProps,\n };\n}\n\n// ── Shared strings helper ──\n\nfunction parseSharedStrings(el: Element | undefined): string[] {\n if (!el) return [];\n const strings: string[] = [];\n for (const si of el.elements ?? []) {\n if (si.name !== \"si\") continue;\n // Handle both <si><t>text</t></si> and <si><r><t>text</t></r>...</si>\n const t = findChild(si, \"t\");\n if (t) {\n strings.push(textOf(t) ?? \"\");\n } else {\n // Rich text: concatenate all <r><t> segments\n const parts: string[] = [];\n for (const r of si.elements ?? []) {\n if (r.name !== \"r\") continue;\n const rt = findChild(r, \"t\");\n if (rt) parts.push(textOf(rt) ?? \"\");\n }\n strings.push(parts.join(\"\"));\n }\n }\n return strings;\n}\n\n// ── Cell reference helpers ──\n\nfunction colFromRef(ref: string): number {\n const match = ref.match(/^([A-Z]+)/);\n return match ? letterToColumn(match[1]) : 1;\n}\n\nfunction rowFromRef(ref: string): number {\n const match = ref.match(/(\\d+)$/);\n return match ? parseInt(match[1], 10) : 1;\n}\n\n// ── Worksheet parsing ──\n\nfunction parseWorksheetElement(wsEl: Element, strings: string[]): WorksheetOptions {\n const opts: Record<string, unknown> = {};\n\n // Sheet name from the parent workbook's sheet element (not available here)\n // Caller should set it\n\n // Columns\n // Elements might be prefixed or unprefixed depending on how the XML parser handles default namespaces.\n const colsEl = findChild(wsEl, \"cols\") ?? findChildByLocalName(wsEl, \"cols\");\n if (colsEl) {\n const columns: ColumnOptions[] = [];\n for (const col of colsEl.elements ?? []) {\n if (localName(col) !== \"col\") continue;\n const min = attrNum(col, \"min\");\n const max = attrNum(col, \"max\");\n if (min === undefined || max === undefined) continue;\n const colOpts: Record<string, unknown> = { min, max };\n const width = attrNum(col, \"width\");\n if (width !== undefined) colOpts.width = width;\n if (attr(col, \"hidden\") === \"1\") colOpts.hidden = true;\n columns.push(colOpts as unknown as ColumnOptions);\n }\n if (columns.length > 0) opts.columns = columns;\n }\n\n // Freeze panes\n const sheetViews = findChildByLocalName(wsEl, \"sheetViews\");\n if (sheetViews) {\n const sheetView = findChildByLocalName(sheetViews, \"sheetView\");\n if (sheetView) {\n const pane = findChildByLocalName(sheetView, \"pane\");\n if (pane) {\n const state = attr(pane, \"state\");\n if (state === \"frozen\") {\n const freezePanes: Record<string, unknown> = {};\n const ySplit = attrNum(pane, \"ySplit\");\n const xSplit = attrNum(pane, \"xSplit\");\n if (ySplit && ySplit > 0) freezePanes.row = ySplit;\n if (xSplit && xSplit > 0) freezePanes.col = xSplit;\n if (Object.keys(freezePanes).length > 0) opts.freezePanes = freezePanes;\n }\n }\n }\n }\n\n // Sheet data (rows)\n const sheetData = findChildByLocalName(wsEl, \"sheetData\");\n const rows: RowOptions[] = [];\n if (sheetData) {\n for (const rowEl of sheetData.elements ?? []) {\n if (localName(rowEl) !== \"row\") continue;\n const rowNumber = attrNum(rowEl, \"r\");\n const rowOpts: Record<string, unknown> = {};\n if (rowNumber !== undefined) rowOpts.rowNumber = rowNumber;\n\n const ht = attrNum(rowEl, \"ht\");\n if (ht !== undefined) rowOpts.height = ht;\n if (attr(rowEl, \"hidden\") === \"1\") rowOpts.hidden = true;\n\n const cells: CellOptions[] = [];\n for (const cellEl of rowEl.elements ?? []) {\n if (localName(cellEl) !== \"c\") continue;\n const ref = attr(cellEl, \"r\");\n const type = attr(cellEl, \"t\");\n const cellOpts: Record<string, unknown> = {};\n if (ref) cellOpts.reference = ref;\n\n const styleIdx = attrNum(cellEl, \"s\");\n if (styleIdx !== undefined) cellOpts.styleIndex = styleIdx;\n\n // Cell value\n const vEl = findChildByLocalName(cellEl, \"v\");\n const isEl = findChildByLocalName(cellEl, \"is\");\n\n if (type === \"s\" && vEl) {\n // Shared string\n const idx = parseInt(textOf(vEl) ?? \"\", 10);\n cellOpts.value = strings[idx] ?? \"\";\n } else if (type === \"b\" && vEl) {\n cellOpts.value = textOf(vEl) === \"1\";\n } else if (type === \"inlineStr\" && isEl) {\n const t = findChildByLocalName(isEl, \"t\");\n cellOpts.value = textOf(t) ?? \"\";\n } else if (vEl) {\n const raw = textOf(vEl) ?? \"\";\n const num = Number(raw);\n cellOpts.value = isNaN(num) ? raw : num;\n }\n\n cells.push(cellOpts as CellOptions);\n }\n\n rowOpts.cells = cells;\n rows.push(rowOpts as RowOptions);\n }\n }\n opts.rows = rows;\n\n // Merge cells\n const mergeCellsEl = findChildByLocalName(wsEl, \"mergeCells\");\n if (mergeCellsEl) {\n const mergeCells: MergeCellOptions[] = [];\n for (const mc of mergeCellsEl.elements ?? []) {\n if (localName(mc) !== \"mergeCell\") continue;\n const ref = attr(mc, \"ref\");\n if (!ref) continue;\n const parts = ref.split(\":\");\n if (parts.length === 2) {\n mergeCells.push({\n from: { row: rowFromRef(parts[0]), col: colFromRef(parts[0]) },\n to: { row: rowFromRef(parts[1]), col: colFromRef(parts[1]) },\n });\n }\n }\n if (mergeCells.length > 0) opts.mergeCells = mergeCells;\n }\n\n // Auto filter\n const autoFilterEl = findChildByLocalName(wsEl, \"autoFilter\");\n if (autoFilterEl) {\n const ref = attr(autoFilterEl, \"ref\");\n if (ref) opts.autoFilter = ref;\n }\n\n return opts as WorksheetOptions;\n}\n\n// ── Helpers ──\n\nfunction localName(el: Element): string {\n const name = el.name ?? \"\";\n const colonIdx = name.indexOf(\":\");\n return colonIdx >= 0 ? name.slice(colonIdx + 1) : name;\n}\n\nfunction findChildByLocalName(parent: Element, name: string): Element | undefined {\n return (parent.elements ?? []).find((el) => localName(el) === name);\n}\n\n/**\n * Parse a .xlsx file and convert it into WorkbookOptions.\n *\n * The returned options can be passed to `new Workbook(parsed)`.\n */\nexport function parseWorkbook(data: DataType): WorkbookOptions {\n const xlsx = parseXlsx(data);\n\n const opts: Record<string, unknown> = {};\n\n // Core properties\n if (xlsx.coreProps) {\n const corePropsEl = xlsx.doc.get(xlsx.coreProps);\n if (corePropsEl) {\n const cp = parseCorePropsElement(corePropsEl);\n if (cp.title) opts.title = cp.title;\n if (cp.subject) opts.subject = cp.subject;\n if (cp.creator) opts.creator = cp.creator;\n if (cp.keywords) opts.keywords = cp.keywords;\n if (cp.description) opts.description = cp.description;\n if (cp.lastModifiedBy) opts.lastModifiedBy = cp.lastModifiedBy;\n if (cp.revision) opts.revision = parseInt(cp.revision, 10);\n }\n }\n\n // Shared strings\n const strings = parseSharedStrings(xlsx.sharedStrings);\n\n // Sheet names from workbook\n const sheetNames: string[] = [];\n if (xlsx.workbook) {\n const sheetsEl = findChildByLocalName(xlsx.workbook, \"sheets\");\n if (sheetsEl) {\n for (const s of sheetsEl.elements ?? []) {\n if (localName(s) !== \"sheet\") continue;\n sheetNames.push(attr(s, \"name\") ?? \"\");\n }\n }\n }\n\n // Parse worksheets\n const worksheets: WorksheetOptions[] = [];\n for (let i = 0; i < xlsx.worksheets.length; i++) {\n const wsPath = xlsx.worksheets[i];\n const wsEl = xlsx.doc.get(wsPath);\n if (!wsEl) continue;\n\n const wsOpts = parseWorksheetElement(wsEl, strings) as Record<string, unknown>;\n if (sheetNames[i]) wsOpts.name = sheetNames[i];\n worksheets.push(wsOpts as WorksheetOptions);\n }\n\n opts.worksheets = worksheets;\n return opts as WorkbookOptions;\n}\n","/**\n * XLSX patching — replace placeholders in existing .xlsx files.\n *\n * Unlike DOCX/PPTX (paragraph-based), XLSX patching targets cell values:\n * - Replaces placeholders in the shared strings table (most common)\n * - Replaces placeholders in inline strings within worksheet cells\n *\n * @module\n */\nimport { OoxmlMimeType, unzipSync, zipAndConvert, strFromU8, toJson } from \"@office-open/core\";\nimport type { OutputByType, OutputType } from \"@office-open/core\";\nimport { toUint8Array } from \"@office-open/core\";\nimport { js2xml } from \"@office-open/xml\";\nimport type { Element } from \"@office-open/xml\";\n\n/** Reusable TextEncoder (stateless, safe to share). */\nconst encoder = new TextEncoder();\n\nexport type InputDataType = Buffer | string | number[] | Uint8Array | ArrayBuffer | Blob;\n\nexport type PatchDocumentOutputType = OutputType;\n\nexport const PatchType = {\n CELL: \"cell\",\n} as const;\n\nexport interface CellPatch {\n /** Replacement value (string, number, boolean, or Date) */\n readonly value: string | number | boolean | Date;\n}\n\nexport type IPatch = CellPatch;\n\nexport interface PatchWorkbookOptions<T extends PatchDocumentOutputType = PatchDocumentOutputType> {\n readonly outputType: T;\n readonly data: InputDataType;\n readonly patches: Readonly<Record<string, IPatch>>;\n readonly placeholderDelimiters?: Readonly<{\n readonly start: string;\n readonly end: string;\n }>;\n}\n\n/**\n * Patch an existing .xlsx workbook by replacing placeholder text in cells.\n *\n * Placeholders are matched in shared strings and inline strings.\n * For string replacements, the shared string value is updated in-place.\n * For non-string replacements, the cell type and value are updated.\n */\nexport const patchWorkbook = async <T extends PatchDocumentOutputType = PatchDocumentOutputType>({\n outputType,\n data,\n patches,\n placeholderDelimiters = { start: \"{{\", end: \"}}\" } as const,\n}: PatchWorkbookOptions<T>): Promise<OutputByType[T]> => {\n const zipContent = unzipSync(toUint8Array(data));\n\n const xmlMap = new Map<string, Element>();\n const binaryMap = new Map<string, Uint8Array>();\n\n // Separate XML files from binary files\n for (const [key, value] of Object.entries(zipContent)) {\n if (key.endsWith(\".xml\") || key.endsWith(\".rels\")) {\n xmlMap.set(key, toJson(strFromU8(value)));\n } else {\n binaryMap.set(key, value);\n }\n }\n\n const { start, end } = placeholderDelimiters;\n\n // Build placeholder → patch map\n const patchMap = new Map<string, IPatch>();\n for (const [key, patch] of Object.entries(patches)) {\n patchMap.set(`${start}${key}${end}`, patch);\n }\n\n // 1. Patch shared strings\n const sst = xmlMap.get(\"xl/sharedStrings.xml\");\n if (sst) {\n patchSharedStrings(sst, patchMap);\n }\n\n // 2. Patch inline strings in worksheets\n const worksheetKeys = Object.keys(zipContent).filter(\n (k) => k.startsWith(\"xl/worksheets/sheet\") && k.endsWith(\".xml\"),\n );\n for (const wsKey of worksheetKeys) {\n const ws = xmlMap.get(wsKey);\n if (ws) patchWorksheetInlineStrings(ws, patchMap);\n }\n\n // Rebuild ZIP\n const files: Record<string, Uint8Array> = {};\n for (const [key, value] of xmlMap) {\n files[key] = encoder.encode(js2xml(value));\n }\n for (const [key, value] of binaryMap) {\n files[key] = value;\n }\n\n return await zipAndConvert(files, outputType, OoxmlMimeType.XLSX);\n};\n\nfunction patchSharedStrings(sst: Element, patchMap: Map<string, IPatch>): void {\n // toJson returns {elements: [{name: \"sst\", ...}]} — unwrap to actual root\n const root = sst.name ? sst : sst.elements?.[0];\n if (!root) return;\n\n for (const si of root.elements ?? []) {\n if (si.name !== \"si\") continue;\n\n // Simple: <si><t>text</t></si>\n const t = findLocalChild(si, \"t\");\n if (t) {\n patchTextElement(t, patchMap);\n } else {\n // Rich text: <si><r><t>text</t></r>...</si>\n for (const r of si.elements ?? []) {\n if (r.name !== \"r\") continue;\n const rt = findLocalChild(r, \"t\");\n if (rt) patchTextElement(rt, patchMap);\n }\n }\n }\n}\n\nfunction patchWorksheetInlineStrings(ws: Element, patchMap: Map<string, IPatch>): void {\n const root = ws.name ? ws : ws.elements?.[0];\n if (!root) return;\n\n const sheetData = findLocalChild(root, \"sheetData\");\n if (!sheetData) return;\n\n for (const row of sheetData.elements ?? []) {\n if (localName(row) !== \"row\") continue;\n for (const cell of row.elements ?? []) {\n if (localName(cell) !== \"c\") continue;\n\n // Check inline strings: <c t=\"inlineStr\"><is><t>text</t></is></c>\n const isEl = findLocalChild(cell, \"is\");\n if (isEl) {\n const t = findLocalChild(isEl, \"t\");\n if (t) patchTextElement(t, patchMap);\n }\n }\n }\n}\n\nfunction patchTextElement(tEl: Element, patchMap: Map<string, IPatch>): void {\n const text = tEl.elements?.[0]?.text;\n if (typeof text !== \"string\") return;\n\n for (const [placeholder, patch] of patchMap) {\n if (text.includes(placeholder)) {\n const newValue = String(patch.value);\n const replaced = text.replace(placeholder, newValue);\n if (tEl.elements) {\n tEl.elements[0] = { ...tEl.elements[0], text: replaced };\n }\n }\n }\n}\n\nfunction localName(el: Element): string {\n const name = el.name ?? \"\";\n const colonIdx = name.indexOf(\":\");\n return colonIdx >= 0 ? name.slice(colonIdx + 1) : name;\n}\n\nfunction findLocalChild(parent: Element, name: string): Element | undefined {\n return (parent.elements ?? []).find((el) => localName(el) === name);\n}\n"],"mappings":";;;;;;;;;AAQA,MAAM,YAAY;AAClB,MAAM,iBAAiB;AACvB,MAAM,kBACJ;AACF,MAAM,cAAc;AACpB,MAAM,sBACJ;AACF,MAAM,aAAa;AACnB,MAAM,aAAa;AA+BnB,MAAM,aAAa;CApBjB;EACE,MAAM;EACN,aAAa;EACb,KAAK;CACP;CACA;EAAE,MAAM;EAAW,aAAa;EAAmB,KAAK;CAAM;CAC9D;EAAE,MAAM;EAAY,aAAa;EAAW,KAAK;CAAmB;CACpE;EACE,MAAM;EACN,aAAa;EACb,KAAK;CACP;CACA;EACE,MAAM;EACN,aAAa;EACb,KAAK;CACP;AAI8B,EAAE,KAAK,MACrC,EAAE,SAAS,YACP,yBAAyB,EAAE,YAAY,eAAe,EAAE,IAAI,OAC5D,0BAA0B,EAAE,YAAY,cAAc,EAAE,IAAI,IAClE,EAAE,KAAK,EAAE;AAET,IAAa,eAAb,cAAkC,iBAAiB;CACjD,iBAAkD,CAAC;CAEnD,cAAqB;EACnB,MAAM,OAAO;CACf;CAEA,aAAoB,OAAqB;EACvC,KAAK,eAAe,KAAK;GACvB,MAAM;GACN,aAAa;GACb,KAAK,uBAAuB,MAAM;EACpC,CAAC;CACH;CAEA,cAAqB,OAAqB;EACxC,KAAK,eAAe,KAAK;GACvB,MAAM;GACN,aAAa;GACb,KAAK,wBAAwB,MAAM;EACrC,CAAC;CACH;CAEA,YAAyB;E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