@json-to-office/core-pptx 1.2.0 → 1.3.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.
- package/dist/index.js +318 -18
- package/dist/index.js.map +1 -1
- package/dist/ir/features.d.ts +1 -1
- package/dist/ir/features.d.ts.map +1 -1
- package/dist/renderers/office-open/chartParts.d.ts +41 -0
- package/dist/renderers/office-open/chartParts.d.ts.map +1 -0
- package/dist/renderers/office-open/emit.d.ts +10 -1
- package/dist/renderers/office-open/emit.d.ts.map +1 -1
- package/dist/renderers/office-open/index.d.ts +2 -2
- package/dist/renderers/office-open/index.d.ts.map +1 -1
- package/dist/renderers/pptxgenjs/index.d.ts.map +1 -1
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/package.json +3 -3
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/utils/warn.ts","../src/ir/types.ts","../src/ir/units.ts","../src/ir/features.ts","../src/renderers/pptxgenjs/fills.ts","../src/renderers/pptxgenjs/chart.ts","../src/renderers/pptxgenjs/table.ts","../src/renderers/pptxgenjs/emit.ts","../src/core/finalizePackage.ts","../src/renderers/pptxgenjs/svgRasterFallback.ts","../src/renderers/pptxgenjs/packaging.ts","../src/renderers/pptxgenjs/index.ts","../src/renderers/office-open/emit.ts","../src/renderers/office-open/index.ts","../src/core/generator.ts","../src/core/generateFromIr.ts","../src/utils/baseDirContext.ts","../src/ir/compiler.ts","../src/utils/color.ts","../src/utils/fontAliasContext.ts","../src/utils/componentDefaults.ts","../src/utils/resolveComponentTree.ts","../src/utils/imageSource.ts","../src/utils/hyperlink.ts","../src/core/grid.ts","../src/ir/resources.ts","../src/renderers/registry.ts","../src/renderers/types.ts","../src/types.ts","../src/core/fontResolution.ts","../src/core/generationContext.ts","../src/themes/defaults.ts","../src/core/generationOptions.ts","../src/utils/environment.ts","../src/core/expandHighcharts.ts","../src/core/resolveImageLayout.ts","../src/core/structure.ts","../src/index.ts","../src/plugin/index.ts","../src/plugin/createPresentationGenerator.ts","../src/plugin/validation.ts","../src/plugin/schema.ts"],"sourcesContent":["import type { PipelineWarning } from '../types';\n\nexport const W = {\n UNKNOWN_COMPONENT: 'UNKNOWN_COMPONENT',\n UNKNOWN_CHART_TYPE: 'UNKNOWN_CHART_TYPE',\n UNKNOWN_SHAPE: 'UNKNOWN_SHAPE',\n CHART_NO_DATA: 'CHART_NO_DATA',\n CHART_INVALID_SERIES: 'CHART_INVALID_SERIES',\n CHART_MULTI_SERIES: 'CHART_MULTI_SERIES',\n CHART_FONT_WEIGHT_DROPPED: 'CHART_FONT_WEIGHT_DROPPED',\n IMAGE_NO_SOURCE: 'IMAGE_NO_SOURCE',\n IMAGE_PROBE_FAILED: 'IMAGE_PROBE_FAILED',\n IMAGE_PATH_OUTSIDE_ROOTS: 'IMAGE_PATH_OUTSIDE_ROOTS',\n IMAGE_SVG_RASTER_FAILED: 'IMAGE_SVG_RASTER_FAILED',\n MISSING_TEMPLATE: 'MISSING_TEMPLATE',\n UNKNOWN_PLACEHOLDER: 'UNKNOWN_PLACEHOLDER',\n PLACEHOLDER_NO_POSITION: 'PLACEHOLDER_NO_POSITION',\n THEME_COLOR_FALLBACK: 'THEME_COLOR_FALLBACK',\n UNKNOWN_COLOR: 'UNKNOWN_COLOR',\n GRID_POSITION_CLAMPED: 'GRID_POSITION_CLAMPED',\n TEXT_NO_CONTENT: 'TEXT_NO_CONTENT',\n UNKNOWN_PATTERN_PRESET: 'UNKNOWN_PATTERN_PRESET',\n ADVANCED_FILL_FALLBACK: 'ADVANCED_FILL_FALLBACK',\n IMAGE_ZERO_BOX: 'IMAGE_ZERO_BOX',\n FONT_UNRESOLVED: 'FONT_UNRESOLVED',\n} as const;\n\nexport type WarningCode = (typeof W)[keyof typeof W];\n\nexport function warn(\n warnings: PipelineWarning[] | undefined,\n code: WarningCode,\n message: string,\n extra?: Partial<PipelineWarning>\n): void {\n if (warnings) {\n warnings.push({ code, message, ...extra });\n } else {\n console.warn(message);\n }\n}\n","/**\n * PptxIR — the renderer-neutral description of a finished presentation.\n *\n * Everything here is plain data: no PptxGenJS objects, no functions, no raw\n * OOXML, no backend-specific shapes. A renderer adapter is the only thing that\n * turns these nodes into a library call.\n *\n * By the time a document reaches this form, all of the following have already\n * happened upstream (see `docs/architecture/office-renderer-ir.md`):\n *\n * - schema validation and structural conflict checks\n * - custom-component expansion\n * - theme resolution — every colour here is an explicit 6-digit hex\n * - component defaults\n * - font resolution/substitution, including synthesized weight aliases\n * - grid and placeholder layout resolution — every position here is EMU\n * - text parsing\n *\n * Units: EMU for geometry, points for font sizes, degrees for angles,\n * percent (0-100) for transparency, ISO 8601 strings for timestamps.\n */\n\n/** English Metric Units per inch. */\nexport const EMU_PER_INCH = 914400;\n/** English Metric Units per point (72 points per inch). */\nexport const EMU_PER_POINT = EMU_PER_INCH / 72;\n\nexport const PPTX_IR_SCHEMA_VERSION = 1;\n\n/* ------------------------------------------------------------------ *\n * Root\n * ------------------------------------------------------------------ */\n\nexport interface PptxIR {\n schemaVersion: typeof PPTX_IR_SCHEMA_VERSION;\n metadata: PptxIrMetadata;\n size: PptxIrSlideSize;\n theme: PptxIrTheme;\n /** Right-to-left reading order for the whole deck. */\n rtl: boolean;\n /** Deck-wide default proofing language (BCP-47). */\n language?: string;\n /** Deduplicated binary/external assets, in first-use order. */\n resources: PptxIrResource[];\n /** Reusable slide masters compiled from authored templates. */\n masters: PptxIrMaster[];\n slides: PptxIrSlide[];\n}\n\nexport interface PptxIrMetadata {\n title?: string;\n author?: string;\n subject?: string;\n company?: string;\n}\n\nexport interface PptxIrSlideSize {\n widthEmu: number;\n heightEmu: number;\n}\n\n/**\n * What survives theme resolution.\n *\n * Colours are already resolved into the elements that use them; the two font\n * families remain because they are set on the presentation itself (the OOXML\n * `<a:fontScheme>` major/minor faces), not per element. `palette` is the\n * resolved colour scheme, kept so an adapter able to emit a real `<a:clrScheme>`\n * can do so.\n */\nexport interface PptxIrTheme {\n name: string;\n headingFont: string;\n bodyFont: string;\n /** Resolved scheme colours, bare uppercase hex, keyed by project-owned slot. */\n palette: Readonly<Record<string, string>>;\n}\n\n/* ------------------------------------------------------------------ *\n * Resources\n * ------------------------------------------------------------------ */\n\n/**\n * An asset referenced by one or more slide elements.\n *\n * `origin` records how the bytes are obtained. Inline sources (base64, raw SVG)\n * are decoded at compile time and carry `bytes` plus a content hash, which is\n * what deduplication and debug snapshots key on. File and remote sources keep\n * their location so the adapter can stream them, exactly as the pipeline did\n * before the IR existed; their identity is the normalised location.\n */\nexport interface PptxIrResource {\n /** Deterministic: `res${n}` in first-use order. */\n id: string;\n kind: 'image';\n origin: PptxIrResourceOrigin;\n /** IANA media type when known, e.g. `image/png`. */\n mediaType?: string;\n /** Intrinsic pixel size, when the compiler probed it. */\n intrinsic?: PptxIrPixelSize;\n}\n\nexport type PptxIrResourceOrigin =\n | PptxIrInlineOrigin\n | PptxIrFileOrigin\n | PptxIrRemoteOrigin;\n\n/** Bytes the compiler already holds (authored base64 or raw SVG markup). */\nexport interface PptxIrInlineOrigin {\n kind: 'inline';\n bytes: Uint8Array;\n byteLength: number;\n /** Lowercase hex SHA-256 of `bytes`; the dedup and snapshot identity. */\n sha256: string;\n}\n\n/** An absolute local path already checked against the allowed roots. */\nexport interface PptxIrFileOrigin {\n kind: 'file';\n path: string;\n}\n\n/** An `http(s)` URL the adapter fetches. */\nexport interface PptxIrRemoteOrigin {\n kind: 'remote';\n url: string;\n}\n\nexport interface PptxIrPixelSize {\n widthPx: number;\n heightPx: number;\n}\n\n/* ------------------------------------------------------------------ *\n * Geometry, colour, fills, lines\n * ------------------------------------------------------------------ */\n\n/**\n * Absolute placement on a slide, in EMU, with optional rotation and flips.\n *\n * `autoWidth` / `autoHeight` mark an axis the author did not constrain. The\n * EMU value is still present as a fallback, but a renderer able to size that\n * axis itself — an OOXML table sizes from its columns — should. \"Unstated\" is\n * information; inventing a number and forgetting that it was invented is how a\n * layout silently stops adapting.\n */\nexport interface PptxIrTransform {\n xEmu: number;\n yEmu: number;\n widthEmu: number;\n heightEmu: number;\n autoWidth?: boolean;\n autoHeight?: boolean;\n /** Clockwise degrees. Omitted means 0. */\n rotationDegrees?: number;\n flipHorizontal?: boolean;\n flipVertical?: boolean;\n}\n\n/**\n * A resolved colour: bare uppercase 6-digit hex, never a theme token.\n *\n * `transparency` is 0-100 where 0 is opaque, matching the authoring surface.\n */\nexport interface PptxIrColor {\n hex: string;\n transparency?: number;\n}\n\nexport type PptxIrFill =\n | PptxIrNoFill\n | PptxIrSolidFill\n | PptxIrGradientFill\n | PptxIrPatternFill\n | PptxIrImageFill;\n\nexport interface PptxIrNoFill {\n kind: 'none';\n}\n\nexport interface PptxIrSolidFill {\n kind: 'solid';\n color: PptxIrColor;\n}\n\n/**\n * A gradient described semantically. Each adapter decides how to realise it —\n * PptxGenJS cannot express one directly and splices XML during packaging;\n * another backend may have a first-class API. Neither concern belongs here.\n */\nexport interface PptxIrGradientFill {\n kind: 'gradient';\n gradient: PptxIrGradient;\n}\n\nexport type PptxIrGradient = PptxIrLinearGradient | PptxIrRadialGradient;\n\nexport interface PptxIrLinearGradient {\n type: 'linear';\n /** Degrees, normalised to [0, 360). */\n angleDegrees: number;\n stops: PptxIrGradientStop[];\n}\n\nexport interface PptxIrRadialGradient {\n type: 'radial';\n focus: PptxIrRadialFocus;\n stops: PptxIrGradientStop[];\n}\n\nexport type PptxIrRadialFocus =\n | 'center'\n | 'topLeft'\n | 'topRight'\n | 'bottomLeft'\n | 'bottomRight';\n\nexport interface PptxIrGradientStop {\n /** Percent along the gradient, 0-100. */\n position: number;\n color: PptxIrColor;\n}\n\nexport interface PptxIrPatternFill {\n kind: 'pattern';\n /** OOXML `prst` preset name, validated at compile time. */\n preset: string;\n foreground: PptxIrColor;\n background: PptxIrColor;\n}\n\nexport interface PptxIrImageFill {\n kind: 'image';\n resourceId: string;\n}\n\nexport interface PptxIrLine {\n color?: PptxIrColor;\n /** Stroke width in points. */\n widthPoints?: number;\n dash?: PptxIrLineDash;\n}\n\nexport type PptxIrLineDash =\n | 'solid'\n | 'dash'\n | 'dashDot'\n | 'lgDash'\n | 'lgDashDot'\n | 'lgDashDotDot'\n | 'sysDash'\n | 'sysDashDot'\n | 'sysDashDotDot'\n | 'sysDot'\n | 'dot';\n\nexport interface PptxIrShadow {\n type: 'outer' | 'inner' | 'none';\n color: PptxIrColor;\n /** Blur radius in points. */\n blurPoints: number;\n /** Offset distance in points. */\n offsetPoints: number;\n angleDegrees: number;\n /** 0-1, as the authoring surface expresses it. */\n opacity: number;\n}\n\n/* ------------------------------------------------------------------ *\n * Hyperlinks\n * ------------------------------------------------------------------ */\n\nexport type PptxIrHyperlink = PptxIrExternalHyperlink | PptxIrSlideHyperlink;\n\nexport interface PptxIrExternalHyperlink {\n kind: 'external';\n url: string;\n tooltip?: string;\n}\n\n/** A jump to another slide, already rebased onto generated slide numbering. */\nexport interface PptxIrSlideHyperlink {\n kind: 'slide';\n /** 1-based index into `PptxIR.slides`. */\n slideIndex: number;\n tooltip?: string;\n}\n\n/* ------------------------------------------------------------------ *\n * Text\n * ------------------------------------------------------------------ */\n\nexport type PptxIrHorizontalAlign = 'left' | 'center' | 'right' | 'justify';\nexport type PptxIrVerticalAlign = 'top' | 'middle' | 'bottom';\n\n/**\n * One run of uniformly-formatted text.\n *\n * Every inherited value has already been cascaded down (component props →\n * named style → theme defaults), so a run states its own formatting outright\n * rather than relying on a parent. `fontFamily` is post-substitution and may be\n * a synthesized weight alias such as `Inter Light`.\n */\nexport interface PptxIrTextRun {\n text: string;\n fontFamily: string;\n /** Points. */\n fontSize: number;\n color: PptxIrColor;\n bold?: boolean;\n italic?: boolean;\n strike?: boolean;\n underline?: PptxIrUnderline;\n superscript?: boolean;\n subscript?: boolean;\n /** Points; positive tracks wider. */\n characterSpacing?: number;\n /** BCP-47 proofing language. */\n language?: string;\n /** End this run with a hard line break. */\n breakAfter?: boolean;\n /** Points of space before the paragraph this run starts. */\n spaceBeforePoints?: number;\n /** Points of space after the paragraph this run ends. */\n spaceAfterPoints?: number;\n hyperlink?: PptxIrHyperlink;\n}\n\nexport interface PptxIrUnderline {\n style: string;\n color?: PptxIrColor;\n}\n\n/**\n * Formatting a text body applies by default.\n *\n * OOXML keeps body-level defaults (`lstStyle`, `endParaRPr`) separate from run\n * properties, and so does this: `PptxIrTextRun` states its own formatting\n * outright — a backend with no body-default concept can render from runs alone\n * — while `defaults` is what an empty paragraph, or a backend that does have\n * the concept, should use.\n */\nexport interface PptxIrRunFormatting {\n fontFamily: string;\n /** Points. */\n fontSize: number;\n color: PptxIrColor;\n bold?: boolean;\n italic?: boolean;\n /** BCP-47 proofing language. */\n language?: string;\n}\n\n/** Paragraph-level settings shared by every run in a text body. */\nexport interface PptxIrTextBodyStyle {\n align?: PptxIrHorizontalAlign;\n verticalAlign: PptxIrVerticalAlign;\n /** Exact line height in points. Mutually exclusive with `lineSpacingMultiple`. */\n lineSpacingPoints?: number;\n /** Line height as a multiple of the font size. */\n lineSpacingMultiple?: number;\n spaceBeforePoints?: number;\n spaceAfterPoints?: number;\n bullet?: PptxIrBullet;\n /**\n * Inset in points: a single value or [top, right, bottom, left].\n *\n * The four-value order is CSS's, which is what the authoring schema states\n * and what the default backend already reads — an adapter that rotates it\n * moves content to the wrong side of the box.\n *\n * Absent means \"no inset stated\" — the format's own default applies. That is\n * a real distinction: a text box states `0` so it aligns exactly to its\n * position, while a shape leaves it unstated and keeps OOXML's default\n * padding.\n */\n insetPoints?: number | [number, number, number, number];\n /** Let the shape grow to fit its text instead of clipping. */\n autoFit?: boolean;\n /** Body-level run defaults. */\n defaults: PptxIrRunFormatting;\n}\n\nexport interface PptxIrBullet {\n /**\n * `bullet` for a glyph, `number` for an ordered list, `none` for a paragraph\n * that states it has no bullet.\n *\n * `none` is not the same as leaving `bullet` unset. Unset inherits whatever\n * the list style or the backend's default provides; `none` is the author\n * saying so, and lowers to `<a:buNone/>` — which is what overriding an\n * inherited bullet takes.\n */\n type: 'bullet' | 'number' | 'none';\n /** Glyph character or numbering style, as OOXML names it. */\n style?: string;\n startAt?: number;\n}\n\n/* ------------------------------------------------------------------ *\n * Slide elements\n * ------------------------------------------------------------------ */\n\nexport type PptxIrElement =\n | PptxIrTextBoxElement\n | PptxIrShapeElement\n | PptxIrImageElement\n | PptxIrTableElement\n | PptxIrChartElement\n | PptxIrGroupElement;\n\n/** Fields every element carries. */\ninterface PptxIrElementBase {\n /** Deterministic, path-derived: e.g. `s1.e3`, `s1.e3.g0`. */\n id: string;\n /** IR path for diagnostics: e.g. `slides[0].elements[3]`. */\n path: string;\n transform: PptxIrTransform;\n /** Accessibility description. */\n altText?: string;\n}\n\nexport interface PptxIrTextBoxElement extends PptxIrElementBase {\n kind: 'textBox';\n runs: PptxIrTextRun[];\n style: PptxIrTextBodyStyle;\n fill?: PptxIrFill;\n line?: PptxIrLine;\n shadow?: PptxIrShadow;\n hyperlink?: PptxIrHyperlink;\n}\n\n/**\n * A preset-geometry shape, optionally carrying text.\n *\n * `geometry` is a project-owned name (see `PPTX_IR_GEOMETRY`), not a PptxGenJS\n * enum member; adapters map it to whatever their backend calls it.\n */\nexport interface PptxIrShapeElement extends PptxIrElementBase {\n kind: 'shape';\n geometry: PptxIrGeometry;\n fill?: PptxIrFill;\n line?: PptxIrLine;\n shadow?: PptxIrShadow;\n /** Corner radius in inches. `roundRect` and friends only. */\n cornerRadius?: number;\n /** Start/end angle in degrees for arc-like geometries. */\n angleRangeDegrees?: [number, number];\n runs?: PptxIrTextRun[];\n style?: PptxIrTextBodyStyle;\n hyperlink?: PptxIrHyperlink;\n}\n\nexport const PPTX_IR_GEOMETRY = [\n 'rect',\n 'roundRect',\n 'ellipse',\n 'triangle',\n 'diamond',\n 'pentagon',\n 'hexagon',\n 'star5',\n 'star6',\n 'line',\n 'rightArrow',\n 'chevron',\n 'cloud',\n 'heart',\n 'lightningBolt',\n] as const;\n\nexport type PptxIrKnownGeometry = (typeof PPTX_IR_GEOMETRY)[number];\n\n/**\n * A geometry name. Known names are checked at compile time; anything else is\n * carried through as `{ custom }` so an adapter that supports a wider preset\n * set can use it and one that does not can fail with a precise diagnostic.\n */\nexport type PptxIrGeometry = PptxIrKnownGeometry | { custom: string };\n\nexport interface PptxIrImageElement extends PptxIrElementBase {\n kind: 'image';\n resourceId: string;\n /** Cropping/scaling already resolved by the compiler where it could be. */\n sizing?: PptxIrImageSizing;\n rounding?: boolean;\n shadow?: PptxIrShadow;\n hyperlink?: PptxIrHyperlink;\n}\n\nexport interface PptxIrImageSizing {\n /**\n * `contain` survives only when the fit could not be computed — the compiler\n * normally resolves it into the transform and drops the sizing.\n */\n type: 'contain' | 'cover' | 'crop';\n widthEmu: number;\n heightEmu: number;\n /** Crop origin in EMU, `crop` only. */\n xEmu?: number;\n yEmu?: number;\n}\n\n/**\n * A table.\n *\n * The authoring surface gives each cell a single string plus its own\n * formatting, so that is what the IR models — not a rich-text body per cell.\n * `defaults` holds the table-level formatting cells inherit; a cell states only\n * what it overrides, which mirrors how OOXML layers `tblPr` under `tcPr`.\n */\nexport interface PptxIrTableElement extends PptxIrElementBase {\n kind: 'table';\n rows: PptxIrTableRow[];\n /** Column widths in EMU. Empty lets the renderer distribute them. */\n columnWidthsEmu: number[];\n /** Row heights in EMU, positionally. Empty lets the renderer auto-size. */\n rowHeightsEmu: number[];\n defaults: PptxIrTableFormatting;\n /** Uniform border applied to the whole table. */\n border?: PptxIrTableBorder;\n /** Table-level background fill. */\n fill?: PptxIrColor;\n /**\n * Corner radius in inches.\n *\n * A semantic request for rounded table corners. OOXML tables have no such\n * property, so each adapter decides how to honour it; the IR does not\n * describe the technique.\n */\n cornerRadiusInches?: number;\n /** Let the table flow onto further slides when it overruns. */\n autoPage?: boolean;\n /** Repeat the first row as a header on each continuation slide. */\n autoPageRepeatHeader?: boolean;\n}\n\n/** Formatting a table applies to every cell that does not override it. */\nexport interface PptxIrTableFormatting {\n fontFamily: string;\n /** Points. */\n fontSize: number;\n color?: PptxIrColor;\n bold?: boolean;\n align?: PptxIrHorizontalAlign;\n verticalAlign: PptxIrVerticalAlign;\n /** Inset in points: one value or [top, right, bottom, left]. */\n insetPoints?: number | [number, number, number, number];\n}\n\nexport interface PptxIrTableRow {\n cells: PptxIrTableCell[];\n}\n\nexport interface PptxIrTableCell {\n text: string;\n /** Only what this cell overrides; everything else comes from `defaults`. */\n formatting?: PptxIrTableCellFormatting;\n fill?: PptxIrColor;\n /** Per-side borders, in [top, right, bottom, left] order. */\n borders?: [\n PptxIrTableBorder,\n PptxIrTableBorder,\n PptxIrTableBorder,\n PptxIrTableBorder,\n ];\n colSpan?: number;\n rowSpan?: number;\n}\n\nexport interface PptxIrTableCellFormatting {\n fontFamily?: string;\n /** Points. */\n fontSize?: number;\n color?: PptxIrColor;\n bold?: boolean;\n italic?: boolean;\n align?: PptxIrHorizontalAlign;\n verticalAlign?: PptxIrVerticalAlign;\n insetPoints?: number | [number, number, number, number];\n}\n\nexport interface PptxIrTableBorder {\n type: 'none' | 'solid' | 'dash' | 'dot';\n color?: PptxIrColor;\n /** Points. */\n widthPoints?: number;\n}\n\n/**\n * A native OOXML chart.\n *\n * Series data is normalised and every colour, font family and label style is\n * already resolved, so no theme lookup or charting library is involved at\n * render time. The option names follow the project's authoring schema, which\n * is itself aligned with PowerPoint's chart vocabulary — they are project-owned\n * names that happen to read like the format's.\n */\nexport interface PptxIrChartElement extends PptxIrElementBase {\n kind: 'chart';\n chartType: PptxIrChartType;\n series: PptxIrChartSeries[];\n options: PptxIrChartOptions;\n}\n\nexport type PptxIrChartType =\n | 'area'\n | 'bar'\n | 'bar3D'\n | 'bubble'\n | 'doughnut'\n | 'line'\n | 'pie'\n | 'radar'\n | 'scatter';\n\nexport interface PptxIrChartSeries {\n name?: string;\n labels?: string[];\n values?: number[];\n /** Bubble sizes, `bubble` charts only. */\n sizes?: number[];\n}\n\n/** A resolved label font: family after weight aliasing, plus the bold toggle. */\nexport interface PptxIrChartLabelFont {\n fontFamily?: string;\n bold?: boolean;\n /** Points. */\n fontSize?: number;\n color?: PptxIrColor;\n}\n\nexport interface PptxIrChartGridLine {\n style?: string;\n size?: number;\n color?: PptxIrColor;\n}\n\nexport interface PptxIrChartOptions {\n /** Resolved series palette, in series order. Empty means \"use the backend's\". */\n colors: string[];\n\n showLegend?: boolean;\n showTitle?: boolean;\n showValue?: boolean;\n showPercent?: boolean;\n showLabel?: boolean;\n showSeriesName?: boolean;\n\n title?: string;\n titleFont: PptxIrChartLabelFont;\n\n legendPosition?: string;\n legendFont: PptxIrChartLabelFont;\n\n categoryAxis: PptxIrChartAxis;\n valueAxis: PptxIrChartValueAxis;\n\n dataBorder?: { widthPoints: number; color: PptxIrColor };\n dataLabelFont: PptxIrChartLabelFont;\n dataLabelPosition?: string;\n\n barDirection?: string;\n barGrouping?: string;\n barGapWidthPercent?: number;\n barOverlapPercent?: number;\n\n lineSmooth?: boolean;\n lineDataSymbol?: string;\n lineSize?: number;\n lineDataSymbolSize?: number;\n\n firstSliceAngle?: number;\n holeSize?: number;\n\n radarStyle?: string;\n}\n\nexport interface PptxIrChartAxis {\n title?: string;\n hidden?: boolean;\n labelRotate?: number;\n labelFont: PptxIrChartLabelFont;\n gridLine?: PptxIrChartGridLine;\n showLine?: boolean;\n}\n\nexport interface PptxIrChartValueAxis extends PptxIrChartAxis {\n minValue?: number;\n maxValue?: number;\n majorUnit?: number;\n labelFormatCode?: string;\n}\n\n/** A group of elements sharing a transform. */\nexport interface PptxIrGroupElement extends PptxIrElementBase {\n kind: 'group';\n children: PptxIrElement[];\n}\n\n/* ------------------------------------------------------------------ *\n * Slides and masters\n * ------------------------------------------------------------------ */\n\nexport interface PptxIrSlide {\n /** Deterministic: `slide${n}`, 1-based in generated order. */\n id: string;\n path: string;\n /** Name of a master in `PptxIR.masters`, when the slide uses one. */\n masterName?: string;\n background?: PptxIrBackground;\n elements: PptxIrElement[];\n notes?: string;\n hidden: boolean;\n transition?: PptxIrTransition;\n}\n\n/**\n * A slide background.\n *\n * Only solid and image backgrounds are backgrounds in the OOXML sense. A\n * gradient background compiles to a full-bleed shape at the back of the slide\n * instead, because that is what it means semantically once resolved — see the\n * compiler.\n */\nexport type PptxIrBackground =\n | { kind: 'solid'; color: PptxIrColor }\n | { kind: 'image'; resourceId: string };\n\nexport interface PptxIrTransition {\n type: string;\n speed?: 'slow' | 'medium' | 'fast';\n}\n\nexport interface PptxIrMaster {\n name: string;\n background?: PptxIrBackground;\n /**\n * Content margin, in inches: a single value or [top, right, bottom, left].\n *\n * Not decoration — a format sizes an unconstrained table against the master's\n * margins, so dropping this silently resizes tables.\n */\n margin?: number | [number, number, number, number];\n /** Fixed decoration drawn on every slide using this master. */\n elements: PptxIrElement[];\n /** Slide-number field placement, when the template defines one. */\n slideNumber?: PptxIrSlideNumber;\n /** Named regions a slide can fill; positions already resolved. */\n placeholders: PptxIrPlaceholder[];\n}\n\nexport interface PptxIrSlideNumber {\n transform: PptxIrTransform;\n color?: PptxIrColor;\n /** Points. */\n fontSize?: number;\n}\n\n/**\n * A placeholder as the *master* declares it.\n *\n * Slide-side placeholder content is not a placeholder in the IR — it has\n * already been merged with the declaration and emitted as a normal element on\n * the slide. This entry exists so a master can still declare the region.\n */\nexport interface PptxIrPlaceholder {\n name: string;\n transform?: PptxIrTransform;\n}\n","/**\n * Unit and identity helpers for PptxIR construction.\n *\n * Authoring expresses geometry in inches (or percent strings); the IR expresses\n * it in EMU. The conversion is a single rounding step, done here so every\n * compile site agrees on it — and so the PptxGenJS adapter can invert it\n * exactly by dividing, since PptxGenJS applies the same `Math.round(in * EMU)`\n * on the way in.\n */\n\nimport { createHash } from 'node:crypto';\nimport { EMU_PER_INCH } from './types';\nimport type { PptxIrColor } from './types';\n\n/** Inches → EMU. */\nexport function inchesToEmu(inches: number): number {\n return Math.round(inches * EMU_PER_INCH);\n}\n\n/** EMU → inches. Lossless against `inchesToEmu` for realistic magnitudes. */\nexport function emuToInches(emu: number): number {\n return emu / EMU_PER_INCH;\n}\n\n/** Slide size in EMU, the frame percentages resolve against. */\nexport interface SlideExtentEmu {\n widthEmu: number;\n heightEmu: number;\n}\n\n/**\n * Resolve an authored dimension to EMU.\n *\n * This reproduces the authoring contract the pipeline has always had, quirks\n * included, because the numbers it produces are the numbers that end up in the\n * package:\n *\n * - a number below 100 is inches\n * - a number of 100 or more is already EMU (nobody authors a 100-inch slide,\n * and callers do pass EMU through)\n * - a percent string resolves against the slide extent *in EMU*, so the single\n * rounding step happens at the end\n * - a bare numeric string is treated as a number\n * - anything else is 0 rather than an error\n *\n * The rules are stated here once so no compile site has to re-derive them.\n */\nexport function resolveDimensionEmu(\n value: number | string,\n axis: 'X' | 'Y',\n extent: SlideExtentEmu\n): number {\n let size: number | string = value;\n if (\n typeof size === 'string' &&\n size.trim() !== '' &&\n !Number.isNaN(Number(size))\n ) {\n size = Number(size);\n }\n if (typeof size === 'number') {\n return size < 100 ? Math.round(EMU_PER_INCH * size) : size;\n }\n if (size.includes('%')) {\n const pct = Number.parseFloat(size);\n if (Number.isNaN(pct)) return 0;\n const axisEmu = axis === 'Y' ? extent.heightEmu : extent.widthEmu;\n return Math.round((pct / 100) * axisEmu);\n }\n return 0;\n}\n\n/**\n * Width used when an element does not state one.\n *\n * 75% of the slide width — the width the pipeline has always produced for an\n * element with no `w`. Materialising it here is what lets the IR promise an\n * explicit transform without changing any output.\n */\nexport function defaultWidthEmu(extent: SlideExtentEmu): number {\n return Math.round(0.75 * extent.widthEmu);\n}\n\n/**\n * Build an IR colour from an already-resolved bare hex string.\n *\n * `resolveColor` (utils/color.ts) is what turns theme tokens into hex; this\n * only normalises casing and attaches transparency, so an unresolved token can\n * never reach the IR by accident.\n */\nexport function irColor(bareHex: string, transparency?: number): PptxIrColor {\n const hex = bareHex.startsWith('#') ? bareHex.slice(1) : bareHex;\n return transparency === undefined\n ? { hex: hex.toUpperCase() }\n : { hex: hex.toUpperCase(), transparency };\n}\n\n/** Normalise degrees into [0, 360). */\nexport function normalizeDegrees(degrees: number): number {\n return ((degrees % 360) + 360) % 360;\n}\n\n/** Lowercase hex SHA-256, the identity used for inline resources. */\nexport function sha256Hex(bytes: Uint8Array): string {\n return createHash('sha256').update(bytes).digest('hex');\n}\n\n/**\n * Deterministic element id from its position in the tree.\n *\n * Ids are derived, never allocated from a counter, so two concurrent\n * generations of the same document produce the same ids and a single\n * generation's ids do not depend on evaluation order.\n */\nexport function elementId(\n slideIndex: number,\n indexPath: readonly number[]\n): string {\n return `s${slideIndex + 1}.${indexPath.map((i) => `e${i}`).join('.')}`;\n}\n","/**\n * PPTX renderer features.\n *\n * A feature is a capability a *backend* must have, not an authoring concept.\n * The compiler records one requirement per IR node that needs one; a renderer\n * declares the set it can satisfy. Anything required but not declared fails\n * before rendering, with the IR path attached.\n *\n * Names are chosen so the boundary is real: `gradient-fills` is separate from\n * `pattern-fills` because a backend can plausibly have one and not the other,\n * while `rich-text` covers multi-run bodies as a single indivisible ability.\n */\n\nexport const PPTX_FEATURES = [\n /** Slide masters compiled from authored templates. */\n 'masters',\n /** Named placeholder regions declared by a master. */\n 'placeholders',\n /** Multiple independently-formatted runs inside one text body. */\n 'rich-text',\n /**\n * Bullet glyphs outside PptxGenJS's single-BMP-character API: astral\n * characters and multi-code-point graphemes.\n */\n 'complex-bullet-glyphs',\n /** Text bodies at all (a single run, uniform formatting). */\n 'text',\n /** Preset-geometry shapes. */\n 'shapes',\n /** Raster and vector images. */\n 'images',\n /** SVG images specifically — many backends need a raster fallback. */\n 'svg',\n /**\n * Drawing only part of a picture: `cover`, `crop`, or a `contain` fit the\n * compiler could not resolve into the frame.\n *\n * A backend without it draws the whole picture into the frame, which is a\n * different image — the wrong region at the wrong scale — with nothing to\n * show that anything was lost.\n */\n 'image-crop',\n /** Masking a picture to rounded corners or a circle. */\n 'image-rounding',\n 'tables',\n /** Merged table cells (colSpan / rowSpan). */\n 'table-merged-cells',\n /**\n * Cell insets on a table.\n *\n * Separate from the inset on a text body: a reader takes a cell's padding\n * from `a:tcPr`, and a backend that can only write text-body insets puts the\n * numbers somewhere nothing reads them.\n */\n 'table-insets',\n /**\n * Rounded table corners.\n *\n * A separate ability because OOXML has no such property: a backend realises\n * it by drawing shapes behind the table, or it cannot realise it at all.\n */\n 'table-rounded-corners',\n /**\n * Flowing an over-long table onto further slides, header row included.\n *\n * Pagination is the backend's, not the IR's — the IR describes one table and\n * says it may split, so a backend that cannot split has to refuse rather than\n * emit a table running off the slide.\n */\n 'table-auto-page',\n /** Native OOXML charts with an embedded workbook. */\n 'charts',\n 'solid-fills',\n 'gradient-fills',\n 'pattern-fills',\n 'image-fills',\n 'lines',\n 'shadows',\n /** Slide backgrounds (solid or image). */\n 'backgrounds',\n 'speaker-notes',\n 'hidden-slides',\n 'transitions',\n /** Hyperlinks to an external URL. */\n 'external-links',\n /** Hyperlinks targeting another slide in the same deck. */\n 'internal-links',\n /** A link covering a text body — realisable on the runs inside it. */\n 'text-hyperlinks',\n /** A link on a shape or image as a whole, which runs cannot stand in for. */\n 'element-hyperlinks',\n /** Rotation on a shape, text box or table. */\n 'rotation',\n /**\n * Any transform on a picture — rotation or flip.\n *\n * One feature rather than three: a backend that cannot rotate a picture\n * generally cannot flip one either, because the option carrying both is\n * simply absent from its picture type.\n */\n 'image-transform',\n 'flip-horizontal',\n 'flip-vertical',\n /** Grouped elements sharing a transform. */\n 'groups',\n /** Per-run proofing language. */\n 'proofing-language',\n /** Right-to-left reading order. */\n 'rtl',\n] as const;\n\nexport type PptxFeature = (typeof PPTX_FEATURES)[number];\n\n/** Every feature, for an adapter that claims the full surface. */\nexport const ALL_PPTX_FEATURES: ReadonlySet<PptxFeature> = new Set(\n PPTX_FEATURES\n);\n\nexport function isPptxFeature(value: string): value is PptxFeature {\n return (PPTX_FEATURES as readonly string[]).includes(value);\n}\n","/**\n * Gradient and pattern fills for the PptxGenJS backend.\n *\n * PptxGenJS has no API for either. The workaround — render a sentinel\n * `<a:solidFill>` on a uniquely-named shape, then splice the real fill element\n * in while packaging — is a property of *this backend*, so it lives here and\n * never in PptxIR or in generic PPTX types. PptxIR describes the gradient\n * semantically; another adapter is free to emit it directly.\n *\n * Colours arriving here are already resolved to hex by the compiler, so\n * building the XML is a pure string operation.\n */\n\nimport type {\n PptxIrColor,\n PptxIrFill,\n PptxIrGradient,\n PptxIrRadialFocus,\n} from '../../ir/types';\n\n/** OOXML angle unit: 60000ths of a degree. */\nconst ANGLE_UNIT = 60000;\n/** OOXML percentage unit: 1000ths of a percent (0-100 → 0-100000). */\nconst PCT_UNIT = 1000;\n\n/** `fillToRect` edges (in 1000ths of a percent) per radial focus corner. */\nconst RADIAL_FOCUS_RECTS: Record<\n PptxIrRadialFocus,\n { l: number; t: number; r: number; b: number }\n> = {\n center: { l: 50000, t: 50000, r: 50000, b: 50000 },\n topLeft: { l: 0, t: 0, r: 100000, b: 100000 },\n topRight: { l: 100000, t: 0, r: 0, b: 100000 },\n bottomLeft: { l: 0, t: 100000, r: 100000, b: 0 },\n bottomRight: { l: 100000, t: 100000, r: 0, b: 0 },\n};\n\n/**\n * A fill to splice into slide XML during packaging.\n *\n * The shape that registered it carries `cNvPr name=\"{objectName}\"`.\n */\nexport interface PendingXmlFill {\n objectName: string;\n /** Complete replacement element, e.g. `<a:gradFill>…</a:gradFill>`. */\n xml: string;\n}\n\n/** Collects pending fills for one render. Never module-global. */\nexport type PendingFillSink = PendingXmlFill[];\n\n/**\n * A colour element that can carry an alpha child.\n *\n * Always paired, even with no alpha: gradient stops may gain one, and the\n * paired form is what the slide XML has always contained for them.\n */\nfunction colorXml(color: PptxIrColor): string {\n const alpha =\n color.transparency !== undefined\n ? `<a:alpha val=\"${Math.round((100 - color.transparency) * PCT_UNIT)}\"/>`\n : '';\n return `<a:srgbClr val=\"${color.hex.toUpperCase()}\">${alpha}</a:srgbClr>`;\n}\n\n/**\n * The compact colour element used inside a pattern fill.\n *\n * Pattern foreground/background carry no transparency, so the element has no\n * children and is written self-closing.\n */\nfunction opaqueColorXml(color: PptxIrColor): string {\n return `<a:srgbClr val=\"${color.hex.toUpperCase()}\"/>`;\n}\n\nexport function buildGradientFillXml(gradient: PptxIrGradient): string {\n const stops = gradient.stops\n .map(\n (stop) =>\n `<a:gs pos=\"${Math.round(stop.position * PCT_UNIT)}\">${colorXml(stop.color)}</a:gs>`\n )\n .join('');\n\n const shade =\n gradient.type === 'radial'\n ? radialShadeXml(gradient.focus)\n : `<a:lin ang=\"${Math.round(gradient.angleDegrees * ANGLE_UNIT)}\" scaled=\"1\"/>`;\n\n return `<a:gradFill rotWithShape=\"1\"><a:gsLst>${stops}</a:gsLst>${shade}</a:gradFill>`;\n}\n\nfunction radialShadeXml(focus: PptxIrRadialFocus): string {\n const rect = RADIAL_FOCUS_RECTS[focus] ?? RADIAL_FOCUS_RECTS.center;\n return `<a:path path=\"circle\"><a:fillToRect l=\"${rect.l}\" t=\"${rect.t}\" r=\"${rect.r}\" b=\"${rect.b}\"/></a:path>`;\n}\n\nexport function buildPatternFillXml(\n preset: string,\n foreground: PptxIrColor,\n background: PptxIrColor\n): string {\n return (\n `<a:pattFill prst=\"${preset}\">` +\n `<a:fgClr>${opaqueColorXml(foreground)}</a:fgClr>` +\n `<a:bgClr>${opaqueColorXml(background)}</a:bgClr>` +\n `</a:pattFill>`\n );\n}\n\n/**\n * Write a sentinel solid fill and register the real fill for splicing.\n *\n * Without a sink — a caller rendering outside the buffer pipeline — the shape\n * keeps the sentinel colour, so the deck still reads as authored instead of\n * falling back to a PptxGenJS default.\n */\nexport function registerAdvancedFill(\n opts: Record<string, unknown>,\n fill: Extract<PptxIrFill, { kind: 'gradient' | 'pattern' }>,\n elementPath: string,\n sink: PendingFillSink | undefined\n): void {\n const sentinel =\n fill.kind === 'gradient' ? fill.gradient.stops[0].color : fill.foreground;\n\n if (sink) {\n const xml =\n fill.kind === 'gradient'\n ? buildGradientFillXml(fill.gradient)\n : buildPatternFillXml(fill.preset, fill.foreground, fill.background);\n const objectName = `__jto_fill_${sink.length}__`;\n sink.push({ objectName, xml });\n opts.objectName = objectName;\n }\n\n void elementPath;\n opts.fill = { color: sentinel.hex };\n}\n","/**\n * PptxIR charts → PptxGenJS.\n *\n * Pure vocabulary translation. Every colour, font family, bold toggle and\n * palette entry was resolved by the compiler, so nothing here consults a theme\n * or decides a default.\n */\n\nimport type PptxGenJS from 'pptxgenjs';\nimport type {\n PptxIrChartAxis,\n PptxIrChartElement,\n PptxIrChartGridLine,\n PptxIrChartLabelFont,\n PptxIrChartValueAxis,\n} from '../../ir/types';\nimport { emuToInches } from '../../ir/units';\n\ntype Opts = Record<string, unknown>;\n\nexport function emitChart(\n slide: PptxGenJS.Slide,\n element: PptxIrChartElement\n): void {\n const data = element.series.map((series) => {\n const entry: Opts = {};\n if (series.name !== undefined) entry.name = series.name;\n if (series.labels) entry.labels = series.labels;\n if (series.values) entry.values = series.values;\n if (series.sizes) entry.sizes = series.sizes;\n return entry;\n });\n\n slide.addChart(\n element.chartType as never,\n data as never,\n chartOpts(element) as never\n );\n}\n\nfunction chartOpts(element: PptxIrChartElement): Opts {\n const { options: o, transform } = element;\n const opts: Opts = {\n x: emuToInches(transform.xEmu),\n y: emuToInches(transform.yEmu),\n w: emuToInches(transform.widthEmu),\n h: emuToInches(transform.heightEmu),\n };\n\n if (o.colors.length > 0) opts.chartColors = [...o.colors];\n\n assignDefined(opts, {\n showLegend: o.showLegend,\n showTitle: o.showTitle,\n showValue: o.showValue,\n showPercent: o.showPercent,\n showLabel: o.showLabel,\n showSerName: o.showSeriesName,\n title: o.title,\n legendPos: o.legendPosition,\n barDir: o.barDirection,\n barGrouping: o.barGrouping,\n barGapWidthPct: o.barGapWidthPercent,\n barOverlapPct: o.barOverlapPercent,\n lineSmooth: o.lineSmooth,\n lineDataSymbol: o.lineDataSymbol,\n lineSize: o.lineSize,\n lineDataSymbolSize: o.lineDataSymbolSize,\n firstSliceAng: o.firstSliceAngle,\n holeSize: o.holeSize,\n radarStyle: o.radarStyle,\n dataLabelPosition: o.dataLabelPosition,\n });\n\n applyLabelFont(opts, o.titleFont, {\n face: 'titleFontFace',\n bold: 'titleBold',\n size: 'titleFontSize',\n color: 'titleColor',\n });\n applyLabelFont(opts, o.legendFont, {\n face: 'legendFontFace',\n size: 'legendFontSize',\n color: 'legendColor',\n });\n applyLabelFont(opts, o.dataLabelFont, {\n face: 'dataLabelFontFace',\n bold: 'dataLabelFontBold',\n size: 'dataLabelFontSize',\n color: 'dataLabelColor',\n });\n\n applyAxis(opts, o.categoryAxis, {\n title: 'catAxisTitle',\n showTitle: 'showCatAxisTitle',\n hidden: 'catAxisHidden',\n labelRotate: 'catAxisLabelRotate',\n gridLine: 'catGridLine',\n showLine: 'catAxisLineShow',\n face: 'catAxisLabelFontFace',\n bold: 'catAxisLabelFontBold',\n size: 'catAxisLabelFontSize',\n color: 'catAxisLabelColor',\n });\n\n applyValueAxis(opts, o.valueAxis);\n\n if (o.dataBorder) {\n opts.dataBorder = {\n pt: o.dataBorder.widthPoints,\n color: o.dataBorder.color.hex,\n };\n }\n\n return opts;\n}\n\ninterface LabelFontKeys {\n face: string;\n /** Absent for the legend, which has no bold toggle in PowerPoint. */\n bold?: string;\n size: string;\n color: string;\n}\n\nfunction applyLabelFont(\n opts: Opts,\n font: PptxIrChartLabelFont,\n keys: LabelFontKeys\n): void {\n if (font.fontFamily !== undefined) opts[keys.face] = font.fontFamily;\n if (font.bold !== undefined && keys.bold) opts[keys.bold] = font.bold;\n if (font.fontSize !== undefined) opts[keys.size] = font.fontSize;\n if (font.color) opts[keys.color] = font.color.hex;\n}\n\ninterface AxisKeys extends LabelFontKeys {\n title: string;\n showTitle: string;\n hidden: string;\n labelRotate: string;\n gridLine: string;\n showLine: string;\n}\n\nfunction applyAxis(opts: Opts, axis: PptxIrChartAxis, keys: AxisKeys): void {\n if (axis.title !== undefined) {\n opts[keys.title] = axis.title;\n opts[keys.showTitle] = true;\n }\n if (axis.hidden !== undefined) opts[keys.hidden] = axis.hidden;\n if (axis.labelRotate !== undefined) opts[keys.labelRotate] = axis.labelRotate;\n if (axis.showLine !== undefined) opts[keys.showLine] = axis.showLine;\n if (axis.gridLine) opts[keys.gridLine] = gridLineOpts(axis.gridLine);\n applyLabelFont(opts, axis.labelFont, keys);\n}\n\nfunction applyValueAxis(opts: Opts, axis: PptxIrChartValueAxis): void {\n applyAxis(opts, axis, {\n title: 'valAxisTitle',\n showTitle: 'showValAxisTitle',\n hidden: 'valAxisHidden',\n labelRotate: 'valAxisLabelRotate',\n gridLine: 'valGridLine',\n showLine: 'valAxisLineShow',\n face: 'valAxisLabelFontFace',\n bold: 'valAxisLabelFontBold',\n size: 'valAxisLabelFontSize',\n color: 'valAxisLabelColor',\n });\n assignDefined(opts, {\n valAxisMinVal: axis.minValue,\n valAxisMaxVal: axis.maxValue,\n valAxisMajorUnit: axis.majorUnit,\n valAxisLabelFormatCode: axis.labelFormatCode,\n });\n}\n\nfunction gridLineOpts(gridLine: PptxIrChartGridLine): Opts {\n const opts: Opts = {};\n if (gridLine.style !== undefined) opts.style = gridLine.style;\n if (gridLine.size !== undefined) opts.size = gridLine.size;\n if (gridLine.color) opts.color = gridLine.color.hex;\n return opts;\n}\n\nfunction assignDefined(target: Opts, values: Opts): void {\n for (const [key, value] of Object.entries(values)) {\n if (value !== undefined) target[key] = value;\n }\n}\n","/**\n * PptxIR tables → PptxGenJS.\n *\n * Two things live here that are properties of *this backend* rather than of a\n * table:\n *\n * 1. **Units.** PptxGenJS's table path uses a different inch/EMU threshold from\n * the rest of its API (20 instead of 100) and does not run x/y/h through its\n * normal parser. Passing EMU directly sidesteps both: any real value is\n * above the threshold, so PptxGenJS uses it verbatim.\n * 2. **Rounded corners.** OOXML tables have no corner radius, and PptxGenJS\n * exposes none. The IR asks for one semantically; this module realises it by\n * drawing rounded rectangles behind the table and making the corner cells\n * transparent so they show through. That technique is not in the IR.\n */\n\nimport type PptxGenJS from 'pptxgenjs';\nimport type {\n PptxIrTableBorder,\n PptxIrTableCell,\n PptxIrTableElement,\n PptxIrTableFormatting,\n} from '../../ir/types';\nimport { emuToInches } from '../../ir/units';\n\ntype Opts = Record<string, unknown>;\n\nconst NO_BORDER = { type: 'none', pt: 0 } as const;\nconst NO_LINE = { type: 'none' } as const;\n\nexport function emitTable(\n slide: PptxGenJS.Slide,\n element: PptxIrTableElement,\n pptx: PptxGenJS\n): void {\n const rounded = roundedCornerPlan(element);\n // The IR always carries a resolved absolute origin, so the backdrop can\n // always be placed. The pre-IR pipeline drew it only when the author happened\n // to write x and y as plain numbers, which left a percentage-positioned\n // rounded table with square corners — see the recorded output differences.\n if (rounded) emitRoundedBackground(slide, element, rounded, pptx);\n\n const rows = element.rows.map((row, rowIndex) =>\n row.cells.map((cell, colIndex) =>\n emitCell(cell, {\n element,\n rounded,\n rowIndex,\n colIndex,\n columnCount: row.cells.length,\n })\n )\n );\n\n slide.addTable(rows as never, tableOpts(element, rounded) as never);\n}\n\n/* ------------------------------------------------------------------ *\n * Table-level options\n * ------------------------------------------------------------------ */\n\nfunction tableOpts(\n element: PptxIrTableElement,\n rounded: RoundedPlan | undefined\n): Opts {\n const opts: Opts = {\n // EMU passes through PptxGenJS's table path untouched — see the note above.\n x: element.transform.xEmu,\n y: element.transform.yEmu,\n };\n if (!element.transform.autoWidth) opts.w = element.transform.widthEmu;\n if (!element.transform.autoHeight) opts.h = element.transform.heightEmu;\n\n if (element.columnWidthsEmu.length > 0) {\n opts.colW = toInchList(element.columnWidthsEmu);\n }\n if (element.rowHeightsEmu.length > 0) {\n opts.rowH = toInchList(element.rowHeightsEmu);\n }\n\n // A rounded table draws its own outline through the background shapes, so\n // the table-level border is suppressed and the per-cell borders take over.\n if (element.border && !rounded) {\n opts.border = borderOpts(element.border);\n }\n if (element.fill) opts.fill = { color: element.fill.hex };\n\n Object.assign(opts, defaultsOpts(element.defaults));\n\n if (element.autoPage) opts.autoPage = true;\n if (element.autoPageRepeatHeader) {\n opts.autoPageRepeatHeader = true;\n opts.autoPageHeaderRows = 1;\n }\n\n if (rounded) {\n opts.w = rounded.widthEmu;\n opts.border = [\n NO_BORDER_TYPE,\n NO_BORDER_TYPE,\n NO_BORDER_TYPE,\n NO_BORDER_TYPE,\n ];\n }\n\n return opts;\n}\n\nconst NO_BORDER_TYPE = { type: 'none' } as const;\n\nfunction defaultsOpts(defaults: PptxIrTableFormatting): Opts {\n const opts: Opts = {\n fontSize: defaults.fontSize,\n fontFace: defaults.fontFamily,\n valign: defaults.verticalAlign,\n };\n if (defaults.bold !== undefined) opts.bold = defaults.bold;\n if (defaults.color) opts.color = defaults.color.hex;\n if (defaults.align) opts.align = defaults.align;\n if (defaults.insetPoints !== undefined) opts.margin = defaults.insetPoints;\n return opts;\n}\n\nfunction borderOpts(border: PptxIrTableBorder): Opts {\n const opts: Opts = { type: border.type };\n if (border.widthPoints !== undefined) opts.pt = border.widthPoints;\n if (border.color) opts.color = border.color.hex;\n return opts;\n}\n\nfunction toInchList(values: readonly number[]): number | number[] {\n const inches = values.map(emuToInches);\n return inches.length === 1 ? inches[0] : inches;\n}\n\n/* ------------------------------------------------------------------ *\n * Cells\n * ------------------------------------------------------------------ */\n\ninterface CellScope {\n element: PptxIrTableElement;\n rounded: RoundedPlan | undefined;\n rowIndex: number;\n colIndex: number;\n columnCount: number;\n}\n\nfunction emitCell(cell: PptxIrTableCell, scope: CellScope): Opts {\n const opts: Opts = {};\n const formatting = cell.formatting;\n\n if (formatting?.color) opts.color = formatting.color.hex;\n if (formatting?.fontSize !== undefined) opts.fontSize = formatting.fontSize;\n if (formatting?.fontFamily) opts.fontFace = formatting.fontFamily;\n if (formatting?.bold !== undefined) opts.bold = formatting.bold;\n if (formatting?.italic) opts.italic = true;\n if (formatting?.align) opts.align = formatting.align;\n if (formatting?.verticalAlign) opts.valign = formatting.verticalAlign;\n if (formatting?.insetPoints !== undefined) {\n opts.margin = formatting.insetPoints;\n }\n if (cell.colSpan !== undefined) opts.colspan = cell.colSpan;\n if (cell.rowSpan !== undefined) opts.rowspan = cell.rowSpan;\n\n if (scope.rounded) {\n applyRoundedCellStyling(opts, cell, scope, scope.rounded);\n } else if (cell.fill) {\n opts.fill = { color: cell.fill.hex };\n }\n\n return Object.keys(opts).length > 0\n ? { text: cell.text, options: opts }\n : { text: cell.text };\n}\n\n/* ------------------------------------------------------------------ *\n * Rounded corners\n * ------------------------------------------------------------------ */\n\ninterface RoundedPlan {\n radiusInches: number;\n bodyFill: string;\n headerFill: string;\n widthEmu: number;\n innerBorder: Opts;\n}\n\n/**\n * Work out whether a rounded table can be drawn, and with which colours.\n *\n * Needs at least a header row and a body row, and an absolute position: the\n * background shapes are placed at the table's own coordinates.\n */\nfunction roundedCornerPlan(\n element: PptxIrTableElement\n): RoundedPlan | undefined {\n if (element.cornerRadiusInches === undefined) return undefined;\n if (element.rows.length < 2) return undefined;\n\n const lastRow = element.rows[element.rows.length - 1];\n const bodyFill =\n element.fill?.hex ?? lastRow?.cells[0]?.fill?.hex ?? 'FFFFFF';\n const headerFill = element.rows[0]?.cells[0]?.fill?.hex ?? bodyFill;\n\n return {\n radiusInches: element.cornerRadiusInches,\n bodyFill,\n headerFill,\n widthEmu: roundedWidthEmu(element),\n innerBorder: element.border ? borderOpts(element.border) : { ...NO_BORDER },\n };\n}\n\n/**\n * Width the background shapes and the table must share.\n *\n * Derived from the column widths when they exist so the shapes line up with\n * the table exactly; otherwise the table's own width.\n */\nfunction roundedWidthEmu(element: PptxIrTableElement): number {\n // An explicit column list is summed as given — including a single-entry\n // list, which names one column rather than a width for every column. With no\n // list the table's own width applies, falling back to 5in when it has none.\n const columns = element.columnWidthsEmu;\n if (columns.length > 0) {\n return columns.reduce((sum, width) => sum + width, 0);\n }\n return element.transform.autoWidth\n ? Math.round(5 * 914400)\n : element.transform.widthEmu;\n}\n\n/**\n * Corner cells go transparent so the rounded shapes behind show through;\n * every other cell stays opaque so no seam appears between them.\n */\nfunction applyRoundedCellStyling(\n opts: Opts,\n cell: PptxIrTableCell,\n scope: CellScope,\n rounded: RoundedPlan\n): void {\n const isHeader = scope.rowIndex === 0;\n const isLastRow = scope.rowIndex === scope.element.rows.length - 1;\n const isCorner =\n (isHeader || isLastRow) &&\n (scope.colIndex === 0 || scope.colIndex === scope.columnCount - 1);\n\n if (!isCorner) {\n opts.fill = {\n color:\n cell.fill?.hex ?? (isHeader ? rounded.headerFill : rounded.bodyFill),\n };\n }\n opts.border = roundedCellBorders(scope, rounded);\n}\n\n/**\n * Per-cell borders for a rounded table: no outer edges (the shapes draw them)\n * and no seam between the header row and the body.\n */\nfunction roundedCellBorders(scope: CellScope, rounded: RoundedPlan): Opts[] {\n const { rowIndex, colIndex, columnCount, element } = scope;\n const isTop = rowIndex === 0;\n const isBottom = rowIndex === element.rows.length - 1;\n const isLeft = colIndex === 0;\n const isRight = colIndex === columnCount - 1;\n const inner = rounded.innerBorder;\n const none: Opts = { ...NO_BORDER };\n\n return [\n isTop || rowIndex === 1 ? none : inner,\n isRight ? none : inner,\n isBottom || rowIndex === 0 ? none : inner,\n isLeft ? none : inner,\n ];\n}\n\n/**\n * Draw the rounded background: a rounded header block with a flat patch over\n * its lower corners, and a rounded body block with a flat patch over its upper\n * corners, so only the outer four corners stay round.\n */\nfunction emitRoundedBackground(\n slide: PptxGenJS.Slide,\n element: PptxIrTableElement,\n rounded: RoundedPlan,\n pptx: PptxGenJS\n): void {\n const xInches = emuToInches(element.transform.xEmu);\n const yInches = emuToInches(element.transform.yEmu);\n const widthInches = emuToInches(rounded.widthEmu);\n\n const rowHeights = element.rowHeightsEmu;\n const headerInches =\n rowHeights.length > 0 ? emuToInches(rowHeights[0]) : 0.45;\n const totalInches =\n rowHeights.length > 1\n ? emuToInches(rowHeights.reduce((sum, h) => sum + h, 0))\n : rowHeights.length === 1\n ? emuToInches(rowHeights[0]) * element.rows.length\n : element.transform.autoHeight\n ? 2\n : emuToInches(element.transform.heightEmu);\n\n slide.addShape(pptx.ShapeType.roundRect, {\n x: xInches,\n y: yInches,\n w: widthInches,\n h: headerInches,\n fill: { color: rounded.headerFill },\n rectRadius: rounded.radiusInches,\n line: { ...NO_LINE },\n } as never);\n slide.addShape(pptx.ShapeType.rect, {\n x: xInches,\n y: yInches + headerInches - rounded.radiusInches,\n w: widthInches,\n h: rounded.radiusInches,\n fill: { color: rounded.headerFill },\n line: { ...NO_LINE },\n } as never);\n\n const bodyY = yInches + headerInches;\n slide.addShape(pptx.ShapeType.roundRect, {\n x: xInches,\n y: bodyY,\n w: widthInches,\n h: totalInches - headerInches,\n fill: { color: rounded.bodyFill },\n rectRadius: rounded.radiusInches,\n line: { ...NO_LINE },\n } as never);\n slide.addShape(pptx.ShapeType.rect, {\n x: xInches,\n y: bodyY,\n w: widthInches,\n h: rounded.radiusInches,\n fill: { color: rounded.bodyFill },\n line: { ...NO_LINE },\n } as never);\n}\n","/**\n * PptxIR → PptxGenJS calls.\n *\n * Each function here maps one IR node onto the option bag PptxGenJS expects.\n * They are deliberately small and free of policy: every cascade, default and\n * unit conversion already happened in the compiler, so this layer only\n * translates vocabulary.\n *\n * Unit note: the IR is in EMU, PptxGenJS takes inches. Dividing is exact\n * against the compiler's `Math.round(inches * 914400)` because PptxGenJS\n * applies the same rounding on the way in.\n */\n\nimport type PptxGenJS from 'pptxgenjs';\nimport { assertNever } from '@json-to-office/shared/rendering';\nimport type {\n PptxIrColor,\n PptxIrElement,\n PptxIrFill,\n PptxIrGeometry,\n PptxIrHyperlink,\n PptxIrImageElement,\n PptxIrLine,\n PptxIrResource,\n PptxIrShadow,\n PptxIrShapeElement,\n PptxIrTextBodyStyle,\n PptxIrTextBoxElement,\n PptxIrTextRun,\n PptxIrTransform,\n} from '../../ir/types';\nimport { emuToInches } from '../../ir/units';\nimport type { PipelineWarning } from '../../types';\nimport { W, warn } from '../../utils/warn';\nimport type { PendingFillSink } from './fills';\nimport { registerAdvancedFill } from './fills';\nimport { emitChart } from './chart';\nimport { emitTable } from './table';\n\ntype Opts = Record<string, unknown>;\n\n/** Resources by id, so an element's `resourceId` can be turned into a source. */\nexport type ResourceLookup = ReadonlyMap<string, PptxIrResource>;\n\nexport interface EmitContext {\n pptx: PptxGenJS;\n resources: ResourceLookup;\n /** Registry for fills PptxGenJS cannot express. Absent disables the splice. */\n pendingFills?: PendingFillSink;\n /** Sink for a shape this backend has no preset for. */\n warnings?: PipelineWarning[];\n}\n\n/* ------------------------------------------------------------------ *\n * Primitives\n * ------------------------------------------------------------------ */\n\nexport function transformOpts(transform: PptxIrTransform): Opts {\n const opts: Opts = {\n x: emuToInches(transform.xEmu),\n y: emuToInches(transform.yEmu),\n w: emuToInches(transform.widthEmu),\n h: emuToInches(transform.heightEmu),\n };\n if (transform.rotationDegrees !== undefined) {\n opts.rotate = transform.rotationDegrees;\n }\n if (transform.flipHorizontal) opts.flipH = true;\n if (transform.flipVertical) opts.flipV = true;\n return opts;\n}\n\n/** PptxGenJS wants bare hex; the IR already stores it that way. */\nexport function colorValue(color: PptxIrColor): string {\n return color.hex;\n}\n\nexport function lineOpts(line: PptxIrLine): Opts {\n const opts: Opts = {};\n if (line.color) opts.color = colorValue(line.color);\n if (line.widthPoints !== undefined) opts.width = line.widthPoints;\n if (line.dash) opts.dashType = line.dash;\n return opts;\n}\n\nexport function shadowOpts(shadow: PptxIrShadow): Opts {\n return {\n type: shadow.type,\n color: colorValue(shadow.color),\n blur: shadow.blurPoints,\n offset: shadow.offsetPoints,\n angle: shadow.angleDegrees,\n opacity: shadow.opacity,\n };\n}\n\nexport function hyperlinkOpts(link: PptxIrHyperlink): Opts {\n return link.kind === 'external'\n ? { url: link.url, tooltip: link.tooltip }\n : { slide: link.slideIndex, tooltip: link.tooltip };\n}\n\n/**\n * Apply a fill.\n *\n * Solid fills map directly. Gradients and patterns do not exist in the\n * PptxGenJS API, so they are registered for the post-generation splice and a\n * sentinel solid fill is written in their place — the workaround lives here,\n * never in the IR.\n */\nexport function applyFill(\n opts: Opts,\n fill: PptxIrFill,\n elementPath: string,\n ctx: EmitContext\n): void {\n switch (fill.kind) {\n case 'none':\n opts.fill = { type: 'none' };\n return;\n case 'solid': {\n const value: Opts = { color: colorValue(fill.color) };\n if (fill.color.transparency !== undefined) {\n value.transparency = fill.color.transparency;\n }\n opts.fill = value;\n return;\n }\n case 'gradient':\n case 'pattern':\n registerAdvancedFill(opts, fill, elementPath, ctx.pendingFills);\n return;\n case 'image':\n // Modelled in the IR; PptxGenJS has no shape image fill. Capability\n // checking rejects this before render, so reaching it is a bug.\n throw new Error(\n `PptxGenJS cannot apply an image fill (${elementPath}); this should have failed capability checking`\n );\n default:\n assertNever(fill, 'PptxIrFill');\n }\n}\n\n/* ------------------------------------------------------------------ *\n * Text\n * ------------------------------------------------------------------ */\n\nexport function textBodyOpts(style: PptxIrTextBodyStyle): Opts {\n const opts: Opts = { valign: style.verticalAlign };\n if (style.insetPoints !== undefined) {\n opts.margin = textBodyMargin(style.insetPoints);\n }\n if (style.align) opts.align = style.align;\n if (style.lineSpacingMultiple !== undefined) {\n opts.lineSpacingMultiple = style.lineSpacingMultiple;\n } else if (style.lineSpacingPoints !== undefined) {\n opts.lineSpacing = style.lineSpacingPoints;\n }\n if (style.spaceBeforePoints !== undefined) {\n opts.paraSpaceBefore = style.spaceBeforePoints;\n }\n if (style.spaceAfterPoints !== undefined) {\n opts.paraSpaceAfter = style.spaceAfterPoints;\n }\n if (style.bullet) opts.bullet = bulletOpt(style.bullet);\n if (style.autoFit) opts.isTextBox = true;\n return opts;\n}\n\n/**\n * A bullet in PptxGenJS's vocabulary.\n *\n * The backend reads three shapes and each has to be hit exactly:\n * - `false` is how it spells `<a:buNone/>`, and an object never reaches that\n * branch, so `type: 'none'` has to become the boolean;\n * - an object with `type: 'number'` becomes `<a:buAutoNum>`;\n * - a custom glyph goes through `characterCode`, a 4-digit hex code point —\n * PptxGenJS ignores `style` on a character bullet and writes no bullet at\n * all, so passing the glyph as `style` loses it silently.\n *\n * Anything else is the default glyph, which is what `true` asks for.\n */\nfunction bulletOpt(\n bullet: NonNullable<PptxIrTextBodyStyle['bullet']>\n): unknown {\n if (bullet.type === 'none') return false;\n if (bullet.type === 'number') {\n return {\n type: 'number',\n ...(bullet.style ? { style: bullet.style } : {}),\n ...(bullet.startAt !== undefined ? { startAt: bullet.startAt } : {}),\n };\n }\n if (bullet.style === undefined) return true;\n const characterCode = bmpCharacterCode(bullet.style);\n if (characterCode === undefined) {\n throw new Error(\n 'PptxGenJS cannot emit an astral or multi-code-point bullet glyph'\n );\n }\n return { characterCode };\n}\n\n/**\n * A glyph as the 4-digit hex code PptxGenJS validates against.\n *\n * Undefined for anything it would reject — an astral code point, or more than\n * one character. Capability preflight refuses those values before emission.\n */\nfunction bmpCharacterCode(glyph: string | undefined): string | undefined {\n if (glyph === undefined) return undefined;\n const points = [...glyph];\n if (points.length !== 1) return undefined;\n const code = points[0].codePointAt(0);\n if (code === undefined || code > 0xffff) return undefined;\n return code.toString(16).toUpperCase().padStart(4, '0');\n}\n\n/**\n * A text-body inset, in the order PptxGenJS's *text* path reads.\n *\n * The IR states `[top, right, bottom, left]`, which is what the authoring\n * schema documents and what PptxGenJS's table path reads. Its text path reads\n * the same four numbers as `[left, right, bottom, top]` — the two disagree\n * inside the library — so the tuple is reordered here rather than in the IR,\n * because it is a property of this backend and nothing else. A scalar is the\n * same on every side and passes through.\n */\nfunction textBodyMargin(\n inset: number | [number, number, number, number]\n): number | [number, number, number, number] {\n if (typeof inset === 'number') return inset;\n const [top, right, bottom, left] = inset;\n return [left, right, bottom, top];\n}\n\n/** Run-level options. Every value is already resolved; nothing cascades here. */\nexport function runOpts(run: PptxIrTextRun): Opts {\n const opts: Opts = {\n fontFace: run.fontFamily,\n fontSize: run.fontSize,\n color: colorValue(run.color),\n };\n if (run.bold !== undefined) opts.bold = run.bold;\n if (run.italic !== undefined) opts.italic = run.italic;\n if (run.strike !== undefined) opts.strike = run.strike;\n if (run.underline)\n opts.underline = run.underline.color\n ? { style: run.underline.style, color: colorValue(run.underline.color) }\n : { style: run.underline.style };\n if (run.superscript !== undefined) opts.superscript = run.superscript;\n if (run.subscript !== undefined) opts.subscript = run.subscript;\n if (run.characterSpacing !== undefined) {\n opts.charSpacing = run.characterSpacing;\n }\n if (run.language) opts.lang = run.language;\n if (run.breakAfter !== undefined) opts.breakLine = run.breakAfter;\n if (run.spaceBeforePoints !== undefined) {\n opts.paraSpaceBefore = run.spaceBeforePoints;\n }\n if (run.spaceAfterPoints !== undefined) {\n opts.paraSpaceAfter = run.spaceAfterPoints;\n }\n if (run.hyperlink) opts.hyperlink = hyperlinkOpts(run.hyperlink);\n return opts;\n}\n\n/**\n * Block-level options for a text body.\n *\n * These come from the body's own defaults, never from whichever run happens to\n * be first: PptxGenJS merges run options over block options, and it also uses\n * the block options for the trailing `endParaRPr`. Hoisting run 0's formatting\n * would leak it onto every later run that does not override it.\n */\nfunction bodyDefaultOpts(style: PptxIrTextBodyStyle): Opts {\n const defaults = style.defaults;\n const opts: Opts = {\n fontFace: defaults.fontFamily,\n fontSize: defaults.fontSize,\n color: colorValue(defaults.color),\n };\n if (defaults.bold !== undefined) opts.bold = defaults.bold;\n if (defaults.italic !== undefined) opts.italic = defaults.italic;\n if (defaults.language) opts.lang = defaults.language;\n return opts;\n}\n\nexport function emitTextBox(\n slide: PptxGenJS.Slide,\n element: PptxIrTextBoxElement,\n ctx: EmitContext\n): void {\n const opts: Opts = {\n ...transformOpts(element.transform),\n ...bodyDefaultOpts(element.style),\n ...textBodyOpts(element.style),\n };\n if (element.fill) applyFill(opts, element.fill, element.path, ctx);\n if (element.shadow) opts.shadow = shadowOpts(element.shadow);\n if (element.hyperlink) opts.hyperlink = hyperlinkOpts(element.hyperlink);\n if (element.altText) opts.altText = element.altText;\n\n emitRuns(slide, element.runs, opts);\n}\n\nfunction emitRuns(\n slide: PptxGenJS.Slide,\n runs: readonly PptxIrTextRun[],\n opts: Opts\n): void {\n if (runs.length === 1) {\n const [only] = runs;\n // A lone run's shared formatting is already hoisted into `opts` by\n // `bodyDefaultOpts`; anything run-specific still has to be applied.\n Object.assign(opts, runOpts(only));\n slide.addText(only.text, opts as never);\n return;\n }\n const segments = runs.map((run) => ({\n text: run.text,\n options: runOpts(run) as never,\n }));\n slide.addText(segments as never, opts as never);\n}\n\n/* ------------------------------------------------------------------ *\n * Shapes\n * ------------------------------------------------------------------ */\n\n/** Map an IR geometry name to a PptxGenJS `ShapeType` member. */\nexport function shapeType(\n geometry: PptxIrGeometry,\n pptx: PptxGenJS\n): unknown | undefined {\n const name = typeof geometry === 'string' ? geometry : geometry.custom;\n return (pptx.ShapeType as unknown as Record<string, unknown>)[name];\n}\n\nexport function emitShape(\n slide: PptxGenJS.Slide,\n element: PptxIrShapeElement,\n ctx: EmitContext\n): void {\n const type = shapeType(element.geometry, ctx.pptx);\n if (type === undefined) {\n // The IR carries any geometry name; only the backend knows which of them\n // it has a preset for. One unrecognised name costs that shape, not the\n // document.\n warn(\n ctx.warnings,\n W.UNKNOWN_SHAPE,\n `Unknown shape type: ${describeGeometry(element.geometry)}`,\n { component: 'shape' }\n );\n return;\n }\n\n const opts: Opts = { ...transformOpts(element.transform) };\n if (element.fill) applyFill(opts, element.fill, element.path, ctx);\n if (element.line) opts.line = lineOpts(element.line);\n if (element.shadow) opts.shadow = shadowOpts(element.shadow);\n if (element.cornerRadius !== undefined)\n opts.rectRadius = element.cornerRadius;\n if (element.angleRangeDegrees) opts.angleRange = element.angleRangeDegrees;\n if (element.hyperlink) opts.hyperlink = hyperlinkOpts(element.hyperlink);\n if (element.altText) opts.altText = element.altText;\n\n if (element.runs && element.runs.length > 0) {\n opts.shape = type;\n if (element.style) {\n Object.assign(opts, bodyDefaultOpts(element.style));\n Object.assign(opts, textBodyOpts(element.style));\n }\n emitRuns(slide, element.runs, opts);\n return;\n }\n\n slide.addShape(type as never, opts as never);\n}\n\nfunction describeGeometry(geometry: PptxIrGeometry): string {\n return typeof geometry === 'string' ? geometry : geometry.custom;\n}\n\n/* ------------------------------------------------------------------ *\n * Images\n * ------------------------------------------------------------------ */\n\n/**\n * Turn a resource into the `path`/`data` pair PptxGenJS expects.\n *\n * Inline bytes become a data URI; file and remote origins keep their location\n * so PptxGenJS streams them exactly as it did before the IR existed.\n */\nexport function imageSourceOpts(resource: PptxIrResource): Opts {\n switch (resource.origin.kind) {\n case 'inline': {\n const base64 = Buffer.from(resource.origin.bytes).toString('base64');\n const mediaType = resource.mediaType ?? 'image/png';\n return { data: `data:${mediaType};base64,${base64}` };\n }\n case 'file':\n return { path: resource.origin.path };\n case 'remote':\n return { path: resource.origin.url };\n default:\n return assertNever(resource.origin, 'PptxIrResourceOrigin');\n }\n}\n\nexport function emitImage(\n slide: PptxGenJS.Slide,\n element: PptxIrImageElement,\n ctx: EmitContext\n): void {\n const resource = ctx.resources.get(element.resourceId);\n if (!resource) {\n throw new Error(\n `Image ${element.path} references unknown resource \"${element.resourceId}\"`\n );\n }\n\n const opts: Opts = {\n ...imageSourceOpts(resource),\n ...transformOpts(element.transform),\n };\n // An extent the author did not state is left to the backend, which derives\n // it from the sizing box. Passing the IR's fallback would override that.\n if (element.transform.autoWidth) delete opts.w;\n if (element.transform.autoHeight) delete opts.h;\n if (element.sizing) {\n // EMU rather than inches: PptxGenJS reads these through the same parser as\n // positions, which treats anything at or above 100 as already-EMU, so\n // passing EMU is exact for any real box size.\n opts.sizing = {\n type: element.sizing.type,\n w: element.sizing.widthEmu,\n h: element.sizing.heightEmu,\n ...(element.sizing.xEmu !== undefined ? { x: element.sizing.xEmu } : {}),\n ...(element.sizing.yEmu !== undefined ? { y: element.sizing.yEmu } : {}),\n };\n }\n if (element.rounding) opts.rounding = true;\n if (element.shadow) opts.shadow = shadowOpts(element.shadow);\n if (element.hyperlink) opts.hyperlink = hyperlinkOpts(element.hyperlink);\n if (element.altText) opts.altText = element.altText;\n\n slide.addImage(opts as never);\n}\n\n/* ------------------------------------------------------------------ *\n * Dispatch\n * ------------------------------------------------------------------ */\n\nexport function emitElement(\n slide: PptxGenJS.Slide,\n element: PptxIrElement,\n ctx: EmitContext\n): void {\n switch (element.kind) {\n case 'textBox':\n emitTextBox(slide, element, ctx);\n return;\n case 'shape':\n emitShape(slide, element, ctx);\n return;\n case 'image':\n emitImage(slide, element, ctx);\n return;\n case 'table':\n emitTable(slide, element, ctx.pptx);\n return;\n case 'chart':\n emitChart(slide, element);\n return;\n case 'group':\n // Reachable only if capability checking let it through, which would be\n // a bug — never a silent drop.\n throw new Error(\n `The pptxgenjs renderer has no emitter for \"${element.kind}\" (${element.path})`\n );\n default:\n assertNever(element, 'PptxIrElement');\n }\n}\n","/**\n * Generic OOXML package finalization.\n *\n * Canonical chart identifiers, pinned core-metadata and ZIP timestamps, and a\n * stable zip encoding. Every one of those is a property of the package rather\n * than of the backend that produced it, so any renderer's output goes through\n * this and nothing here knows which one ran.\n *\n * Backend repairs — the sentinel gradient/pattern splice, the table-style\n * GUID, the SVG preview fix — live with the backend that needs them, in\n * `renderers/pptxgenjs/packaging.ts`. Both halves share one `JSZip` so the\n * package is still read once and written once.\n */\n\nimport JSZip from 'jszip';\n\n/** Stable default shared by package entries and OOXML core metadata. */\nexport const DEFAULT_GENERATED_AT = '2000-01-01T00:00:00.000Z';\n\n/** What a caller may say about how the package is stamped. */\nexport interface PresentationPackagingOptions {\n /** Normalize metadata and ZIP timestamps. Defaults to true. */\n deterministic?: boolean;\n /** Clock used when deterministic packaging is enabled. */\n generatedAt?: Date | string;\n}\n\nexport async function readPackage(buffer: Buffer): Promise<JSZip> {\n return JSZip.loadAsync(buffer);\n}\n\nexport async function writePackage(zip: JSZip): Promise<Buffer> {\n return generateZip(zip);\n}\n\nexport function resolveGeneratedAt(value?: Date | string): Date {\n const date =\n value === undefined ? new Date(DEFAULT_GENERATED_AT) : new Date(value);\n if (Number.isNaN(date.getTime())) {\n throw new Error(`Invalid generatedAt value: ${String(value)}`);\n }\n if (date.getUTCFullYear() < 1980) {\n throw new Error(\n 'generatedAt must be on or after 1980-01-01 for ZIP compatibility'\n );\n }\n return date;\n}\n\n/**\n * Finalize a package in place: canonical chart ids, then pinned timestamps.\n *\n * In place rather than buffer-in/buffer-out so an adapter that has already\n * opened the zip for its own repairs does not pay for a second pass.\n */\nexport async function finalizePackage(\n zip: JSZip,\n generatedAt: Date\n): Promise<void> {\n await canonicalizeChartIds(zip);\n await canonicalizePackage(zip, generatedAt);\n}\n\n/** Finalize a package a caller holds only as bytes. */\nexport async function finalizePackageBuffer(\n buffer: Buffer,\n options: { generatedAt?: Date | string } = {}\n): Promise<Buffer> {\n const zip = await readPackage(buffer);\n await finalizePackage(zip, resolveGeneratedAt(options.generatedAt));\n return writePackage(zip);\n}\n\nfunction replaceCoreTimestamp(\n xml: string,\n tag: 'created' | 'modified',\n value: string\n): string {\n const expression = new RegExp(\n `(<dcterms:${tag}\\\\b[^>]*>)[^<]*(</dcterms:${tag}>)`,\n 'g'\n );\n return xml.replace(expression, `$1${value}$2`);\n}\n\nconst EMBEDDED_OFFICE_PACKAGE = /\\.(?:docx|pptx|xlsx|xlsm)$/i;\n\nfunction remapChartReferences(\n value: string,\n chartIds: ReadonlyMap<number, number>\n): string {\n return value\n .replace(/chart(\\d+)\\.xml/g, (match, rawId: string) => {\n const id = chartIds.get(Number(rawId));\n return id === undefined ? match : `chart${id}.xml`;\n })\n .replace(\n /Microsoft_Excel_Worksheet(\\d+)\\.xlsx/g,\n (match, rawId: string) => {\n const id = chartIds.get(Number(rawId));\n return id === undefined ? match : `Microsoft_Excel_Worksheet${id}.xlsx`;\n }\n );\n}\n\nasync function canonicalizeChartIds(zip: JSZip): Promise<void> {\n const sourceIds = Object.keys(zip.files)\n .map((path) => path.match(/^ppt\\/charts\\/chart(\\d+)\\.xml$/)?.[1])\n .filter((value): value is string => value !== undefined)\n .map(Number)\n .sort((a, b) => a - b);\n const chartIds = new Map(sourceIds.map((id, index) => [id, index + 1]));\n if (chartIds.size === 0) return;\n\n // Rewrite relationship/content-type targets using one mapping pass so\n // overlapping IDs (2→1, 3→2) cannot cascade into each other.\n for (const [path, entry] of Object.entries(zip.files)) {\n if (entry.dir || (!path.endsWith('.xml') && !path.endsWith('.rels'))) {\n continue;\n }\n const xml = await entry.async('string');\n const remapped = remapChartReferences(xml, chartIds);\n if (remapped !== xml) zip.file(path, remapped);\n }\n\n const renames: Array<{\n from: string;\n to: string;\n data: Buffer;\n date: Date;\n }> = [];\n for (const [path, entry] of Object.entries(zip.files)) {\n if (entry.dir) continue;\n const remappedPath = remapChartReferences(path, chartIds);\n if (remappedPath === path) continue;\n renames.push({\n from: path,\n to: remappedPath,\n data: await entry.async('nodebuffer'),\n date: entry.date,\n });\n }\n\n // Remove every source before adding destinations to avoid overwriting a\n // source path that another chart still needs.\n for (const entry of renames) zip.remove(entry.from);\n for (const entry of renames) {\n zip.file(entry.to, entry.data, { date: entry.date });\n }\n}\n\nasync function generateZip(zip: JSZip): Promise<Buffer> {\n return (await zip.generateAsync({\n type: 'nodebuffer',\n compression: 'DEFLATE',\n compressionOptions: { level: 6 },\n platform: 'DOS',\n streamFiles: false,\n })) as Buffer;\n}\n\nasync function canonicalizePackage(\n zip: JSZip,\n generatedAt: Date,\n depth = 0\n): Promise<void> {\n const timestamp = generatedAt.toISOString().replace(/\\.\\d{3}Z$/, 'Z');\n const coreEntry = zip.file('docProps/core.xml');\n if (coreEntry) {\n let coreXml = await coreEntry.async('string');\n coreXml = replaceCoreTimestamp(coreXml, 'created', timestamp);\n coreXml = replaceCoreTimestamp(coreXml, 'modified', timestamp);\n zip.file('docProps/core.xml', coreXml);\n }\n\n // Native charts contain generated XLSX packages with their own volatile\n // core.xml and ZIP timestamps. Normalize those recursively as well, or an\n // otherwise-stable outer PPTX still changes bytes on every build.\n if (depth < 3) {\n for (const [path, entry] of Object.entries(zip.files)) {\n if (entry.dir || !EMBEDDED_OFFICE_PACKAGE.test(path)) continue;\n try {\n const nested = await JSZip.loadAsync(await entry.async('nodebuffer'));\n await canonicalizePackage(nested, generatedAt, depth + 1);\n zip.file(path, await generateZip(nested));\n } catch {\n // Opaque/encrypted user-provided packages cannot be normalized safely.\n }\n }\n }\n\n for (const entry of Object.values(zip.files)) {\n entry.date = generatedAt;\n }\n}\n","/**\n * Raster fallbacks for inline SVG pictures (PPTX)\n *\n * An SVG picture ships as two media parts: the SVG itself, referenced by\n * `<asvg:svgBlip>` inside the blip's `<a:extLst>`, plus a PNG preview\n * referenced by the `<a:blip r:embed>` that every consumer understands.\n * PptxGenJS builds that preview with a browser canvas, so under Node it\n * writes its hardcoded broken-image placeholder instead\n * (gitbrent/PptxGenJS#401) and every viewer without svgBlip support —\n * LibreOffice <= 7.x, Google Slides, Office < 2016 — draws a red X.\n *\n * This pass rasterizes each SVG part and overwrites its paired PNG. It is a\n * best-effort repair: any failure leaves the placeholder in place and reports\n * a warning, because a broken preview still beats a package that failed to\n * build.\n */\nimport path from 'node:path';\nimport type JSZip from 'jszip';\nimport type { PipelineWarning } from '../../types';\nimport { W, warn } from '../../utils/warn';\n\ntype ResvgModule = typeof import('@resvg/resvg-js');\ntype FitTo = { mode: 'width' | 'height'; value: number };\n\nconst EMU_PER_INCH = 914400;\n/** 3x of PowerPoint's 96 DPI baseline — ~288 DPI, sharp when projected. */\nconst RASTER_SCALE = 3;\nconst MAX_EDGE_PX = 4096;\nconst MIN_EDGE_PX = 16;\n/** Used when a picture carries no `<a:xfrm>` extent to size against. */\nconst DEFAULT_EDGE_PX = 1024;\n\nconst PART_PATTERNS = [\n /^ppt\\/slides\\/slide\\d+\\.xml$/,\n /^ppt\\/slideLayouts\\/[^/]+\\.xml$/,\n /^ppt\\/slideMasters\\/[^/]+\\.xml$/,\n];\n\nconst SVG_BLIP = /<asvg:svgBlip\\b[^>]*r:embed=\"([^\"]+)\"/g;\nconst BLIP = /<a:blip\\b[^>]*r:embed=\"([^\"]+)\"/g;\nconst EXTENT = /<a:ext\\s+cx=\"(\\d+)\"\\s+cy=\"(\\d+)\"/;\nconst RELATIONSHIP = /<Relationship\\b([^>]*)>/g;\n\ninterface WorkItem {\n svgPart: string;\n cx?: number;\n cy?: number;\n}\n\nlet resvgModule: Promise<ResvgModule> | undefined;\n\nfunction loadResvg(): Promise<ResvgModule> {\n resvgModule ??= import('@resvg/resvg-js');\n return resvgModule;\n}\n\n/** Map `Id` -> package-absolute part path for one part's sibling .rels file. */\nasync function readRelationships(\n zip: JSZip,\n partPath: string\n): Promise<Map<string, string>> {\n const dir = path.posix.dirname(partPath);\n const relsPath = `${dir}/_rels/${path.posix.basename(partPath)}.rels`;\n const targets = new Map<string, string>();\n const entry = zip.file(relsPath);\n if (!entry) return targets;\n\n const xml = await entry.async('string');\n for (const match of xml.matchAll(RELATIONSHIP)) {\n const attrs = match[1];\n if (/\\bTargetMode=\"External\"/.test(attrs)) continue;\n const id = /\\bId=\"([^\"]+)\"/.exec(attrs)?.[1];\n const target = /\\bTarget=\"([^\"]+)\"/.exec(attrs)?.[1];\n if (!id || !target) continue;\n targets.set(\n id,\n target.startsWith('/')\n ? target.slice(1)\n : path.posix.normalize(path.posix.join(dir, target))\n );\n }\n return targets;\n}\n\n/**\n * Collect the svg/png part pairs referenced by one slide-family part. The\n * preview rId is the `<a:blip r:embed>` immediately preceding the svgBlip —\n * the svgBlip lives inside that blip's own `<a:extLst>` — and the placed size\n * is the `<a:ext cx cy>` that follows it inside the same `<p:pic>`.\n */\nfunction collectWorkItems(\n xml: string,\n rels: ReadonlyMap<string, string>,\n items: Map<string, WorkItem>\n): void {\n const blips = [...xml.matchAll(BLIP)];\n\n for (const svgBlip of xml.matchAll(SVG_BLIP)) {\n const at = svgBlip.index ?? 0;\n const preview = blips.filter((blip) => (blip.index ?? 0) < at).pop();\n if (!preview) continue;\n\n const pngPart = rels.get(preview[1]);\n const svgPart = rels.get(svgBlip[1]);\n if (!pngPart || !svgPart) continue;\n\n const picEnd = xml.indexOf('</p:pic>', at);\n const extent = EXTENT.exec(picEnd === -1 ? '' : xml.slice(at, picEnd));\n const cx = extent ? Number(extent[1]) : undefined;\n const cy = extent ? Number(extent[2]) : undefined;\n\n // PptxGenJS can point two pictures at one preview part; size it for the\n // largest box it has to cover. The axes max independently on purpose:\n // resvg scales uniformly, so one bitmap covers every box that shares the\n // part only when its width clears the widest and its height the tallest.\n // Keeping whichever single box is largest by area undersizes the other.\n const existing = items.get(pngPart);\n items.set(pngPart, {\n svgPart,\n cx: Math.max(cx ?? 0, existing?.cx ?? 0) || undefined,\n cy: Math.max(cy ?? 0, existing?.cy ?? 0) || undefined,\n });\n }\n}\n\nfunction toPixels(emu: number): number {\n const px = Math.round((emu / EMU_PER_INCH) * 96 * RASTER_SCALE);\n return Math.min(MAX_EDGE_PX, Math.max(MIN_EDGE_PX, px));\n}\n\n/**\n * Pick the axis to scale by so the bitmap covers the placed box on both axes:\n * an SVG wider than its box has to be sized by height, anything else by width.\n */\nfunction resolveFitTo(\n intrinsicAspect: number,\n cx: number | undefined,\n cy: number | undefined\n): FitTo {\n if (!cx || !cy) return { mode: 'width', value: DEFAULT_EDGE_PX };\n\n const wide = intrinsicAspect > cx / cy;\n const mode = wide ? 'height' : 'width';\n let value = wide ? toPixels(cy) : toPixels(cx);\n\n const other = wide\n ? Math.round(value * intrinsicAspect)\n : Math.round(value / intrinsicAspect);\n const longest = Math.max(value, other);\n if (longest > MAX_EDGE_PX) {\n value = Math.max(MIN_EDGE_PX, Math.floor((value * MAX_EDGE_PX) / longest));\n }\n return { mode, value };\n}\n\n/**\n * Replace the broken-image placeholders PptxGenJS writes for inline SVG\n * pictures with real rasterizations of those SVGs. Never throws: a missing\n * native binding or an SVG resvg rejects degrades to a warning and leaves the\n * package as generated.\n *\n * @returns whether any part of the zip was rewritten.\n */\nexport async function repairSvgRasterFallbacks(\n zip: JSZip,\n warnings?: PipelineWarning[]\n): Promise<boolean> {\n const pending = new Map<string, WorkItem>();\n\n for (const [partPath, entry] of Object.entries(zip.files)) {\n if (entry.dir || !PART_PATTERNS.some((rule) => rule.test(partPath))) {\n continue;\n }\n const xml = await entry.async('string');\n if (!xml.includes('asvg:svgBlip')) continue;\n\n collectWorkItems(xml, await readRelationships(zip, partPath), pending);\n }\n\n if (pending.size === 0) return false;\n\n let Resvg: ResvgModule['Resvg'];\n try {\n ({ Resvg } = await loadResvg());\n } catch (error) {\n warn(\n warnings,\n W.IMAGE_SVG_RASTER_FAILED,\n `Could not load the SVG rasterizer, so inline SVG images keep PowerPoint's broken-image fallback: ${String(error)}`,\n { component: 'image' }\n );\n return false;\n }\n\n const rendered = new Map<string, Buffer>();\n let changed = false;\n\n for (const [pngPart, item] of pending) {\n try {\n // Repair only a preview that is really there: a dangling relationship\n // target would otherwise have this pass author a brand new media part.\n if (!zip.file(pngPart)) {\n throw new Error(`missing preview part ${pngPart}`);\n }\n const source = zip.file(item.svgPart);\n if (!source) throw new Error(`missing part ${item.svgPart}`);\n const svg = await source.async('string');\n\n const probe = new Resvg(svg);\n const fitTo = resolveFitTo(probe.width / probe.height, item.cx, item.cy);\n const key = `${fitTo.mode}:${fitTo.value}\\n${svg}`;\n\n let png = rendered.get(key);\n if (!png) {\n png = Buffer.from(new Resvg(svg, { fitTo }).render().asPng());\n rendered.set(key, png);\n }\n\n // Timestamps are normalized afterwards by canonicalizePackage.\n zip.file(pngPart, png);\n changed = true;\n } catch (error) {\n warn(\n warnings,\n W.IMAGE_SVG_RASTER_FAILED,\n `Could not rasterize ${item.svgPart}, so it keeps PowerPoint's broken-image fallback: ${String(error)}`,\n { component: 'image' }\n );\n }\n }\n\n return changed;\n}\n","/**\n * Packaging for PptxGenJS output.\n *\n * Everything here exists because of what PptxGenJS emits, and would be wrong\n * to apply to another backend's bytes:\n *\n * - **Gradient and pattern fills.** The library has no API for either, so the\n * emitter registers the fill XML against a sentinel shape name and this pass\n * splices it in, restoring a normal name on the way out.\n * - **The table style GUID.** PptxGenJS hard-codes Medium Style 2 Accent 1 on\n * every table, which paints banding and accent borders the author never\n * asked for. Swapping it for No Style No Grid leaves the explicit borders\n * the emitter already wrote.\n * - **SVG previews.** The library builds them with a browser canvas, so under\n * Node it writes a broken-image placeholder — see `svgRasterFallback.ts`.\n *\n * Deterministic timestamps, canonical chart ids and the zip encoding are not\n * repairs; they are properties of an OOXML package. Those live in\n * `core/finalizePackage.ts` and run on the same open zip, so the package is\n * still read once and written once — which is what the byte-stable corpus was\n * recorded against.\n */\n\nimport {\n finalizePackage,\n readPackage,\n resolveGeneratedAt,\n writePackage,\n} from '../../core/finalizePackage';\nimport { repairSvgRasterFallbacks } from './svgRasterFallback';\nimport type { PendingXmlFill, PipelineWarning } from '../../types';\n\n/** PptxGenJS hard-codes this on every table it writes. */\nconst MEDIUM_STYLE_2_ACCENT_1 = '{5C22544A-7EE6-4342-B048-85BDC9FD1C3A}';\nconst NO_STYLE_NO_GRID = '{2D5ABB26-0587-4C30-8999-92F81FD0307C}';\n\nconst SLIDE_PART = /^ppt\\/slides\\/slide\\d+\\.xml$/;\n\nexport interface PptxGenJsPackagingOptions {\n /**\n * Gradient/pattern fills registered during rendering. Each entry names a\n * shape (via its sentinel `cNvPr name`) whose `<a:solidFill>` is swapped for\n * the registered fill XML.\n */\n pendingFills?: readonly PendingXmlFill[];\n /** Normalize metadata and ZIP timestamps. Defaults to true. */\n deterministic?: boolean;\n /** Clock used when deterministic packaging is enabled. */\n generatedAt?: Date | string;\n /**\n * Sink for repairs that need to report, e.g. an SVG that cannot rasterize.\n * When omitted their failures go to `console.warn`.\n */\n warnings?: PipelineWarning[];\n}\n\n/**\n * Splice registered gradient/pattern fills into a slide XML string. For every\n * pending fill whose sentinel objectName appears in this slide, the first\n * `<a:solidFill>` inside that shape's `<p:sp>` (its shape fill — line and run\n * fills come later in the element) is replaced with the registered fill XML,\n * and the sentinel marker name is swapped for a normal shape name.\n */\nfunction applyPendingFills(\n xml: string,\n pendingFills: readonly PendingXmlFill[]\n): string {\n let out = xml;\n for (const [index, fill] of pendingFills.entries()) {\n const marker = `name=\"${fill.objectName}\"`;\n const markerIdx = out.indexOf(marker);\n if (markerIdx === -1) continue;\n\n const spEnd = out.indexOf('</p:sp>', markerIdx);\n const solidStart = out.indexOf('<a:solidFill>', markerIdx);\n const solidEndTag = '</a:solidFill>';\n const solidEnd = out.indexOf(solidEndTag, solidStart);\n if (\n solidStart !== -1 &&\n solidEnd !== -1 &&\n spEnd !== -1 &&\n solidStart < spEnd\n ) {\n out =\n out.slice(0, solidStart) +\n fill.xml +\n out.slice(solidEnd + solidEndTag.length);\n }\n\n // Restore a normal name attribute so the sentinel never ships.\n out =\n out.slice(0, markerIdx) +\n `name=\"Fill ${index + 1}\"` +\n out.slice(markerIdx + marker.length);\n }\n return out;\n}\n\n/**\n * Apply the backend repairs, then hand the same zip to generic finalization.\n *\n * Returns the input buffer untouched when nothing needed doing, which only\n * happens with `deterministic: false` — PptxGenJS stamps both `core.xml` and\n * its ZIP entries with the wall clock, so a deterministic build always\n * rewrites something.\n */\nexport async function packagePptxGenJsBuffer(\n buffer: Buffer,\n options: PptxGenJsPackagingOptions = {}\n): Promise<Buffer> {\n const zip = await readPackage(buffer);\n let changed = false;\n\n for (const [path, entry] of Object.entries(zip.files)) {\n if (!SLIDE_PART.test(path)) continue;\n let xml = await entry.async('string');\n let fileChanged = false;\n if (xml.includes(MEDIUM_STYLE_2_ACCENT_1)) {\n xml = xml.replaceAll(MEDIUM_STYLE_2_ACCENT_1, NO_STYLE_NO_GRID);\n fileChanged = true;\n }\n if (options.pendingFills?.length) {\n const withFills = applyPendingFills(xml, options.pendingFills);\n if (withFills !== xml) {\n xml = withFills;\n fileChanged = true;\n }\n }\n if (fileChanged) {\n zip.file(path, xml);\n changed = true;\n }\n }\n\n changed = (await repairSvgRasterFallbacks(zip, options.warnings)) || changed;\n\n if (options.deterministic !== false) {\n await finalizePackage(zip, resolveGeneratedAt(options.generatedAt));\n changed = true;\n }\n\n if (!changed) return buffer;\n\n return writePackage(zip);\n}\n","/**\n * The PptxGenJS renderer.\n *\n * This is the only place in `core-pptx` production code allowed to import\n * `pptxgenjs`. It consumes PptxIR and nothing else — no author JSON, no\n * `ProcessedPresentation`, no theme lookups.\n */\n\nimport PptxGenJS from 'pptxgenjs';\nimport { ALL_PPTX_FEATURES, type PptxFeature } from '../../ir/features';\nimport type {\n PptxIR,\n PptxIrBackground,\n PptxIrMaster,\n PptxIrResource,\n PptxIrSlide,\n} from '../../ir/types';\nimport { emuToInches } from '../../ir/units';\nimport type { PipelineWarning } from '../../types';\nimport type { PptxRenderOptions, PptxRenderer, PptxRendererId } from '../types';\nimport { emitElement, imageSourceOpts, type EmitContext } from './emit';\nimport type { PendingFillSink } from './fills';\nimport { packagePptxGenJsBuffer } from './packaging';\n\nexport const PPTXGENJS_RENDERER_ID: PptxRendererId = 'pptxgenjs';\n\n/**\n * Everything the PptxGenJS backend can express.\n *\n * The exclusions are real gaps, not omissions:\n * - `image-fills` — no shape image-fill API\n * - `transitions` — no transition API (and none in the pre-IR pipeline either)\n * - `groups` — no grouping API; groups are flattened upstream or rejected\n * - `complex-bullet-glyphs` — the API accepts only a four-digit BMP code\n */\nconst PPTXGENJS_CAPABILITIES: ReadonlySet<PptxFeature> = new Set(\n [...ALL_PPTX_FEATURES].filter(\n (feature) =>\n feature !== 'image-fills' &&\n feature !== 'transitions' &&\n feature !== 'groups' &&\n feature !== 'complex-bullet-glyphs'\n )\n);\n\nexport function createPptxGenJsRenderer(): PptxRenderer {\n return {\n id: PPTXGENJS_RENDERER_ID,\n format: 'pptx',\n capabilities: PPTXGENJS_CAPABILITIES,\n async render(ir: PptxIR, options?: PptxRenderOptions): Promise<Uint8Array> {\n const pendingFills: PendingFillSink = [];\n const pptx = buildPresentation(ir, pendingFills, options?.warnings);\n const raw = (await pptx.write({\n outputType: 'nodebuffer',\n })) as Buffer;\n const packaged = await packagePptxGenJsBuffer(raw, {\n pendingFills,\n deterministic: options?.deterministic,\n generatedAt: options?.generatedAt,\n warnings: options?.warnings,\n });\n return new Uint8Array(packaged);\n },\n };\n}\n\n/**\n * Build the PptxGenJS object graph for an IR document.\n *\n * Exported for tests: it is the interesting half of the adapter, and asserting\n * on the object graph is far cheaper than unzipping a package.\n */\nexport function buildPresentation(\n ir: PptxIR,\n pendingFills?: PendingFillSink,\n warnings?: PipelineWarning[]\n): PptxGenJS {\n const pptx = new PptxGenJS();\n\n if (ir.metadata.title) pptx.title = ir.metadata.title;\n if (ir.metadata.author) pptx.author = ir.metadata.author;\n if (ir.metadata.subject) pptx.subject = ir.metadata.subject;\n if (ir.metadata.company) pptx.company = ir.metadata.company;\n\n pptx.defineLayout({\n name: 'CUSTOM',\n width: emuToInches(ir.size.widthEmu),\n height: emuToInches(ir.size.heightEmu),\n });\n pptx.layout = 'CUSTOM';\n\n if (ir.rtl) pptx.rtlMode = true;\n\n pptx.theme = {\n headFontFace: ir.theme.headingFont,\n bodyFontFace: ir.theme.bodyFont,\n };\n\n const resources = new Map<string, PptxIrResource>(\n ir.resources.map((resource) => [resource.id, resource])\n );\n const ctx: EmitContext = { pptx, resources, pendingFills, warnings };\n\n for (const master of ir.masters) {\n pptx.defineSlideMaster(masterProps(master, resources) as never);\n }\n\n for (const slide of ir.slides) {\n emitSlide(pptx, slide, ctx);\n }\n\n return pptx;\n}\n\n/**\n * Master properties PptxGenJS understands.\n *\n * A master's fixed decoration is *not* passed as `objects`: the pipeline draws\n * template objects onto each slide instead, which is what the IR records, and\n * doing both would double them.\n */\nfunction masterProps(\n master: PptxIrMaster,\n resources: ReadonlyMap<string, PptxIrResource>\n): Record<string, unknown> {\n const props: Record<string, unknown> = { title: master.name };\n\n const background = backgroundProps(master.background, resources);\n if (background) props.background = background;\n if (master.margin !== undefined) props.margin = master.margin;\n\n if (master.slideNumber) {\n const slideNumber: Record<string, unknown> = {\n x: emuToInches(master.slideNumber.transform.xEmu),\n y: emuToInches(master.slideNumber.transform.yEmu),\n w: emuToInches(master.slideNumber.transform.widthEmu),\n h: emuToInches(master.slideNumber.transform.heightEmu),\n };\n if (master.slideNumber.color) {\n slideNumber.color = master.slideNumber.color.hex;\n }\n if (master.slideNumber.fontSize !== undefined) {\n slideNumber.fontSize = master.slideNumber.fontSize;\n }\n props.slideNumber = slideNumber;\n }\n\n return props;\n}\n\nfunction backgroundProps(\n background: PptxIrBackground | undefined,\n resources: ReadonlyMap<string, PptxIrResource>\n): Record<string, unknown> | undefined {\n if (!background) return undefined;\n if (background.kind === 'solid') return { color: background.color.hex };\n\n const resource = resources.get(background.resourceId);\n if (!resource) return undefined;\n return imageSourceOpts(resource);\n}\n\nfunction emitSlide(\n pptx: PptxGenJS,\n slideIr: PptxIrSlide,\n ctx: EmitContext\n): void {\n const slide = slideIr.masterName\n ? pptx.addSlide({ masterName: slideIr.masterName })\n : pptx.addSlide();\n\n const background = backgroundProps(slideIr.background, ctx.resources);\n if (background) slide.background = background as never;\n\n if (slideIr.hidden) slide.hidden = true;\n\n for (const element of slideIr.elements) {\n emitElement(slide, element, ctx);\n }\n\n if (slideIr.notes) slide.addNotes(slideIr.notes);\n}\n","/**\n * PptxIR → `@office-open/pptx` options.\n *\n * The mapping is unusually direct because the two models agree on units: EMU\n * for geometry, points for font sizes, degrees for angles, percent for gradient\n * stops. Bare numbers reach the backend in exactly those units — the\n * `UniversalMeasure` string form is never used here, because a value that has\n * already been resolved has no business being re-parsed.\n *\n * Backend gaps are handled by *not declaring the capability* in `index.ts`, so\n * anything this module cannot express has already been rejected before it is\n * called. Reaching a `throw` here is a bug, not a user error.\n */\n\nimport { assertNever } from '@json-to-office/shared/rendering';\nimport type {\n PptxIrBackground,\n PptxIrColor,\n PptxIrElement,\n PptxIrFill,\n PptxIrGeometry,\n PptxIrGroupElement,\n PptxIrHyperlink,\n PptxIrImageElement,\n PptxIrLine,\n PptxIrResource,\n PptxIrShadow,\n PptxIrShapeElement,\n PptxIrTableBorder,\n PptxIrTableElement,\n PptxIrTextBodyStyle,\n PptxIrTextBoxElement,\n PptxIrTextRun,\n PptxIrTransform,\n} from '../../ir/types';\n\ntype Opts = Record<string, unknown>;\n\nexport type ResourceLookup = ReadonlyMap<string, PptxIrResource>;\n\nexport interface OfficeOpenEmitContext {\n resources: ResourceLookup;\n /** Bytes for file and remote resources, fetched before rendering. */\n resourceBytes: ReadonlyMap<string, Uint8Array>;\n /**\n * Allocates the drawing id for the next element on the current slide.\n *\n * The backend numbers elements from a counter that lives for the life of the\n * process, so a second render of the same deck produces different ids and\n * different bytes. Numbering them here, per slide, makes a render depend only\n * on its input.\n */\n nextId: () => number;\n}\n\n/* ------------------------------------------------------------------ *\n * Primitives\n * ------------------------------------------------------------------ */\n\n/** Geometry: a bare `prst` name, which is what the backend interpolates. */\nfunction geometryName(geometry: PptxIrGeometry): string {\n return typeof geometry === 'string' ? geometry : geometry.custom;\n}\n\nfunction frame(transform: PptxIrTransform): Opts {\n return {\n x: transform.xEmu,\n y: transform.yEmu,\n width: transform.widthEmu,\n height: transform.heightEmu,\n };\n}\n\n/**\n * A colour.\n *\n * `FillOptions` accepts a bare hex string for the common opaque case; anything\n * with transparency needs the object form with an `alpha` transform.\n */\nfunction color(value: PptxIrColor): unknown {\n if (value.transparency === undefined) return value.hex;\n return {\n type: 'srgb',\n value: value.hex,\n transforms: { alpha: 100 - value.transparency },\n };\n}\n\n/**\n * OOXML `prst` pattern names → the backend's friendly names.\n *\n * `PresetPattern` spells `pct25` as `percent25`; the IR carries the OOXML name,\n * so the mapping happens here rather than in the IR.\n */\nconst PATTERN_NAMES: Readonly<Record<string, string>> = {\n pct5: 'percent5',\n pct10: 'percent10',\n pct20: 'percent20',\n pct25: 'percent25',\n pct30: 'percent30',\n pct40: 'percent40',\n pct50: 'percent50',\n pct60: 'percent60',\n pct70: 'percent70',\n pct75: 'percent75',\n pct80: 'percent80',\n pct90: 'percent90',\n horz: 'horizontal',\n vert: 'vertical',\n ltHorz: 'lightHorizontal',\n ltVert: 'lightVertical',\n dkHorz: 'darkHorizontal',\n dkVert: 'darkVertical',\n narHorz: 'narrowHorizontal',\n narVert: 'narrowVertical',\n cross: 'cross',\n diagCross: 'diagonalCross',\n upDiag: 'upwardDiagonal',\n dnDiag: 'downwardDiagonal',\n ltUpDiag: 'lightUpwardDiagonal',\n ltDnDiag: 'lightDownwardDiagonal',\n dkUpDiag: 'darkUpwardDiagonal',\n dkDnDiag: 'darkDownwardDiagonal',\n wdUpDiag: 'wideUpwardDiagonal',\n wdDnDiag: 'wideDownwardDiagonal',\n smGrid: 'smallGrid',\n lgGrid: 'largeGrid',\n dotGrid: 'dottedGrid',\n smCheck: 'smallCheckerBoard',\n lgCheck: 'largeCheckerBoard',\n trellis: 'trellis',\n divot: 'divot',\n shingle: 'shingle',\n weave: 'weave',\n plaid: 'plaid',\n sphere: 'sphere',\n zigZag: 'zigZag',\n wave: 'wave',\n};\n\nexport function fill(value: PptxIrFill, ctx: OfficeOpenEmitContext): unknown {\n switch (value.kind) {\n case 'none':\n return { type: 'none' };\n case 'solid':\n return { type: 'solid', color: color(value.color) };\n case 'gradient': {\n const stops = value.gradient.stops.map((stop) => ({\n position: stop.position,\n color: color(stop.color),\n }));\n return value.gradient.type === 'radial'\n ? { type: 'gradient', path: 'circle', stops }\n : { type: 'gradient', angle: value.gradient.angleDegrees, stops };\n }\n case 'pattern':\n return {\n type: 'pattern',\n pattern: PATTERN_NAMES[value.preset] ?? value.preset,\n foregroundColor: color(value.foreground),\n backgroundColor: color(value.background),\n };\n case 'image': {\n const bytes = ctx.resourceBytes.get(value.resourceId);\n const resource = ctx.resources.get(value.resourceId);\n if (!bytes || !resource) {\n throw new Error(\n `image fill references unresolved resource \"${value.resourceId}\"`\n );\n }\n return { type: 'blip', data: bytes, imageType: pictureType(resource) };\n }\n default:\n return assertNever(value, 'PptxIrFill');\n }\n}\n\nfunction outline(line: PptxIrLine): Opts {\n const opts: Opts = {};\n if (line.color) opts.fill = { type: 'solid', color: color(line.color) };\n // Outline width is EMU; the IR keeps stroke width in points.\n if (line.widthPoints !== undefined) {\n opts.width = Math.round(line.widthPoints * 12700);\n }\n if (line.dash) opts.dash = line.dash;\n return opts;\n}\n\nfunction effects(shadow: PptxIrShadow): Opts {\n return {\n outerShadow: {\n blurRadius: Math.round(shadow.blurPoints * 12700),\n distance: Math.round(shadow.offsetPoints * 12700),\n direction: shadow.angleDegrees,\n color: {\n type: 'srgb',\n value: shadow.color.hex,\n transforms: { alpha: Math.round(shadow.opacity * 100) },\n },\n },\n };\n}\n\nfunction hyperlink(link: PptxIrHyperlink): Opts {\n return link.kind === 'external'\n ? { url: link.url, ...(link.tooltip ? { tooltip: link.tooltip } : {}) }\n : {\n slide: link.slideIndex,\n ...(link.tooltip ? { tooltip: link.tooltip } : {}),\n };\n}\n\n/* ------------------------------------------------------------------ *\n * Text\n * ------------------------------------------------------------------ */\n\nconst ALIGNMENT: Readonly<Record<string, string>> = {\n left: 'left',\n center: 'center',\n right: 'right',\n justify: 'justify',\n};\n\nconst ANCHOR: Readonly<Record<string, string>> = {\n top: 't',\n middle: 'ctr',\n bottom: 'b',\n};\n\nfunction runProperties(run: PptxIrTextRun): Opts {\n const opts: Opts = {\n size: run.fontSize,\n font: run.fontFamily,\n fill: { type: 'solid', color: color(run.color) },\n };\n if (run.bold !== undefined) opts.bold = run.bold;\n if (run.italic !== undefined) opts.italic = run.italic;\n if (run.strike) opts.strike = 'single';\n if (run.underline) opts.underline = 'single';\n if (run.superscript) opts.baseline = 30;\n if (run.subscript) opts.baseline = -25;\n if (run.characterSpacing !== undefined) opts.spacing = run.characterSpacing;\n if (run.language) opts.lang = run.language;\n if (run.hyperlink) opts.hyperlink = hyperlink(run.hyperlink);\n return opts;\n}\n\n/**\n * Build a text body.\n *\n * `breakAfter` on a run starts a new paragraph, which is how the IR expresses a\n * hard break inside a body.\n */\nexport function textBody(\n runs: readonly PptxIrTextRun[],\n style: PptxIrTextBodyStyle | undefined\n): Opts {\n const paragraphs: Opts[] = [];\n let current: Opts[] = [];\n\n const flush = () => {\n paragraphs.push({\n ...(style ? { properties: paragraphProperties(style) } : {}),\n children: current,\n });\n current = [];\n };\n\n for (const run of runs) {\n current.push({ text: run.text, ...runProperties(run) });\n if (run.breakAfter) flush();\n }\n if (current.length > 0 || paragraphs.length === 0) flush();\n\n const body: Opts = { paragraphs };\n if (style) {\n body.anchor = ANCHOR[style.verticalAlign] ?? 't';\n if (style.autoFit) body.autoFit = 'shape';\n if (style.insetPoints !== undefined) {\n body.margins = insetMargins(style.insetPoints);\n }\n }\n return body;\n}\n\n/**\n * A body or cell inset, in the backend's per-side form.\n *\n * The four-value tuple is CSS-ordered — `[top, right, bottom, left]` — which is\n * what the authoring schema states and what the default backend reads. Naming\n * the sides here rather than positionally is what keeps the two adapters\n * agreeing on which edge a value belongs to.\n */\nfunction insetMargins(inset: number | [number, number, number, number]): Opts {\n const toEmu = (points: number) => Math.round(points * 12700);\n if (typeof inset === 'number') {\n const value = toEmu(inset);\n return { left: value, top: value, right: value, bottom: value };\n }\n const [top, right, bottom, left] = inset;\n return {\n left: toEmu(left),\n top: toEmu(top),\n right: toEmu(right),\n bottom: toEmu(bottom),\n };\n}\n\nfunction paragraphProperties(style: PptxIrTextBodyStyle): Opts {\n const opts: Opts = {};\n if (style.align) opts.alignment = ALIGNMENT[style.align] ?? style.align;\n if (style.lineSpacingMultiple !== undefined) {\n opts.lineSpacingPercent = style.lineSpacingMultiple * 100;\n } else if (style.lineSpacingPoints !== undefined) {\n opts.lineSpacingPoints = style.lineSpacingPoints;\n }\n if (style.spaceBeforePoints !== undefined) {\n opts.spaceBefore = style.spaceBeforePoints;\n }\n if (style.spaceAfterPoints !== undefined) {\n opts.spaceAfter = style.spaceAfterPoints;\n }\n if (style.bullet) opts.bullet = bulletOption(style.bullet);\n return opts;\n}\n\n/**\n * A bullet in the backend's vocabulary.\n *\n * The discriminants are the backend's own — `char`, `autoNum`, `none` — and it\n * writes nothing at all for a value it does not recognise, so a near-miss here\n * is a silent loss rather than a type error.\n */\nfunction bulletOption(\n bullet: NonNullable<PptxIrTextBodyStyle['bullet']>\n): Opts {\n if (bullet.type === 'none') return { type: 'none' };\n if (bullet.type === 'number') {\n return {\n type: 'autoNum',\n ...(bullet.style ? { format: bullet.style } : {}),\n ...(bullet.startAt !== undefined ? { startAt: bullet.startAt } : {}),\n };\n }\n return { type: 'char', char: bullet.style ?? '•' };\n}\n\n/* ------------------------------------------------------------------ *\n * Elements\n * ------------------------------------------------------------------ */\n\nfunction textBoxChild(\n element: PptxIrTextBoxElement,\n ctx: OfficeOpenEmitContext\n): Opts {\n // A shape cannot carry a link here, so a body-level link is pushed onto the\n // runs it covers — which is what the link means anyway.\n const runs = element.hyperlink\n ? element.runs.map((run) => ({ ...run, hyperlink: element.hyperlink }))\n : element.runs;\n\n const shape: Opts = {\n id: ctx.nextId(),\n ...frame(element.transform),\n geometry: 'rect',\n textBody: textBody(runs, element.style),\n };\n if (element.fill) shape.fill = fill(element.fill, ctx);\n else shape.fill = { type: 'none' };\n if (element.line) shape.outline = outline(element.line);\n if (element.shadow) shape.effects = effects(element.shadow);\n if (element.transform.rotationDegrees !== undefined) {\n shape.rotation = element.transform.rotationDegrees;\n }\n if (element.altText) shape.description = element.altText;\n return { shape };\n}\n\nfunction shapeChild(\n element: PptxIrShapeElement,\n ctx: OfficeOpenEmitContext\n): Opts {\n const shape: Opts = {\n id: ctx.nextId(),\n ...frame(element.transform),\n geometry: geometryName(element.geometry),\n };\n if (element.fill) shape.fill = fill(element.fill, ctx);\n if (element.line) shape.outline = outline(element.line);\n if (element.shadow) shape.effects = effects(element.shadow);\n if (element.transform.rotationDegrees !== undefined) {\n shape.rotation = element.transform.rotationDegrees;\n }\n if (element.transform.flipHorizontal) shape.flipHorizontal = true;\n if (element.runs && element.runs.length > 0) {\n shape.textBody = textBody(element.runs, element.style);\n }\n if (element.altText) shape.description = element.altText;\n return { shape };\n}\n\n/** Media type → the backend's picture `type` discriminator. */\nfunction pictureType(resource: PptxIrResource): string {\n switch (resource.mediaType) {\n case 'image/jpeg':\n return 'jpg';\n case 'image/gif':\n return 'gif';\n case 'image/bmp':\n return 'bmp';\n case 'image/png':\n return 'png';\n default:\n // Guessing would label an SVG — or anything else — as a PNG and ship a\n // broken image. Capability checking rejects the types this backend\n // cannot take, so an unknown one here means the media type could not be\n // determined at all.\n throw new Error(\n `cannot determine the picture type for resource \"${resource.id}\"` +\n (resource.mediaType ? ` (media type ${resource.mediaType})` : '')\n );\n }\n}\n\nfunction pictureChild(\n element: PptxIrImageElement,\n ctx: OfficeOpenEmitContext\n): Opts {\n const resource = ctx.resources.get(element.resourceId);\n const bytes = ctx.resourceBytes.get(element.resourceId);\n if (!resource || !bytes) {\n throw new Error(\n `image ${element.path} references unresolved resource \"${element.resourceId}\"`\n );\n }\n const picture: Opts = {\n id: ctx.nextId(),\n ...frame(element.transform),\n data: bytes,\n type: pictureType(resource),\n };\n if (element.shadow) picture.effects = effects(element.shadow);\n if (element.altText) picture.description = element.altText;\n return { picture };\n}\n\n/**\n * A table.\n *\n * Cells carry `children` (paragraphs), not a text body, and cell formatting is\n * flattened onto the single run each cell holds — the authoring surface gives a\n * cell one string, so one run is the whole of it.\n *\n * Table-level border, fill and inset are cell properties here. The backend's\n * own `TableOptions.borders` distributes only to the *edge* cells, which is a\n * frame rather than the grid the IR describes, and it has no table-level fill\n * at all — so both are pushed onto every cell that does not override them,\n * which is the same thing the default backend's table options mean.\n *\n * Merged cells, rounded corners and pagination are deliberately absent from\n * this adapter's capabilities: the backend expresses a merge as\n * `restart`/`continue` markers on the covered cells whereas the IR carries span\n * counts, OOXML has no table corner radius, and nothing here can flow a table\n * onto a second slide.\n */\nfunction tableChild(\n element: PptxIrTableElement,\n ctx: OfficeOpenEmitContext\n): Opts {\n const columnCount = Math.max(\n ...element.rows.map((row) => row.cells.length),\n 1\n );\n const columnWidths =\n element.columnWidthsEmu.length === columnCount\n ? [...element.columnWidthsEmu]\n : evenColumns(element, columnCount);\n\n const rows = element.rows.map((row, rowIndex) => {\n const out: Opts = {\n cells: row.cells.map((cell) => tableCell(cell, element)),\n };\n const height = element.rowHeightsEmu[rowIndex];\n if (height !== undefined) out.height = height;\n return out;\n });\n\n return {\n table: {\n id: ctx.nextId(),\n ...frame(element.transform),\n columnWidths,\n rows,\n },\n };\n}\n\nfunction tableCell(\n cell: PptxIrTableElement['rows'][number]['cells'][number],\n element: PptxIrTableElement\n): Opts {\n const formatting = cell.formatting;\n const defaults = element.defaults;\n\n const runProps: Opts = {\n size: formatting?.fontSize ?? defaults.fontSize,\n font: formatting?.fontFamily ?? defaults.fontFamily,\n };\n const cellColor = formatting?.color ?? defaults.color;\n if (cellColor) runProps.fill = { type: 'solid', color: color(cellColor) };\n const bold = formatting?.bold ?? defaults.bold;\n if (bold !== undefined) runProps.bold = bold;\n if (formatting?.italic !== undefined) runProps.italic = formatting.italic;\n\n const align = formatting?.align ?? defaults.align;\n const paragraph: Opts = {\n children: [{ text: cell.text, ...runProps }],\n };\n if (align) {\n paragraph.properties = { alignment: ALIGNMENT[align] ?? align };\n }\n\n const out: Opts = {\n children: [paragraph],\n verticalAlign: ANCHOR[formatting?.verticalAlign ?? defaults.verticalAlign],\n };\n\n // Cell first, table second — the table's value is the default a cell may\n // override, exactly as `tblPr` layers under `tcPr`.\n const fill = cell.fill ?? element.fill;\n if (fill) out.fill = { type: 'solid', color: color(fill) };\n\n // No cell inset. `TableCellOptions.margins` writes `lIns`/`tIns` onto the\n // cell's own `a:bodyPr`, and a reader takes a cell's padding from\n // `a:tcPr/@marL` — a LibreOffice render moves not one point for a 40pt\n // margin written that way. `table-insets` is therefore not declared, and a\n // table with one is refused before any of this runs.\n\n const borders = cellBorders(cell, element);\n if (borders) out.borders = borders;\n\n return out;\n}\n\n/** OOXML dash names for the IR's border vocabulary. `none` draws nothing. */\nconst BORDER_DASH: Record<string, string | undefined> = {\n solid: 'solid',\n dash: 'dash',\n dot: 'sysDot',\n};\n\n/**\n * A cell's four edges.\n *\n * Per-side borders win where the IR carries them; otherwise the table's uniform\n * border applies to every edge of every cell, which is what \"uniform\" means and\n * what the default backend draws.\n */\nfunction cellBorders(\n cell: PptxIrTableElement['rows'][number]['cells'][number],\n element: PptxIrTableElement\n): Opts | undefined {\n if (cell.borders) {\n const [top, right, bottom, left] = cell.borders;\n const out: Opts = {};\n if (top.type !== 'none') out.top = borderLine(top);\n if (right.type !== 'none') out.right = borderLine(right);\n if (bottom.type !== 'none') out.bottom = borderLine(bottom);\n if (left.type !== 'none') out.left = borderLine(left);\n return Object.keys(out).length > 0 ? out : undefined;\n }\n\n const border = element.border;\n if (!border || border.type === 'none') return undefined;\n const line = borderLine(border);\n return { top: line, right: line, bottom: line, left: line };\n}\n\nfunction borderLine(border: PptxIrTableBorder): Opts {\n const dashStyle = BORDER_DASH[border.type];\n return {\n // Points → EMU: a bare number is EMU to this backend, and a border stated\n // in points would otherwise be drawn 12,700 times too thin.\n ...(border.widthPoints !== undefined\n ? { width: Math.round(border.widthPoints * 12700) }\n : {}),\n ...(border.color ? { color: color(border.color) } : {}),\n ...(dashStyle ? { dashStyle } : {}),\n };\n}\n\n/** Even column widths when the IR did not carry a matching set. */\nfunction evenColumns(\n element: PptxIrTableElement,\n columnCount: number\n): number[] {\n const each = Math.floor(element.transform.widthEmu / columnCount);\n return Array.from({ length: columnCount }, () => each);\n}\n\nfunction groupChild(\n element: PptxIrGroupElement,\n ctx: OfficeOpenEmitContext\n): Opts {\n const group: Opts = {\n id: ctx.nextId(),\n ...frame(element.transform),\n childOffset: { x: element.transform.xEmu, y: element.transform.yEmu },\n childExtents: {\n width: element.transform.widthEmu,\n height: element.transform.heightEmu,\n },\n children: element.children.map((child) => slideChild(child, ctx)),\n };\n if (element.transform.rotationDegrees !== undefined) {\n group.rotation = element.transform.rotationDegrees;\n }\n return { group };\n}\n\nexport function slideChild(\n element: PptxIrElement,\n ctx: OfficeOpenEmitContext\n): Opts {\n switch (element.kind) {\n case 'textBox':\n return textBoxChild(element, ctx);\n case 'shape':\n return shapeChild(element, ctx);\n case 'image':\n return pictureChild(element, ctx);\n case 'table':\n return tableChild(element, ctx);\n case 'group':\n return groupChild(element, ctx);\n case 'chart':\n // `charts` is not in this adapter's capability set — see index.ts.\n throw new Error(\n `the office-open renderer does not emit charts (${element.path})`\n );\n default:\n return assertNever(element, 'PptxIrElement');\n }\n}\n\nexport function background(\n value: PptxIrBackground,\n ctx: OfficeOpenEmitContext\n): Opts {\n if (value.kind === 'solid') {\n return { fill: { type: 'solid', color: color(value.color) } };\n }\n return { fill: fill({ kind: 'image', resourceId: value.resourceId }, ctx) };\n}\n","/**\n * The experimental `@office-open/pptx` renderer.\n *\n * Selecting it is explicit and opt-in; `pptxgenjs` stays the default. The\n * backend is an optional peer dependency, resolved at call time so a missing\n * package surfaces as an install hint rather than a module-resolution failure.\n *\n * The capability set below is deliberately narrow. A feature is listed only\n * when it has been proven against the real package, never from its README, and\n * a gap in the backend is expressed by *omitting* the capability — which makes\n * the compiler reject the document before any bytes exist, instead of shipping\n * a deck with content quietly missing.\n */\n\nimport { readFile } from 'node:fs/promises';\nimport { finalizePackageBuffer } from '../../core/finalizePackage';\nimport { ALL_PPTX_FEATURES, type PptxFeature } from '../../ir/features';\nimport type { PptxIR, PptxIrResource } from '../../ir/types';\nimport type { PptxRenderOptions, PptxRenderer, PptxRendererId } from '../types';\nimport { background, slideChild, type OfficeOpenEmitContext } from './emit';\n\nexport const OFFICE_OPEN_PPTX_RENDERER_ID: PptxRendererId = 'office-open';\n\n/**\n * Module specifier held in a variable so TypeScript does not resolve the\n * optional dependency at build time and the failure lands at selection time.\n */\nconst OFFICE_OPEN_PPTX = '@office-open/pptx';\n\n/**\n * What this adapter does *not* declare, and why. Each is a verified gap, not\n * an unfinished mapping:\n *\n * - `svg` — `PictureOptions.type` excludes SVG and no code path creates an SVG\n * media entry, so an SVG would ship as a broken image.\n * - `charts` — chart XML is written without the embedded workbook, so the\n * chart renders but \"Edit Data\" fails. A chart you cannot edit is not the\n * chart that was asked for.\n * - `image-transform` — `PictureOptions` carries neither `rotation` nor a flip,\n * so any transform on a picture would be silently discarded.\n * - `image-crop`, `image-rounding` — `PictureOptions` is `{data, type}` plus a\n * frame and effects: no source rectangle, no geometry. A cropped picture\n * would be drawn whole into the frame and a circular one would come out\n * rectangular, neither with anything to show for it.\n * - `flip-vertical` — no pptx option type carries it, on any element.\n * - `element-hyperlinks` — `NonVisualDrawingPropertiesOptions` is\n * `{name, description, title, hidden}`: a shape or picture cannot carry a\n * link. Only runs can, which is why `text-hyperlinks` *is* declared and is\n * realised by putting the link on the runs inside the body.\n * - `masters`, `placeholders` — layout and master generation are supported by\n * the backend but not yet mapped here, and an unmapped master would lose\n * every template object.\n * - `table-merged-cells` — the backend marks merges as `restart`/`continue` on\n * the covered cells while the IR carries span counts; the translation is\n * real work and is not yet proven by a test.\n * - `table-rounded-corners` — OOXML tables have no corner radius. The default\n * backend fakes one with shapes drawn behind the table; that technique is\n * not in the IR and is not reproduced here.\n * - `table-auto-page` — nothing in this backend flows a table onto a second\n * slide, so an over-long table would run off the bottom of the first.\n * - `table-insets` — `TableCellOptions.margins` writes the insets onto the\n * cell's own `a:bodyPr`, and a reader takes a cell's padding from\n * `a:tcPr/@marL`: rendering the same table with a 0pt and a 40pt margin puts\n * the text in exactly the same place.\n * - `image-fills` on a shape are supported and declared; the resource bytes are\n * fetched before rendering.\n *\n * Table border and fill *are* declared: the backend has no table-level form of\n * either, but both are cell properties there and the adapter pushes them onto\n * every cell — see `tableChild` in `emit.ts`.\n */\nconst UNSUPPORTED: ReadonlySet<PptxFeature> = new Set<PptxFeature>([\n 'svg',\n 'charts',\n 'image-transform',\n 'image-crop',\n 'image-rounding',\n 'flip-vertical',\n 'element-hyperlinks',\n 'masters',\n 'placeholders',\n 'table-merged-cells',\n 'table-rounded-corners',\n 'table-auto-page',\n 'table-insets',\n]);\n\nconst OFFICE_OPEN_CAPABILITIES: ReadonlySet<PptxFeature> = new Set(\n [...ALL_PPTX_FEATURES].filter((feature) => !UNSUPPORTED.has(feature))\n);\n\ninterface OfficeOpenBackend {\n generatePresentation: (\n options: Record<string, unknown>,\n packerOptions?: { type?: string }\n ) => Promise<Uint8Array>;\n}\n\nexport async function createOfficeOpenPptxRenderer(): Promise<PptxRenderer> {\n // Throws `Cannot find package '@office-open/pptx'` when the optional\n // dependency is absent; the registry rewrites that into an install hint.\n const backend = (await import(\n /* @vite-ignore */ OFFICE_OPEN_PPTX\n )) as unknown as OfficeOpenBackend;\n\n if (typeof backend.generatePresentation !== 'function') {\n throw new Error(\n `${OFFICE_OPEN_PPTX} does not export generatePresentation(); the installed version is not compatible with this adapter.`\n );\n }\n\n return {\n id: OFFICE_OPEN_PPTX_RENDERER_ID,\n format: 'pptx',\n capabilities: OFFICE_OPEN_CAPABILITIES,\n async render(ir: PptxIR, options?: PptxRenderOptions): Promise<Uint8Array> {\n const presentation = await buildPresentationOptions(ir);\n const bytes = await backend.generatePresentation(presentation, {\n type: 'uint8array',\n });\n const raw = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);\n\n if (options?.deterministic === false) return raw;\n // Generic package finalization. The backend stamps core metadata and ZIP\n // entries with the wall clock, so the same deck rendered twice differs.\n // Pinning those is a property of an OOXML package rather than of this\n // backend, which is why the same pass runs over the default backend's\n // output too.\n return new Uint8Array(\n await finalizePackageBuffer(Buffer.from(raw), {\n generatedAt: options?.generatedAt,\n })\n );\n },\n };\n}\n\n/**\n * Build the backend's document object for an IR presentation.\n *\n * Exported for tests: asserting on this object is far cheaper, and far more\n * legible, than unzipping a package.\n */\nexport async function buildPresentationOptions(\n ir: PptxIR\n): Promise<Record<string, unknown>> {\n // Drawing ids restart at 2 on each slide — 1 is the slide's own group — so\n // they depend on position in the deck and nothing else.\n let nextDrawingId = 2;\n const ctx: OfficeOpenEmitContext = {\n resources: new Map(ir.resources.map((r) => [r.id, r])),\n resourceBytes: await loadResourceBytes(ir.resources),\n nextId: () => nextDrawingId++,\n };\n\n const presentation: Record<string, unknown> = {\n size: { width: ir.size.widthEmu, height: ir.size.heightEmu },\n slides: ir.slides.map((slide) => {\n nextDrawingId = 2;\n const out: Record<string, unknown> = {\n children: slide.elements.map((element) => slideChild(element, ctx)),\n };\n if (slide.background) {\n out.background = background(slide.background, ctx);\n }\n if (slide.notes) out.notes = slide.notes;\n if (slide.hidden) out.hidden = true;\n if (slide.transition) {\n out.transition = {\n type: slide.transition.type,\n ...(slide.transition.speed ? { speed: slide.transition.speed } : {}),\n };\n }\n return out;\n }),\n };\n\n if (ir.rtl) presentation.rtl = true;\n if (ir.metadata.title) presentation.title = ir.metadata.title;\n if (ir.metadata.author) presentation.creator = ir.metadata.author;\n if (ir.metadata.subject) presentation.subject = ir.metadata.subject;\n // `company` is an *extended* property — `docProps/app.xml`, not `core.xml` —\n // which is why it is not a sibling of the three above (#262).\n if (ir.metadata.company) {\n presentation.appProperties = { company: ir.metadata.company };\n }\n\n const theme = themeOptions(ir);\n if (theme) {\n // A theme belongs to a master, and the backend generates a default master\n // when none is declared. Declaring one here is what gives the deck a\n // `theme1.xml` carrying the authored fonts and palette rather than\n // PowerPoint's Office defaults (#258).\n presentation.masters = [{ name: ir.theme.name || 'Default', theme }];\n }\n\n return presentation;\n}\n\n/**\n * The authored theme, as the backend's `ThemeOptions`.\n *\n * Only what survives IR theme resolution: the major/minor font faces, which\n * are set on the presentation rather than on any element, and the resolved\n * palette. Element colours are already literal hex by this point, so the\n * scheme is not what draws the deck — it is what PowerPoint offers when\n * someone edits it, and what newly inserted content picks up.\n */\nfunction themeOptions(ir: PptxIR): Record<string, unknown> | undefined {\n const { headingFont, bodyFont, palette, name } = ir.theme;\n const colorScheme = colorSchemeOptions(palette);\n if (!headingFont && !bodyFont && !colorScheme) return undefined;\n\n return {\n ...(name ? { name } : {}),\n fontScheme: {\n ...(name ? { name } : {}),\n ...(headingFont\n ? { majorFont: { latin: { typeface: headingFont } } }\n : {}),\n ...(bodyFont ? { minorFont: { latin: { typeface: bodyFont } } } : {}),\n },\n ...(colorScheme ? { colorScheme } : {}),\n };\n}\n\n/**\n * OOXML scheme slot ← the IR palette's project-owned slot.\n *\n * `PptxIrTheme.palette` is keyed by the project's own vocabulary, so an adapter\n * that writes a real `<a:clrScheme>` has to know which of those names each\n * OOXML slot holds. The pairing is the one the authoring surface already\n * accepts as aliases — see `SEMANTIC_TO_THEME_KEY` in `utils/color.ts`, which\n * resolves `accent1`, `tx1` and friends against the same slots.\n *\n * A palette entry with no OOXML counterpart is left out rather than invented\n * into a spare accent.\n */\nconst SCHEME_SLOTS: ReadonlyArray<readonly [string, string]> = [\n ['dark1', 'text'],\n ['light1', 'background'],\n ['dark2', 'text2'],\n ['light2', 'background2'],\n ['accent1', 'primary'],\n ['accent2', 'secondary'],\n ['accent3', 'accent'],\n ['accent4', 'accent4'],\n ['accent5', 'accent5'],\n ['accent6', 'accent6'],\n];\n\nfunction colorSchemeOptions(\n palette: Readonly<Record<string, string>>\n): Record<string, string> | undefined {\n const scheme: Record<string, string> = {};\n for (const [slot, key] of SCHEME_SLOTS) {\n const value = palette[key];\n if (value) scheme[slot] = value;\n }\n return Object.keys(scheme).length > 0 ? scheme : undefined;\n}\n\n/**\n * Read the bytes for every resource.\n *\n * The backend embeds media by value, so file and remote resources — which the\n * IR deliberately keeps as locations, so a large deck is not held in memory by\n * the default path — are materialised here, in the adapter that needs them.\n */\nasync function loadResourceBytes(\n resources: readonly PptxIrResource[]\n): Promise<Map<string, Uint8Array>> {\n const entries = await Promise.all(\n resources.map(async (resource) => {\n switch (resource.origin.kind) {\n case 'inline':\n return [resource.id, resource.origin.bytes] as const;\n case 'file':\n return [\n resource.id,\n new Uint8Array(await readFile(resource.origin.path)),\n ] as const;\n case 'remote': {\n const response = await fetch(resource.origin.url);\n if (!response.ok) {\n throw new Error(\n `failed to fetch image ${resource.origin.url}: ${response.status} ${response.statusText}`\n );\n }\n return [\n resource.id,\n new Uint8Array(await response.arrayBuffer()),\n ] as const;\n }\n }\n })\n );\n return new Map(entries);\n}\n","/**\n * Presentation generation entry points.\n *\n * Every path here compiles the authoring tree to PptxIR and hands it to a\n * renderer adapter; nothing in this module knows which backend that is. The\n * default is `pptxgenjs`, which reproduces the output this pipeline has always\n * produced — see `src/__tests__/corpus-goldens.test.ts`.\n */\n\nimport { writeFileSync } from 'fs';\nimport type {\n PipelineWarning,\n PresentationComponentDefinition,\n} from '../types';\nimport { generateBufferViaIr } from './generateFromIr';\n\nexport {\n PresentationValidationError,\n assertNoContentConflicts,\n assertValidPresentation,\n isPresentationComponentDefinition,\n} from './generationOptions';\nexport type {\n GenerationOptions,\n GenerationResult,\n GenerationValidationOptions,\n} from './generationOptions';\n\nimport {\n isPresentationComponentDefinition,\n type GenerationOptions,\n type GenerationResult,\n} from './generationOptions';\n\n/**\n * Generate a `.pptx` buffer from a presentation definition.\n */\nexport async function generateBufferFromJson(\n jsonConfig: string | PresentationComponentDefinition,\n options?: GenerationOptions\n): Promise<Buffer> {\n const result = await generateBufferWithWarnings(jsonConfig, options);\n return result.buffer;\n}\n\n/**\n * Generate a `.pptx` buffer, returning the pipeline warnings alongside it.\n */\nexport async function generateBufferWithWarnings(\n jsonConfig: string | PresentationComponentDefinition,\n options?: GenerationOptions\n): Promise<GenerationResult> {\n const { buffer, warnings } = await generateBufferViaIr(jsonConfig, options);\n return { buffer, warnings };\n}\n\n/**\n * Generate and save a `.pptx` file from a presentation definition.\n */\nexport async function generateAndSaveFromJson(\n jsonConfig: string | PresentationComponentDefinition,\n outputPath: string,\n options?: GenerationOptions\n): Promise<void> {\n const buffer = await generateBufferFromJson(jsonConfig, options);\n writeFileSync(outputPath, buffer);\n}\n\n/**\n * Generate from a JSON file path.\n */\nexport async function generateFromFile(\n filePath: string,\n outputPath: string,\n options?: GenerationOptions\n): Promise<void> {\n const { readFileSync } = await import('fs');\n const json = readFileSync(filePath, 'utf-8');\n await generateAndSaveFromJson(json, outputPath, options);\n}\n\nexport type { PipelineWarning };\n\n/**\n * The main API surface.\n *\n * Buffer- and file-oriented only: no member returns a renderer-native object.\n */\nexport const PresentationGenerator = {\n generateBufferFromJson,\n generateBufferWithWarnings,\n generateAndSaveFromJson,\n generateFromFile,\n isPresentationComponentDefinition,\n};\n","/**\n * The IR-based PPTX generation path.\n *\n * Same prologue as `generateBufferWithWarnings` — props defaulting, inline\n * theme normalisation, theme resolution, export-mode pre-pass, font\n * resolution — and then, instead of calling PptxGenJS directly, it compiles to\n * PptxIR, checks the selected renderer can express it, and hands the IR to an\n * adapter.\n *\n * Not yet the default. It becomes the default when every component the legacy\n * path renders is lowered by the compiler and the parity fixtures pass through\n * it; until then `compilePresentation` reports anything it cannot lower and\n * this function refuses rather than shipping a deck with content missing.\n */\n\nimport { assertRendererSupports } from '@json-to-office/shared/rendering';\nimport { PPTX_RENDERER_IDS } from '@json-to-office/shared-pptx';\nimport { runWithBaseDir } from '../utils/baseDirContext';\nimport { compilePresentation } from '../ir/compiler';\nimport type { PptxIR } from '../ir/types';\nimport { resolvePptxRenderer } from '../renderers/registry';\nimport type {\n PipelineWarning,\n PresentationComponentDefinition,\n ProcessedPresentation,\n} from '../types';\nimport { isPresentationComponent } from '../types';\nimport { resolveDocumentFonts } from './fontResolution';\nimport { resolveThemeContext } from './generationContext';\nimport {\n assertNoContentConflicts,\n assertValidPresentationForGeneration,\n type GenerationOptions,\n} from './generationOptions';\nimport { expandHighchartsComponents } from './expandHighcharts';\nimport { resolveImageLayout } from './resolveImageLayout';\nimport { processPresentation } from './structure';\n\n/** Alias kept for readability at call sites inside the IR pipeline. */\nexport type IrGenerationOptions = GenerationOptions;\n\nexport interface IrGenerationResult {\n buffer: Buffer;\n warnings: PipelineWarning[];\n}\n\n/**\n * Thrown when the compiler meets a component it does not lower yet.\n *\n * Silently dropping the component would be worse than failing: the deck would\n * look complete and not be. This disappears when the compiler covers every\n * component kind.\n */\nexport class UncompiledComponentError extends Error {\n public readonly code = 'UNCOMPILED_COMPONENT';\n public readonly components: ReadonlyArray<{ name: string; path: string }>;\n\n constructor(components: ReadonlyArray<{ name: string; path: string }>) {\n const names = [...new Set(components.map((c) => c.name))]\n .map((n) => `\"${n}\"`)\n .join(', ');\n super(\n `The PptxIR compiler does not lower ${names} yet, so the IR path would ` +\n `drop ${components.length} component(s):\\n` +\n components.map((c) => ` - ${c.name} at ${c.path}`).join('\\n')\n );\n this.name = 'UncompiledComponentError';\n this.components = [...components];\n }\n}\n\n/**\n * Compile a presentation document to PptxIR without rendering it.\n *\n * Runs the same pre-passes as generation, so what comes back is the IR that\n * would be rendered — not a near-miss that omits image fitting.\n */\nexport async function compileDocumentToIr(\n jsonConfig: string | PresentationComponentDefinition,\n options?: IrGenerationOptions\n): Promise<{\n ir: PptxIR;\n warnings: PipelineWarning[];\n required: ReturnType<typeof compilePresentation>['required'];\n unsupported: ReturnType<typeof compilePresentation>['unsupported'];\n}> {\n const component = parseDocument(jsonConfig);\n const selectedRenderer = options?.renderer ?? component.renderer;\n assertValidPresentationForGeneration(\n selectedRenderer && PPTX_RENDERER_IDS.includes(selectedRenderer)\n ? { ...component, renderer: selectedRenderer }\n : component,\n options?.validation\n );\n const warnings: PipelineWarning[] = [];\n\n const context = resolveThemeContext(component, {\n customThemes: options?.customThemes,\n fonts: options?.fonts,\n warnings,\n });\n\n assertNoContentConflicts(context.document);\n\n const result = await runWithBaseDir(options?.baseDir, async () => {\n const processed = processPresentation(context.document, {\n ...options,\n theme: context.theme,\n });\n const expansion = await expandHighchartsComponents(\n processed,\n options?.services?.highcharts,\n warnings\n );\n const laidOut = await resolveImageLayout(expansion.presentation, warnings);\n const compiled = compilePresentation(laidOut, warnings);\n return {\n ...compiled,\n unsupported: [...compiled.unsupported, ...expansion.unexpanded],\n };\n });\n\n return {\n ir: result.ir,\n warnings: result.warnings,\n required: result.required,\n unsupported: result.unsupported,\n };\n}\n\n/** Generate a `.pptx` buffer through PptxIR and the selected renderer. */\nexport async function generateBufferViaIr(\n jsonConfig: string | PresentationComponentDefinition,\n options?: IrGenerationOptions\n): Promise<IrGenerationResult> {\n const component = parseDocument(jsonConfig);\n const selectedRenderer = options?.renderer ?? component.renderer;\n const effectiveOptions = selectedRenderer\n ? { ...options, renderer: selectedRenderer }\n : options;\n assertValidPresentationForGeneration(\n selectedRenderer && PPTX_RENDERER_IDS.includes(selectedRenderer)\n ? { ...component, renderer: selectedRenderer }\n : component,\n options?.validation\n );\n const warnings: PipelineWarning[] = [];\n\n const context = resolveThemeContext(component, {\n customThemes: options?.customThemes,\n fonts: options?.fonts,\n warnings,\n });\n\n assertNoContentConflicts(context.document);\n\n // Fires `fonts.onResolved` for the preview stager, exactly as the legacy\n // path does. The PPTX itself never embeds font bytes.\n await resolveDocumentFonts(\n context.document,\n context.theme,\n warnings,\n options?.fonts\n );\n\n // Relative asset paths are resolved during compilation, so the base-directory\n // scope has to span it (#142).\n const buffer = await runWithBaseDir(options?.baseDir, () =>\n renderProcessedViaIr(\n processPresentation(context.document, {\n ...effectiveOptions,\n theme: context.theme,\n }),\n warnings,\n effectiveOptions\n )\n );\n\n return { buffer, warnings };\n}\n\n/**\n * Compile a processed presentation and render it with the selected backend.\n *\n * Shared by both entry points — the core buffer API and the plugin generator —\n * so the two cannot drift in which expansions run, which capabilities are\n * checked, or how the package is finalised.\n *\n * The caller is responsible for the base-directory scope: relative asset paths\n * are resolved during compilation (#142).\n */\nexport async function renderProcessedViaIr(\n processed: ProcessedPresentation,\n warnings: PipelineWarning[],\n options?: IrRenderOptions\n): Promise<Buffer> {\n // `highcharts` fetches a PNG from an export server; resolving it before\n // compilation keeps the IR free of any service dependency.\n const expansion = await expandHighchartsComponents(\n processed,\n options?.services?.highcharts,\n warnings\n );\n // Fitting an image needs its intrinsic size, which needs I/O; resolving it\n // here keeps the compiler synchronous and free of file access.\n const laidOut = await resolveImageLayout(expansion.presentation, warnings);\n const compiled = compilePresentation(laidOut, warnings);\n\n const missing = [...compiled.unsupported, ...expansion.unexpanded];\n if (missing.length > 0) {\n throw new UncompiledComponentError(missing);\n }\n\n const renderer = await resolvePptxRenderer(options?.renderer);\n assertRendererSupports(compiled.required, renderer);\n\n const bytes = await renderer.render(compiled.ir, {\n ...(options?.deterministic !== undefined\n ? { deterministic: options.deterministic }\n : {}),\n ...(options?.generatedAt !== undefined\n ? { generatedAt: toDate(options.generatedAt) }\n : {}),\n // Post-render repairs report into the same list as the rest of the\n // pipeline, so a caller sees one set of warnings.\n warnings,\n });\n\n return Buffer.from(bytes);\n}\n\n/** The subset of options `renderProcessedViaIr` reads. */\nexport type IrRenderOptions = Pick<\n GenerationOptions,\n 'renderer' | 'services' | 'deterministic' | 'generatedAt'\n>;\n\nfunction parseDocument(\n jsonConfig: string | PresentationComponentDefinition\n): PresentationComponentDefinition {\n if (typeof jsonConfig !== 'string') return jsonConfig;\n const parsed = JSON.parse(jsonConfig);\n if (!isPresentationComponent(parsed)) {\n throw new Error('Parsed JSON must be a presentation component');\n }\n return parsed;\n}\n\nfunction toDate(value: Date | string): Date {\n return value instanceof Date ? value : new Date(value);\n}\n","import { AsyncLocalStorage } from 'node:async_hooks';\nimport { isAbsolute, resolve } from 'node:path';\n\nconst baseDirStorage = new AsyncLocalStorage<string>();\n\n/**\n * Scope the document base directory for a generation run, so relative asset\n * paths (`image.props.path`, slide background images) resolve against the\n * document's own location rather than `process.cwd()` (#142). No baseDir →\n * plain callback, preserving the historical cwd-relative behavior. Mirrors\n * core-docx/src/utils/generationContext.ts.\n */\nexport function runWithBaseDir<T>(\n baseDir: string | undefined,\n callback: () => T\n): T {\n return baseDir === undefined\n ? callback()\n : baseDirStorage.run(resolve(baseDir), callback);\n}\n\n/** The active document base directory, if a generation scope set one. */\nexport function getBaseDir(): string | undefined {\n return baseDirStorage.getStore();\n}\n\n/**\n * Resolve a relative file path against the active base directory. Absolute\n * paths pass through; with no active baseDir the path is returned as-is,\n * which pptxgenjs / `fs` resolve against cwd — the legacy behavior. The\n * rewrite must happen eagerly at render time: pptxgenjs reads `path` entries\n * later, during `write()`, outside any generation scope.\n */\nexport function resolveFromBaseDir(filePath: string): string {\n const base = baseDirStorage.getStore();\n if (!base || isAbsolute(filePath)) return filePath;\n return resolve(base, filePath);\n}\n","/**\n * Compile a processed presentation into PptxIR.\n *\n * The input is `ProcessedPresentation` — the authoring tree after schema\n * validation, custom-component expansion, theme resolution and component\n * defaults. What remains, and what this module does, is the last mile of\n * resolution: grid cells become EMU transforms, placeholder content is merged\n * with its declaration, theme colour tokens become hex, the font cascade is\n * flattened onto every run, and page-number placeholders are substituted.\n *\n * No renderer is imported here, and none may be. The output is plain data.\n *\n * Scope: this is the Phase 2 vertical slice — metadata, slide size, slides,\n * solid backgrounds, text bodies (single and rich-run), images and preset\n * shapes. Component kinds outside that slice are reported through\n * `unsupported`, so a caller can tell \"not yet compiled\" from \"compiled to\n * nothing\".\n */\n\nimport {\n FeatureRequirementCollector,\n type FeatureRequirement,\n} from '@json-to-office/shared/rendering';\nimport type { TextSegment } from '@json-to-office/shared-pptx';\nimport { PATTERN_FILL_PRESETS } from '@json-to-office/shared-pptx';\nimport type {\n GridConfig,\n PipelineWarning,\n PptxComponentInput,\n PptxThemeConfig,\n ProcessedPresentation,\n ProcessedSlide,\n SlideContext,\n StyleName,\n TemplateSlideDefinition,\n} from '../types';\nimport { definedChartColorTokens, resolveColor } from '../utils/color';\nimport { applyFontWeight } from '../utils/fontAliasContext';\nimport { getDefaultsForType } from '../utils/componentDefaults';\nimport { resolveComponentDefaults } from '../utils/resolveComponentTree';\nimport { resolveImageSource, safeLocalPath } from '../utils/imageSource';\nimport {\n HYPERLINK_SLIDE_UNRESOLVED,\n type HyperlinkProps,\n} from '../utils/hyperlink';\nimport { mergeGridConfigs, resolveComponentGridPosition } from '../core/grid';\nimport { mergeWithDefaults } from '@json-to-office/shared';\nimport { W, warn } from '../utils/warn';\nimport type { PptxFeature } from './features';\nimport {\n ResourceTable,\n mediaTypeFromLocation,\n parseDataUri,\n} from './resources';\nimport {\n PPTX_IR_GEOMETRY,\n PPTX_IR_SCHEMA_VERSION,\n type PptxIR,\n type PptxIrBackground,\n type PptxIrBullet,\n type PptxIrColor,\n type PptxIrElement,\n type PptxIrFill,\n type PptxIrGeometry,\n type PptxIrGradient,\n type PptxIrHyperlink,\n type PptxIrImageSizing,\n type PptxIrKnownGeometry,\n type PptxIrLine,\n type PptxIrMaster,\n type PptxIrPlaceholder,\n type PptxIrRunFormatting,\n type PptxIrChartGridLine,\n type PptxIrChartLabelFont,\n type PptxIrChartOptions,\n type PptxIrChartType,\n type PptxIrShadow,\n type PptxIrTableBorder,\n type PptxIrTableCell,\n type PptxIrTableCellFormatting,\n type PptxIrTableElement,\n type PptxIrTableFormatting,\n type PptxIrTableRow,\n type PptxIrSlide,\n type PptxIrTextBodyStyle,\n type PptxIrTextRun,\n type PptxIrTransform,\n type PptxIrTransition,\n} from './types';\nimport {\n defaultWidthEmu,\n elementId,\n inchesToEmu,\n irColor,\n normalizeDegrees,\n resolveDimensionEmu,\n type SlideExtentEmu,\n} from './units';\n\n/** A component kind the compiler does not yet lower into IR. */\nexport interface UnsupportedComponent {\n name: string;\n path: string;\n}\n\nexport interface PptxCompileResult {\n ir: PptxIR;\n /** Backend capabilities the IR needs, with the IR path that needs them. */\n required: readonly FeatureRequirement<PptxFeature>[];\n warnings: PipelineWarning[];\n /**\n * Components the compiler could not lower. Empty once the migration is\n * complete; until then this is what keeps the legacy path authoritative\n * instead of silently dropping content.\n */\n unsupported: UnsupportedComponent[];\n}\n\n/** Shared mutable state for one compilation. Never module-global. */\ninterface CompileContext {\n theme: PptxThemeConfig;\n warnings: PipelineWarning[];\n features: FeatureRequirementCollector<PptxFeature>;\n resources: ResourceTable;\n unsupported: UnsupportedComponent[];\n slideWidthInches: number;\n slideHeightInches: number;\n /** Slide extent in EMU — what percentage dimensions resolve against. */\n extent: SlideExtentEmu;\n}\n\nexport function compilePresentation(\n processed: ProcessedPresentation,\n warnings: PipelineWarning[] = []\n): PptxCompileResult {\n const ctx: CompileContext = {\n theme: processed.theme,\n warnings,\n features: new FeatureRequirementCollector<PptxFeature>(),\n resources: new ResourceTable(),\n unsupported: [],\n slideWidthInches: processed.slideWidth,\n slideHeightInches: processed.slideHeight,\n extent: {\n widthEmu: inchesToEmu(processed.slideWidth),\n heightEmu: inchesToEmu(processed.slideHeight),\n },\n };\n\n const masters = (processed.templates ?? []).map((template, index) =>\n compileMaster(template, index, processed, ctx)\n );\n if (masters.length > 0) {\n ctx.features.require('masters', 'masters');\n }\n\n const slides = processed.slides.map((slide, index) =>\n compileSlide(slide, index, processed, ctx)\n );\n\n if (processed.rtlMode) ctx.features.require('rtl', 'rtl');\n\n const ir: PptxIR = {\n schemaVersion: PPTX_IR_SCHEMA_VERSION,\n metadata: { ...processed.metadata },\n size: { ...ctx.extent },\n theme: {\n name: processed.theme.name,\n headingFont: processed.theme.fonts.heading,\n bodyFont: processed.theme.fonts.body,\n palette: resolvePalette(processed.theme),\n },\n rtl: processed.rtlMode,\n ...(processed.language ? { language: processed.language } : {}),\n resources: ctx.resources.list(),\n masters,\n slides,\n };\n\n return {\n ir,\n required: ctx.features.list(),\n warnings: ctx.warnings,\n unsupported: ctx.unsupported,\n };\n}\n\n/* ------------------------------------------------------------------ *\n * Theme\n * ------------------------------------------------------------------ */\n\n/**\n * Resolve every theme colour slot to hex.\n *\n * Slots may name other slots; `resolveColor` walks those chains. Resolution\n * runs without a warning sink because an unset optional slot is normal here —\n * it only matters when an element actually references it, and that call site\n * reports it.\n */\nfunction resolvePalette(theme: PptxThemeConfig): Record<string, string> {\n const palette: Record<string, string> = {};\n for (const [slot, value] of Object.entries(theme.colors)) {\n if (typeof value !== 'string' || value.length === 0) continue;\n palette[slot] = resolveColor(value, theme).toUpperCase();\n }\n return palette;\n}\n\n/* ------------------------------------------------------------------ *\n * Masters\n * ------------------------------------------------------------------ */\n\nfunction compileMaster(\n template: TemplateSlideDefinition,\n templateIndex: number,\n processed: ProcessedPresentation,\n ctx: CompileContext\n): PptxIrMaster {\n const path = `masters[${templateIndex}]`;\n const background = compileBackground(\n template.background,\n `${path}.background`,\n ctx\n );\n\n // A template's fixed objects are drawn onto every slide that uses it, not\n // into the master part — that is what the pipeline has always done, and it\n // is what `compileSlide` records. Compiling them here as well would put the\n // same content in the IR twice. The field stays on the master for a backend\n // that supports genuine master-level decoration.\n const elements: PptxIrElement[] = [];\n\n const placeholders: PptxIrPlaceholder[] = (template.placeholders ?? []).map(\n (placeholder) => {\n const transform = optionalTransform(\n placeholder.x,\n placeholder.y,\n placeholder.w,\n placeholder.h,\n ctx\n );\n return transform\n ? { name: placeholder.name, transform }\n : { name: placeholder.name };\n }\n );\n if (placeholders.length > 0) {\n ctx.features.require('placeholders', `${path}.placeholders`);\n }\n\n const master: PptxIrMaster = {\n name: template.name,\n ...(background ? { background } : {}),\n ...(template.margin !== undefined ? { margin: template.margin } : {}),\n elements,\n placeholders,\n };\n\n if (template.slideNumber) {\n const sn = template.slideNumber;\n master.slideNumber = {\n transform: {\n xEmu: inchesToEmu(sn.x),\n yEmu: inchesToEmu(sn.y),\n widthEmu: inchesToEmu(sn.w ?? 1),\n heightEmu: inchesToEmu(sn.h ?? 0.3),\n },\n ...(sn.color\n ? { color: irColor(resolveColor(sn.color, ctx.theme, ctx.warnings)) }\n : {}),\n ...(sn.fontSize !== undefined ? { fontSize: sn.fontSize } : {}),\n };\n }\n\n // A template gradient background is not a background: it compiles to a\n // full-bleed shape at the back of every slide that uses the template. The\n // slide compiler emits it, because that is where slide element order lives.\n void processed;\n\n return master;\n}\n\n/* ------------------------------------------------------------------ *\n * Slides\n * ------------------------------------------------------------------ */\n\nfunction compileSlide(\n slide: ProcessedSlide,\n slideIndex: number,\n processed: ProcessedPresentation,\n ctx: CompileContext\n): PptxIrSlide {\n const path = `slides[${slideIndex}]`;\n const templates = new Map(\n (processed.templates ?? []).map((template) => [template.name, template])\n );\n const template = slide.template ? templates.get(slide.template) : undefined;\n if (slide.template && !template) {\n warn(\n ctx.warnings,\n W.MISSING_TEMPLATE,\n `Unknown template \"${slide.template}\". Available: ${[...templates.keys()].join(', ')}`,\n { slide: slideIndex }\n );\n }\n\n const elements: PptxIrElement[] = [];\n let nextIndex = 0;\n const push = (element: PptxIrElement | undefined) => {\n if (element) elements.push(element);\n nextIndex += 1;\n };\n\n // A gradient background renders as a full-bleed rectangle added first, so it\n // sits behind everything else. The slide's own background wins over the\n // template's, matching the pre-IR pipeline.\n const gradientSource =\n slide.background?.gradient ??\n (slide.background ? undefined : template?.background?.gradient);\n let background: PptxIrBackground | undefined;\n if (gradientSource) {\n const gradient = compileGradient(\n gradientSource,\n `${path}.background.gradient`,\n ctx\n );\n if (gradient) {\n ctx.features.require('gradient-fills', `${path}.background`);\n elements.push({\n kind: 'shape',\n id: elementId(slideIndex, [nextIndex]),\n path: `${path}.elements[${nextIndex}]`,\n transform: {\n xEmu: 0,\n yEmu: 0,\n widthEmu: inchesToEmu(ctx.slideWidthInches),\n heightEmu: inchesToEmu(ctx.slideHeightInches),\n },\n geometry: 'rect',\n fill: { kind: 'gradient', gradient },\n });\n ctx.features.require('shapes', `${path}.elements[${nextIndex}]`);\n nextIndex += 1;\n }\n } else {\n background = compileBackground(slide.background, `${path}.background`, ctx);\n }\n\n const effectiveGrid = mergeGridConfigs(processed.grid, template?.grid);\n\n // Template fixed objects draw beneath slide content.\n // Template objects are drawn onto this slide, so they see this slide's\n // context: a `{PAGE_NUMBER}` in a template header has to resolve, and its\n // runs inherit the deck language like any other.\n for (const object of template?.objects ?? []) {\n push(\n compileComponent(object, {\n ctx,\n path: `${path}.elements[${nextIndex}]`,\n id: elementId(slideIndex, [nextIndex]),\n slideCtx: slideContextFor(slideIndex, processed),\n })\n );\n }\n\n for (const component of slide.components) {\n const resolved = resolveComponentGridPosition(\n component,\n effectiveGrid,\n ctx.slideWidthInches,\n ctx.slideHeightInches,\n ctx.warnings\n );\n push(\n compileComponent(resolved, {\n ctx,\n path: `${path}.elements[${nextIndex}]`,\n id: elementId(slideIndex, [nextIndex]),\n slideCtx: slideContextFor(slideIndex, processed),\n })\n );\n }\n\n for (const component of compilePlaceholderComponents(\n slide,\n template,\n effectiveGrid,\n slideIndex,\n ctx\n )) {\n push(\n compileComponent(component, {\n ctx,\n path: `${path}.elements[${nextIndex}]`,\n id: elementId(slideIndex, [nextIndex]),\n slideCtx: slideContextFor(slideIndex, processed),\n })\n );\n }\n\n if (slide.notes) ctx.features.require('speaker-notes', `${path}.notes`);\n if (slide.hidden) ctx.features.require('hidden-slides', `${path}.hidden`);\n if (background) ctx.features.require('backgrounds', `${path}.background`);\n\n const transition = compileTransition(slide.transition);\n if (transition) ctx.features.require('transitions', `${path}.transition`);\n\n return {\n id: `slide${slideIndex + 1}`,\n path,\n ...(slide.template ? { masterName: slide.template } : {}),\n ...(background ? { background } : {}),\n elements,\n ...(slide.notes ? { notes: slide.notes } : {}),\n hidden: slide.hidden === true,\n ...(transition ? { transition } : {}),\n };\n}\n\n/**\n * An authored transition.\n *\n * `none` is an authored transition too — it says \"do not inherit one\" — but\n * OOXML expresses that by omitting `<p:transition>`, so it lowers to nothing\n * and asks nothing of the backend.\n */\nfunction compileTransition(\n transition: ProcessedSlide['transition']\n): PptxIrTransition | undefined {\n const type = transition?.type;\n if (!type || type === 'none') return undefined;\n return {\n type,\n ...(transition?.speed\n ? { speed: transition.speed as PptxIrTransition['speed'] }\n : {}),\n };\n}\n\nfunction slideContextFor(\n slideIndex: number,\n processed: ProcessedPresentation\n): SlideContext {\n return {\n slideNumber: slideIndex + 1,\n totalSlides: processed.slides.length,\n pageNumberFormat: processed.pageNumberFormat,\n language: processed.language,\n };\n}\n\n/**\n * Merge slide-side placeholder content with its master declaration.\n *\n * Precedence matches the pre-IR renderer: componentDefaults < declared\n * position < declared defaults < the component's own props.\n */\nfunction compilePlaceholderComponents(\n slide: ProcessedSlide,\n template: TemplateSlideDefinition | undefined,\n effectiveGrid: GridConfig | undefined,\n slideIndex: number,\n ctx: CompileContext\n): PptxComponentInput[] {\n if (!slide.placeholders) return [];\n const out: PptxComponentInput[] = [];\n\n if (!template) {\n // No template: a placeholder is only renderable if it positions itself.\n for (const [name, component] of Object.entries(slide.placeholders)) {\n const defaulted = resolveComponentDefaults(component, ctx.theme);\n const positioned =\n defaulted.props.x != null ||\n defaulted.props.y != null ||\n defaulted.props.grid;\n if (!positioned) {\n warn(\n ctx.warnings,\n W.PLACEHOLDER_NO_POSITION,\n `Placeholder \"${name}\" has no template and no explicit position — skipped`,\n { slide: slideIndex }\n );\n continue;\n }\n out.push(\n resolveComponentGridPosition(\n defaulted,\n effectiveGrid,\n ctx.slideWidthInches,\n ctx.slideHeightInches,\n ctx.warnings\n )\n );\n }\n return out;\n }\n\n const declared = new Map(\n (template.placeholders ?? []).map((placeholder) => [\n placeholder.name,\n placeholder,\n ])\n );\n\n for (const [name, component] of Object.entries(slide.placeholders)) {\n const definition = declared.get(name);\n if (!definition) {\n warn(\n ctx.warnings,\n W.UNKNOWN_PLACEHOLDER,\n `Unknown placeholder \"${name}\" in template \"${slide.template}\". Available: ${[...declared.keys()].join(', ')}`,\n { slide: slideIndex }\n );\n continue;\n }\n\n const gridResolved = resolveComponentGridPosition(\n component,\n effectiveGrid,\n ctx.slideWidthInches,\n ctx.slideHeightInches,\n ctx.warnings\n );\n\n const typeDefaults = getDefaultsForType(component.name, ctx.theme);\n const positionDefaults: Record<string, unknown> = {};\n if (definition.x != null) positionDefaults.x = definition.x;\n if (definition.y != null) positionDefaults.y = definition.y;\n if (definition.w != null) positionDefaults.w = definition.w;\n if (definition.h != null) positionDefaults.h = definition.h;\n\n let props = mergeWithDefaults(positionDefaults, typeDefaults);\n props = mergeWithDefaults(definition.defaults?.props ?? {}, props);\n props = mergeWithDefaults(gridResolved.props, props);\n\n out.push({ ...gridResolved, props });\n }\n\n return out;\n}\n\n/* ------------------------------------------------------------------ *\n * Components\n * ------------------------------------------------------------------ */\n\ninterface ComponentScope {\n ctx: CompileContext;\n path: string;\n id: string;\n slideCtx?: SlideContext;\n}\n\nfunction compileComponent(\n component: PptxComponentInput,\n scope: ComponentScope\n): PptxIrElement | undefined {\n if (component.enabled === false) return undefined;\n\n switch (component.name) {\n case 'text':\n return compileText(component, scope);\n case 'shape':\n return compileShape(component, scope);\n case 'image':\n return compileImage(component, scope);\n case 'table':\n return compileTable(component, scope);\n case 'chart':\n return compileChart(component, scope);\n case 'highcharts':\n // Modelled in the IR, not yet lowered. Recorded rather than dropped.\n scope.ctx.unsupported.push({ name: component.name, path: scope.path });\n return undefined;\n default:\n warn(\n scope.ctx.warnings,\n W.UNKNOWN_COMPONENT,\n `Unknown PPTX component type: ${component.name}`,\n { component: component.name }\n );\n return undefined;\n }\n}\n\n/* ------------------------------------------------------------------ *\n * Text\n * ------------------------------------------------------------------ */\n\ninterface TextRunProps {\n text: string;\n color?: string;\n bold?: boolean;\n fontWeight?: number;\n italic?: boolean;\n underline?: boolean | { style?: string; color?: string };\n strike?: boolean;\n fontSize?: number;\n fontFace?: string;\n superscript?: boolean;\n subscript?: boolean;\n charSpacing?: number;\n breakLine?: boolean;\n}\n\nfunction compileText(\n component: PptxComponentInput,\n scope: ComponentScope\n): PptxIrElement | undefined {\n const { ctx, path } = scope;\n const props = component.props as Record<string, any>;\n const runProps: TextRunProps[] | undefined =\n Array.isArray(props.runs) && props.runs.length > 0 ? props.runs : undefined;\n\n if (props.text === undefined && !runProps) {\n warn(\n ctx.warnings,\n W.TEXT_NO_CONTENT,\n 'Text component has neither \"text\" nor \"runs\" — skipped',\n { component: 'text' }\n );\n return undefined;\n }\n\n const named = namedStyle(props.style, ctx.theme);\n // Component override wins over the deck default; with neither set the\n // renderer falls back to its own default, so nothing is recorded.\n const cascade = fontCascade(\n props,\n named,\n ctx,\n (props.language as string | undefined) ?? scope.slideCtx?.language\n );\n\n const lineCount = runProps\n ? runProps.reduce(\n (count, run) =>\n count +\n (run.breakLine ? 1 : 0) +\n (run.text.match(/\\n/g)?.length ?? 0),\n 1\n )\n : ((props.text as string).match(/\\n/g)?.length ?? 0) + 1;\n\n // The derived height has always been sized from the component's own font\n // size or the theme default — not from the named style's size. Using\n // `cascade.fontSize` here would silently resize every styled text box that\n // omits an explicit height.\n const heightFontSize =\n (props.fontSize as number | undefined) ?? ctx.theme.defaults.fontSize ?? 18;\n const transform = textTransform(props, heightFontSize, lineCount, ctx);\n const autoFit = props.h === undefined;\n\n const hyperlink = compileHyperlink(props.hyperlink, 'text', ctx, path);\n // The link belongs to the text box, not to each run: attaching it per run\n // emits one identical external relationship per run.\n const runs: PptxIrTextRun[] = runProps\n ? runProps.map((run) =>\n compileRichRun(run, cascade, undefined, scope.slideCtx, ctx)\n )\n : [\n {\n text: substitutePageNumbers(props.text as string, scope.slideCtx),\n ...baseRunFormatting(cascade),\n ...(cascade.strike != null ? { strike: cascade.strike } : {}),\n ...(cascade.underline ? { underline: cascade.underline } : {}),\n ...(cascade.language ? { language: cascade.language } : {}),\n ...(props.breakLine ? { breakAfter: true } : {}),\n },\n ];\n\n ctx.features.require('text', path);\n if (runs.length > 1) ctx.features.require('rich-text', path);\n if (cascade.language) ctx.features.require('proofing-language', path);\n if (hyperlink) ctx.features.require('text-hyperlinks', path);\n\n const fill = props.fill\n ? compileSolidFillFromProps(props.fill, `${path}.fill`, ctx)\n : undefined;\n if (fill) ctx.features.require('solid-fills', `${path}.fill`);\n\n const shadow = compileShadow(props.shadow, ctx);\n if (shadow) ctx.features.require('shadows', `${path}.shadow`);\n\n const bodyStyle = textBodyStyle(props, named, cascade, {\n autoFit,\n // Text boxes have always defaulted their inset to 0 so the text lines up\n // exactly with the position the author (or the grid) gave it.\n defaultInsetPoints: 0,\n });\n requireBulletFeatures(bodyStyle.bullet, path, ctx);\n\n return {\n kind: 'textBox',\n id: scope.id,\n path,\n transform,\n runs,\n style: bodyStyle,\n ...(fill ? { fill } : {}),\n ...(shadow ? { shadow } : {}),\n ...(hyperlink ? { hyperlink } : {}),\n };\n}\n\ninterface FontCascade {\n fontFamily: string;\n /** The family before weight aliasing, used to resolve per-run aliases. */\n baseFamily: string;\n fontSize: number;\n color: PptxIrColor;\n bold?: boolean;\n italic?: boolean;\n fontWeight?: number;\n characterSpacing?: number;\n underline?: PptxIrTextRun['underline'];\n strike?: boolean;\n language?: string;\n}\n\nfunction namedStyle(\n style: unknown,\n theme: PptxThemeConfig\n): { style?: ReturnType<typeof pickStyle>; isHeading: boolean } {\n const name = typeof style === 'string' ? (style as StyleName) : undefined;\n return {\n style: name ? pickStyle(theme, name) : undefined,\n isHeading: name !== undefined && /^(title|heading)/.test(name),\n };\n}\n\nfunction pickStyle(theme: PptxThemeConfig, name: StyleName) {\n return theme.styles?.[name];\n}\n\n/**\n * Flatten component props → named style → theme defaults into one set of run\n * formatting values, applying weight aliasing exactly once.\n */\nfunction fontCascade(\n props: Record<string, any>,\n named: ReturnType<typeof namedStyle>,\n ctx: CompileContext,\n /**\n * Proofing language for the runs. Text bodies inherit the deck default when\n * they do not name one; shapes never carry a language, so they pass nothing.\n */\n language?: string\n): FontCascade {\n const style = named.style;\n const fontSize =\n props.fontSize ?? style?.fontSize ?? ctx.theme.defaults.fontSize;\n const baseFamily =\n props.fontFace ??\n style?.fontFace ??\n (named.isHeading ? ctx.theme.fonts.heading : ctx.theme.fonts.body);\n const color = irColor(\n resolveColor(\n props.color ??\n props.fontColor ??\n style?.fontColor ??\n ctx.theme.defaults.fontColor,\n ctx.theme,\n ctx.warnings\n )\n );\n\n const bold = props.bold ?? style?.bold;\n const italic = props.italic ?? style?.italic;\n const fontWeight = props.fontWeight ?? style?.fontWeight;\n const characterSpacing = props.charSpacing ?? style?.charSpacing;\n\n let fontFamily = baseFamily;\n let effectiveBold = bold;\n let effectiveItalic = italic;\n if (fontWeight != null || bold === true) {\n const aliased = applyFontWeight({\n family: baseFamily,\n fontWeight,\n italic,\n bold,\n });\n if (aliased.fontFace !== undefined) fontFamily = aliased.fontFace;\n if (aliased.bold !== undefined) effectiveBold = aliased.bold;\n if (aliased.italic !== undefined) effectiveItalic = aliased.italic;\n }\n\n return {\n fontFamily,\n baseFamily,\n fontSize,\n color,\n ...(effectiveBold != null ? { bold: effectiveBold } : {}),\n ...(effectiveItalic != null ? { italic: effectiveItalic } : {}),\n ...(fontWeight != null ? { fontWeight } : {}),\n ...(characterSpacing != null ? { characterSpacing } : {}),\n ...(props.underline !== undefined\n ? { underline: compileUnderline(props.underline, ctx) }\n : {}),\n ...(props.strike != null ? { strike: props.strike as boolean } : {}),\n ...(language ? { language } : {}),\n };\n}\n\nfunction baseRunFormatting(\n cascade: FontCascade\n): Pick<\n PptxIrTextRun,\n 'fontFamily' | 'fontSize' | 'color' | 'bold' | 'italic' | 'characterSpacing'\n> {\n return {\n fontFamily: cascade.fontFamily,\n fontSize: cascade.fontSize,\n color: cascade.color,\n ...(cascade.bold != null ? { bold: cascade.bold } : {}),\n ...(cascade.italic != null ? { italic: cascade.italic } : {}),\n ...(cascade.characterSpacing != null\n ? { characterSpacing: cascade.characterSpacing }\n : {}),\n };\n}\n\nfunction compileRichRun(\n run: TextRunProps,\n cascade: FontCascade,\n hyperlink: PptxIrHyperlink | undefined,\n slideCtx: SlideContext | undefined,\n ctx: CompileContext\n): PptxIrTextRun {\n const effectiveWeight = run.fontWeight ?? cascade.fontWeight;\n const effectiveBold = run.bold ?? cascade.bold;\n const effectiveItalic = run.italic ?? cascade.italic;\n\n let fontFamily = run.fontFace ?? cascade.fontFamily;\n let bold = effectiveBold;\n let italic = effectiveItalic;\n\n // Only alias when the run inherits the component family. A run that names\n // its own face has already chosen it; re-aliasing would double the suffix.\n if (\n run.fontFace == null &&\n (effectiveWeight != null || effectiveBold === true)\n ) {\n const aliased = applyFontWeight({\n family: cascade.baseFamily,\n fontWeight: effectiveWeight,\n italic: effectiveItalic,\n bold: effectiveBold,\n });\n if (aliased.fontFace !== undefined) fontFamily = aliased.fontFace;\n if (aliased.bold !== undefined) bold = aliased.bold;\n if (aliased.italic !== undefined) italic = aliased.italic;\n }\n\n // Component-level underline and strike cascade into every run, exactly as\n // size, family and colour do. Reading only the run's own value silently drops\n // formatting the author set once for the whole body.\n const underline =\n run.underline !== undefined\n ? compileUnderline(run.underline, ctx)\n : cascade.underline;\n const strike = run.strike ?? cascade.strike;\n\n return {\n text: substitutePageNumbers(run.text, slideCtx),\n fontFamily,\n fontSize: run.fontSize ?? cascade.fontSize,\n color:\n run.color != null\n ? irColor(resolveColor(run.color, ctx.theme, ctx.warnings))\n : cascade.color,\n ...(bold != null ? { bold } : {}),\n ...(italic != null ? { italic } : {}),\n ...(strike != null ? { strike } : {}),\n ...(underline ? { underline } : {}),\n ...(run.superscript != null ? { superscript: run.superscript } : {}),\n ...(run.subscript != null ? { subscript: run.subscript } : {}),\n ...(run.charSpacing != null\n ? { characterSpacing: run.charSpacing }\n : cascade.characterSpacing != null\n ? { characterSpacing: cascade.characterSpacing }\n : {}),\n ...(cascade.language ? { language: cascade.language } : {}),\n ...(run.breakLine != null ? { breakAfter: run.breakLine } : {}),\n ...(hyperlink ? { hyperlink } : {}),\n };\n}\n\nfunction compileUnderline(\n underline: boolean | { style?: string; color?: string },\n ctx: CompileContext\n): PptxIrTextRun['underline'] {\n if (typeof underline === 'boolean') {\n return underline ? { style: 'sng' } : undefined;\n }\n return {\n style: underline.style ?? 'sng',\n ...(underline.color\n ? {\n color: irColor(\n resolveColor(underline.color, ctx.theme, ctx.warnings)\n ),\n }\n : {}),\n };\n}\n\nfunction substitutePageNumbers(\n text: string,\n slideCtx: SlideContext | undefined\n): string {\n if (!slideCtx) return text;\n const { slideNumber, totalSlides, pageNumberFormat } = slideCtx;\n const format = (n: number) =>\n pageNumberFormat === '09'\n ? String(n).padStart(String(totalSlides).length, '0')\n : String(n);\n return text\n .replace(/\\{PAGE_NUMBER\\}/g, format(slideNumber))\n .replace(/\\{PAGE_COUNT\\}/g, format(totalSlides));\n}\n\ninterface TextBodyStyleOptions {\n autoFit?: boolean;\n /**\n * Inset to state when the component does not set `margin`. A text box\n * defaults to 0 so it aligns exactly to its position; a shape states\n * nothing and keeps the format's own padding.\n */\n defaultInsetPoints?: number;\n}\n\nfunction textBodyStyle(\n props: Record<string, any>,\n named: ReturnType<typeof namedStyle>,\n cascade: FontCascade,\n options: TextBodyStyleOptions = {}\n): PptxIrTextBodyStyle {\n const style = named.style;\n const align = props.align ?? style?.align;\n const lineSpacing = props.lineSpacing ?? style?.lineSpacing;\n const spaceAfter = props.paraSpaceAfter ?? style?.paraSpaceAfter;\n const inset = props.margin ?? options.defaultInsetPoints;\n\n return {\n ...(align ? { align: align as PptxIrTextBodyStyle['align'] } : {}),\n verticalAlign: (props.valign ??\n 'top') as PptxIrTextBodyStyle['verticalAlign'],\n ...(props.lineSpacingMultiple !== undefined\n ? { lineSpacingMultiple: props.lineSpacingMultiple }\n : lineSpacing !== undefined\n ? { lineSpacingPoints: lineSpacing }\n : {}),\n ...(props.paraSpaceBefore !== undefined\n ? { spaceBeforePoints: props.paraSpaceBefore }\n : {}),\n ...(spaceAfter !== undefined ? { spaceAfterPoints: spaceAfter } : {}),\n ...(props.bullet !== undefined\n ? { bullet: compileBullet(props.bullet) }\n : {}),\n ...(inset !== undefined\n ? { insetPoints: inset as PptxIrTextBodyStyle['insetPoints'] }\n : {}),\n ...(options.autoFit ? { autoFit: true } : {}),\n defaults: bodyDefaults(cascade),\n };\n}\n\n/** The body-level formatting an empty paragraph inherits. */\nfunction bodyDefaults(cascade: FontCascade): PptxIrRunFormatting {\n return {\n fontFamily: cascade.fontFamily,\n fontSize: cascade.fontSize,\n color: cascade.color,\n ...(cascade.bold != null ? { bold: cascade.bold } : {}),\n ...(cascade.italic != null ? { italic: cascade.italic } : {}),\n ...(cascade.language ? { language: cascade.language } : {}),\n };\n}\n\n/**\n * An authored bullet value, as the IR states it.\n *\n * `false` is a statement, not an absence: it has to reach the backend as an\n * explicit \"no bullet\", because the paragraph may be inheriting one from a\n * named style or from the format's own list style. Compiling it to an enabled\n * bullet is what #254 was.\n */\nfunction compileBullet(\n bullet: boolean | { type?: string; style?: string; startAt?: number }\n): PptxIrBullet {\n if (typeof bullet === 'boolean') {\n return { type: bullet ? 'bullet' : 'none' };\n }\n return {\n type: bullet.type === 'number' ? 'number' : 'bullet',\n ...(bullet.style ? { style: bullet.style } : {}),\n ...(bullet.startAt !== undefined ? { startAt: bullet.startAt } : {}),\n };\n}\n\n/** Record glyphs the default backend cannot represent without substitution. */\nfunction requireBulletFeatures(\n bullet: PptxIrBullet | undefined,\n path: string,\n ctx: CompileContext\n): void {\n if (bullet?.type !== 'bullet' || bullet.style === undefined) return;\n const points = [...bullet.style];\n const codePoint = points[0]?.codePointAt(0);\n if (points.length !== 1 || codePoint === undefined || codePoint > 0xffff) {\n ctx.features.require('complex-bullet-glyphs', `${path}.bullet.style`);\n }\n}\n\n/**\n * Position a text box, reproducing the pre-IR default height.\n *\n * When no height is authored, the renderer used to derive one from the font\n * size and line count so LibreOffice — which draws `cy=\"0\"` as blank — still\n * showed the text. That derivation is layout, so it belongs here.\n */\nfunction textTransform(\n props: Record<string, any>,\n fontSize: number,\n lineCount: number,\n ctx: CompileContext\n): PptxIrTransform {\n // With no authored height, derive one from the font size and line count —\n // LibreOffice draws `cy=\"0\"` as blank, so the pipeline has always supplied a\n // height here rather than letting it default to zero.\n const heightEmu =\n props.h !== undefined\n ? resolveDimensionEmu(props.h, 'Y', ctx.extent)\n : inchesToEmu(Math.max(0.5, (fontSize / 72) * 1.6 * lineCount));\n\n return {\n xEmu:\n props.x !== undefined ? resolveDimensionEmu(props.x, 'X', ctx.extent) : 0,\n yEmu:\n props.y !== undefined ? resolveDimensionEmu(props.y, 'Y', ctx.extent) : 0,\n widthEmu:\n props.w !== undefined\n ? resolveDimensionEmu(props.w, 'X', ctx.extent)\n : defaultWidthEmu(ctx.extent),\n heightEmu,\n ...rotationProperty(props.rotate),\n };\n}\n\n/* ------------------------------------------------------------------ *\n * Shapes\n * ------------------------------------------------------------------ */\n\nconst GEOMETRY_ALIASES: Record<string, PptxIrKnownGeometry> = {\n arrow: 'rightArrow',\n lightning: 'lightningBolt',\n};\n\nfunction compileShape(\n component: PptxComponentInput,\n scope: ComponentScope\n): PptxIrElement | undefined {\n const { ctx, path } = scope;\n const props = component.props as Record<string, any>;\n\n // A geometry outside the known preset set is carried as `{ custom }` rather\n // than rejected: the backends do not agree on which presets exist, so only\n // an adapter can tell an arc from a typo.\n const geometry = compileGeometry(props.type);\n const named = namedStyle(props.style, ctx.theme);\n\n const fill = compileFill(props.fill, `${path}.fill`, ctx);\n if (fill) requireFillFeature(fill, `${path}.fill`, ctx);\n\n const line = compileLine(props.line, ctx);\n if (line) ctx.features.require('lines', `${path}.line`);\n\n const shadow = compileShadow(props.shadow, ctx);\n if (shadow) ctx.features.require('shadows', `${path}.shadow`);\n\n const hasText =\n props.text !== undefined &&\n (!Array.isArray(props.text) || props.text.length > 0);\n\n let runs: PptxIrTextRun[] | undefined;\n let style: PptxIrTextBodyStyle | undefined;\n if (hasText) {\n const cascade = fontCascade(props, named, ctx);\n runs = Array.isArray(props.text)\n ? (props.text as TextSegment[]).map((segment) =>\n compileTextSegment(segment, cascade, ctx)\n )\n : [{ text: props.text as string, ...baseRunFormatting(cascade) }];\n style = textBodyStyle(props, named, cascade);\n requireBulletFeatures(style.bullet, path, ctx);\n ctx.features.require('text', path);\n if (runs.length > 1) ctx.features.require('rich-text', path);\n }\n\n const hyperlink = compileHyperlink(props.hyperlink, 'shape', ctx, path);\n\n ctx.features.require('shapes', path);\n if (hyperlink) ctx.features.require('element-hyperlinks', path);\n const transform = shapeTransform(props, ctx);\n requireTransformFeatures(transform, path, 'shape', ctx);\n\n return {\n kind: 'shape',\n id: scope.id,\n path,\n transform,\n geometry,\n ...(fill ? { fill } : {}),\n ...(line ? { line } : {}),\n ...(shadow ? { shadow } : {}),\n ...(props.rectRadius !== undefined\n ? { cornerRadius: props.rectRadius as number }\n : {}),\n ...(props.angleRange !== undefined\n ? { angleRangeDegrees: props.angleRange as [number, number] }\n : {}),\n ...(runs ? { runs } : {}),\n ...(style ? { style } : {}),\n ...(hyperlink ? { hyperlink } : {}),\n };\n}\n\nfunction compileGeometry(type: unknown): PptxIrGeometry {\n const name = typeof type === 'string' ? type : '';\n const aliased = GEOMETRY_ALIASES[name] ?? name;\n return (PPTX_IR_GEOMETRY as readonly string[]).includes(aliased)\n ? (aliased as PptxIrKnownGeometry)\n : { custom: name };\n}\n\nfunction compileTextSegment(\n segment: TextSegment,\n cascade: FontCascade,\n ctx: CompileContext\n): PptxIrTextRun {\n const segmentWeight = (segment as TextSegment & { fontWeight?: number })\n .fontWeight;\n const effectiveWeight = segmentWeight ?? cascade.fontWeight;\n const effectiveBold = segment.bold ?? cascade.bold;\n const effectiveItalic = segment.italic ?? cascade.italic;\n\n let fontFamily = segment.fontFace ?? cascade.fontFamily;\n let bold = effectiveBold;\n let italic = effectiveItalic;\n\n if (\n segment.fontFace == null &&\n (effectiveWeight != null || effectiveBold === true)\n ) {\n const aliased = applyFontWeight({\n family: cascade.baseFamily,\n fontWeight: effectiveWeight,\n italic: effectiveItalic,\n bold: effectiveBold,\n });\n if (aliased.fontFace !== undefined) fontFamily = aliased.fontFace;\n if (aliased.bold !== undefined) bold = aliased.bold;\n if (aliased.italic !== undefined) italic = aliased.italic;\n }\n\n return {\n text: segment.text,\n fontFamily,\n fontSize: segment.fontSize ?? cascade.fontSize,\n color:\n segment.color != null\n ? irColor(resolveColor(segment.color, ctx.theme, ctx.warnings))\n : cascade.color,\n ...(bold != null ? { bold } : {}),\n ...(italic != null ? { italic } : {}),\n ...(segment.charSpacing != null\n ? { characterSpacing: segment.charSpacing }\n : cascade.characterSpacing != null\n ? { characterSpacing: cascade.characterSpacing }\n : {}),\n ...(segment.breakLine != null ? { breakAfter: segment.breakLine } : {}),\n ...(segment.spaceBefore != null\n ? { spaceBeforePoints: segment.spaceBefore }\n : {}),\n ...(segment.spaceAfter != null\n ? { spaceAfterPoints: segment.spaceAfter }\n : {}),\n };\n}\n\n/**\n * Position any absolutely-placed element.\n *\n * Unstated x, y and h are zero; unstated width falls back to\n * `defaultWidthEmu`, which is the width such an element has always been given.\n */\nfunction shapeTransform(\n props: Record<string, any>,\n ctx: CompileContext,\n options: { markAuto?: boolean } = {}\n): PptxIrTransform {\n const autoWidth = options.markAuto && props.w === undefined;\n const autoHeight = options.markAuto && props.h === undefined;\n return {\n ...(autoWidth ? { autoWidth: true } : {}),\n ...(autoHeight ? { autoHeight: true } : {}),\n xEmu:\n props.x !== undefined ? resolveDimensionEmu(props.x, 'X', ctx.extent) : 0,\n yEmu:\n props.y !== undefined ? resolveDimensionEmu(props.y, 'Y', ctx.extent) : 0,\n widthEmu:\n props.w !== undefined\n ? resolveDimensionEmu(props.w, 'X', ctx.extent)\n : defaultWidthEmu(ctx.extent),\n heightEmu:\n props.h !== undefined ? resolveDimensionEmu(props.h, 'Y', ctx.extent) : 0,\n ...rotationProperty(props.rotate),\n ...(props.flipH ? { flipHorizontal: true } : {}),\n ...(props.flipV ? { flipVertical: true } : {}),\n };\n}\n\n/** Omit full-turn rotations: they are identity, not a backend requirement. */\nfunction rotationProperty(\n value: unknown\n): Pick<PptxIrTransform, 'rotationDegrees'> {\n if (typeof value !== 'number' || value % 360 === 0) return {};\n return { rotationDegrees: value };\n}\n\n/**\n * Record the transform abilities an element actually uses.\n *\n * Rotation is split by element kind because backends differ: one may rotate a\n * shape but not a picture. Flips are separate for the same reason.\n */\nfunction requireTransformFeatures(\n transform: PptxIrTransform,\n path: string,\n kind: 'shape' | 'image',\n ctx: CompileContext\n): void {\n const transformed =\n transform.rotationDegrees !== undefined ||\n transform.flipHorizontal === true ||\n transform.flipVertical === true;\n if (!transformed) return;\n\n if (kind === 'image') {\n // A picture type that carries no rotation generally carries no flip\n // either, so one requirement covers both.\n ctx.features.require('image-transform', path);\n return;\n }\n\n if (transform.rotationDegrees !== undefined) {\n ctx.features.require('rotation', path);\n }\n if (transform.flipHorizontal) ctx.features.require('flip-horizontal', path);\n if (transform.flipVertical) ctx.features.require('flip-vertical', path);\n}\n\n/* ------------------------------------------------------------------ *\n * Images\n * ------------------------------------------------------------------ */\n\nfunction compileImage(\n component: PptxComponentInput,\n scope: ComponentScope\n): PptxIrElement | undefined {\n const { ctx, path } = scope;\n const props = component.props as Record<string, any>;\n\n const source = resolveImageSource(props);\n if (!source) {\n warn(\n ctx.warnings,\n W.IMAGE_NO_SOURCE,\n 'Image component missing path, base64, and svg',\n { component: 'image' }\n );\n return undefined;\n }\n\n const resourceId = internImageSource(source, path, ctx);\n if (resourceId === undefined) return undefined;\n\n const resource = ctx.resources.get(resourceId);\n ctx.features.require('images', path);\n if (resource?.mediaType === 'image/svg+xml') {\n ctx.features.require('svg', path);\n }\n\n const shadow = compileShadow(props.shadow, ctx);\n if (shadow) ctx.features.require('shadows', `${path}.shadow`);\n\n const hyperlink = compileHyperlink(props.hyperlink, 'image', ctx, path);\n if (hyperlink) ctx.features.require('element-hyperlinks', path);\n\n // An image with a sizing box and no stated extent takes its size from that\n // box; materialising a default width here would override it.\n const transform = shapeTransform(props, ctx, { markAuto: true });\n requireTransformFeatures(transform, path, 'image', ctx);\n\n const sizing = compileImageSizing(props.sizing, ctx);\n if (sizing) ctx.features.require('image-crop', `${path}.sizing`);\n if (props.rounding)\n ctx.features.require('image-rounding', `${path}.rounding`);\n\n return {\n kind: 'image',\n id: scope.id,\n path,\n transform,\n resourceId,\n ...(sizing ? { sizing } : {}),\n ...(props.rounding ? { rounding: true } : {}),\n ...(shadow ? { shadow } : {}),\n ...(hyperlink ? { hyperlink } : {}),\n ...(props.alt ? { altText: props.alt as string } : {}),\n };\n}\n\n/**\n * Turn a resolved image source string into a resource id.\n *\n * Data URIs are decoded to bytes here so identical inline images collapse to a\n * single resource. File paths keep the same allowed-root policy the pre-IR\n * pipeline enforced, and are rejected — with a warning, not silently — when\n * they escape it.\n */\nfunction internImageSource(\n source: string,\n path: string,\n ctx: CompileContext\n): string | undefined {\n const inline = parseDataUri(source);\n if (inline) {\n return ctx.resources.intern({\n kind: 'inline',\n bytes: inline.bytes,\n mediaType: inline.mediaType,\n });\n }\n\n if (/^https?:\\/\\//.test(source)) {\n return ctx.resources.intern({\n kind: 'remote',\n url: source,\n ...(mediaTypeFromLocation(source)\n ? { mediaType: mediaTypeFromLocation(source) }\n : {}),\n });\n }\n\n const resolved = safeLocalPath(source);\n if (resolved === undefined) {\n warn(\n ctx.warnings,\n W.IMAGE_PATH_OUTSIDE_ROOTS,\n `Image path resolves outside the document base directory: ${source}`,\n { component: 'image' }\n );\n return undefined;\n }\n void path;\n return ctx.resources.intern({\n kind: 'file',\n path: resolved,\n ...(mediaTypeFromLocation(resolved)\n ? { mediaType: mediaTypeFromLocation(resolved) }\n : {}),\n });\n}\n\n/**\n * Carry an image's sizing through to the IR.\n *\n * `contain` never reaches here: `resolveImageLayout` fits and centres the\n * element itself and drops the sizing, because the box has already been\n * honoured by the transform.\n */\nfunction compileImageSizing(\n sizing:\n | {\n type?: string;\n w?: number | string;\n h?: number | string;\n x?: number | string;\n y?: number | string;\n }\n | undefined,\n ctx: CompileContext\n): PptxIrImageSizing | undefined {\n if (!sizing?.type) return undefined;\n const type =\n sizing.type === 'cover'\n ? 'cover'\n : sizing.type === 'contain'\n ? 'contain'\n : 'crop';\n return {\n type,\n widthEmu: resolveDimensionEmu(sizing.w ?? 0, 'X', ctx.extent),\n heightEmu: resolveDimensionEmu(sizing.h ?? 0, 'Y', ctx.extent),\n ...(sizing.x !== undefined\n ? { xEmu: resolveDimensionEmu(sizing.x, 'X', ctx.extent) }\n : {}),\n ...(sizing.y !== undefined\n ? { yEmu: resolveDimensionEmu(sizing.y, 'Y', ctx.extent) }\n : {}),\n };\n}\n\n/* ------------------------------------------------------------------ *\n * Tables\n * ------------------------------------------------------------------ */\n\n/**\n * Characters PowerPoint may promote to colour emoji.\n *\n * Appending VS15 (U+FE0E) forces text presentation. This is a property of how\n * the *format* is rendered, not of any one backend, so it belongs here rather\n * than in an adapter.\n */\nconst EMOJI_PRONE_CHARS = /[✓✔✗✘☐☑☒★☆●○■□▶◀▲▼⚡⚠❌❓❗]/gu;\n\nfunction forceTextPresentation(text: string): string {\n return text.replace(EMOJI_PRONE_CHARS, (char) => `${char}\\uFE0E`);\n}\n\ninterface AuthoredTableCell {\n text: string;\n color?: string;\n fill?: string;\n fontSize?: number;\n fontFace?: string;\n bold?: boolean;\n fontWeight?: number;\n italic?: boolean;\n align?: string;\n valign?: string;\n colspan?: number;\n rowspan?: number;\n margin?: number | number[];\n}\n\nfunction compileTable(\n component: PptxComponentInput,\n scope: ComponentScope\n): PptxIrElement | undefined {\n const { ctx, path } = scope;\n const props = component.props as Record<string, any>;\n const authoredRows = (props.rows ?? []) as Array<\n Array<string | AuthoredTableCell>\n >;\n\n const defaults = compileTableDefaults(props, ctx);\n const rows: PptxIrTableRow[] = authoredRows.map((row) => ({\n cells: row.map((cell) => compileTableCell(cell, props, ctx)),\n }));\n\n const border = compileTableBorder(props.border, ctx);\n const cornerRadius =\n typeof props.borderRadius === 'number' && props.borderRadius > 0\n ? props.borderRadius\n : undefined;\n\n ctx.features.require('tables', path);\n if (\n rows.some((row) =>\n row.cells.some((cell) => cell.colSpan != null || cell.rowSpan != null)\n )\n ) {\n ctx.features.require('table-merged-cells', path);\n }\n if (cornerRadius !== undefined) {\n ctx.features.require('table-rounded-corners', `${path}.borderRadius`);\n }\n if (props.autoPage) {\n ctx.features.require('table-auto-page', `${path}.autoPage`);\n }\n if (props.autoPageRepeatHeader) {\n ctx.features.require('table-auto-page', `${path}.autoPageRepeatHeader`);\n }\n if (defaults.insetPoints !== undefined) {\n ctx.features.require('table-insets', `${path}.margin`);\n }\n rows.forEach((row, rowIndex) =>\n row.cells.forEach((cell, cellIndex) => {\n if (cell.formatting?.insetPoints !== undefined) {\n ctx.features.require(\n 'table-insets',\n `${path}.rows[${rowIndex}][${cellIndex}].margin`\n );\n }\n })\n );\n\n const element: PptxIrTableElement = {\n kind: 'table',\n id: scope.id,\n path,\n transform: tableTransform(props, ctx),\n rows,\n columnWidthsEmu: toEmuList(props.colW, 'X', ctx),\n rowHeightsEmu: toEmuList(props.rowH, 'Y', ctx),\n defaults,\n ...(border ? { border } : {}),\n ...(props.fill\n ? { fill: irColor(resolveColor(props.fill, ctx.theme, ctx.warnings)) }\n : {}),\n ...(cornerRadius !== undefined ? { cornerRadiusInches: cornerRadius } : {}),\n ...(props.autoPage ? { autoPage: true } : {}),\n ...(props.autoPageRepeatHeader ? { autoPageRepeatHeader: true } : {}),\n };\n return element;\n}\n\n/**\n * Table geometry.\n *\n * Width and height are marked auto when the author states neither, because an\n * OOXML table sizes from its columns and rows. Position resolves through the\n * same rule every other element uses — the pre-IR pipeline applied a different\n * inch/EMU threshold to tables than to shapes, which is a backend detail, not\n * an authoring rule (see docs/architecture/office-renderer-ir.md).\n */\nfunction tableTransform(\n props: Record<string, any>,\n ctx: CompileContext\n): PptxIrTransform {\n const hasWidth = props.w !== undefined;\n const hasHeight = props.h !== undefined;\n return {\n xEmu:\n props.x !== undefined ? resolveDimensionEmu(props.x, 'X', ctx.extent) : 0,\n yEmu:\n props.y !== undefined ? resolveDimensionEmu(props.y, 'Y', ctx.extent) : 0,\n widthEmu: hasWidth\n ? resolveDimensionEmu(props.w, 'X', ctx.extent)\n : defaultWidthEmu(ctx.extent),\n heightEmu: hasHeight ? resolveDimensionEmu(props.h, 'Y', ctx.extent) : 0,\n ...(hasWidth ? {} : { autoWidth: true }),\n ...(hasHeight ? {} : { autoHeight: true }),\n };\n}\n\nfunction toEmuList(\n value: number | number[] | undefined,\n axis: 'X' | 'Y',\n ctx: CompileContext\n): number[] {\n if (value === undefined) return [];\n const values = Array.isArray(value) ? value : [value];\n return values.map((v) => resolveDimensionEmu(v, axis, ctx.extent));\n}\n\nfunction compileTableDefaults(\n props: Record<string, any>,\n ctx: CompileContext\n): PptxIrTableFormatting {\n const family = (props.fontFace as string | undefined) ?? ctx.theme.fonts.body;\n let fontFamily = family;\n let bold: boolean | undefined;\n\n if (props.fontWeight != null) {\n const aliased = applyFontWeight({\n family,\n fontWeight: props.fontWeight as number,\n });\n if (aliased.fontFace !== undefined) fontFamily = aliased.fontFace;\n // Only ever true: a table-level `bold: false` is inert, because the cell\n // cascade ignores falsy table options.\n if (aliased.bold === true) bold = true;\n }\n\n return {\n fontFamily,\n fontSize:\n (props.fontSize as number | undefined) ?? ctx.theme.defaults.fontSize,\n ...(bold !== undefined ? { bold } : {}),\n ...(props.color\n ? { color: irColor(resolveColor(props.color, ctx.theme, ctx.warnings)) }\n : {}),\n ...(props.align\n ? { align: props.align as PptxIrTableFormatting['align'] }\n : {}),\n verticalAlign: (props.valign ??\n 'middle') as PptxIrTableFormatting['verticalAlign'],\n ...(props.margin !== undefined\n ? { insetPoints: props.margin as PptxIrTableFormatting['insetPoints'] }\n : {}),\n };\n}\n\nfunction compileTableCell(\n cell: string | AuthoredTableCell,\n tableProps: Record<string, any>,\n ctx: CompileContext\n): PptxIrTableCell {\n if (typeof cell === 'string') {\n return { text: forceTextPresentation(cell) };\n }\n\n const formatting: PptxIrTableCellFormatting = {};\n if (cell.color) {\n formatting.color = irColor(\n resolveColor(cell.color, ctx.theme, ctx.warnings)\n );\n }\n if (cell.fontSize) formatting.fontSize = cell.fontSize;\n if (cell.fontFace) formatting.fontFamily = cell.fontFace;\n // `!== undefined`, not truthiness: a table-level weight sets bold on every\n // cell that stays silent, so a cell meaning `false` has to say so.\n if (cell.bold !== undefined) formatting.bold = cell.bold;\n if (cell.italic) formatting.italic = true;\n\n if (cell.fontWeight != null || cell.bold !== undefined) {\n const aliased = applyFontWeight({\n family:\n cell.fontFace ??\n (tableProps.fontFace as string | undefined) ??\n ctx.theme.fonts.body,\n fontWeight: cell.fontWeight,\n italic: cell.italic,\n bold: cell.bold,\n });\n if (aliased.fontFace !== undefined)\n formatting.fontFamily = aliased.fontFace;\n if (aliased.bold !== undefined) formatting.bold = aliased.bold;\n if (aliased.italic !== undefined) formatting.italic = aliased.italic;\n }\n\n if (cell.align) {\n formatting.align = cell.align as PptxIrTableCellFormatting['align'];\n }\n if (cell.valign) {\n formatting.verticalAlign =\n cell.valign as PptxIrTableCellFormatting['verticalAlign'];\n }\n if (cell.margin !== undefined) {\n formatting.insetPoints =\n cell.margin as PptxIrTableCellFormatting['insetPoints'];\n }\n\n return {\n text: forceTextPresentation(cell.text),\n ...(Object.keys(formatting).length > 0 ? { formatting } : {}),\n ...(cell.fill\n ? { fill: irColor(resolveColor(cell.fill, ctx.theme, ctx.warnings)) }\n : {}),\n ...(cell.colspan !== undefined && cell.colspan > 1\n ? { colSpan: cell.colspan }\n : {}),\n ...(cell.rowspan !== undefined && cell.rowspan > 1\n ? { rowSpan: cell.rowspan }\n : {}),\n };\n}\n\nfunction compileTableBorder(\n border: { type?: string; pt?: number; color?: string } | undefined,\n ctx: CompileContext\n): PptxIrTableBorder | undefined {\n if (!border) return undefined;\n return {\n type: (border.type ?? 'solid') as PptxIrTableBorder['type'],\n widthPoints: border.pt ?? 1,\n color: irColor(\n resolveColor(border.color ?? '000000', ctx.theme, ctx.warnings)\n ),\n };\n}\n\n/* ------------------------------------------------------------------ *\n * Charts\n * ------------------------------------------------------------------ */\n\nconst CHART_TYPES: readonly PptxIrChartType[] = [\n 'area',\n 'bar',\n 'bar3D',\n 'bubble',\n 'doughnut',\n 'line',\n 'pie',\n 'radar',\n 'scatter',\n];\n\ninterface AuthoredChartSeries {\n name?: string;\n labels?: string[];\n values?: number[];\n sizes?: number[];\n}\n\nfunction compileChart(\n component: PptxComponentInput,\n scope: ComponentScope\n): PptxIrElement | undefined {\n const { ctx, path } = scope;\n const props = component.props as Record<string, any>;\n\n const chartType = (CHART_TYPES as readonly string[]).includes(props.type)\n ? (props.type as PptxIrChartType)\n : undefined;\n if (!chartType) {\n warn(\n ctx.warnings,\n W.UNKNOWN_CHART_TYPE,\n `Unknown chart type: ${props.type}`,\n {\n component: 'chart',\n }\n );\n return undefined;\n }\n\n const authored = (props.data ?? []) as AuthoredChartSeries[];\n if (authored.length === 0) {\n warn(ctx.warnings, W.CHART_NO_DATA, 'Chart component has no data series', {\n component: 'chart',\n });\n return undefined;\n }\n for (const series of authored) {\n if (!series.labels || !series.values) {\n warn(\n ctx.warnings,\n W.CHART_INVALID_SERIES,\n `Chart series \"${series.name ?? '(unnamed)'}\" missing labels or values`,\n { component: 'chart' }\n );\n return undefined;\n }\n }\n if (\n (chartType === 'pie' || chartType === 'doughnut') &&\n authored.length > 1\n ) {\n warn(\n ctx.warnings,\n W.CHART_MULTI_SERIES,\n `${props.type} chart has ${authored.length} series — only the first will render`,\n { component: 'chart' }\n );\n }\n\n ctx.features.require('charts', path);\n\n return {\n kind: 'chart',\n id: scope.id,\n path,\n transform: shapeTransform(props, ctx),\n chartType,\n series: authored.map((series) => ({\n ...(series.name !== undefined ? { name: series.name } : {}),\n ...(series.labels ? { labels: series.labels } : {}),\n ...(series.values ? { values: series.values } : {}),\n ...(series.sizes ? { sizes: series.sizes } : {}),\n })),\n options: compileChartOptions(props, ctx),\n };\n}\n\n/**\n * Resolve a chart label font.\n *\n * PowerPoint chart labels carry no numeric weight, so a non-RIBBI weight only\n * survives as a synthesized sub-family (\"Inter\" at 300 → \"Inter Light\");\n * 400/700 stay on the family and use the slot's bold toggle. `hasBoldToggle`\n * is false for the legend, which has none — a weight that would need one is\n * reported rather than silently rendered as Regular.\n */\nfunction compileChartLabelFont(\n ctx: CompileContext,\n slot: string,\n face: string | undefined,\n weight: number | undefined,\n hasBoldToggle: boolean,\n extra: {\n fontSize?: number;\n color?: PptxIrColor;\n /** Bold set alongside the weight; an explicit weight overrides it. */\n boldFallback?: boolean;\n } = {}\n): PptxIrChartLabelFont {\n const { boldFallback, ...rest } = extra;\n const font: PptxIrChartLabelFont = { ...rest };\n if (boldFallback !== undefined) font.bold = boldFallback;\n\n if (weight === undefined) {\n if (face !== undefined) font.fontFamily = face;\n return font;\n }\n\n const aliased = applyFontWeight({\n family: face ?? ctx.theme.fonts?.body,\n fontWeight: weight,\n });\n if (aliased.fontFace !== undefined) font.fontFamily = aliased.fontFace;\n if (hasBoldToggle) {\n // Assign even when false: an explicit weight has to win over a bold\n // toggle set alongside it.\n font.bold = aliased.bold === true;\n } else if (aliased.bold === true) {\n warn(\n ctx.warnings,\n W.CHART_FONT_WEIGHT_DROPPED,\n `Chart ${slot} weight ${weight} renders as Regular — PowerPoint gives the legend no bold toggle, and only non-RIBBI weights resolve to a sub-family face`,\n { component: 'chart' }\n );\n }\n return font;\n}\n\nfunction compileChartOptions(\n props: Record<string, any>,\n ctx: CompileContext\n): PptxIrChartOptions {\n // Author-supplied colours keep the loud fallback for an undefined token; the\n // implicit palette skips tokens the theme leaves unset or unresolvable, which\n // is what DOCX does too. An empty list stays empty so the backend uses its\n // own — a zero-length palette would paint every series black.\n const colorSources: string[] =\n props.chartColors ?? definedChartColorTokens(ctx.theme);\n const colors = colorSources.map((color) =>\n resolveColor(color, ctx.theme, ctx.warnings).toUpperCase()\n );\n\n const themeTextColor = irColor(resolveColor('text', ctx.theme, ctx.warnings));\n const resolved = (value: string | undefined): PptxIrColor =>\n value\n ? irColor(resolveColor(value, ctx.theme, ctx.warnings))\n : themeTextColor;\n\n return {\n colors,\n\n ...pick(props, {\n showLegend: 'showLegend',\n showTitle: 'showTitle',\n showValue: 'showValue',\n showPercent: 'showPercent',\n showLabel: 'showLabel',\n showSeriesName: 'showSerName',\n }),\n\n ...(props.title !== undefined ? { title: props.title as string } : {}),\n titleFont: compileChartLabelFont(\n ctx,\n 'titleFontFace',\n props.titleFontFace,\n props.titleFontWeight,\n true,\n {\n ...(props.titleFontSize !== undefined\n ? { fontSize: props.titleFontSize as number }\n : {}),\n color: resolved(props.titleColor),\n }\n ),\n\n ...(props.legendPos !== undefined\n ? { legendPosition: props.legendPos as string }\n : {}),\n legendFont: compileChartLabelFont(\n ctx,\n 'legendFontFace',\n props.legendFontFace,\n props.legendFontWeight,\n false,\n {\n ...(props.legendFontSize !== undefined\n ? { fontSize: props.legendFontSize as number }\n : {}),\n color: resolved(props.legendColor),\n }\n ),\n\n categoryAxis: {\n ...(props.catAxisTitle !== undefined\n ? { title: props.catAxisTitle as string }\n : {}),\n ...(props.catAxisHidden !== undefined\n ? { hidden: props.catAxisHidden as boolean }\n : {}),\n ...(props.catAxisLabelRotate !== undefined\n ? { labelRotate: props.catAxisLabelRotate as number }\n : {}),\n ...(props.catAxisLineShow !== undefined\n ? { showLine: props.catAxisLineShow as boolean }\n : {}),\n ...(props.catGridLine !== undefined\n ? { gridLine: compileGridLine(props.catGridLine, ctx) }\n : {}),\n labelFont: compileChartLabelFont(\n ctx,\n 'catAxisLabelFontFace',\n props.catAxisLabelFontFace,\n props.catAxisLabelFontWeight,\n true,\n {\n ...(props.catAxisLabelFontSize !== undefined\n ? { fontSize: props.catAxisLabelFontSize as number }\n : {}),\n color: resolved(props.catAxisLabelColor),\n }\n ),\n },\n\n valueAxis: {\n ...(props.valAxisTitle !== undefined\n ? { title: props.valAxisTitle as string }\n : {}),\n ...(props.valAxisHidden !== undefined\n ? { hidden: props.valAxisHidden as boolean }\n : {}),\n ...(props.valAxisMinVal !== undefined\n ? { minValue: props.valAxisMinVal as number }\n : {}),\n ...(props.valAxisMaxVal !== undefined\n ? { maxValue: props.valAxisMaxVal as number }\n : {}),\n ...(props.valAxisMajorUnit !== undefined\n ? { majorUnit: props.valAxisMajorUnit as number }\n : {}),\n ...(props.valAxisLabelFormatCode !== undefined\n ? { labelFormatCode: props.valAxisLabelFormatCode as string }\n : {}),\n ...(props.valAxisLineShow !== undefined\n ? { showLine: props.valAxisLineShow as boolean }\n : {}),\n ...(props.valGridLine !== undefined\n ? { gridLine: compileGridLine(props.valGridLine, ctx) }\n : {}),\n labelFont: compileChartLabelFont(\n ctx,\n 'valAxisLabelFontFace',\n props.valAxisLabelFontFace,\n props.valAxisLabelFontWeight,\n true,\n {\n ...(props.valAxisLabelFontSize !== undefined\n ? { fontSize: props.valAxisLabelFontSize as number }\n : {}),\n color: resolved(props.valAxisLabelColor),\n }\n ),\n },\n\n ...(props.dataBorder !== undefined\n ? {\n dataBorder: {\n widthPoints: props.dataBorder.pt as number,\n color: irColor(\n resolveColor(props.dataBorder.color, ctx.theme, ctx.warnings)\n ),\n },\n }\n : {}),\n dataLabelFont: compileChartLabelFont(\n ctx,\n 'dataLabelFontFace',\n props.dataLabelFontFace,\n props.dataLabelFontWeight,\n true,\n {\n ...(props.dataLabelFontSize !== undefined\n ? { fontSize: props.dataLabelFontSize as number }\n : {}),\n color: resolved(props.dataLabelColor),\n ...(props.dataLabelFontBold !== undefined\n ? { boldFallback: props.dataLabelFontBold as boolean }\n : {}),\n }\n ),\n ...(props.dataLabelPosition !== undefined\n ? { dataLabelPosition: props.dataLabelPosition as string }\n : {}),\n\n ...pick(props, {\n barDirection: 'barDir',\n barGrouping: 'barGrouping',\n barGapWidthPercent: 'barGapWidthPct',\n barOverlapPercent: 'barOverlapPct',\n lineSmooth: 'lineSmooth',\n lineDataSymbol: 'lineDataSymbol',\n lineSize: 'lineSize',\n lineDataSymbolSize: 'lineDataSymbolSize',\n firstSliceAngle: 'firstSliceAng',\n holeSize: 'holeSize',\n radarStyle: 'radarStyle',\n }),\n };\n}\n\n/** Copy authored props onto IR names, skipping anything the author omitted. */\nfunction pick(\n props: Record<string, any>,\n mapping: Record<string, string>\n): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const [irName, authoredName] of Object.entries(mapping)) {\n if (props[authoredName] !== undefined) out[irName] = props[authoredName];\n }\n return out;\n}\n\nfunction compileGridLine(\n gridLine: { style?: string; size?: number; color?: string },\n ctx: CompileContext\n): PptxIrChartGridLine {\n return {\n ...(gridLine.style !== undefined ? { style: gridLine.style } : {}),\n ...(gridLine.size !== undefined ? { size: gridLine.size } : {}),\n ...(gridLine.color !== undefined\n ? {\n color: irColor(resolveColor(gridLine.color, ctx.theme, ctx.warnings)),\n }\n : {}),\n };\n}\n\n/* ------------------------------------------------------------------ *\n * Shared: fills, lines, shadows, hyperlinks, backgrounds\n * ------------------------------------------------------------------ */\n\nfunction compileBackground(\n background:\n | {\n color?: string;\n gradient?: unknown;\n image?: { path?: string; base64?: string };\n }\n | undefined,\n path: string,\n ctx: CompileContext\n): PptxIrBackground | undefined {\n if (!background) return undefined;\n\n if (background.color) {\n return {\n kind: 'solid',\n color: irColor(resolveColor(background.color, ctx.theme, ctx.warnings)),\n };\n }\n\n if (background.image) {\n const source = resolveImageSource(background.image);\n if (!source) return undefined;\n const resourceId = internImageSource(source, path, ctx);\n return resourceId === undefined ? undefined : { kind: 'image', resourceId };\n }\n\n return undefined;\n}\n\nfunction compileFill(\n fill:\n | {\n color?: string;\n transparency?: number;\n gradient?: unknown;\n pattern?: { preset: string; foreground: string; background: string };\n }\n | undefined,\n path: string,\n ctx: CompileContext\n): PptxIrFill | undefined {\n if (!fill) return undefined;\n\n let gradient = fill.gradient;\n let pattern = fill.pattern;\n\n if (gradient && pattern) {\n warn(\n ctx.warnings,\n W.ADVANCED_FILL_FALLBACK,\n 'Shape fill sets both \"gradient\" and \"pattern\" — using the gradient',\n { component: 'shape' }\n );\n pattern = undefined;\n }\n\n let unknownPresetForeground: string | undefined;\n if (\n pattern &&\n !(PATTERN_FILL_PRESETS as readonly string[]).includes(pattern.preset)\n ) {\n warn(\n ctx.warnings,\n W.UNKNOWN_PATTERN_PRESET,\n `Unknown pattern preset \"${pattern.preset}\" — falling back to solid foreground`,\n { component: 'shape' }\n );\n unknownPresetForeground = pattern.foreground;\n pattern = undefined;\n }\n\n if (gradient) {\n const compiled = compileGradient(gradient, path, ctx);\n if (compiled) return { kind: 'gradient', gradient: compiled };\n }\n\n if (pattern) {\n return {\n kind: 'pattern',\n preset: pattern.preset,\n foreground: irColor(\n resolveColor(pattern.foreground, ctx.theme, ctx.warnings)\n ),\n background: irColor(\n resolveColor(pattern.background, ctx.theme, ctx.warnings)\n ),\n };\n }\n\n const solid = fill.color ?? unknownPresetForeground;\n if (solid === undefined) return undefined;\n return {\n kind: 'solid',\n color: irColor(\n resolveColor(solid, ctx.theme, ctx.warnings),\n fill.transparency\n ),\n };\n}\n\nfunction compileSolidFillFromProps(\n fill: { color: string; transparency?: number },\n path: string,\n ctx: CompileContext\n): PptxIrFill | undefined {\n void path;\n return {\n kind: 'solid',\n color: irColor(\n resolveColor(fill.color, ctx.theme, ctx.warnings),\n fill.transparency\n ),\n };\n}\n\nfunction requireFillFeature(\n fill: PptxIrFill,\n path: string,\n ctx: CompileContext\n): void {\n switch (fill.kind) {\n case 'solid':\n ctx.features.require('solid-fills', path);\n return;\n case 'gradient':\n ctx.features.require('gradient-fills', path);\n return;\n case 'pattern':\n ctx.features.require('pattern-fills', path);\n return;\n case 'image':\n ctx.features.require('image-fills', path);\n return;\n case 'none':\n return;\n }\n}\n\nfunction compileGradient(\n gradient: unknown,\n path: string,\n ctx: CompileContext\n): PptxIrGradient | undefined {\n if (!gradient || typeof gradient !== 'object') return undefined;\n const source = gradient as {\n type?: string;\n angle?: number;\n focus?: string;\n stops?: Array<{ color: string; pos: number; transparency?: number }>;\n };\n const stops = (source.stops ?? []).map((stop) => ({\n position: stop.pos,\n color: irColor(\n resolveColor(stop.color, ctx.theme, ctx.warnings),\n stop.transparency\n ),\n }));\n if (stops.length === 0) {\n warn(\n ctx.warnings,\n W.ADVANCED_FILL_FALLBACK,\n `Gradient at ${path} has no stops — ignored`,\n { component: 'shape' }\n );\n return undefined;\n }\n\n if (source.type === 'radial') {\n return {\n type: 'radial',\n focus: (source.focus ?? 'center') as PptxIrGradient extends {\n focus: infer F;\n }\n ? F\n : never,\n stops,\n } as PptxIrGradient;\n }\n\n return {\n type: 'linear',\n angleDegrees: normalizeDegrees(source.angle ?? 0),\n stops,\n };\n}\n\nfunction compileLine(\n line: { color?: string; width?: number; dashType?: string } | undefined,\n ctx: CompileContext\n): PptxIrLine | undefined {\n if (!line) return undefined;\n const compiled: PptxIrLine = {};\n if (line.color) {\n compiled.color = irColor(resolveColor(line.color, ctx.theme, ctx.warnings));\n }\n if (line.width !== undefined) compiled.widthPoints = line.width;\n if (line.dashType) compiled.dash = line.dashType as PptxIrLine['dash'];\n // An empty `line: {}` is an authored request for the format's default\n // outline, which is not the same as no outline at all.\n return compiled;\n}\n\nfunction compileShadow(\n shadow:\n | {\n type?: string;\n color?: string;\n blur?: number;\n offset?: number;\n angle?: number;\n opacity?: number;\n }\n | undefined,\n ctx: CompileContext\n): PptxIrShadow | undefined {\n if (!shadow) return undefined;\n return {\n type: (shadow.type ?? 'outer') as PptxIrShadow['type'],\n color: irColor(\n resolveColor(shadow.color ?? '000000', ctx.theme, ctx.warnings)\n ),\n blurPoints: shadow.blur ?? 3,\n offsetPoints: shadow.offset ?? 3,\n angleDegrees: shadow.angle ?? 45,\n opacity: shadow.opacity ?? 0.5,\n };\n}\n\n/**\n * Compile a hyperlink, dropping unresolvable slide refs with a warning.\n *\n * An unresolved ref must never reach a renderer: it would emit a relationship\n * to a slide part that is not in the archive, which PowerPoint reports as a\n * damaged file.\n */\nfunction compileHyperlink(\n hyperlink: HyperlinkProps | undefined,\n componentName: string,\n ctx: CompileContext,\n path: string\n): PptxIrHyperlink | undefined {\n if (!hyperlink) return undefined;\n\n if (hyperlink.url) {\n ctx.features.require('external-links', path);\n return {\n kind: 'external',\n url: hyperlink.url,\n ...(hyperlink.tooltip ? { tooltip: hyperlink.tooltip } : {}),\n };\n }\n\n if (hyperlink.unresolvedSlideRef != null) {\n // HYPERLINK_SLIDE_UNRESOLVED lives outside the `W` registry (it is owned by\n // utils/hyperlink.ts), so push it the same way `applyHyperlink` does.\n ctx.warnings.push({\n code: HYPERLINK_SLIDE_UNRESOLVED,\n message:\n `hyperlink.slide ${hyperlink.unresolvedSlideRef} matches no slide in the generated ` +\n `presentation (slide disabled, or index out of range) — hyperlink dropped`,\n component: componentName,\n });\n return undefined;\n }\n\n if (hyperlink.slide) {\n ctx.features.require('internal-links', path);\n return {\n kind: 'slide',\n slideIndex: hyperlink.slide,\n ...(hyperlink.tooltip ? { tooltip: hyperlink.tooltip } : {}),\n };\n }\n\n return undefined;\n}\n\nfunction optionalTransform(\n x: number | undefined,\n y: number | undefined,\n w: number | undefined,\n h: number | undefined,\n ctx: CompileContext\n): PptxIrTransform | undefined {\n if (x == null && y == null && w == null && h == null) return undefined;\n return {\n xEmu: inchesToEmu(x ?? 0),\n yEmu: inchesToEmu(y ?? 0),\n widthEmu: w != null ? inchesToEmu(w) : defaultWidthEmu(ctx.extent),\n heightEmu: h != null ? inchesToEmu(h) : 0,\n };\n}\n","/**\n * Color utilities for PPTX generation.\n * pptxgenjs expects bare 6-char hex (e.g. 'FF0000'), but our theme\n * convention uses '#'-prefixed values (e.g. '#FF0000').\n */\n\nimport type { PptxThemeConfig, PipelineWarning } from '../types';\nimport { SEMANTIC_COLOR_NAMES } from '@json-to-office/shared-pptx';\nimport { DEFAULT_CHART_THEME_COLORS } from '@json-to-office/shared';\nimport { warn, W } from './warn';\n\n// Build identity entries from the shared source of truth, then add aliases\nconst SEMANTIC_TO_THEME_KEY: Record<string, keyof PptxThemeConfig['colors']> = {\n ...Object.fromEntries(SEMANTIC_COLOR_NAMES.map((n) => [n, n])),\n // Aliases (PowerPoint XML compat)\n accent1: 'primary',\n accent2: 'secondary',\n accent3: 'accent',\n tx1: 'text',\n tx2: 'text2',\n bg1: 'background',\n bg2: 'background2',\n};\n\n/**\n * Default series-color tokens for charts, used by the native `chart` component\n * and the `highcharts` component. Defined in @json-to-office/shared so the DOCX\n * `highcharts` component resolves the same tokens; re-exported here because\n * every PPTX call site already imports colors from this module.\n */\nexport { DEFAULT_CHART_THEME_COLORS };\n\n/**\n * Follow a stored theme color value to bare hex, or undefined when it never\n * reaches one. The theme schema lets a slot name another slot\n * (`\"accent4\": \"primary\"`), so a stored value is only a color once the\n * reference chain has been walked — without this, `accent4` resolved to the\n * literal string `primary` and pptxgenjs silently painted the series black.\n *\n * Mirrors DOCX `toChartColor`/`resolveColor` (core-docx colorUtils) on casing:\n * the stored value passes through verbatim when it is already hex, and anything\n * reached by following a reference is normalized to uppercase. Two deliberate\n * divergences: `seen` turns a reference cycle into \"unresolvable\" instead of the\n * stack overflow the DOCX version would hit, and 3-char shorthand is expanded\n * here but not by DOCX, so `\"accent4\": \"#abc\"` fills the slot in a deck and\n * drops it in a document.\n */\nfunction chainToHex(\n value: string,\n theme: PptxThemeConfig,\n seen: Set<string>\n): string | undefined {\n const bare = value.startsWith('#') ? value.slice(1) : value;\n if (/^[0-9A-Fa-f]{6}$/.test(bare)) return bare;\n // Expand 3-char hex shorthand (e.g. 'FFF' → 'FFFFFF')\n if (/^[0-9A-Fa-f]{3}$/.test(bare)) {\n return bare[0] + bare[0] + bare[1] + bare[1] + bare[2] + bare[2];\n }\n const themeKey = SEMANTIC_TO_THEME_KEY[value];\n if (!themeKey || seen.has(themeKey)) return undefined;\n seen.add(themeKey);\n const next = theme?.colors?.[themeKey];\n if (typeof next !== 'string' || next.length === 0) return undefined;\n return chainToHex(next, theme, seen)?.toUpperCase();\n}\n\n/**\n * The default chart palette narrowed to the tokens this theme actually defines\n * *and* can resolve to a color. Both PPTX chart paths build their implicit\n * palette from this, so an unset accent4-6 is skipped — matching DOCX — instead\n * of resolving to `primary` six times over, and a slot holding an unresolvable\n * value is dropped rather than posted as `#primary`. Author-supplied colors must\n * NOT go through here: naming an undefined token stays a loud `resolveColor`\n * fallback + warning.\n */\nexport function definedChartColorTokens(theme: PptxThemeConfig): string[] {\n const colors = theme?.colors as\n | Record<string, string | undefined>\n | undefined;\n if (!colors) return [];\n return DEFAULT_CHART_THEME_COLORS.filter((token) => {\n const themeKey = SEMANTIC_TO_THEME_KEY[token] ?? token;\n const value = colors[themeKey];\n if (typeof value !== 'string' || value.length === 0) return false;\n return chainToHex(value, theme, new Set([themeKey])) !== undefined;\n });\n}\n\n/**\n * Resolve a color value to bare hex (no '#' prefix).\n * Accepts hex colors (with or without '#') or semantic theme color names.\n */\nexport function resolveColor(\n color: string,\n theme: PptxThemeConfig,\n warnings?: PipelineWarning[]\n): string {\n const themeKey = SEMANTIC_TO_THEME_KEY[color];\n if (themeKey) {\n const resolved = theme.colors[themeKey];\n if (resolved) {\n const hex = chainToHex(resolved, theme, new Set([themeKey]));\n if (hex) return hex;\n // Defined but not a color (e.g. a name reference that goes nowhere).\n // Never hand the literal on to pptxgenjs — it renders black in silence.\n warn(\n warnings,\n W.UNKNOWN_COLOR,\n `Theme color \"${themeKey}\" is \"${resolved}\", which is not a hex color or a theme color name; falling back to primary`\n );\n return resolvePrimary(theme);\n }\n // Fall back to primary for unset optional colors\n warn(\n warnings,\n W.THEME_COLOR_FALLBACK,\n `Theme color \"${themeKey}\" not defined, falling back to primary`\n );\n return resolvePrimary(theme);\n }\n // Not a semantic name — treat as literal hex\n const bare = color.startsWith('#') ? color.slice(1) : color;\n // Expand 3-char hex shorthand (e.g. 'FFF' → 'FFFFFF')\n if (/^[0-9A-Fa-f]{3}$/.test(bare)) {\n return bare[0] + bare[0] + bare[1] + bare[1] + bare[2] + bare[2];\n }\n if (!/^[0-9A-Fa-f]{6}$/.test(bare)) {\n warn(\n warnings,\n W.UNKNOWN_COLOR,\n `Unknown color value: \"${color}\", treating as literal`\n );\n }\n return bare;\n}\n\n/** The `primary` fallback, itself chain-resolved so it can't leak a token name. */\nfunction resolvePrimary(theme: PptxThemeConfig): string {\n const primary = theme.colors.primary;\n return (\n chainToHex(primary, theme, new Set(['primary'])) ??\n (primary.startsWith('#') ? primary.slice(1) : primary)\n );\n}\n","/**\n * Resolve (family, weight, italic) into the PPTX run's final `(fontFace,\n * bold, italic)` triple. Non-RIBBI weights are rewritten to synthetic\n * sub-family names (e.g. \"Inter Light\") so PowerPoint / LibreOffice can\n * resolve the matching installed face; RIBBI stays on the canonical\n * family and uses native bold/italic toggles.\n *\n * Mirrors the DOCX `applyFontWeightAlias` helper so both cores coerce\n * fontWeight identically.\n */\n\nimport { synthesizeFamilyName } from '@json-to-office/shared';\n\nexport function applyFontWeight(params: {\n family?: string;\n fontWeight?: number;\n italic?: boolean;\n bold?: boolean;\n}): { fontFace?: string; bold?: boolean; italic?: boolean } {\n if (!params.family) {\n const weight =\n params.fontWeight ?? (params.bold === true ? 700 : undefined);\n return {\n bold: weight != null ? weight >= 600 : params.bold,\n italic: params.italic,\n };\n }\n const weight = params.fontWeight ?? (params.bold === true ? 700 : undefined);\n const synth = synthesizeFamilyName(\n params.family,\n weight,\n params.italic === true\n );\n return { fontFace: synth.family, bold: synth.bold, italic: synth.italic };\n}\n","/**\n * PPTX Component Default Resolution System\n * Provides theme-based default configurations for components\n */\n\nimport type { PptxThemeConfig } from '../types';\nimport type {\n PptxComponentDefaults,\n TextComponentDefaults,\n ImageComponentDefaults,\n ShapeComponentDefaults,\n TableComponentDefaults,\n HighchartsComponentDefaults,\n ChartComponentDefaults,\n TextProps,\n PptxImageProps,\n ShapeProps,\n PptxTableProps,\n PptxHighchartsProps,\n PptxChartProps,\n} from '@json-to-office/shared-pptx';\nimport { mergeWithDefaults } from '@json-to-office/shared';\n\n// ── Getters ──────────────────────────────────────────────────────────\n\nexport function getComponentDefaults(\n theme: PptxThemeConfig\n): PptxComponentDefaults {\n return theme.componentDefaults || {};\n}\n\nexport function getTextDefaults(theme: PptxThemeConfig): TextComponentDefaults {\n return getComponentDefaults(theme).text || {};\n}\n\nexport function getImageDefaults(\n theme: PptxThemeConfig\n): ImageComponentDefaults {\n return getComponentDefaults(theme).image || {};\n}\n\nexport function getShapeDefaults(\n theme: PptxThemeConfig\n): ShapeComponentDefaults {\n return getComponentDefaults(theme).shape || {};\n}\n\nexport function getTableDefaults(\n theme: PptxThemeConfig\n): TableComponentDefaults {\n return getComponentDefaults(theme).table || {};\n}\n\nexport function getHighchartsDefaults(\n theme: PptxThemeConfig\n): HighchartsComponentDefaults {\n return getComponentDefaults(theme).highcharts || {};\n}\n\nexport function getChartDefaults(\n theme: PptxThemeConfig\n): ChartComponentDefaults {\n return getComponentDefaults(theme).chart || {};\n}\n\nexport function getCustomComponentDefaults(\n theme: PptxThemeConfig,\n componentName: string\n): Record<string, unknown> {\n const defaults = getComponentDefaults(theme);\n return ((defaults as any)?.[componentName] as Record<string, unknown>) || {};\n}\n\n// ── Resolvers ────────────────────────────────────────────────────────\n\nexport function resolveTextProps(\n props: TextProps,\n theme: PptxThemeConfig\n): TextProps {\n return mergeWithDefaults(props, getTextDefaults(theme));\n}\n\nexport function resolveImageProps(\n props: PptxImageProps,\n theme: PptxThemeConfig\n): PptxImageProps {\n return mergeWithDefaults(props, getImageDefaults(theme));\n}\n\nexport function resolveShapeProps(\n props: ShapeProps,\n theme: PptxThemeConfig\n): ShapeProps {\n return mergeWithDefaults(props, getShapeDefaults(theme));\n}\n\nexport function resolveTableProps(\n props: PptxTableProps,\n theme: PptxThemeConfig\n): PptxTableProps {\n return mergeWithDefaults(props, getTableDefaults(theme));\n}\n\nexport function resolveHighchartsProps(\n props: PptxHighchartsProps,\n theme: PptxThemeConfig\n): PptxHighchartsProps {\n return mergeWithDefaults(props, getHighchartsDefaults(theme));\n}\n\nexport function resolveChartProps(\n props: PptxChartProps,\n theme: PptxThemeConfig\n): PptxChartProps {\n return mergeWithDefaults(props, getChartDefaults(theme));\n}\n\nexport function resolveCustomComponentProps<T extends Record<string, unknown>>(\n props: T,\n theme: PptxThemeConfig,\n componentName: string\n): T {\n const defaults = getCustomComponentDefaults(theme, componentName);\n return mergeWithDefaults(props, defaults as Partial<T>);\n}\n\n// ── Generic lookup ───────────────────────────────────────────────────\n\nconst TYPE_GETTERS: Record<\n string,\n (t: PptxThemeConfig) => Record<string, unknown>\n> = {\n text: getTextDefaults,\n image: getImageDefaults,\n shape: getShapeDefaults,\n table: getTableDefaults,\n highcharts: getHighchartsDefaults,\n chart: getChartDefaults,\n};\n\n/**\n * Get the flat componentDefaults object for a given component type.\n * Use this when you need the raw defaults without merging into props\n * (e.g. for injecting into a multi-layer shallow spread).\n */\nexport function getDefaultsForType(\n componentName: string,\n theme: PptxThemeConfig\n): Record<string, unknown> {\n const getter = TYPE_GETTERS[componentName];\n return getter\n ? getter(theme)\n : getCustomComponentDefaults(theme, componentName);\n}\n","/**\n * Centralized Component Defaults Resolution\n * Walks the component tree and resolves theme componentDefaults\n * on every component before any rendering or structure processing.\n */\n\nimport type { PptxComponentInput, PptxThemeConfig } from '../types';\nimport {\n resolveTextProps,\n resolveImageProps,\n resolveShapeProps,\n resolveTableProps,\n resolveHighchartsProps,\n resolveChartProps,\n resolveCustomComponentProps,\n} from './componentDefaults';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- resolver map needs wide input to accept all prop types\ntype Resolver = (props: any, theme: PptxThemeConfig) => Record<string, unknown>;\n\nconst RESOLVER_MAP: Record<string, Resolver> = {\n text: resolveTextProps,\n image: resolveImageProps,\n shape: resolveShapeProps,\n table: resolveTableProps,\n highcharts: resolveHighchartsProps,\n chart: resolveChartProps,\n};\n\n/**\n * Resolve componentDefaults for a single component.\n * Known components use their typed resolver; unknown names\n * fall back to resolveCustomComponentProps.\n */\nexport function resolveComponentDefaults(\n component: PptxComponentInput,\n theme: PptxThemeConfig\n): PptxComponentInput {\n const resolver = RESOLVER_MAP[component.name];\n const resolvedProps = resolver\n ? resolver(component.props, theme)\n : resolveCustomComponentProps(\n component.props as Record<string, unknown>,\n theme,\n component.name\n );\n\n return { ...component, props: resolvedProps };\n}\n\n/**\n * Recursively walk the component tree and resolve componentDefaults\n * on every component. Returns a new tree (no mutation).\n */\nexport function resolveComponentTree(\n components: PptxComponentInput[],\n theme: PptxThemeConfig\n): PptxComponentInput[] {\n return components.map((component) => {\n const resolved = resolveComponentDefaults(component, theme);\n\n if (resolved.children && resolved.children.length > 0) {\n return {\n ...resolved,\n children: resolveComponentTree(resolved.children, theme),\n };\n }\n\n return resolved;\n });\n}\n","/**\n * Image source resolution (PPTX)\n *\n * Resolves the three mutually-exclusive image sources into a single string that\n * can be probed and handed to pptxgenjs. Precedence mirrors core-docx:\n * `svg > base64 > path`. Raw SVG markup is wrapped into an `image/svg+xml`\n * data URI so it embeds as a vector (PowerPoint 2016+).\n */\nimport path from 'node:path';\nimport { getBaseDir, resolveFromBaseDir } from './baseDirContext';\n\n/** A source field counts only when it carries a non-empty (non-whitespace) value. */\nconst hasValue = (v?: string): v is string =>\n typeof v === 'string' && v.trim().length > 0;\n\nexport function resolveImageSource(props: {\n svg?: string;\n base64?: string;\n path?: string;\n}): string | undefined {\n if (hasValue(props.svg)) {\n const encoded = Buffer.from(props.svg, 'utf-8').toString('base64');\n return `data:image/svg+xml;base64,${encoded}`;\n }\n // Mirror the conflict-validator predicate: blank base64/path are treated as\n // absent, so a whitespace-only value can't shadow a real later source.\n if (hasValue(props.base64)) return props.base64;\n if (hasValue(props.path)) return props.path;\n return undefined;\n}\n\n/**\n * Local files must live under the document base directory (when set) or CWD —\n * path-traversal guard (#142). `resolved` must already be absolute.\n */\nexport function isAllowedLocalPath(resolved: string): boolean {\n const baseDir = getBaseDir();\n const allowedRoots = baseDir ? [baseDir, process.cwd()] : [process.cwd()];\n return allowedRoots.some(\n (root) => resolved.startsWith(root + path.sep) || resolved === root\n );\n}\n\n/**\n * Resolve a source string that may be a URL, data URI, or local file path:\n * URLs and data URIs pass through; local paths resolve against the active\n * document base directory when the generation scope set one, eagerly —\n * pptxgenjs reads `path` entries during write(), outside the generation\n * scope. Returns `undefined` when a local path escapes the allowed roots, so\n * out-of-root paths never reach pptxgenjs (#142).\n */\nexport function safeLocalPath(source: string): string | undefined {\n if (/^(https?:\\/\\/|data:)/.test(source)) return source;\n const resolved = path.resolve(resolveFromBaseDir(source));\n return isAllowedLocalPath(resolved) ? resolved : undefined;\n}\n","/**\n * Slide-targeted hyperlinks\n *\n * `hyperlink.slide` is 1-based over the slides *as authored* in the JSON —\n * slides carrying `enabled: false` still count. Structure processing remaps\n * every ref to the position its target ends up at in the generated deck, so\n * toggling one slide off never silently retargets the links after it.\n *\n * A ref that cannot be resolved — target dropped, or index outside the\n * authored range — is marked unresolved here and dropped by the writer with a\n * warning. It must never reach pptxgenjs: it would emit a relationship to a\n * `slideN.xml` part that is not in the archive, which PowerPoint reports as a\n * damaged file.\n */\n\nimport type { PipelineWarning, PptxComponentInput } from '../types';\n\nexport const HYPERLINK_SLIDE_UNRESOLVED = 'HYPERLINK_SLIDE_UNRESOLVED';\n\nexport interface HyperlinkProps {\n url?: string;\n slide?: number;\n tooltip?: string;\n /** Internal: authored `slide` ref that resolves to no rendered slide. */\n unresolvedSlideRef?: number;\n}\n\n/** Authored 1-based slide number -> rendered 1-based slide number. */\nexport type SlideIndexMap = ReadonlyMap<number, number>;\n\nfunction remapHyperlink(\n hyperlink: HyperlinkProps,\n map: SlideIndexMap\n): HyperlinkProps {\n // `url` wins over `slide` at write time, so leave those refs alone.\n if (hyperlink.url || hyperlink.slide == null) return hyperlink;\n\n const rendered = map.get(hyperlink.slide);\n if (rendered === undefined) {\n const { slide, ...rest } = hyperlink;\n return { ...rest, unresolvedSlideRef: slide };\n }\n return rendered === hyperlink.slide\n ? hyperlink\n : { ...hyperlink, slide: rendered };\n}\n\n/**\n * Rewrite `hyperlink.slide` in a bare props bag. Template placeholder\n * `defaults` are merged into a component at render time without ever being a\n * component themselves, so they need rebasing on their own — otherwise a\n * `defaults.props.hyperlink.slide` reaches the writer as a raw authored index.\n */\nexport function remapHyperlinkProps<T extends Record<string, unknown>>(\n props: T,\n map: SlideIndexMap\n): T {\n const hyperlink = props.hyperlink as HyperlinkProps | undefined;\n if (!hyperlink || typeof hyperlink !== 'object') return props;\n\n const remapped = remapHyperlink(hyperlink, map);\n return remapped === hyperlink ? props : { ...props, hyperlink: remapped };\n}\n\n/** Rewrite every `hyperlink.slide` in a component subtree. Returns a new tree. */\nexport function remapHyperlinkSlideRefs(\n component: PptxComponentInput,\n map: SlideIndexMap\n): PptxComponentInput {\n const hyperlink = component.props?.hyperlink as HyperlinkProps | undefined;\n let next = component;\n\n if (hyperlink && typeof hyperlink === 'object') {\n const remapped = remapHyperlink(hyperlink, map);\n if (remapped !== hyperlink) {\n next = { ...next, props: { ...next.props, hyperlink: remapped } };\n }\n }\n\n if (next.children && next.children.length > 0) {\n next = {\n ...next,\n children: next.children.map((child) =>\n remapHyperlinkSlideRefs(child, map)\n ),\n };\n }\n\n return next;\n}\n\n/**\n * Write the pptxgenjs `hyperlink` option, dropping unresolvable slide refs.\n * Shared by every component that accepts a hyperlink.\n */\nexport function applyHyperlink(\n opts: Record<string, unknown>,\n hyperlink: HyperlinkProps | undefined,\n componentName: string,\n warnings?: PipelineWarning[]\n): void {\n if (!hyperlink) return;\n\n if (hyperlink.url) {\n opts.hyperlink = { url: hyperlink.url, tooltip: hyperlink.tooltip };\n return;\n }\n\n if (hyperlink.unresolvedSlideRef != null) {\n const message =\n `hyperlink.slide ${hyperlink.unresolvedSlideRef} matches no slide in the generated ` +\n `presentation (slide disabled, or index out of range) — hyperlink dropped`;\n if (warnings) {\n warnings.push({\n code: HYPERLINK_SLIDE_UNRESOLVED,\n message,\n component: componentName,\n });\n } else {\n console.warn(message);\n }\n return;\n }\n\n if (hyperlink.slide) {\n opts.hyperlink = { slide: hyperlink.slide, tooltip: hyperlink.tooltip };\n }\n}\n","/**\n * Grid Layout Resolution\n * Converts grid coordinates to absolute x/y/w/h positions\n */\n\nimport type { GridConfig, GridPosition, PptxComponentInput, PipelineWarning } from '../types';\nimport { warn, W } from '../utils/warn';\n\nexport const DEFAULT_GRID_CONFIG: Required<{\n columns: number;\n rows: number;\n margin: { top: number; right: number; bottom: number; left: number };\n gutter: { column: number; row: number };\n}> = {\n columns: 12,\n rows: 6,\n margin: { top: 0.5, right: 0.5, bottom: 0.5, left: 0.5 },\n gutter: { column: 0.2, row: 0.2 },\n};\n\nfunction resolveMargin(margin: GridConfig['margin']) {\n if (margin == null) return DEFAULT_GRID_CONFIG.margin;\n if (typeof margin === 'number') return { top: margin, right: margin, bottom: margin, left: margin };\n return margin;\n}\n\nfunction resolveGutter(gutter: GridConfig['gutter']) {\n if (gutter == null) return DEFAULT_GRID_CONFIG.gutter;\n if (typeof gutter === 'number') return { column: gutter, row: gutter };\n return gutter;\n}\n\n/**\n * Merge a template-level grid override on top of the presentation grid.\n * Template fields take precedence; nested margin/gutter objects are shallow-merged.\n * Both sides are normalized to object form before merging so that a shorthand\n * base (e.g. margin: 0.5) combined with a partial override (e.g. { top: 1.1 })\n * doesn't lose the other sides.\n */\nexport function mergeGridConfigs(\n base: GridConfig | undefined,\n override: GridConfig | undefined\n): GridConfig | undefined {\n if (!override) return base;\n if (!base) return override;\n\n const merged: GridConfig = {\n columns: override.columns ?? base.columns,\n rows: override.rows ?? base.rows,\n };\n\n // Merge margin — normalize both to object form first\n if (override.margin !== undefined) {\n if (typeof override.margin === 'number') {\n merged.margin = override.margin;\n } else {\n merged.margin = { ...resolveMargin(base.margin), ...override.margin };\n }\n } else {\n merged.margin = base.margin;\n }\n\n // Merge gutter — same normalization\n if (override.gutter !== undefined) {\n if (typeof override.gutter === 'number') {\n merged.gutter = override.gutter;\n } else {\n merged.gutter = { ...resolveGutter(base.gutter), ...override.gutter };\n }\n } else {\n merged.gutter = base.gutter;\n }\n\n return merged;\n}\n\nexport function resolveGridPosition(\n gridPos: GridPosition,\n gridConfig: GridConfig | undefined,\n slideWidth: number,\n slideHeight: number,\n warnings?: PipelineWarning[]\n): { x: number; y: number; w: number; h: number } {\n const cols = Math.max(1, gridConfig?.columns ?? DEFAULT_GRID_CONFIG.columns);\n const rows = Math.max(1, gridConfig?.rows ?? DEFAULT_GRID_CONFIG.rows);\n const margin = resolveMargin(gridConfig?.margin);\n const gutter = resolveGutter(gridConfig?.gutter);\n\n const col = Math.max(0, Math.min(gridPos.column, cols - 1));\n const row = Math.max(0, Math.min(gridPos.row, rows - 1));\n const colSpan = Math.max(1, Math.min(gridPos.columnSpan ?? 1, cols - col));\n const rowSpan = Math.max(1, Math.min(gridPos.rowSpan ?? 1, rows - row));\n\n if (gridPos.column !== col || gridPos.row !== row) {\n warn(warnings, W.GRID_POSITION_CLAMPED,\n `Grid position clamped: column ${gridPos.column}→${col}, row ${gridPos.row}→${row} (grid: ${cols}×${rows})`\n );\n }\n\n const availableW = slideWidth - margin.left - margin.right;\n const availableH = slideHeight - margin.top - margin.bottom;\n const trackW = (availableW - (cols - 1) * gutter.column) / cols;\n const trackH = (availableH - (rows - 1) * gutter.row) / rows;\n\n const x = margin.left + col * (trackW + gutter.column);\n const y = margin.top + row * (trackH + gutter.row);\n const w = colSpan * trackW + (colSpan - 1) * gutter.column;\n const h = rowSpan * trackH + (rowSpan - 1) * gutter.row;\n\n return { x, y, w, h };\n}\n\nexport function resolveComponentGridPosition(\n component: PptxComponentInput,\n gridConfig: GridConfig | undefined,\n slideWidth: number,\n slideHeight: number,\n warnings?: PipelineWarning[]\n): PptxComponentInput {\n const gridPos = component.props.grid as GridPosition | undefined;\n if (!gridPos) return component;\n\n const resolved = resolveGridPosition(gridPos, gridConfig, slideWidth, slideHeight, warnings);\n\n const { grid: _grid, ...restProps } = component.props; // eslint-disable-line no-unused-vars, @typescript-eslint/no-unused-vars\n const newProps = { ...restProps };\n\n // When explicit values use percentage strings, convert grid-resolved inches\n // to percentages too so pptxgenjs receives consistent units per element.\n const hasPercentX = typeof newProps.x === 'string' || typeof newProps.w === 'string';\n const hasPercentY = typeof newProps.y === 'string' || typeof newProps.h === 'string';\n\n const toPercX = (v: number) => `${+((v / slideWidth) * 100).toFixed(2)}%`;\n const toPercY = (v: number) => `${+((v / slideHeight) * 100).toFixed(2)}%`;\n\n // Grid sets x/y/w/h, but explicit values on the element override individually\n if (newProps.x == null) newProps.x = hasPercentX ? toPercX(resolved.x) : resolved.x;\n if (newProps.y == null) newProps.y = hasPercentY ? toPercY(resolved.y) : resolved.y;\n if (newProps.w == null) newProps.w = hasPercentX ? toPercX(resolved.w) : resolved.w;\n if (newProps.h == null) newProps.h = hasPercentY ? toPercY(resolved.h) : resolved.h;\n\n return { ...component, props: newProps };\n}\n","/**\n * Resource table used while compiling a presentation to PptxIR.\n *\n * One table per compilation — never module-global — so concurrent generations\n * cannot share ids or entries.\n *\n * Identity depends on where the bytes come from. Inline sources (authored\n * base64, raw SVG) are decoded once and keyed by content hash, so the same\n * image authored twice becomes one resource. File and remote sources keep\n * their location and are keyed by it, because reading every file at compile\n * time would change when I/O happens and how much of a large deck is resident\n * in memory.\n */\n\nimport type {\n PptxIrPixelSize,\n PptxIrResource,\n PptxIrResourceOrigin,\n} from './types';\nimport { sha256Hex } from './units';\n\nexport interface InlineResourceInput {\n kind: 'inline';\n bytes: Uint8Array;\n mediaType?: string;\n}\n\nexport interface FileResourceInput {\n kind: 'file';\n path: string;\n mediaType?: string;\n}\n\nexport interface RemoteResourceInput {\n kind: 'remote';\n url: string;\n mediaType?: string;\n}\n\nexport type ResourceInput =\n | InlineResourceInput\n | FileResourceInput\n | RemoteResourceInput;\n\nexport class ResourceTable {\n private readonly byKey = new Map<string, PptxIrResource>();\n private readonly order: PptxIrResource[] = [];\n\n /**\n * Add a resource (or return the existing one with matching identity) and\n * return its id.\n */\n intern(input: ResourceInput, intrinsic?: PptxIrPixelSize): string {\n const origin = toOrigin(input);\n const key = identity(origin);\n const existing = this.byKey.get(key);\n if (existing) {\n // A later reference may have probed dimensions the first one skipped.\n if (!existing.intrinsic && intrinsic) existing.intrinsic = intrinsic;\n return existing.id;\n }\n\n const resource: PptxIrResource = {\n id: `res${this.order.length + 1}`,\n kind: 'image',\n origin,\n ...(input.mediaType ? { mediaType: input.mediaType } : {}),\n ...(intrinsic ? { intrinsic } : {}),\n };\n this.byKey.set(key, resource);\n this.order.push(resource);\n return resource.id;\n }\n\n /** Every resource, in first-use order. */\n list(): PptxIrResource[] {\n return this.order;\n }\n\n get(id: string): PptxIrResource | undefined {\n return this.order.find((r) => r.id === id);\n }\n}\n\nfunction toOrigin(input: ResourceInput): PptxIrResourceOrigin {\n switch (input.kind) {\n case 'inline':\n return {\n kind: 'inline',\n bytes: input.bytes,\n byteLength: input.bytes.byteLength,\n sha256: sha256Hex(input.bytes),\n };\n case 'file':\n return { kind: 'file', path: input.path };\n case 'remote':\n return { kind: 'remote', url: input.url };\n }\n}\n\nfunction identity(origin: PptxIrResourceOrigin): string {\n switch (origin.kind) {\n case 'inline':\n return `sha256:${origin.sha256}`;\n case 'file':\n return `file:${origin.path}`;\n case 'remote':\n return `remote:${origin.url}`;\n }\n}\n\n/**\n * Split a `data:` URI into its media type and decoded bytes.\n *\n * Returns `undefined` for anything that is not a base64 data URI, so callers\n * can fall back to treating the string as a location.\n */\nexport function parseDataUri(\n source: string\n): { mediaType: string; bytes: Uint8Array } | undefined {\n const match = /^data:([^;,]+)(;[^,]*)?,(.*)$/s.exec(source);\n if (!match) return undefined;\n const [, mediaType, params, payload] = match;\n const isBase64 = (params ?? '').includes(';base64');\n const bytes = isBase64\n ? new Uint8Array(Buffer.from(payload, 'base64'))\n : new Uint8Array(Buffer.from(decodeURIComponent(payload), 'utf-8'));\n return { mediaType, bytes };\n}\n\n/** Guess a media type from a file extension or URL path. */\nexport function mediaTypeFromLocation(location: string): string | undefined {\n const withoutQuery = location.split(/[?#]/)[0];\n const ext = withoutQuery\n .slice(withoutQuery.lastIndexOf('.') + 1)\n .toLowerCase();\n switch (ext) {\n case 'png':\n return 'image/png';\n case 'jpg':\n case 'jpeg':\n return 'image/jpeg';\n case 'gif':\n return 'image/gif';\n case 'svg':\n return 'image/svg+xml';\n case 'webp':\n return 'image/webp';\n case 'bmp':\n return 'image/bmp';\n case 'tif':\n case 'tiff':\n return 'image/tiff';\n default:\n return undefined;\n }\n}\n","/**\n * PPTX renderer registry.\n *\n * Adapters are registered as async factories so an optional backend is only\n * imported when it is actually selected — choosing `pptxgenjs` never loads\n * `@office-open/pptx`, and a missing optional dependency surfaces as an\n * actionable install hint rather than a bare module-resolution failure.\n */\n\nimport { RendererRegistry } from '@json-to-office/shared/rendering';\nimport type { PptxFeature } from '../ir/features';\nimport type { PptxIR } from '../ir/types';\nimport {\n DEFAULT_PPTX_RENDERER_ID,\n type PptxRenderer,\n type PptxRendererId,\n} from './types';\n\nconst registry = new RendererRegistry<PptxIR, PptxFeature, PptxRendererId>(\n 'pptx',\n DEFAULT_PPTX_RENDERER_ID\n);\n\nregistry.register('pptxgenjs', async () => {\n const { createPptxGenJsRenderer } = await import('./pptxgenjs/index');\n return createPptxGenJsRenderer();\n});\n\nregistry.register('office-open', async () => {\n const { createOfficeOpenPptxRenderer } = await import('./office-open/index');\n return createOfficeOpenPptxRenderer();\n});\n\n/** Resolve a renderer by id, defaulting to `pptxgenjs`. */\nexport function resolvePptxRenderer(\n id?: PptxRendererId\n): Promise<PptxRenderer> {\n return registry.resolve(id);\n}\n\n/** Renderer ids registered for PPTX. */\nexport function pptxRendererIds(): readonly PptxRendererId[] {\n return registry.ids();\n}\n\nexport function isPptxRendererId(value: string): value is PptxRendererId {\n return registry.has(value);\n}\n","/**\n * PPTX renderer contracts.\n *\n * Format-specific bindings of the shared `OfficeRenderer` contract. Nothing in\n * this file imports a backend; the adapters under `pptxgenjs/` and\n * `office-open/` do, and they are the only places allowed to.\n */\n\nimport type {\n OfficeRenderer,\n RenderOptions,\n} from '@json-to-office/shared/rendering';\nimport type { PptxFeature } from '../ir/features';\nimport type { PptxIR } from '../ir/types';\nimport type { PipelineWarning } from '../types';\nimport {\n DEFAULT_PPTX_RENDERER_ID,\n type PptxRendererId,\n} from '@json-to-office/shared-pptx';\n\n/**\n * Renderer ids available for PPTX.\n *\n * `pptxgenjs` is the default and must keep producing today's output.\n * `office-open` is experimental and opt-in.\n */\nexport { DEFAULT_PPTX_RENDERER_ID };\nexport type { PptxRendererId };\n\n/**\n * Render options for PPTX.\n *\n * Adds a warning sink to the shared contract. Post-render repairs — the SVG\n * preview fix, for one — can find problems that the author should hear about,\n * and those have to reach the same structured warning list the rest of the\n * pipeline uses rather than `console.warn`.\n */\nexport interface PptxRenderOptions extends RenderOptions {\n warnings?: PipelineWarning[];\n}\n\nexport interface PptxRenderer\n extends OfficeRenderer<PptxIR, PptxFeature, PptxRendererId> {\n render(document: PptxIR, options?: PptxRenderOptions): Promise<Uint8Array>;\n}\n\nexport type { RenderOptions };\n","/**\n * PPTX Core Types\n */\n\nimport type {\n ServicesConfig,\n FontRegistryDefinition,\n} from '@json-to-office/shared';\nimport type {\n GradientFill,\n PptxComponentDefaults,\n PptxRendererId,\n} from '@json-to-office/shared-pptx';\n\nexport interface PptxComponentInput {\n name: string;\n id?: string;\n enabled?: boolean;\n props: Record<string, any>;\n children?: PptxComponentInput[];\n}\n\nexport interface PresentationComponentDefinition {\n name: 'pptx';\n $schema?: string;\n /** Renderer backend. Omitted defaults to pptxgenjs. */\n renderer?: PptxRendererId;\n id?: string;\n props: {\n title?: string;\n author?: string;\n subject?: string;\n company?: string;\n theme?: string;\n fontRegistry?: FontRegistryDefinition;\n slideWidth?: number;\n slideHeight?: number;\n rtlMode?: boolean;\n language?: string;\n pageNumberFormat?: '9' | '09';\n componentDefaults?: PptxComponentDefaults;\n grid?: GridConfig;\n templates?: TemplateSlideDefinition[];\n };\n children?: PptxComponentInput[];\n}\n\n/** A presentation explicitly targeted at one renderer profile. */\nexport type PresentationComponentDefinitionFor<R extends PptxRendererId> = Omit<\n PresentationComponentDefinition,\n 'renderer'\n> &\n (R extends 'pptxgenjs' ? { renderer?: R } : { renderer: R });\n\nexport interface SlideComponentDefinition {\n name: 'slide';\n id?: string;\n /** Optional: every slide prop is optional, so validation accepts a slide with none. */\n props?: {\n background?: {\n color?: string;\n gradient?: GradientFill;\n image?: { path?: string; base64?: string };\n };\n transition?: {\n type?: string;\n speed?: string;\n };\n notes?: string;\n layout?: string;\n hidden?: boolean;\n template?: string;\n placeholders?: Record<string, PptxComponentInput>;\n };\n children?: PptxComponentInput[];\n}\n\nexport interface ProcessedPresentation {\n metadata: {\n title?: string;\n author?: string;\n subject?: string;\n company?: string;\n };\n theme: PptxThemeConfig;\n grid?: GridConfig;\n slideWidth: number;\n slideHeight: number;\n rtlMode: boolean;\n /** Default presentation language (BCP-47) for spell-checking */\n language?: string;\n pageNumberFormat: '9' | '09';\n slides: ProcessedSlide[];\n templates?: TemplateSlideDefinition[];\n services?: ServicesConfig;\n}\n\nexport interface ProcessedSlide {\n components: PptxComponentInput[];\n background?: {\n color?: string;\n gradient?: GradientFill;\n image?: { path?: string; base64?: string };\n };\n /**\n * Slide transition, as authored.\n *\n * Carried through processing rather than dropped there: a backend without a\n * transition API has to be told the deck wants one so it can refuse, and a\n * backend with one has to be able to write it (#257).\n */\n transition?: { type?: string; speed?: string };\n notes?: string;\n layout?: string;\n hidden?: boolean;\n template?: string;\n placeholders?: Record<string, PptxComponentInput>;\n}\n\nexport interface GridConfig {\n columns?: number;\n rows?: number;\n margin?:\n | number\n | { top: number; right: number; bottom: number; left: number };\n gutter?: number | { column: number; row: number };\n}\n\nexport interface GridPosition {\n column: number;\n row: number;\n columnSpan?: number;\n rowSpan?: number;\n}\n\nexport interface TextStyle {\n fontSize?: number;\n fontFace?: string;\n fontColor?: string;\n bold?: boolean;\n /**\n * Per-style weight (100–900). Overrides `bold` when set — renderer picks\n * the closest embedded variant via CSS font-matching and emits the run\n * under a synthetic family alias (e.g. \"Inter Light\" for weight 300).\n */\n fontWeight?: number;\n italic?: boolean;\n align?: string;\n lineSpacing?: number;\n charSpacing?: number;\n paraSpaceAfter?: number;\n}\n\nexport type StyleName =\n | 'title'\n | 'subtitle'\n | 'heading1'\n | 'heading2'\n | 'heading3'\n | 'body'\n | 'caption';\n\nexport interface PptxThemeConfig {\n name: string;\n colors: {\n primary: string;\n secondary: string;\n accent: string;\n background: string;\n text: string;\n text2?: string;\n background2?: string;\n accent4?: string;\n accent5?: string;\n accent6?: string;\n };\n fonts: {\n heading: string;\n body: string;\n };\n fontRegistry?: FontRegistryDefinition;\n defaults: {\n fontSize: number;\n fontColor: string;\n };\n styles?: Partial<Record<StyleName, TextStyle>>;\n componentDefaults?: PptxComponentDefaults;\n}\n\nexport interface PlaceholderDefinition {\n name: string;\n x?: number;\n y?: number;\n w?: number;\n h?: number;\n grid?: GridPosition;\n defaults?: PptxComponentInput;\n}\n\nexport interface TemplateSlideDefinition {\n name: string;\n background?: {\n color?: string;\n gradient?: GradientFill;\n image?: { path?: string; base64?: string };\n };\n margin?: number | [number, number, number, number];\n slideNumber?: {\n x: number;\n y: number;\n w?: number;\n h?: number;\n color?: string;\n fontSize?: number;\n };\n objects?: PptxComponentInput[];\n placeholders?: PlaceholderDefinition[];\n grid?: GridConfig;\n}\n\nexport interface SlideContext {\n slideNumber: number;\n totalSlides: number;\n pageNumberFormat: '9' | '09';\n /** Default presentation language (BCP-47); text runs inherit it unless overridden */\n language?: string;\n}\n\nexport interface SlideRenderContext {\n slideCtx?: SlideContext;\n services?: ServicesConfig;\n slideWidth: number;\n slideHeight: number;\n /**\n * Per-generation registry of fills (gradient/pattern) that pptxgenjs cannot\n * express. Components render a sentinel solid fill tagged with a unique\n * objectName; the PptxGenJS packaging pass swaps the sentinel for the real\n * fill XML after generation.\n */\n pendingFills?: PendingXmlFill[];\n}\n\n/**\n * A fill to be spliced into the slide XML during packaging. The component that\n * registered it rendered a sentinel `<a:solidFill>` on a shape whose\n * `cNvPr name` equals `objectName`.\n */\nexport interface PendingXmlFill {\n objectName: string;\n /** Complete replacement fill element (e.g. `<a:gradFill>…</a:gradFill>`). */\n xml: string;\n}\n\nexport interface PipelineWarning {\n code: string; // WarningCode at call sites; string here to avoid circular import\n message: string;\n component?: string;\n slide?: number;\n}\n\nexport function isPresentationComponent(\n component: unknown\n): component is PresentationComponentDefinition {\n return (\n typeof component === 'object' &&\n component !== null &&\n (component as any).name === 'pptx'\n );\n}\n\nexport function isSlideComponent(\n component: unknown\n): component is SlideComponentDefinition {\n return (\n typeof component === 'object' &&\n component !== null &&\n (component as any).name === 'slide'\n );\n}\n","/**\n * Shared font-resolution helper used by BOTH entry paths into renderPresentation:\n *\n * - core/generator.ts → generateBufferWithWarnings (non-plugin)\n * - plugin/createPresentationGenerator.ts → generate (plugin-aware)\n *\n * Keeping it in one place ensures both paths validate, materialize, and fire\n * the `onResolved` side-channel consumed by the LibreOffice preview stager.\n */\n\nimport type { FontRuntimeOpts, ResolvedFont } from '@json-to-office/shared';\nimport {\n collectFontNamesFromPptx,\n validateFontReferences,\n FontRegistry,\n documentFontRegistry,\n themeFontRegistry,\n mergeFontRegistries,\n} from '@json-to-office/shared';\nimport {\n loadFileFontSource,\n FontDiskCache,\n fetchVariableFontSource,\n} from '@json-to-office/shared/fonts/node';\nimport type {\n PipelineWarning,\n PresentationComponentDefinition,\n} from '../types';\nimport type { PptxThemeConfig } from '../types';\nimport { warn, W } from '../utils/warn';\n\nexport async function resolveDocumentFonts(\n document: PresentationComponentDefinition,\n theme: PptxThemeConfig,\n warnings: PipelineWarning[],\n fonts?: FontRuntimeOpts\n): Promise<ResolvedFont[]> {\n const names = new Set<string>();\n for (const n of collectFontNamesFromPptx(document)) names.add(n);\n for (const n of collectFontNamesFromPptx(theme as unknown)) names.add(n);\n if (names.size === 0) return [];\n\n // Merge the declared registries with runtime overrides. Precedence:\n // theme < document < fonts.extraEntries (see registry.ts's resolution\n // rules). This MUST run before validation, not after the `onResolved`\n // short-circuit below: a presentation with a valid registry and no preview\n // listener would otherwise still report every registered family as\n // FONT_UNRESOLVED.\n const registryEntries = mergeFontRegistries(\n themeFontRegistry(theme),\n documentFontRegistry(document),\n fonts?.extraEntries\n );\n\n // Validate unconditionally — strict mode must fire even when no consumer\n // is listening via onResolved (CLI / library callers that just want\n // build-time validation of font references).\n const validation = validateFontReferences({\n referencedNames: names,\n registeredEntries: registryEntries,\n });\n if (validation.warnings.length > 0) {\n if (fonts?.strict) {\n throw new Error(\n `Unresolved font references (strict mode):\\n` +\n validation.warnings.map((w) => ` - ${w.message}`).join('\\n')\n );\n }\n for (const w of validation.warnings) {\n warn(warnings, W.FONT_UNRESOLVED, w.message, {\n component: 'fontRegistry',\n });\n }\n }\n\n // Registry resolution (Google/URL/file fetches) only runs when a consumer\n // is listening via onResolved — typically the LibreOffice preview stager.\n // Office output never embeds bytes, so skipping fetches when nobody cares\n // keeps library callers from paying network cost.\n if (!fonts?.onResolved) return [];\n\n const registry = new FontRegistry({\n // Spread keeps baseDir/googleFonts/mode/substitution intact for\n // materializeSource; extraEntries carries the merged registry.\n opts: { ...fonts, extraEntries: registryEntries },\n fileLoader: loadFileFontSource,\n variableLoader: fetchVariableFontSource,\n diskCache: fonts?.googleFonts?.cacheDir\n ? new FontDiskCache(fonts.googleFonts.cacheDir)\n : undefined,\n });\n const resolved = await registry.resolveMany(names);\n for (const r of resolved) {\n for (const msg of r.warnings) {\n warn(warnings, W.FONT_UNRESOLVED, msg, {\n component: 'fontRegistry',\n });\n }\n }\n // Fire the side-channel here so callers never have to remember. The\n // short-circuit above guarantees we only reach this point when a\n // listener is registered.\n fonts.onResolved(resolved);\n return resolved;\n}\n","/**\n * Shared generation prologue.\n *\n * Both entry points — `generateBufferWithWarnings` (core) and\n * `createPresentationGenerator` (plugin) — must resolve the same theme, run\n * the same export-mode pre-pass before slide processing runs. Keeping two\n * copies of that is how DOCX silently dropped a\n * root-level prop from one path (#133); this module is the single definition\n * so the next root-level prop cannot diverge (#134). Mirrors\n * core-docx/src/core/generationContext.ts.\n *\n * The prologue deliberately stops before font resolution: the core path\n * resolves fonts straight after this, while the plugin path must first expand\n * custom components (which can introduce new families). The export-mode\n * pre-pass runs here, BEFORE expansion, so custom components reading\n * `theme.fonts.*` during render see substituted names, not the original\n * non-safe ones.\n */\n\nimport type {\n PresentationComponentDefinition,\n PptxThemeConfig,\n PipelineWarning,\n} from '../types';\nimport type { FontRuntimeOpts } from '@json-to-office/shared';\nimport { applyExportMode } from '@json-to-office/shared';\nimport { getPptxTheme } from '../themes/defaults';\n\nexport interface ThemeContextOptions {\n customThemes?: Record<string, PptxThemeConfig>;\n fonts?: FontRuntimeOpts;\n warnings?: PipelineWarning[];\n /**\n * Base theme name when the document doesn't name one. The plugin builder\n * passes its constructor-supplied string theme; defaults to 'default'.\n */\n defaultThemeName?: string;\n /**\n * Theme lookup for the base `props.theme` name. The plugin builder passes\n * its own (customThemes → doc-named built-in → constructor theme object →\n * built-in); omit it to use customThemes → built-in. `authored` is true\n * when the name came from the document's own `props.theme` (as opposed to\n * `defaultThemeName` or the 'default' fallback), so the lookup can honor\n * an explicitly doc-named built-in without the constructor object\n * swallowing the default name too (#141).\n */\n resolveNamedTheme?: (name: string, authored: boolean) => PptxThemeConfig;\n}\n\nexport interface GenerationThemeContext {\n /**\n * The document after the export-mode pre-pass rewrote font references.\n * `props.theme` stays as authored (name or inline object) — callers hand\n * `theme` to `processPresentation` by value instead of round-tripping it\n * through a name lookup (#135).\n */\n document: PresentationComponentDefinition;\n theme: PptxThemeConfig;\n}\n\nexport function resolveThemeContext(\n documentIn: PresentationComponentDefinition,\n options: ThemeContextOptions = {}\n): GenerationThemeContext {\n const { customThemes, fonts, warnings, defaultThemeName, resolveNamedTheme } =\n options;\n\n // A root written without a `props` key is defaulted here — otherwise the\n // first downstream `document.props.*` read throws a raw TypeError. Only\n // `undefined` is defaulted: `props: null` is malformed and must be rejected\n // rather than quietly rewritten into a valid shape. Both entry points\n // validate before reaching here when validation is enabled (the PPTX\n // validator rejects a missing `props`); this covers the\n // `validation: { enabled: false }` route. Matches DOCX.\n if (documentIn.props === null) {\n throw new Error(\n 'Document `props` is null. Omit it, or provide an object — ' +\n 'a null props cannot carry a theme.'\n );\n }\n let document =\n documentIn.props === undefined ? { ...documentIn, props: {} } : documentIn;\n\n // An inline theme object (self-contained document) resolves directly and\n // wins over any customThemes entry sharing its name, on both paths. The\n // document keeps the authored object — nothing downstream resolves the\n // theme by name anymore.\n let inlineTheme: PptxThemeConfig | undefined;\n if (\n typeof document.props.theme === 'object' &&\n document.props.theme !== null\n ) {\n inlineTheme = document.props.theme as PptxThemeConfig;\n }\n\n const authoredThemeName =\n typeof document.props.theme === 'string' ? document.props.theme : undefined;\n const baseThemeName = inlineTheme\n ? inlineTheme.name || 'inline-theme'\n : authoredThemeName ?? defaultThemeName ?? 'default';\n let theme =\n inlineTheme ??\n (resolveNamedTheme\n ? resolveNamedTheme(baseThemeName, authoredThemeName !== undefined)\n : customThemes?.[baseThemeName] ?? getPptxTheme(baseThemeName));\n\n // Export-mode pre-pass: substitute rewrites non-safe families in place;\n // custom leaves refs untouched and resolution short-circuits to empty.\n const mode = applyExportMode({ doc: document, theme, fonts });\n document = mode.doc;\n theme = mode.theme;\n for (const w of mode.warnings) {\n warnings?.push({\n code: w.code,\n message: w.message,\n component: 'fontRegistry',\n });\n }\n\n return {\n document,\n theme,\n };\n}\n","/**\n * PPTX Theme Defaults\n */\n\nimport type { PptxThemeConfig, TextStyle, StyleName } from '../types';\n\nconst DEFAULT_STYLES: Partial<Record<StyleName, TextStyle>> = {\n title: { fontSize: 36, bold: true, fontColor: 'text', align: 'center' },\n subtitle: { fontSize: 20, italic: true, fontColor: 'text2', align: 'center' },\n heading1: { fontSize: 28, bold: true, fontColor: 'primary' },\n heading2: { fontSize: 22, bold: true, fontColor: 'primary' },\n heading3: { fontSize: 18, bold: true, fontColor: 'text' },\n body: { fontSize: 14 },\n caption: { fontSize: 10, italic: true, fontColor: 'text2' },\n};\n\nexport const DEFAULT_PPTX_THEME: PptxThemeConfig = {\n name: 'default',\n colors: {\n primary: '#4472C4',\n secondary: '#ED7D31',\n accent: '#70AD47',\n background: '#FFFFFF',\n text: '#333333',\n text2: '#44546A',\n background2: '#E7E6E6',\n accent4: '#FFC000',\n accent5: '#5B9BD5',\n accent6: '#70AD47',\n },\n fonts: {\n heading: 'Arial',\n body: 'Arial',\n },\n defaults: {\n fontSize: 18,\n fontColor: '#333333',\n },\n styles: DEFAULT_STYLES,\n};\n\nconst PPTX_THEMES: Record<string, PptxThemeConfig> = {\n default: DEFAULT_PPTX_THEME,\n dark: {\n name: 'dark',\n colors: {\n primary: '#5B9BD5',\n secondary: '#FF6F61',\n accent: '#6BCB77',\n background: '#2D2D2D',\n text: '#FFFFFF',\n text2: '#CCCCCC',\n background2: '#3D3D3D',\n accent4: '#FFB347',\n accent5: '#77DD77',\n accent6: '#AEC6CF',\n },\n fonts: {\n heading: 'Arial',\n body: 'Arial',\n },\n defaults: {\n fontSize: 18,\n fontColor: '#FFFFFF',\n },\n styles: DEFAULT_STYLES,\n },\n minimal: {\n name: 'minimal',\n colors: {\n primary: '#000000',\n secondary: '#666666',\n accent: '#999999',\n background: '#FFFFFF',\n text: '#000000',\n text2: '#444444',\n background2: '#F5F5F5',\n accent4: '#BBBBBB',\n accent5: '#DDDDDD',\n accent6: '#888888',\n },\n fonts: {\n heading: 'Helvetica',\n body: 'Helvetica',\n },\n defaults: {\n fontSize: 18,\n fontColor: '#000000',\n },\n styles: DEFAULT_STYLES,\n },\n};\n\nexport function getPptxTheme(name: string): PptxThemeConfig {\n return PPTX_THEMES[name] || DEFAULT_PPTX_THEME;\n}\n\n/**\n * Whether `name` is a known built-in theme. `getPptxTheme` never misses (it\n * falls back to the default theme), so callers that need to distinguish \"a\n * real built-in\" from \"an unknown name\" must check here first.\n */\nexport function hasPptxTheme(name: string): boolean {\n return Object.prototype.hasOwnProperty.call(PPTX_THEMES, name);\n}\n\nexport const pptxThemes = PPTX_THEMES;\n","/**\n * Generation options and the pre-generation gates.\n *\n * Extracted from `generator.ts` so the IR pipeline can use them without\n * importing the module that now delegates to it.\n */\n\nimport type { ServicesConfig, FontRuntimeOpts } from '@json-to-office/shared';\nimport {\n collectImageSourceConflicts,\n collectTextContentConflicts,\n validateJsonPresentationDocument,\n validatePresentationDocument,\n type ValidationError,\n} from '@json-to-office/shared-pptx';\nimport type {\n PipelineWarning,\n PptxThemeConfig,\n PresentationComponentDefinition,\n} from '../types';\nimport type { PresentationPackagingOptions } from './finalizePackage';\nimport type { PptxRendererId } from '../renderers/types';\n\nexport interface GenerationValidationOptions {\n /** Validate the complete component tree before rendering. Defaults to true. */\n enabled?: boolean;\n /** Accept unknown props while still enforcing required fields and types. */\n allowUnknownFields?: boolean;\n}\n\nexport interface GenerationOptions extends PresentationPackagingOptions {\n customThemes?: Record<string, PptxThemeConfig>;\n /**\n * Fully resolved theme, set by the generation prologue after the\n * export-mode pre-pass. Wins over the `props.theme` name/inline lookup in\n * `processPresentation` — omit it (direct callers) to fall back to that.\n */\n theme?: PptxThemeConfig;\n services?: ServicesConfig;\n fonts?: FontRuntimeOpts;\n validation?: GenerationValidationOptions;\n /**\n * Directory that relative asset paths (image `path` props, slide\n * background images) resolve against. Defaults to `process.cwd()` when\n * absent (#142).\n */\n baseDir?: string;\n /**\n * Backend that turns the compiled presentation into bytes.\n *\n * Defaults to `pptxgenjs`, which is what every existing caller gets.\n * `office-open` is experimental and opt-in: it declares a subset of\n * features and fails before rendering on anything outside it.\n */\n renderer?: PptxRendererId;\n}\n\n/** Result from `generateBufferWithWarnings`. */\nexport interface GenerationResult {\n buffer: Buffer;\n warnings: PipelineWarning[];\n}\n\n/** Error thrown when a presentation fails the generation validation gate. */\nexport class PresentationValidationError extends Error {\n public readonly errors: ValidationError[];\n\n constructor(errors: ValidationError[]) {\n super(\n `Presentation validation failed:\\n${errors\n .map((error) => ` - ${error.path}: ${error.message}`)\n .join('\\n')}`\n );\n this.name = 'PresentationValidationError';\n this.errors = errors;\n }\n}\n\nexport function assertValidPresentation(\n input: string | unknown,\n validation?: GenerationValidationOptions\n): void {\n assertValidPresentationInternal(input, validation, false);\n}\n\n/** Keep compiler capability diagnostics authoritative during generation. */\nexport function assertValidPresentationForGeneration(\n input: string | unknown,\n validation?: GenerationValidationOptions\n): void {\n assertValidPresentationInternal(input, validation, true);\n}\n\nfunction assertValidPresentationInternal(\n input: string | unknown,\n validation: GenerationValidationOptions | undefined,\n deferRendererProfileErrors: boolean\n): void {\n if (validation?.enabled === false) return;\n\n const options = {\n allowUnknownFields: validation?.allowUnknownFields,\n };\n const result =\n typeof input === 'string'\n ? validateJsonPresentationDocument(input, options)\n : validatePresentationDocument(input, options);\n\n const errors = deferRendererProfileErrors\n ? result.errors.filter(\n (error) => error.code !== 'unsupported_renderer_feature'\n )\n : result.errors;\n if (errors.length > 0) {\n throw new PresentationValidationError(errors);\n }\n}\n\n/**\n * Structural rules the per-component schema can't express: image sources\n * (path/base64/svg) are mutually exclusive, and text components carry\n * exactly one of text/runs. Reject conflicting payloads before rendering so\n * they can't be silently resolved by runtime precedence. Matches core-docx,\n * which fails generation on the same image conflict.\n *\n * Runs unconditionally — the validators also collect these conflicts, so this\n * is the net for `validation: { enabled: false }`. Shared with the plugin\n * path, which checks the expanded tree (custom components can emit\n * conflicting payloads too).\n */\nexport function assertNoContentConflicts(document: unknown): void {\n const sourceConflicts = [\n ...collectImageSourceConflicts(document),\n ...collectTextContentConflicts(document),\n ];\n if (sourceConflicts.length > 0) {\n throw new Error(\n `Document validation failed:\\n${sourceConflicts\n .map((e) => ` - ${e.path}: ${e.message}`)\n .join('\\n')}`\n );\n }\n}\n\n/** Type guard for a presentation component definition. */\nexport function isPresentationComponentDefinition(\n definition: unknown\n): definition is PresentationComponentDefinition {\n if (typeof definition !== 'object' || definition === null) return false;\n const def = definition as Record<string, unknown>;\n return def.name === 'pptx' && 'props' in def;\n}\n","/**\n * Environment detection utilities\n */\n\n/**\n * Check if the current environment is Node.js\n */\nexport function isNodeEnvironment(): boolean {\n return (\n typeof process !== 'undefined' &&\n process.versions != null &&\n process.versions.node != null &&\n typeof process.versions.node === 'string'\n );\n}\n","/**\n * Highcharts → image, before compilation.\n *\n * A `highcharts` component is authoring sugar: it describes a chart that an\n * export server renders to a PNG. That fetch is I/O, and the result is just an\n * image, so it is resolved here — an authoring-only expansion — rather than in\n * the compiler or an adapter. By the time PptxIR exists there is no chart\n * service left to depend on.\n *\n * This mirrors how the DOCX pipeline pre-rasterizes `visual` components.\n */\n\nimport type { HighchartsServiceConfig } from '@json-to-office/shared';\nimport type { PptxHighchartsProps } from '@json-to-office/shared-pptx';\nimport type {\n PipelineWarning,\n PptxComponentInput,\n PptxThemeConfig,\n ProcessedPresentation,\n} from '../types';\nimport { definedChartColorTokens, resolveColor } from '../utils/color';\nimport { isNodeEnvironment } from '../utils/environment';\n\n/** Screen pixels per inch, the unit the export server reports sizes in. */\nconst PX_PER_INCH = 96;\nconst DEFAULT_EXPORT_SERVER_URL = 'http://localhost:7801';\n\nexport interface HighchartsExpansionResult {\n presentation: ProcessedPresentation;\n /**\n * Highcharts components this pass did not reach.\n *\n * Placeholder content is merged with its declaration during compilation, so\n * expanding it here would use pre-merge dimensions. Rather than render a\n * chart at the wrong size, those are reported and the caller refuses.\n */\n unexpanded: Array<{ name: string; path: string }>;\n}\n\n/**\n * Replace every `highcharts` component with the `image` it renders to.\n *\n * Slide components and template objects are expanded in place. The presentation\n * is copied rather than mutated so a caller's tree is never altered.\n */\nexport async function expandHighchartsComponents(\n presentation: ProcessedPresentation,\n services: HighchartsServiceConfig | undefined,\n warnings: PipelineWarning[]\n): Promise<HighchartsExpansionResult> {\n const unexpanded: HighchartsExpansionResult['unexpanded'] = [];\n\n const templates = presentation.templates\n ? await Promise.all(\n presentation.templates.map(async (template, index) => ({\n ...template,\n objects: template.objects\n ? await expandList(\n template.objects,\n `masters[${index}].elements`,\n presentation.theme,\n services,\n warnings\n )\n : template.objects,\n }))\n )\n : presentation.templates;\n\n const slides = await Promise.all(\n presentation.slides.map(async (slide, index) => {\n for (const [name, component] of Object.entries(\n slide.placeholders ?? {}\n )) {\n if (component.name === 'highcharts') {\n unexpanded.push({\n name: 'highcharts',\n path: `slides[${index}].placeholders.${name}`,\n });\n }\n }\n return {\n ...slide,\n components: await expandList(\n slide.components,\n `slides[${index}].elements`,\n presentation.theme,\n services,\n warnings\n ),\n };\n })\n );\n\n return {\n presentation: { ...presentation, slides, templates },\n unexpanded,\n };\n}\n\nasync function expandList(\n components: PptxComponentInput[],\n path: string,\n theme: PptxThemeConfig,\n services: HighchartsServiceConfig | undefined,\n warnings: PipelineWarning[]\n): Promise<PptxComponentInput[]> {\n const out: PptxComponentInput[] = [];\n for (const [index, component] of components.entries()) {\n out.push(\n component.name === 'highcharts'\n ? await expandOne(\n component,\n `${path}[${index}]`,\n theme,\n services,\n warnings\n )\n : component\n );\n }\n return out;\n}\n\nasync function expandOne(\n component: PptxComponentInput,\n path: string,\n theme: PptxThemeConfig,\n services: HighchartsServiceConfig | undefined,\n warnings: PipelineWarning[]\n): Promise<PptxComponentInput> {\n const props = component.props as unknown as PptxHighchartsProps;\n const chart = await renderChart(\n withThemeColors(props, theme, warnings),\n services\n );\n\n void path;\n return {\n ...component,\n name: 'image',\n props: {\n base64: chart.dataUri,\n x: props.x ?? 0,\n y: props.y ?? 0,\n w: props.w ?? chart.widthPx / PX_PER_INCH,\n h: props.h ?? chart.heightPx / PX_PER_INCH,\n },\n };\n}\n\ninterface RenderedChart {\n dataUri: string;\n widthPx: number;\n heightPx: number;\n}\n\nasync function renderChart(\n config: PptxHighchartsProps,\n services: HighchartsServiceConfig | undefined\n): Promise<RenderedChart> {\n if (!isNodeEnvironment()) {\n throw new Error(\n 'Highcharts export server requires a Node.js environment. ' +\n 'Chart generation is not available in browser environments.'\n );\n }\n\n const serverUrl = exportServerUrl(config.serverUrl, services?.serverUrl);\n const requestBody = {\n infile: config.options,\n type: 'png',\n b64: true,\n scale: config.scale,\n // Forwarded verbatim only when present, so the payload stays byte-identical\n // for callers that omit it.\n ...(config.resources ? { resources: config.resources } : {}),\n };\n\n const resolvedHeaders =\n typeof services?.headers === 'function'\n ? await services.headers(requestBody)\n : services?.headers;\n\n const response = await fetch(`${serverUrl}/export`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', ...resolvedHeaders },\n body: JSON.stringify(requestBody),\n }).catch((error) => {\n throw new Error(\n `Highcharts Export Server is not running at ${serverUrl}. ` +\n 'Start it with: npx highcharts-export-server --enableServer true\\n' +\n `Cause: ${error instanceof Error ? error.message : String(error)}`\n );\n });\n\n if (!response.ok) {\n throw new Error(\n `Highcharts export server returned ${response.status}: ${response.statusText}`\n );\n }\n\n return {\n dataUri: `data:image/png;base64,${await response.text()}`,\n widthPx: config.options.chart?.width ?? 960,\n heightPx: config.options.chart?.height ?? 720,\n };\n}\n\nfunction exportServerUrl(propsUrl?: string, servicesUrl?: string): string {\n const raw = propsUrl || servicesUrl || DEFAULT_EXPORT_SERVER_URL;\n return raw.startsWith('http') ? raw : `http://${raw}`;\n}\n\n/**\n * Inject the theme's chart palette when the config sets no top-level `colors`.\n *\n * Without it, series render in the Highcharts default palette and ignore the\n * document theme. Slots the theme leaves unset are skipped — the same rule the\n * native chart component and DOCX both follow — so the palette never repeats\n * `primary`. An explicit `colors` always wins.\n */\nfunction withThemeColors(\n props: PptxHighchartsProps,\n theme: PptxThemeConfig,\n warnings: PipelineWarning[]\n): PptxHighchartsProps {\n if (!props.options || props.options.colors || !theme?.colors) return props;\n const palette = definedChartColorTokens(theme).map(\n (token) => `#${resolveColor(token, theme, warnings)}`\n );\n if (palette.length === 0) return props;\n return { ...props, options: { ...props.options, colors: palette } };\n}\n","/**\n * Image layout resolution, before compilation.\n *\n * Fitting an image needs its intrinsic pixel size, and getting that means I/O —\n * reading a file, or fetching a URL. That makes it a pre-pass rather than part\n * of the compiler, which stays synchronous and pure. What arrives at the\n * compiler is an image component whose `w`/`h` (and `sizing`, where it\n * survives) are already decided.\n *\n * Three cases need the intrinsic size:\n *\n * - exactly one of `w`/`h` given, no `sizing` — the other is derived from the\n * aspect ratio\n * - `sizing.type === 'contain'` — the image is fitted inside the box and\n * centred here, because the backend's own `contain` produces negative crop\n * values when the aspect ratios differ\n * - `sizing.type === 'cover'` — the backend crops correctly once it is given\n * the real intrinsic dimensions\n */\n\nimport path from 'node:path';\nimport probe from 'probe-image-size';\nimport type {\n PipelineWarning,\n PptxComponentInput,\n ProcessedPresentation,\n} from '../types';\nimport { resolveFromBaseDir } from '../utils/baseDirContext';\nimport { isAllowedLocalPath, resolveImageSource } from '../utils/imageSource';\nimport { W, warn } from '../utils/warn';\n\ninterface ImageSizing {\n type: string;\n w?: number | string;\n h?: number | string;\n}\n\n/** Resolve every image component's geometry across the presentation. */\nexport async function resolveImageLayout(\n presentation: ProcessedPresentation,\n warnings: PipelineWarning[]\n): Promise<ProcessedPresentation> {\n const resolve = (components: PptxComponentInput[]) =>\n resolveList(components, presentation, warnings);\n\n const [slides, templates] = await Promise.all([\n Promise.all(\n presentation.slides.map(async (slide) => ({\n ...slide,\n components: await resolve(slide.components),\n ...(slide.placeholders\n ? {\n placeholders: Object.fromEntries(\n await Promise.all(\n Object.entries(slide.placeholders).map(\n async ([name, component]) =>\n [name, (await resolve([component]))[0]] as const\n )\n )\n ),\n }\n : {}),\n }))\n ),\n presentation.templates\n ? Promise.all(\n presentation.templates.map(async (template) => ({\n ...template,\n ...(template.objects\n ? { objects: await resolve(template.objects) }\n : {}),\n }))\n )\n : Promise.resolve(presentation.templates),\n ]);\n\n return { ...presentation, slides, templates };\n}\n\nasync function resolveList(\n components: PptxComponentInput[],\n presentation: ProcessedPresentation,\n warnings: PipelineWarning[]\n): Promise<PptxComponentInput[]> {\n const out: PptxComponentInput[] = [];\n for (const component of components) {\n out.push(\n component.name === 'image'\n ? await resolveOne(component, presentation, warnings)\n : component\n );\n }\n return out;\n}\n\nasync function resolveOne(\n component: PptxComponentInput,\n presentation: ProcessedPresentation,\n warnings: PipelineWarning[]\n): Promise<PptxComponentInput> {\n const props = component.props as Record<string, unknown>;\n const source = resolveImageSource(\n props as Parameters<typeof resolveImageSource>[0]\n );\n if (!source) return component;\n\n const sizing = props.sizing as ImageSizing | undefined;\n const hasWidth = props.w !== undefined;\n const hasHeight = props.h !== undefined;\n const slideWidth = presentation.slideWidth;\n const slideHeight = presentation.slideHeight;\n\n const needsIntrinsic =\n (hasWidth !== hasHeight && !sizing) ||\n sizing?.type === 'contain' ||\n sizing?.type === 'cover';\n const intrinsic = needsIntrinsic\n ? await probeIntrinsicSize(source, warnings)\n : undefined;\n\n const next: Record<string, unknown> = { ...props };\n\n // Derive the missing dimension from the aspect ratio.\n if (hasWidth !== hasHeight && !sizing) {\n if (intrinsic && intrinsic.width > 0 && intrinsic.height > 0) {\n const aspect = intrinsic.width / intrinsic.height;\n if (hasWidth) {\n const width = toInches(props.w as number | string, slideWidth);\n next.w = width;\n next.h = width / aspect;\n } else {\n const height = toInches(props.h as number | string, slideHeight);\n next.h = height;\n next.w = height * aspect;\n }\n }\n return { ...component, props: next };\n }\n\n if (!sizing) return component;\n\n if (sizing.type !== 'contain' && sizing.type !== 'cover') {\n next.sizing = {\n ...sizing,\n w: toInches((sizing.w ?? props.w ?? 0) as number | string, slideWidth),\n h: toInches((sizing.h ?? props.h ?? 0) as number | string, slideHeight),\n };\n return { ...component, props: next };\n }\n\n const boxWidth = toInches(\n (sizing.w ?? props.w ?? 0) as number | string,\n slideWidth\n );\n const boxHeight = toInches(\n (sizing.h ?? props.h ?? 0) as number | string,\n slideHeight\n );\n\n if (boxWidth <= 0 || boxHeight <= 0) {\n warn(\n warnings,\n W.IMAGE_ZERO_BOX,\n `Image sizing box resolved to zero (${boxWidth}x${boxHeight})`,\n { component: 'image' }\n );\n }\n\n const usable =\n intrinsic &&\n intrinsic.width > 0 &&\n intrinsic.height > 0 &&\n boxWidth > 0 &&\n boxHeight > 0;\n\n if (!usable) {\n next.sizing = { ...sizing, w: boxWidth, h: boxHeight };\n return { ...component, props: next };\n }\n\n const imageAspect = intrinsic.width / intrinsic.height;\n\n if (sizing.type === 'contain') {\n // Fit inside the box, preserving the aspect ratio, centred. The element\n // ends up exactly the fitted size, so no sizing is passed on.\n const boxAspect = boxWidth / boxHeight;\n const fitWidth =\n imageAspect > boxAspect ? boxWidth : boxHeight * imageAspect;\n const fitHeight =\n imageAspect > boxAspect ? boxWidth / imageAspect : boxHeight;\n const baseX = toInches((props.x ?? 0) as number | string, slideWidth);\n const baseY = toInches((props.y ?? 0) as number | string, slideHeight);\n\n next.x = baseX + (boxWidth - fitWidth) / 2;\n next.y = baseY + (boxHeight - fitHeight) / 2;\n next.w = fitWidth;\n next.h = fitHeight;\n delete next.sizing;\n return { ...component, props: next };\n }\n\n // Cover: the backend crops correctly once given the real intrinsic size.\n next.w = intrinsic.width;\n next.h = intrinsic.height;\n next.sizing = { type: 'cover', w: boxWidth, h: boxHeight };\n return { ...component, props: next };\n}\n\n/**\n * Resolve a dimension to inches.\n *\n * Deliberately the plain rule — a number is inches, a percent resolves against\n * the axis — because these values feed the fitting arithmetic, where \"inches\"\n * is the only interpretation that makes sense.\n */\nfunction toInches(value: number | string, axisInches: number): number {\n if (typeof value === 'number') return value;\n if (value.endsWith('%')) {\n const pct = Number.parseFloat(value);\n return !Number.isNaN(pct) && pct >= 0 ? (pct / 100) * axisInches : 0;\n }\n const n = Number(value);\n return Number.isNaN(n) ? 0 : n;\n}\n\n/** Block requests to private, loopback and link-local hosts. */\nfunction isPrivateUrl(urlString: string): boolean {\n try {\n const { hostname } = new URL(urlString);\n if (\n hostname === 'localhost' ||\n hostname === '127.0.0.1' ||\n hostname === '::1' ||\n hostname === '[::1]' ||\n hostname.startsWith('10.') ||\n hostname.startsWith('192.168.') ||\n hostname.startsWith('169.254.') ||\n hostname.endsWith('.local') ||\n hostname.endsWith('.internal')\n ) {\n return true;\n }\n if (hostname.startsWith('172.')) {\n const second = Number.parseInt(hostname.split('.')[1], 10);\n if (second >= 16 && second <= 31) return true;\n }\n return false;\n } catch {\n return true;\n }\n}\n\nasync function probeIntrinsicSize(\n source: string,\n warnings: PipelineWarning[]\n): Promise<{ width: number; height: number } | undefined> {\n try {\n if (/^data:image\\//.test(source)) {\n const base64Data = source.split(',')[1];\n if (!base64Data) return undefined;\n const result = probe.sync(Buffer.from(base64Data, 'base64'));\n return result\n ? { width: result.width, height: result.height }\n : undefined;\n }\n\n if (/^https?:\\/\\//.test(source)) {\n if (isPrivateUrl(source)) return undefined;\n const result = await probe(source, { timeout: 5000 });\n return { width: result.width, height: result.height };\n }\n\n // Local file — restricted to the document base directory (or CWD) to\n // prevent path traversal (#142).\n const resolved = path.resolve(resolveFromBaseDir(source));\n if (!isAllowedLocalPath(resolved)) return undefined;\n const { createReadStream } = await import('fs');\n const result = await probe(createReadStream(resolved));\n return result ? { width: result.width, height: result.height } : undefined;\n } catch (error) {\n warn(\n warnings,\n W.IMAGE_PROBE_FAILED,\n `Image probe failed: ${error instanceof Error ? error.message : String(error)}`,\n { component: 'image' }\n );\n return undefined;\n }\n}\n","/**\n * Structure Processing\n * JSON -> internal model\n */\n\nimport type {\n PptxComponentInput,\n PptxThemeConfig,\n PresentationComponentDefinition,\n ProcessedPresentation,\n ProcessedSlide,\n SlideComponentDefinition,\n TemplateSlideDefinition,\n} from '../types';\nimport { isSlideComponent } from '../types';\nimport {\n resolveGridPosition,\n resolveComponentGridPosition,\n mergeGridConfigs,\n} from './grid';\nimport { getPptxTheme } from '../themes';\nimport type { GenerationOptions } from './generator';\nimport { resolveComponentTree } from '../utils/resolveComponentTree';\nimport {\n remapHyperlinkProps,\n remapHyperlinkSlideRefs,\n} from '../utils/hyperlink';\nimport { mergeWithDefaults } from '@json-to-office/shared';\n\n/** A slide child is rendered unless it carries `enabled: false`. */\nfunction isSlideEnabled(child: object): boolean {\n return !(\n 'enabled' in child && (child as { enabled?: boolean }).enabled === false\n );\n}\n\n/**\n * Map authored 1-based slide numbers (disabled slides included) to their\n * position in the generated deck. Dropped slides are absent from the map, so\n * hyperlinks pointing at them resolve to nothing instead of to whichever slide\n * happened to shift into that number.\n */\nfunction buildSlideIndexMap(\n children: PptxComponentInput[]\n): Map<number, number> {\n const map = new Map<number, number>();\n let authored = 0;\n let rendered = 0;\n for (const child of children) {\n if (!isSlideComponent(child)) continue;\n authored++;\n if (isSlideEnabled(child)) map.set(authored, ++rendered);\n }\n return map;\n}\n\nexport function processPresentation(\n document: PresentationComponentDefinition,\n options?: GenerationOptions\n): ProcessedPresentation {\n const { props, children = [] } = document;\n\n // The generation prologue hands the resolved theme over directly — after\n // the export-mode pre-pass, so a name lookup here would resurrect\n // pre-substitute font families. The `props.theme` resolution below (a name,\n // or an inline theme config object embedded in the document itself —\n // self-contained documents-as-data) is the fallback for direct callers.\n const baseTheme =\n options?.theme ??\n (typeof props.theme === 'object' && props.theme !== null\n ? (props.theme as PptxThemeConfig)\n : options?.customThemes?.[props.theme ?? 'default'] ??\n getPptxTheme(props.theme ?? 'default'));\n\n // Merge presentation-level componentDefaults on top of theme-level ones\n const presDefaults = props.componentDefaults;\n const theme = presDefaults\n ? {\n ...baseTheme,\n componentDefaults: mergeWithDefaults(\n presDefaults,\n baseTheme.componentDefaults || {}\n ),\n }\n : baseTheme;\n\n const slideWidth = props.slideWidth ?? 10;\n const slideHeight = props.slideHeight ?? 7.5;\n\n const slideIndexMap = buildSlideIndexMap(children);\n\n // Process template slide definitions\n let templates: TemplateSlideDefinition[] | undefined;\n if (props.templates && props.templates.length > 0) {\n templates = props.templates.map((m: TemplateSlideDefinition) => {\n const effectiveGrid = mergeGridConfigs(props.grid, m.grid);\n\n // Rebase slide refs in placeholder `defaults`, then resolve grid\n // positions. `defaults.props` is merged into the rendered component by\n // core/render.ts, so it reaches the writer just like a component's own\n // props and needs the same remapping.\n const resolvedPhs = m.placeholders?.map((ph) => {\n const phDefaults = ph.defaults;\n const defaultProps = phDefaults?.props\n ? remapHyperlinkProps(phDefaults.props, slideIndexMap)\n : undefined;\n const base =\n phDefaults && defaultProps && defaultProps !== phDefaults.props\n ? { ...ph, defaults: { ...phDefaults, props: defaultProps } }\n : ph;\n\n if (!base.grid) return base;\n const abs = resolveGridPosition(\n base.grid,\n effectiveGrid,\n slideWidth,\n slideHeight\n );\n return {\n ...base,\n x: base.x ?? abs.x,\n y: base.y ?? abs.y,\n w: base.w ?? abs.w,\n h: base.h ?? abs.h,\n grid: undefined,\n };\n });\n\n // Resolve componentDefaults then grid positions on fixed objects\n const defaultedObjects = m.objects\n ? resolveComponentTree(m.objects, theme)\n : undefined;\n const resolvedObjects = defaultedObjects?.map((obj) =>\n remapHyperlinkSlideRefs(\n resolveComponentGridPosition(\n obj,\n effectiveGrid,\n slideWidth,\n slideHeight\n ),\n slideIndexMap\n )\n );\n\n return { ...m, placeholders: resolvedPhs, objects: resolvedObjects };\n });\n }\n\n const slides: ProcessedSlide[] = [];\n\n for (const child of children) {\n if (isSlideComponent(child)) {\n // `enabled: false` drops the slide entirely; absent means enabled\n if (!isSlideEnabled(child)) continue;\n\n const slideComponents: PptxComponentInput[] = [];\n if (child.children) {\n for (const slideChild of child.children) {\n slideComponents.push(slideChild);\n }\n }\n\n // Resolve componentDefaults on all slide components, then rebase\n // slide-targeted hyperlinks onto the generated slide numbering\n const resolvedComponents = resolveComponentTree(\n slideComponents,\n theme\n ).map((component) => remapHyperlinkSlideRefs(component, slideIndexMap));\n\n // Every slide prop is optional, so validation accepts a slide with no\n // `props` at all (the deep validator checks an empty object in that\n // case). Generation has to accept the same documents validation does.\n const slideProps: NonNullable<SlideComponentDefinition['props']> =\n child.props ?? {};\n\n const placeholders = slideProps.placeholders as\n | Record<string, PptxComponentInput>\n | undefined;\n\n slides.push({\n components: resolvedComponents,\n background: slideProps.background,\n transition: slideProps.transition,\n notes: slideProps.notes,\n layout: slideProps.layout,\n hidden: slideProps.hidden,\n template: slideProps.template,\n placeholders: placeholders\n ? Object.fromEntries(\n Object.entries(placeholders).map(([name, component]) => [\n name,\n remapHyperlinkSlideRefs(component, slideIndexMap),\n ])\n )\n : undefined,\n });\n }\n }\n\n return {\n metadata: {\n title: props.title,\n author: props.author,\n subject: props.subject,\n company: props.company,\n },\n theme,\n grid: props.grid,\n slideWidth,\n slideHeight,\n rtlMode: props.rtlMode ?? false,\n language: props.language,\n pageNumberFormat: props.pageNumberFormat ?? '9',\n slides,\n templates,\n services: options?.services,\n };\n}\n","// Version information\nexport function getPptxCoreVersion(): string {\n return 'PptxCore v1.0.0';\n}\n\n// Core API — buffer and file oriented; no member exposes a renderer object.\nexport {\n generateBufferFromJson,\n generateBufferWithWarnings,\n generateAndSaveFromJson,\n generateFromFile,\n isPresentationComponentDefinition,\n PresentationValidationError,\n PresentationGenerator,\n} from './core/generator';\n\nexport type {\n GenerationOptions,\n GenerationResult,\n GenerationValidationOptions,\n} from './core/generator';\n\n// Renderer selection. The IR itself stays internal to this package for now.\nexport type { PptxRendererId } from './renderers/types';\nexport { DEFAULT_PPTX_RENDERER_ID } from './renderers/types';\nexport { isPptxRendererId, pptxRendererIds } from './renderers/registry';\nexport { UncompiledComponentError } from './core/generateFromIr';\nexport { DEFAULT_GENERATED_AT } from './core/finalizePackage';\nexport type { PresentationPackagingOptions } from './core/finalizePackage';\n\n// Types\nexport type {\n PptxComponentInput,\n PresentationComponentDefinition,\n PresentationComponentDefinitionFor,\n SlideComponentDefinition,\n ProcessedPresentation,\n ProcessedSlide,\n PptxThemeConfig,\n PipelineWarning,\n SlideContext,\n SlideRenderContext,\n} from './types';\n\nexport { isPresentationComponent, isSlideComponent } from './types';\n\n// Warning utilities\nexport { W as WarningCodes } from './utils/warn';\nexport type { WarningCode } from './utils/warn';\n\n// Themes\nexport { DEFAULT_PPTX_THEME, getPptxTheme, pptxThemes } from './themes';\n\n// Plugin system\nexport {\n createComponent,\n createVersion,\n createPresentationGenerator,\n resolveComponentVersion,\n validateComponentProps,\n validatePresentation,\n cleanComponentProps,\n ComponentValidationError,\n DuplicateComponentError,\n generatePluginPresentationSchema,\n exportPluginSchema,\n} from './plugin';\n\nexport type {\n CustomComponent,\n ComponentVersion,\n ComponentVersionMap,\n RenderFunction,\n RenderContext,\n PresentationGeneratorOptions,\n PresentationGenerator as PluginPresentationGenerator,\n PresentationGeneratorBuilder,\n BufferGenerationResult as PluginBufferGenerationResult,\n FileGenerationResult as PluginFileGenerationResult,\n GenerateFileOptions as PluginGenerateFileOptions,\n GenerateOptions as PluginGenerateOptions,\n GenerationValidationOptions as PluginGenerationValidationOptions,\n ValidationResult as PluginValidationResult,\n ExtractCustomComponentType,\n CustomComponentUnion,\n ExtendedPptxComponentInput,\n ExtendedPresentationComponent,\n InferBuilderComponents,\n InferDocumentType,\n InferComponentDefinition,\n ComponentValidationResult,\n ValidationError as PluginValidationError,\n} from './plugin';\n","/**\n * Plugin system for json-to-pptx\n *\n * @example\n * ```typescript\n * import { createComponent, createVersion, createPresentationGenerator } from '@json-to-office/core-pptx/plugin';\n * import { Type } from '@sinclair/typebox';\n *\n * const bannerComponent = createComponent({\n * name: 'banner' as const,\n * versions: {\n * '1.0.0': createVersion({\n * propsSchema: Type.Object({ title: Type.String() }),\n * render: async ({ props }) => [{\n * name: 'text',\n * props: { text: props.title, x: 0.5, y: 0.5, w: 9, h: 1 }\n * }]\n * })\n * }\n * });\n *\n * const generator = createPresentationGenerator()\n * .addComponent(bannerComponent);\n * ```\n */\n\n// Component creation (from shared)\nexport {\n createComponent,\n createVersion,\n type CustomComponent,\n type ComponentVersion,\n type ComponentVersionMap,\n type RenderFunction,\n type RenderContext,\n} from '@json-to-office/shared/plugin';\n\n// Generator\nexport {\n createPresentationGenerator,\n type PresentationGeneratorOptions,\n} from './createPresentationGenerator';\n\n// Types\nexport {\n type PresentationGenerator,\n type PresentationGeneratorBuilder,\n type BufferGenerationResult,\n type FileGenerationResult,\n type GenerateFileOptions,\n type GenerateOptions,\n type GenerationValidationOptions,\n type ValidationResult,\n type ExtractCustomComponentType,\n type CustomComponentUnion,\n type ExtendedPptxComponentInput,\n type ExtendedPresentationComponent,\n type InferBuilderComponents,\n type InferDocumentType,\n type InferComponentDefinition,\n} from './types';\n\n// Validation\nexport {\n validateComponentProps,\n validatePresentation,\n cleanComponentProps,\n ComponentValidationError,\n DuplicateComponentError,\n type ValidationError,\n type ComponentValidationResult,\n} from './validation';\n\n// Schema\nexport { generatePluginPresentationSchema, exportPluginSchema } from './schema';\n\n// Version resolution (from shared)\nexport { resolveComponentVersion } from '@json-to-office/shared/plugin';\n","import type { TSchema } from '@sinclair/typebox';\nimport type { CustomComponent } from '@json-to-office/shared/plugin';\nimport {\n resolveComponentVersion,\n DuplicateComponentError,\n ComponentValidationError,\n} from '@json-to-office/shared/plugin';\nimport type {\n PptxComponentInput,\n PresentationComponentDefinition,\n PipelineWarning,\n PptxThemeConfig,\n} from '../types';\nimport type {\n ExtendedPresentationComponent,\n PresentationGeneratorBuilder,\n BufferGenerationResult,\n FileGenerationResult,\n GenerateFileOptions,\n GenerateOptions,\n GenerationValidationOptions,\n ValidationResult,\n} from './types';\nimport { validatePresentation, cleanComponentProps } from './validation';\nimport { generatePluginPresentationSchema, exportPluginSchema } from './schema';\nimport { processPresentation } from '../core/structure';\nimport type { PresentationPackagingOptions } from '../core/finalizePackage';\nimport { renderProcessedViaIr } from '../core/generateFromIr';\nimport type { PptxRendererId } from '../renderers/types';\nimport { getPptxTheme, hasPptxTheme } from '../themes';\nimport type { ServicesConfig, FontRuntimeOpts } from '@json-to-office/shared';\nimport { resolveDocumentFonts } from '../core/fontResolution';\nimport { resolveThemeContext } from '../core/generationContext';\nimport { runWithBaseDir } from '../utils/baseDirContext';\nimport { assertNoContentConflicts } from '../core/generator';\n\n/**\n * Options for creating a presentation generator\n */\nexport interface PresentationGeneratorOptions\n extends PresentationPackagingOptions {\n /** Theme configuration or theme name */\n theme?: PptxThemeConfig | string;\n /** Custom themes map */\n customThemes?: Record<string, PptxThemeConfig>;\n /** Enable debug logging */\n debug?: boolean;\n /** External service configuration (e.g. Highcharts export server) */\n services?: ServicesConfig;\n /** Font resolution options — extraEntries, Google Fonts config, onResolved hook. */\n fonts?: FontRuntimeOpts;\n /** Default validation behavior; per-call options take precedence. */\n validation?: GenerationValidationOptions;\n /**\n * Directory that relative asset paths (image `path` props, slide\n * background images) resolve against. Per-call `options.baseDir`\n * overrides it; defaults to `process.cwd()` when neither is set (#142).\n */\n baseDir?: string;\n /**\n * Backend that turns the compiled presentation into bytes. Per-call\n * `options.renderer` overrides it; defaults to `pptxgenjs`.\n */\n renderer?: PptxRendererId;\n}\n\n/**\n * Internal state held by each builder instance\n */\ninterface BuilderState {\n components: readonly CustomComponent<any, any, any>[];\n componentNames: Set<string>;\n theme?: PptxThemeConfig | string;\n customThemes?: Record<string, PptxThemeConfig>;\n debug: boolean;\n services?: ServicesConfig;\n fonts?: FontRuntimeOpts;\n validation?: GenerationValidationOptions;\n packaging: PresentationPackagingOptions;\n baseDir?: string;\n renderer?: PptxRendererId;\n}\n\ntype ValidateEmitted = (\n emitted: PptxComponentInput[],\n componentLabel: string,\n parentName?: string\n) => void;\n\n/**\n * Create the builder implementation with the given state\n */\nfunction createBuilderImpl<\n TComponents extends readonly CustomComponent<any, any, any>[],\n>(state: BuilderState): PresentationGeneratorBuilder<TComponents> {\n const componentMap = new Map(state.components.map((c) => [c.name, c]));\n\n /**\n * Process custom components in slide children, recursively resolving them\n * to standard PptxComponentInput elements.\n */\n async function processSlideComponents(\n components: PptxComponentInput[],\n warningsCollector: PipelineWarning[],\n theme: PptxThemeConfig,\n validateEmitted: ValidateEmitted | undefined,\n parentName?: string,\n depth = 0\n ): Promise<PptxComponentInput[]> {\n if (depth > 20) {\n throw new Error(\n 'Maximum component nesting depth exceeded (20). Check for circular component references.'\n );\n }\n const processed: PptxComponentInput[] = [];\n\n for (const componentData of components) {\n const customComponent = componentMap.get(componentData.name);\n\n if (customComponent) {\n try {\n if (!componentData.props) {\n throw new Error(\n `Custom component '${componentData.name}' must have a 'props' property. ` +\n `Use format: { name: '${componentData.name}', props: {...} }`\n );\n }\n\n const componentWithVersion = componentData as {\n name: string;\n version?: string;\n props: Record<string, any>;\n children?: PptxComponentInput[];\n };\n\n // Resolve version\n const versionEntry = resolveComponentVersion(\n customComponent.name,\n customComponent.versions,\n componentWithVersion.version\n );\n\n // Validate and clean props\n const cleanedProps = cleanComponentProps(\n versionEntry,\n componentWithVersion.props\n );\n\n // Process nested children if container\n let nestedChildren: unknown[] | undefined;\n if (\n componentWithVersion.children &&\n Array.isArray(componentWithVersion.children)\n ) {\n nestedChildren = await processSlideComponents(\n componentWithVersion.children,\n warningsCollector,\n theme,\n validateEmitted,\n undefined,\n depth + 1\n );\n }\n\n // Create addWarning callback\n const versionLabel = componentWithVersion.version\n ? `${customComponent.name}@${componentWithVersion.version}`\n : customComponent.name;\n\n const addWarning = (\n message: string,\n context?: Record<string, unknown>\n ) => {\n warningsCollector.push({\n code: (context?.code as string) ?? 'PLUGIN_WARNING',\n message,\n component: versionLabel,\n slide: context?.slide as number | undefined,\n });\n };\n\n // Call render\n const result = await versionEntry.render({\n props: cleanedProps,\n theme,\n addWarning,\n children: nestedChildren,\n });\n\n const resultComponents = (\n Array.isArray(result) ? result : [result]\n ) as PptxComponentInput[];\n\n validateEmitted?.(resultComponents, versionLabel, parentName);\n\n // Recursively process in case result contains more custom components\n const processedResult = await processSlideComponents(\n resultComponents,\n warningsCollector,\n theme,\n validateEmitted,\n parentName,\n depth + 1\n );\n processed.push(...processedResult);\n\n if (state.debug) {\n console.log(\n `Processed custom component '${versionLabel}':`,\n processedResult\n );\n }\n } catch (error) {\n if (error instanceof ComponentValidationError) {\n throw error;\n }\n throw new Error(\n `Error processing custom component '${customComponent.name}': ${\n error instanceof Error ? error.message : String(error)\n }`\n );\n }\n } else {\n // Standard component — process children recursively\n if (componentData.children && Array.isArray(componentData.children)) {\n const processedChildren = await processSlideComponents(\n componentData.children,\n warningsCollector,\n theme,\n validateEmitted,\n componentData.name,\n depth + 1\n );\n processed.push({\n ...componentData,\n children: processedChildren,\n });\n } else {\n processed.push(componentData);\n }\n }\n }\n\n return processed;\n }\n\n /**\n * Add a custom component to the generator\n */\n function addComponent<TNewComponent extends CustomComponent<any, any, any>>(\n component: TNewComponent\n ): PresentationGeneratorBuilder<readonly [...TComponents, TNewComponent]> {\n if (!component.name) {\n throw new Error('Component name is required');\n }\n\n if (state.componentNames.has(component.name)) {\n throw new DuplicateComponentError(component.name);\n }\n\n const newComponentNames = new Set(state.componentNames);\n newComponentNames.add(component.name);\n\n const newState: BuilderState = {\n components: [...state.components, component],\n componentNames: newComponentNames,\n theme: state.theme,\n customThemes: state.customThemes,\n debug: state.debug,\n services: state.services,\n fonts: state.fonts,\n validation: state.validation,\n packaging: state.packaging,\n baseDir: state.baseDir,\n renderer: state.renderer,\n };\n\n return createBuilderImpl<readonly [...TComponents, TNewComponent]>(\n newState\n );\n }\n\n /**\n * Generate a presentation buffer\n */\n async function generate(\n document: ExtendedPresentationComponent<TComponents>,\n options?: GenerateOptions\n ): Promise<BufferGenerationResult> {\n try {\n let internalDocument =\n document as unknown as PresentationComponentDefinition;\n const renderer =\n options?.renderer ?? state.renderer ?? internalDocument.renderer;\n const validationDocument =\n renderer === undefined\n ? internalDocument\n : { ...internalDocument, renderer };\n\n const validationOptions: GenerationValidationOptions = {\n ...state.validation,\n ...options?.validation,\n };\n if (validationOptions.enabled !== false) {\n const result = validatePresentation(\n validationDocument,\n state.components as unknown as CustomComponent<TSchema>[],\n { allowUnknownFields: validationOptions.allowUnknownFields }\n );\n if (!result.valid) {\n throw new ComponentValidationError(result.errors, internalDocument);\n }\n } else if (!internalDocument || internalDocument.name !== 'pptx') {\n throw new Error('Top-level component must be a pptx component');\n }\n\n const warnings: PipelineWarning[] = [];\n\n // Props defaulting, inline-theme normalization, theme resolution\n // (customThemes → constructor theme → built-in) and export-mode pre-pass\n // — shared with the core pipeline so the two\n // cannot drift (see core/generationContext.ts). The pre-pass runs\n // BEFORE custom-component expansion so any component that reads\n // `theme.fonts.*` during render sees the substituted names, not the\n // original non-safe ones.\n //\n // Theme precedence: customThemes[name] → doc-named built-in →\n // constructor `state.theme` object → built-in, with the lookup name\n // taken from doc-level `props.theme` (or `defaultThemeName` when the\n // doc names none). A document explicitly naming a known built-in gets\n // it; the constructor object fills in when the doc names nothing or\n // names something nothing recognizes (#141). The `authored` guard on\n // the built-in step matters twice over: an unauthored default name\n // must not shadow the constructor object, and an authored UNKNOWN name\n // must still reach the constructor object (getPptxTheme never misses —\n // a doc naming \"wiseair\" must render the app's theme, not silently\n // fall back to default). Matches the DOCX plugin\n // (resolveDocumentTheme) exactly.\n const context = resolveThemeContext(internalDocument, {\n customThemes: state.customThemes,\n fonts: state.fonts,\n warnings,\n defaultThemeName:\n typeof state.theme === 'string' ? state.theme : undefined,\n resolveNamedTheme: (name, authored) =>\n state.customThemes?.[name] ??\n (authored && hasPptxTheme(name) ? getPptxTheme(name) : undefined) ??\n (typeof state.theme === 'object' && state.theme !== null\n ? state.theme\n : getPptxTheme(name)),\n });\n const modedRoot = context.document;\n const resolvedTheme = context.theme;\n\n // A custom render() creates a new, previously unseen boundary in the\n // component tree. Validate its output in the authored parent context so\n // dead props and illegal placement cannot reach the renderer silently.\n const validateEmitted: ValidateEmitted | undefined =\n validationOptions.enabled === false\n ? undefined\n : (emitted, componentLabel, parentName) => {\n let validationDocument: PresentationComponentDefinition;\n if (parentName === 'pptx') {\n validationDocument = {\n ...modedRoot,\n ...(renderer !== undefined ? { renderer } : {}),\n children: emitted,\n };\n } else if (parentName === 'slide') {\n validationDocument = {\n ...modedRoot,\n ...(renderer !== undefined ? { renderer } : {}),\n children: [{ name: 'slide', props: {}, children: emitted }],\n };\n } else {\n // Custom container semantics are plugin-defined. The complete\n // expanded-tree pass below validates the final standard tree.\n return;\n }\n\n const result = validatePresentation(\n validationDocument,\n state.components as unknown as CustomComponent<TSchema>[],\n { allowUnknownFields: validationOptions.allowUnknownFields }\n );\n if (!result.valid) {\n throw new ComponentValidationError(\n result.errors.map((error) => ({\n ...error,\n message: `custom component '${componentLabel}' emitted invalid output — ${error.message}`,\n })),\n emitted\n );\n }\n };\n\n // Process custom components in all slide children\n const processedChildren = modedRoot.children\n ? await processAllSlides(\n modedRoot.children,\n warnings,\n resolvedTheme,\n validateEmitted\n )\n : [];\n\n const processedDocument: PresentationComponentDefinition = {\n ...modedRoot,\n children: processedChildren,\n };\n\n // Validate the fully expanded tree once more. This covers output from\n // nested custom containers whose intermediate parent semantics are\n // plugin-defined and therefore cannot be checked at render time.\n if (validationOptions.enabled !== false) {\n const result = validatePresentation(\n {\n ...processedDocument,\n ...(renderer !== undefined ? { renderer } : {}),\n },\n [],\n {\n allowUnknownFields: validationOptions.allowUnknownFields,\n }\n );\n if (!result.valid) {\n throw new ComponentValidationError(\n result.errors.map((error) => ({\n ...error,\n message: `expanded plugin output failed validation — ${error.message}`,\n })),\n processedDocument\n );\n }\n }\n\n // resolveDocumentFonts fires `fonts.onResolved` internally when a\n // listener is registered (LibreOffice preview stager). The PPTX\n // itself never embeds bytes.\n await resolveDocumentFonts(\n processedDocument,\n resolvedTheme,\n warnings,\n state.fonts\n );\n\n // Unconditional conflict gate on the expanded tree — the tree that\n // reaches the renderer, so it also covers payloads emitted by custom\n // components. The validators above collect the same conflicts with\n // richer paths when validation is enabled; this is the net for\n // `validation: { enabled: false }`, where the core path already threw\n // and this path silently resolved by runtime precedence.\n assertNoContentConflicts(processedDocument);\n\n // processPresentation takes the resolved (post-substitute) theme by\n // value — the document's `props.theme` stays as authored and is not\n // consulted again.\n // Scope the document base directory over process+render: relative\n // asset paths are rewritten eagerly there — pptxgenjs reads them\n // later, during write() (#142). Matches the core pipeline.\n const buffer = await runWithBaseDir(\n options?.baseDir ?? state.baseDir,\n () =>\n renderProcessedViaIr(\n processPresentation(processedDocument, {\n theme: resolvedTheme,\n services: state.services,\n }),\n warnings,\n {\n renderer,\n services: state.services,\n deterministic:\n options?.deterministic ?? state.packaging.deterministic,\n generatedAt: options?.generatedAt ?? state.packaging.generatedAt,\n }\n )\n );\n\n return { buffer, warnings };\n } catch (error) {\n if (state.debug) {\n console.error('Presentation generation error:', error);\n }\n throw error;\n }\n }\n\n /**\n * Process custom components inside all slides.\n * Walks the top-level children (slides), then processes each slide's children.\n */\n async function processAllSlides(\n children: PptxComponentInput[],\n warnings: PipelineWarning[],\n theme: PptxThemeConfig,\n validateEmitted: ValidateEmitted | undefined\n ): Promise<PptxComponentInput[]> {\n const result: PptxComponentInput[] = [];\n\n for (const child of children) {\n if (child.name === 'slide' && child.children) {\n const processedSlideChildren = await processSlideComponents(\n child.children,\n warnings,\n theme,\n validateEmitted,\n 'slide'\n );\n result.push({ ...child, children: processedSlideChildren });\n } else {\n // Non-slide top-level children — process in case they're custom\n const processedTopLevel = await processSlideComponents(\n [child],\n warnings,\n theme,\n validateEmitted,\n 'pptx'\n );\n result.push(...processedTopLevel);\n }\n }\n\n return result;\n }\n\n /**\n * Generate and save to file\n */\n async function generateFile(\n document: ExtendedPresentationComponent<TComponents>,\n outputPath: string,\n options?: GenerateFileOptions\n ): Promise<FileGenerationResult> {\n const { buffer, warnings } = await generate(document, options);\n const fs = await import('fs/promises');\n await fs.writeFile(outputPath, new Uint8Array(buffer));\n return { warnings };\n }\n\n /**\n * Get registered component names\n */\n function getComponentNames(): string[] {\n return Array.from(state.componentNames);\n }\n\n /**\n * Validate a document without generating it\n */\n function validate(\n document: ExtendedPresentationComponent<TComponents>\n ): ValidationResult {\n try {\n const internalDocument =\n document as unknown as PresentationComponentDefinition;\n const result = validatePresentation(\n internalDocument,\n state.components as unknown as CustomComponent<TSchema>[]\n );\n if (!result.valid) {\n return {\n valid: false,\n errors: result.errors.map((e) => ({\n path: e.path,\n message: e.message,\n })),\n };\n }\n return { valid: true };\n } catch (error) {\n if (error instanceof ComponentValidationError) {\n return {\n valid: false,\n errors: error.errors.map((e) => ({\n path: e.path,\n message: e.message,\n })),\n };\n }\n return {\n valid: false,\n errors: [\n {\n path: 'document',\n message: error instanceof Error ? error.message : String(error),\n },\n ],\n };\n }\n }\n\n /**\n * Generate the extended JSON schema\n */\n function generateSchema(): TSchema {\n return generatePluginPresentationSchema(\n state.components as unknown as CustomComponent<TSchema>[]\n );\n }\n\n /**\n * Export the schema to a file\n */\n async function exportSchemaToFile(\n outputPath: string,\n options?: { prettyPrint?: boolean }\n ): Promise<void> {\n await exportPluginSchema(\n state.components as unknown as CustomComponent<TSchema>[],\n outputPath,\n options\n );\n }\n\n return Object.freeze({\n addComponent,\n generate,\n generateBuffer: generate,\n generateFile,\n getComponentNames,\n validate,\n generateSchema,\n exportSchema: exportSchemaToFile,\n });\n}\n\n/**\n * Create a presentation generator with chainable component registration.\n */\nexport function createPresentationGenerator(\n options: PresentationGeneratorOptions = {}\n): PresentationGeneratorBuilder<readonly []> {\n const initialState: BuilderState = {\n components: [],\n componentNames: new Set(),\n theme: options.theme,\n customThemes: options.customThemes,\n debug: options.debug ?? false,\n services: options.services,\n fonts: options.fonts,\n validation: options.validation,\n packaging: {\n deterministic: options.deterministic,\n generatedAt: options.generatedAt,\n },\n baseDir: options.baseDir,\n renderer: options.renderer,\n };\n\n return createBuilderImpl<readonly []>(initialState);\n}\n","import type { TSchema, Static } from '@sinclair/typebox';\nimport type { CustomComponent } from '@json-to-office/shared/plugin';\nimport type { PresentationComponentDefinition } from '../types';\nimport {\n resolveComponentVersion,\n validateCustomComponentProps,\n ComponentValidationError,\n type ComponentValidationResult,\n} from '@json-to-office/shared/plugin';\nimport type { ValidationError } from '@json-to-office/shared';\nimport { validatePresentationDocument } from '@json-to-office/shared-pptx';\n\n// Re-export errors from shared\nexport {\n DuplicateComponentError,\n ComponentValidationError,\n} from '@json-to-office/shared/plugin';\nexport type { ComponentValidationResult } from '@json-to-office/shared/plugin';\nexport type { ValidationError } from '@json-to-office/shared';\n\n/**\n * Validate component props against a schema.\n */\nexport function validateComponentProps<TPropsSchema extends TSchema>(\n schema: { propsSchema: TPropsSchema },\n props: unknown,\n componentName?: string,\n opts?: { clean?: boolean; applyDefaults?: boolean }\n): ComponentValidationResult<TPropsSchema> {\n return validateCustomComponentProps<TPropsSchema>(schema.propsSchema, props, {\n // Render-time cleaning remains the default. The document-validation path\n // passes clean:false so unknown custom props are rejected when the custom\n // schema declares additionalProperties:false.\n clean: opts?.clean ?? true,\n applyDefaults: opts?.applyDefaults ?? true,\n componentName,\n });\n}\n\n/**\n * Validate presentation and all custom components (version-aware).\n *\n * Standard nodes and tree structure are checked by the shared deep validator;\n * custom component props are then checked against their resolved version.\n */\nexport function validatePresentation(\n document: PresentationComponentDefinition,\n customComponents: CustomComponent<any, any, any>[],\n options?: { allowUnknownFields?: boolean }\n): { valid: boolean; errors: ValidationError[] } {\n const knownCustomNames = new Set(customComponents.map((c) => c.name));\n\n // Validate all standard nodes and tree structure. Registered custom nodes\n // are deferred to the version-aware pass below, while their descendants are\n // still walked by the unified validator.\n const documentResult = validatePresentationDocument(document, {\n knownCustomNames,\n allowUnknownFields: options?.allowUnknownFields,\n });\n const errors: ValidationError[] = [...documentResult.errors];\n\n function validateComponents(components: any[], pathPrefix = 'children') {\n components.forEach((componentData, index) => {\n if (\n !componentData ||\n typeof componentData !== 'object' ||\n Array.isArray(componentData)\n ) {\n return;\n }\n\n const customComponent = customComponents.find(\n (cc) => cc.name === componentData.name\n );\n\n if (customComponent) {\n const versionEntry = resolveComponentVersion(\n customComponent.name,\n customComponent.versions,\n componentData.version\n );\n\n const validation = validateComponentProps(\n versionEntry,\n componentData.props,\n customComponent.name,\n { clean: options?.allowUnknownFields === true }\n );\n\n if (!validation.valid && validation.errors) {\n const indexedErrors = validation.errors.map(\n (error: ValidationError) => ({\n ...error,\n path: `${pathPrefix}[${index}].${error.path}`,\n })\n );\n errors.push(...indexedErrors);\n }\n }\n\n // Recurse into children (slides, containers, etc.)\n if (componentData.children && Array.isArray(componentData.children)) {\n validateComponents(\n componentData.children,\n `${pathPrefix}[${index}].children`\n );\n }\n });\n }\n\n if (document && Array.isArray(document.children)) {\n validateComponents(document.children);\n }\n\n return errors.length > 0\n ? { valid: false, errors }\n : { valid: true, errors: [] };\n}\n\n/**\n * Validates component props and returns typed props or throws.\n */\nexport function getValidatedProps<TPropsSchema extends TSchema>(\n schema: { propsSchema: TPropsSchema },\n props: unknown\n): Static<TPropsSchema> {\n const validation = validateComponentProps(schema, props);\n\n if (!validation.valid) {\n throw new ComponentValidationError(validation.errors || [], props);\n }\n\n return validation.data!;\n}\n\nexport const cleanComponentProps = getValidatedProps;\n","import type { TSchema } from '@sinclair/typebox';\nimport type { CustomComponent } from '@json-to-office/shared/plugin';\nimport {\n generateUnifiedDocumentSchema,\n type CustomComponentInfo,\n} from '@json-to-office/shared-pptx';\n\n/**\n * Generate a JSON schema for plugin-enhanced presentations at RUNTIME.\n */\nexport function generatePluginPresentationSchema(\n customComponents: CustomComponent<any, any, any>[]\n): TSchema {\n const customComponentInfos: CustomComponentInfo[] = customComponents.map(\n (component) => {\n const versionKeys = Object.keys(component.versions);\n\n const versions = versionKeys.map((v) => ({\n version: v,\n propsSchema: component.versions[v].propsSchema,\n hasChildren: component.versions[v].hasChildren === true,\n description: component.versions[v].description,\n }));\n\n return {\n name: component.name,\n versions,\n };\n }\n );\n\n return generateUnifiedDocumentSchema({\n customComponents: customComponentInfos,\n });\n}\n\n/**\n * Export a plugin-enhanced JSON schema to a file at RUNTIME\n */\nexport async function exportPluginSchema(\n customComponents: CustomComponent<any, any, any>[],\n outputPath: string,\n options: { prettyPrint?: boolean } = {}\n): Promise<void> {\n const { prettyPrint = true } = options;\n\n const { convertToJsonSchema, exportSchemaToFile } = await import(\n '@json-to-office/shared'\n );\n\n const schema = generatePluginPresentationSchema(customComponents);\n\n const jsonSchema = convertToJsonSchema(schema, {\n $schema: 'http://json-schema.org/draft-07/schema#',\n });\n\n await exportSchemaToFile(jsonSchema, outputPath, { prettyPrint });\n}\n"],"mappings":";;;;;;;;;;;AA6BO,SAAS,KACd,UACA,MACA,SACA,OACM;AACN,MAAI,UAAU;AACZ,aAAS,KAAK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ACN;AAAA,MACA;AAAA,IACF;AAAA,EACF;AAEA,SAAO,OAAO,OAAO;AAAA,IACnB;AAAA,IACA;AAAA,IACA,gBAAgB;AAAA,IAChB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,cAAc;AAAA,EAChB,CAAC;AACH;AAKO,SAAS,4BACd,UAAwC,CAAC,GACE;AAC3C,QAAM,eAA6B;AAAA,IACjC,YAAY,CAAC;AAAA,IACb,gBAAgB,oBAAI,IAAI;AAAA,IACxB,OAAO,QAAQ;AAAA,IACf,cAAc,QAAQ;AAAA,IACtB,OAAO,QAAQ,SAAS;AAAA,IACxB,UAAU,QAAQ;AAAA,IAClB,OAAO,QAAQ;AAAA,IACf,YAAY,QAAQ;AAAA,IACpB,WAAW;AAAA,MACT,eAAe,QAAQ;AAAA,MACvB,aAAa,QAAQ;AAAA,IACvB;AAAA,IACA,SAAS,QAAQ;AAAA,IACjB,UAAU,QAAQ;AAAA,EACpB;AAEA,SAAO,kBAA+B,YAAY;AACpD;;;AD9jBA,SAAS,2BAAAG,gCAA+B;;;AD5EjC,SAAS,qBAA6B;AAC3C,SAAO;AACT;","names":["color","background","fill","color","fill","path","path","EMU_PER_INCH","probe","fill","path","background","assertNever","fill","init_emit","init_emit","color","weight","hyperlink","mergeWithDefaults","path","background","template","mergeWithDefaults","hyperlink","fill","color","createPptxGenJsRenderer","createOfficeOpenPptxRenderer","registry","path","path","resolve","result","path","mergeWithDefaults","slideChild","resolveComponentVersion","DuplicateComponentError","ComponentValidationError","validatePresentationDocument","ComponentValidationError","resolveComponentVersion","ComponentValidationError","DuplicateComponentError","validationDocument","resolveComponentVersion"]}
|
|
1
|
+
{"version":3,"sources":["../src/utils/warn.ts","../src/ir/types.ts","../src/ir/units.ts","../src/ir/features.ts","../src/renderers/pptxgenjs/fills.ts","../src/renderers/pptxgenjs/chart.ts","../src/renderers/pptxgenjs/table.ts","../src/renderers/pptxgenjs/emit.ts","../src/core/finalizePackage.ts","../src/renderers/pptxgenjs/svgRasterFallback.ts","../src/renderers/pptxgenjs/packaging.ts","../src/renderers/pptxgenjs/index.ts","../src/renderers/office-open/chartParts.ts","../src/renderers/office-open/emit.ts","../src/renderers/office-open/index.ts","../src/core/generator.ts","../src/core/generateFromIr.ts","../src/utils/baseDirContext.ts","../src/ir/compiler.ts","../src/utils/color.ts","../src/utils/fontAliasContext.ts","../src/utils/componentDefaults.ts","../src/utils/resolveComponentTree.ts","../src/utils/imageSource.ts","../src/utils/hyperlink.ts","../src/core/grid.ts","../src/ir/resources.ts","../src/renderers/registry.ts","../src/renderers/types.ts","../src/types.ts","../src/core/fontResolution.ts","../src/core/generationContext.ts","../src/themes/defaults.ts","../src/core/generationOptions.ts","../src/utils/environment.ts","../src/core/expandHighcharts.ts","../src/core/resolveImageLayout.ts","../src/core/structure.ts","../src/index.ts","../src/plugin/index.ts","../src/plugin/createPresentationGenerator.ts","../src/plugin/validation.ts","../src/plugin/schema.ts"],"sourcesContent":["import type { PipelineWarning } from '../types';\n\nexport const W = {\n UNKNOWN_COMPONENT: 'UNKNOWN_COMPONENT',\n UNKNOWN_CHART_TYPE: 'UNKNOWN_CHART_TYPE',\n UNKNOWN_SHAPE: 'UNKNOWN_SHAPE',\n CHART_NO_DATA: 'CHART_NO_DATA',\n CHART_INVALID_SERIES: 'CHART_INVALID_SERIES',\n CHART_MULTI_SERIES: 'CHART_MULTI_SERIES',\n CHART_FONT_WEIGHT_DROPPED: 'CHART_FONT_WEIGHT_DROPPED',\n IMAGE_NO_SOURCE: 'IMAGE_NO_SOURCE',\n IMAGE_PROBE_FAILED: 'IMAGE_PROBE_FAILED',\n IMAGE_PATH_OUTSIDE_ROOTS: 'IMAGE_PATH_OUTSIDE_ROOTS',\n IMAGE_SVG_RASTER_FAILED: 'IMAGE_SVG_RASTER_FAILED',\n MISSING_TEMPLATE: 'MISSING_TEMPLATE',\n UNKNOWN_PLACEHOLDER: 'UNKNOWN_PLACEHOLDER',\n PLACEHOLDER_NO_POSITION: 'PLACEHOLDER_NO_POSITION',\n THEME_COLOR_FALLBACK: 'THEME_COLOR_FALLBACK',\n UNKNOWN_COLOR: 'UNKNOWN_COLOR',\n GRID_POSITION_CLAMPED: 'GRID_POSITION_CLAMPED',\n TEXT_NO_CONTENT: 'TEXT_NO_CONTENT',\n UNKNOWN_PATTERN_PRESET: 'UNKNOWN_PATTERN_PRESET',\n ADVANCED_FILL_FALLBACK: 'ADVANCED_FILL_FALLBACK',\n IMAGE_ZERO_BOX: 'IMAGE_ZERO_BOX',\n FONT_UNRESOLVED: 'FONT_UNRESOLVED',\n} as const;\n\nexport type WarningCode = (typeof W)[keyof typeof W];\n\nexport function warn(\n warnings: PipelineWarning[] | undefined,\n code: WarningCode,\n message: string,\n extra?: Partial<PipelineWarning>\n): void {\n if (warnings) {\n warnings.push({ code, message, ...extra });\n } else {\n console.warn(message);\n }\n}\n","/**\n * PptxIR — the renderer-neutral description of a finished presentation.\n *\n * Everything here is plain data: no PptxGenJS objects, no functions, no raw\n * OOXML, no backend-specific shapes. A renderer adapter is the only thing that\n * turns these nodes into a library call.\n *\n * By the time a document reaches this form, all of the following have already\n * happened upstream (see `docs/architecture/office-renderer-ir.md`):\n *\n * - schema validation and structural conflict checks\n * - custom-component expansion\n * - theme resolution — every colour here is an explicit 6-digit hex\n * - component defaults\n * - font resolution/substitution, including synthesized weight aliases\n * - grid and placeholder layout resolution — every position here is EMU\n * - text parsing\n *\n * Units: EMU for geometry, points for font sizes, degrees for angles,\n * percent (0-100) for transparency, ISO 8601 strings for timestamps.\n */\n\n/** English Metric Units per inch. */\nexport const EMU_PER_INCH = 914400;\n/** English Metric Units per point (72 points per inch). */\nexport const EMU_PER_POINT = EMU_PER_INCH / 72;\n\nexport const PPTX_IR_SCHEMA_VERSION = 1;\n\n/* ------------------------------------------------------------------ *\n * Root\n * ------------------------------------------------------------------ */\n\nexport interface PptxIR {\n schemaVersion: typeof PPTX_IR_SCHEMA_VERSION;\n metadata: PptxIrMetadata;\n size: PptxIrSlideSize;\n theme: PptxIrTheme;\n /** Right-to-left reading order for the whole deck. */\n rtl: boolean;\n /** Deck-wide default proofing language (BCP-47). */\n language?: string;\n /** Deduplicated binary/external assets, in first-use order. */\n resources: PptxIrResource[];\n /** Reusable slide masters compiled from authored templates. */\n masters: PptxIrMaster[];\n slides: PptxIrSlide[];\n}\n\nexport interface PptxIrMetadata {\n title?: string;\n author?: string;\n subject?: string;\n company?: string;\n}\n\nexport interface PptxIrSlideSize {\n widthEmu: number;\n heightEmu: number;\n}\n\n/**\n * What survives theme resolution.\n *\n * Colours are already resolved into the elements that use them; the two font\n * families remain because they are set on the presentation itself (the OOXML\n * `<a:fontScheme>` major/minor faces), not per element. `palette` is the\n * resolved colour scheme, kept so an adapter able to emit a real `<a:clrScheme>`\n * can do so.\n */\nexport interface PptxIrTheme {\n name: string;\n headingFont: string;\n bodyFont: string;\n /** Resolved scheme colours, bare uppercase hex, keyed by project-owned slot. */\n palette: Readonly<Record<string, string>>;\n}\n\n/* ------------------------------------------------------------------ *\n * Resources\n * ------------------------------------------------------------------ */\n\n/**\n * An asset referenced by one or more slide elements.\n *\n * `origin` records how the bytes are obtained. Inline sources (base64, raw SVG)\n * are decoded at compile time and carry `bytes` plus a content hash, which is\n * what deduplication and debug snapshots key on. File and remote sources keep\n * their location so the adapter can stream them, exactly as the pipeline did\n * before the IR existed; their identity is the normalised location.\n */\nexport interface PptxIrResource {\n /** Deterministic: `res${n}` in first-use order. */\n id: string;\n kind: 'image';\n origin: PptxIrResourceOrigin;\n /** IANA media type when known, e.g. `image/png`. */\n mediaType?: string;\n /** Intrinsic pixel size, when the compiler probed it. */\n intrinsic?: PptxIrPixelSize;\n}\n\nexport type PptxIrResourceOrigin =\n | PptxIrInlineOrigin\n | PptxIrFileOrigin\n | PptxIrRemoteOrigin;\n\n/** Bytes the compiler already holds (authored base64 or raw SVG markup). */\nexport interface PptxIrInlineOrigin {\n kind: 'inline';\n bytes: Uint8Array;\n byteLength: number;\n /** Lowercase hex SHA-256 of `bytes`; the dedup and snapshot identity. */\n sha256: string;\n}\n\n/** An absolute local path already checked against the allowed roots. */\nexport interface PptxIrFileOrigin {\n kind: 'file';\n path: string;\n}\n\n/** An `http(s)` URL the adapter fetches. */\nexport interface PptxIrRemoteOrigin {\n kind: 'remote';\n url: string;\n}\n\nexport interface PptxIrPixelSize {\n widthPx: number;\n heightPx: number;\n}\n\n/* ------------------------------------------------------------------ *\n * Geometry, colour, fills, lines\n * ------------------------------------------------------------------ */\n\n/**\n * Absolute placement on a slide, in EMU, with optional rotation and flips.\n *\n * `autoWidth` / `autoHeight` mark an axis the author did not constrain. The\n * EMU value is still present as a fallback, but a renderer able to size that\n * axis itself — an OOXML table sizes from its columns — should. \"Unstated\" is\n * information; inventing a number and forgetting that it was invented is how a\n * layout silently stops adapting.\n */\nexport interface PptxIrTransform {\n xEmu: number;\n yEmu: number;\n widthEmu: number;\n heightEmu: number;\n autoWidth?: boolean;\n autoHeight?: boolean;\n /** Clockwise degrees. Omitted means 0. */\n rotationDegrees?: number;\n flipHorizontal?: boolean;\n flipVertical?: boolean;\n}\n\n/**\n * A resolved colour: bare uppercase 6-digit hex, never a theme token.\n *\n * `transparency` is 0-100 where 0 is opaque, matching the authoring surface.\n */\nexport interface PptxIrColor {\n hex: string;\n transparency?: number;\n}\n\nexport type PptxIrFill =\n | PptxIrNoFill\n | PptxIrSolidFill\n | PptxIrGradientFill\n | PptxIrPatternFill\n | PptxIrImageFill;\n\nexport interface PptxIrNoFill {\n kind: 'none';\n}\n\nexport interface PptxIrSolidFill {\n kind: 'solid';\n color: PptxIrColor;\n}\n\n/**\n * A gradient described semantically. Each adapter decides how to realise it —\n * PptxGenJS cannot express one directly and splices XML during packaging;\n * another backend may have a first-class API. Neither concern belongs here.\n */\nexport interface PptxIrGradientFill {\n kind: 'gradient';\n gradient: PptxIrGradient;\n}\n\nexport type PptxIrGradient = PptxIrLinearGradient | PptxIrRadialGradient;\n\nexport interface PptxIrLinearGradient {\n type: 'linear';\n /** Degrees, normalised to [0, 360). */\n angleDegrees: number;\n stops: PptxIrGradientStop[];\n}\n\nexport interface PptxIrRadialGradient {\n type: 'radial';\n focus: PptxIrRadialFocus;\n stops: PptxIrGradientStop[];\n}\n\nexport type PptxIrRadialFocus =\n | 'center'\n | 'topLeft'\n | 'topRight'\n | 'bottomLeft'\n | 'bottomRight';\n\nexport interface PptxIrGradientStop {\n /** Percent along the gradient, 0-100. */\n position: number;\n color: PptxIrColor;\n}\n\nexport interface PptxIrPatternFill {\n kind: 'pattern';\n /** OOXML `prst` preset name, validated at compile time. */\n preset: string;\n foreground: PptxIrColor;\n background: PptxIrColor;\n}\n\nexport interface PptxIrImageFill {\n kind: 'image';\n resourceId: string;\n}\n\nexport interface PptxIrLine {\n color?: PptxIrColor;\n /** Stroke width in points. */\n widthPoints?: number;\n dash?: PptxIrLineDash;\n}\n\nexport type PptxIrLineDash =\n | 'solid'\n | 'dash'\n | 'dashDot'\n | 'lgDash'\n | 'lgDashDot'\n | 'lgDashDotDot'\n | 'sysDash'\n | 'sysDashDot'\n | 'sysDashDotDot'\n | 'sysDot'\n | 'dot';\n\nexport interface PptxIrShadow {\n type: 'outer' | 'inner' | 'none';\n color: PptxIrColor;\n /** Blur radius in points. */\n blurPoints: number;\n /** Offset distance in points. */\n offsetPoints: number;\n angleDegrees: number;\n /** 0-1, as the authoring surface expresses it. */\n opacity: number;\n}\n\n/* ------------------------------------------------------------------ *\n * Hyperlinks\n * ------------------------------------------------------------------ */\n\nexport type PptxIrHyperlink = PptxIrExternalHyperlink | PptxIrSlideHyperlink;\n\nexport interface PptxIrExternalHyperlink {\n kind: 'external';\n url: string;\n tooltip?: string;\n}\n\n/** A jump to another slide, already rebased onto generated slide numbering. */\nexport interface PptxIrSlideHyperlink {\n kind: 'slide';\n /** 1-based index into `PptxIR.slides`. */\n slideIndex: number;\n tooltip?: string;\n}\n\n/* ------------------------------------------------------------------ *\n * Text\n * ------------------------------------------------------------------ */\n\nexport type PptxIrHorizontalAlign = 'left' | 'center' | 'right' | 'justify';\nexport type PptxIrVerticalAlign = 'top' | 'middle' | 'bottom';\n\n/**\n * One run of uniformly-formatted text.\n *\n * Every inherited value has already been cascaded down (component props →\n * named style → theme defaults), so a run states its own formatting outright\n * rather than relying on a parent. `fontFamily` is post-substitution and may be\n * a synthesized weight alias such as `Inter Light`.\n */\nexport interface PptxIrTextRun {\n text: string;\n fontFamily: string;\n /** Points. */\n fontSize: number;\n color: PptxIrColor;\n bold?: boolean;\n italic?: boolean;\n strike?: boolean;\n underline?: PptxIrUnderline;\n superscript?: boolean;\n subscript?: boolean;\n /** Points; positive tracks wider. */\n characterSpacing?: number;\n /** BCP-47 proofing language. */\n language?: string;\n /** End this run with a hard line break. */\n breakAfter?: boolean;\n /** Points of space before the paragraph this run starts. */\n spaceBeforePoints?: number;\n /** Points of space after the paragraph this run ends. */\n spaceAfterPoints?: number;\n hyperlink?: PptxIrHyperlink;\n}\n\nexport interface PptxIrUnderline {\n style: string;\n color?: PptxIrColor;\n}\n\n/**\n * Formatting a text body applies by default.\n *\n * OOXML keeps body-level defaults (`lstStyle`, `endParaRPr`) separate from run\n * properties, and so does this: `PptxIrTextRun` states its own formatting\n * outright — a backend with no body-default concept can render from runs alone\n * — while `defaults` is what an empty paragraph, or a backend that does have\n * the concept, should use.\n */\nexport interface PptxIrRunFormatting {\n fontFamily: string;\n /** Points. */\n fontSize: number;\n color: PptxIrColor;\n bold?: boolean;\n italic?: boolean;\n /** BCP-47 proofing language. */\n language?: string;\n}\n\n/** Paragraph-level settings shared by every run in a text body. */\nexport interface PptxIrTextBodyStyle {\n align?: PptxIrHorizontalAlign;\n verticalAlign: PptxIrVerticalAlign;\n /** Exact line height in points. Mutually exclusive with `lineSpacingMultiple`. */\n lineSpacingPoints?: number;\n /** Line height as a multiple of the font size. */\n lineSpacingMultiple?: number;\n spaceBeforePoints?: number;\n spaceAfterPoints?: number;\n bullet?: PptxIrBullet;\n /**\n * Inset in points: a single value or [top, right, bottom, left].\n *\n * The four-value order is CSS's, which is what the authoring schema states\n * and what the default backend already reads — an adapter that rotates it\n * moves content to the wrong side of the box.\n *\n * Absent means \"no inset stated\" — the format's own default applies. That is\n * a real distinction: a text box states `0` so it aligns exactly to its\n * position, while a shape leaves it unstated and keeps OOXML's default\n * padding.\n */\n insetPoints?: number | [number, number, number, number];\n /** Let the shape grow to fit its text instead of clipping. */\n autoFit?: boolean;\n /** Body-level run defaults. */\n defaults: PptxIrRunFormatting;\n}\n\nexport interface PptxIrBullet {\n /**\n * `bullet` for a glyph, `number` for an ordered list, `none` for a paragraph\n * that states it has no bullet.\n *\n * `none` is not the same as leaving `bullet` unset. Unset inherits whatever\n * the list style or the backend's default provides; `none` is the author\n * saying so, and lowers to `<a:buNone/>` — which is what overriding an\n * inherited bullet takes.\n */\n type: 'bullet' | 'number' | 'none';\n /** Glyph character or numbering style, as OOXML names it. */\n style?: string;\n startAt?: number;\n}\n\n/* ------------------------------------------------------------------ *\n * Slide elements\n * ------------------------------------------------------------------ */\n\nexport type PptxIrElement =\n | PptxIrTextBoxElement\n | PptxIrShapeElement\n | PptxIrImageElement\n | PptxIrTableElement\n | PptxIrChartElement\n | PptxIrGroupElement;\n\n/** Fields every element carries. */\ninterface PptxIrElementBase {\n /** Deterministic, path-derived: e.g. `s1.e3`, `s1.e3.g0`. */\n id: string;\n /** IR path for diagnostics: e.g. `slides[0].elements[3]`. */\n path: string;\n transform: PptxIrTransform;\n /** Accessibility description. */\n altText?: string;\n}\n\nexport interface PptxIrTextBoxElement extends PptxIrElementBase {\n kind: 'textBox';\n runs: PptxIrTextRun[];\n style: PptxIrTextBodyStyle;\n fill?: PptxIrFill;\n line?: PptxIrLine;\n shadow?: PptxIrShadow;\n hyperlink?: PptxIrHyperlink;\n}\n\n/**\n * A preset-geometry shape, optionally carrying text.\n *\n * `geometry` is a project-owned name (see `PPTX_IR_GEOMETRY`), not a PptxGenJS\n * enum member; adapters map it to whatever their backend calls it.\n */\nexport interface PptxIrShapeElement extends PptxIrElementBase {\n kind: 'shape';\n geometry: PptxIrGeometry;\n fill?: PptxIrFill;\n line?: PptxIrLine;\n shadow?: PptxIrShadow;\n /** Corner radius in inches. `roundRect` and friends only. */\n cornerRadius?: number;\n /** Start/end angle in degrees for arc-like geometries. */\n angleRangeDegrees?: [number, number];\n runs?: PptxIrTextRun[];\n style?: PptxIrTextBodyStyle;\n hyperlink?: PptxIrHyperlink;\n}\n\nexport const PPTX_IR_GEOMETRY = [\n 'rect',\n 'roundRect',\n 'ellipse',\n 'triangle',\n 'diamond',\n 'pentagon',\n 'hexagon',\n 'star5',\n 'star6',\n 'line',\n 'rightArrow',\n 'chevron',\n 'cloud',\n 'heart',\n 'lightningBolt',\n] as const;\n\nexport type PptxIrKnownGeometry = (typeof PPTX_IR_GEOMETRY)[number];\n\n/**\n * A geometry name. Known names are checked at compile time; anything else is\n * carried through as `{ custom }` so an adapter that supports a wider preset\n * set can use it and one that does not can fail with a precise diagnostic.\n */\nexport type PptxIrGeometry = PptxIrKnownGeometry | { custom: string };\n\nexport interface PptxIrImageElement extends PptxIrElementBase {\n kind: 'image';\n resourceId: string;\n /** Cropping/scaling already resolved by the compiler where it could be. */\n sizing?: PptxIrImageSizing;\n rounding?: boolean;\n shadow?: PptxIrShadow;\n hyperlink?: PptxIrHyperlink;\n}\n\nexport interface PptxIrImageSizing {\n /**\n * `contain` survives only when the fit could not be computed — the compiler\n * normally resolves it into the transform and drops the sizing.\n */\n type: 'contain' | 'cover' | 'crop';\n widthEmu: number;\n heightEmu: number;\n /** Crop origin in EMU, `crop` only. */\n xEmu?: number;\n yEmu?: number;\n}\n\n/**\n * A table.\n *\n * The authoring surface gives each cell a single string plus its own\n * formatting, so that is what the IR models — not a rich-text body per cell.\n * `defaults` holds the table-level formatting cells inherit; a cell states only\n * what it overrides, which mirrors how OOXML layers `tblPr` under `tcPr`.\n */\nexport interface PptxIrTableElement extends PptxIrElementBase {\n kind: 'table';\n rows: PptxIrTableRow[];\n /** Column widths in EMU. Empty lets the renderer distribute them. */\n columnWidthsEmu: number[];\n /** Row heights in EMU, positionally. Empty lets the renderer auto-size. */\n rowHeightsEmu: number[];\n defaults: PptxIrTableFormatting;\n /** Uniform border applied to the whole table. */\n border?: PptxIrTableBorder;\n /** Table-level background fill. */\n fill?: PptxIrColor;\n /**\n * Corner radius in inches.\n *\n * A semantic request for rounded table corners. OOXML tables have no such\n * property, so each adapter decides how to honour it; the IR does not\n * describe the technique.\n */\n cornerRadiusInches?: number;\n /** Let the table flow onto further slides when it overruns. */\n autoPage?: boolean;\n /** Repeat the first row as a header on each continuation slide. */\n autoPageRepeatHeader?: boolean;\n}\n\n/** Formatting a table applies to every cell that does not override it. */\nexport interface PptxIrTableFormatting {\n fontFamily: string;\n /** Points. */\n fontSize: number;\n color?: PptxIrColor;\n bold?: boolean;\n align?: PptxIrHorizontalAlign;\n verticalAlign: PptxIrVerticalAlign;\n /** Inset in points: one value or [top, right, bottom, left]. */\n insetPoints?: number | [number, number, number, number];\n}\n\nexport interface PptxIrTableRow {\n cells: PptxIrTableCell[];\n}\n\nexport interface PptxIrTableCell {\n text: string;\n /** Only what this cell overrides; everything else comes from `defaults`. */\n formatting?: PptxIrTableCellFormatting;\n fill?: PptxIrColor;\n /** Per-side borders, in [top, right, bottom, left] order. */\n borders?: [\n PptxIrTableBorder,\n PptxIrTableBorder,\n PptxIrTableBorder,\n PptxIrTableBorder,\n ];\n colSpan?: number;\n rowSpan?: number;\n}\n\nexport interface PptxIrTableCellFormatting {\n fontFamily?: string;\n /** Points. */\n fontSize?: number;\n color?: PptxIrColor;\n bold?: boolean;\n italic?: boolean;\n align?: PptxIrHorizontalAlign;\n verticalAlign?: PptxIrVerticalAlign;\n insetPoints?: number | [number, number, number, number];\n}\n\nexport interface PptxIrTableBorder {\n type: 'none' | 'solid' | 'dash' | 'dot';\n color?: PptxIrColor;\n /** Points. */\n widthPoints?: number;\n}\n\n/**\n * A native OOXML chart.\n *\n * Series data is normalised and every colour, font family and label style is\n * already resolved, so no theme lookup or charting library is involved at\n * render time. The option names follow the project's authoring schema, which\n * is itself aligned with PowerPoint's chart vocabulary — they are project-owned\n * names that happen to read like the format's.\n */\nexport interface PptxIrChartElement extends PptxIrElementBase {\n kind: 'chart';\n chartType: PptxIrChartType;\n series: PptxIrChartSeries[];\n options: PptxIrChartOptions;\n}\n\nexport type PptxIrChartType =\n | 'area'\n | 'bar'\n | 'bar3D'\n | 'bubble'\n | 'doughnut'\n | 'line'\n | 'pie'\n | 'radar'\n | 'scatter';\n\nexport interface PptxIrChartSeries {\n name?: string;\n labels?: string[];\n values?: number[];\n /** Bubble sizes, `bubble` charts only. */\n sizes?: number[];\n}\n\n/** A resolved label font: family after weight aliasing, plus the bold toggle. */\nexport interface PptxIrChartLabelFont {\n fontFamily?: string;\n bold?: boolean;\n /** Points. */\n fontSize?: number;\n color?: PptxIrColor;\n}\n\nexport interface PptxIrChartGridLine {\n style?: string;\n size?: number;\n color?: PptxIrColor;\n}\n\nexport interface PptxIrChartOptions {\n /** Resolved series palette, in series order. Empty means \"use the backend's\". */\n colors: string[];\n\n showLegend?: boolean;\n showTitle?: boolean;\n showValue?: boolean;\n showPercent?: boolean;\n showLabel?: boolean;\n showSeriesName?: boolean;\n\n title?: string;\n titleFont: PptxIrChartLabelFont;\n\n legendPosition?: string;\n legendFont: PptxIrChartLabelFont;\n\n categoryAxis: PptxIrChartAxis;\n valueAxis: PptxIrChartValueAxis;\n\n dataBorder?: { widthPoints: number; color: PptxIrColor };\n dataLabelFont: PptxIrChartLabelFont;\n dataLabelPosition?: string;\n\n barDirection?: string;\n barGrouping?: string;\n barGapWidthPercent?: number;\n barOverlapPercent?: number;\n\n lineSmooth?: boolean;\n lineDataSymbol?: string;\n lineSize?: number;\n lineDataSymbolSize?: number;\n\n firstSliceAngle?: number;\n holeSize?: number;\n\n radarStyle?: string;\n}\n\nexport interface PptxIrChartAxis {\n title?: string;\n hidden?: boolean;\n labelRotate?: number;\n labelFont: PptxIrChartLabelFont;\n gridLine?: PptxIrChartGridLine;\n showLine?: boolean;\n}\n\nexport interface PptxIrChartValueAxis extends PptxIrChartAxis {\n minValue?: number;\n maxValue?: number;\n majorUnit?: number;\n labelFormatCode?: string;\n}\n\n/** A group of elements sharing a transform. */\nexport interface PptxIrGroupElement extends PptxIrElementBase {\n kind: 'group';\n children: PptxIrElement[];\n}\n\n/* ------------------------------------------------------------------ *\n * Slides and masters\n * ------------------------------------------------------------------ */\n\nexport interface PptxIrSlide {\n /** Deterministic: `slide${n}`, 1-based in generated order. */\n id: string;\n path: string;\n /** Name of a master in `PptxIR.masters`, when the slide uses one. */\n masterName?: string;\n background?: PptxIrBackground;\n elements: PptxIrElement[];\n notes?: string;\n hidden: boolean;\n transition?: PptxIrTransition;\n}\n\n/**\n * A slide background.\n *\n * Only solid and image backgrounds are backgrounds in the OOXML sense. A\n * gradient background compiles to a full-bleed shape at the back of the slide\n * instead, because that is what it means semantically once resolved — see the\n * compiler.\n */\nexport type PptxIrBackground =\n | { kind: 'solid'; color: PptxIrColor }\n | { kind: 'image'; resourceId: string };\n\nexport interface PptxIrTransition {\n type: string;\n speed?: 'slow' | 'medium' | 'fast';\n}\n\nexport interface PptxIrMaster {\n name: string;\n background?: PptxIrBackground;\n /**\n * Content margin, in inches: a single value or [top, right, bottom, left].\n *\n * Not decoration — a format sizes an unconstrained table against the master's\n * margins, so dropping this silently resizes tables.\n */\n margin?: number | [number, number, number, number];\n /** Fixed decoration drawn on every slide using this master. */\n elements: PptxIrElement[];\n /** Slide-number field placement, when the template defines one. */\n slideNumber?: PptxIrSlideNumber;\n /** Named regions a slide can fill; positions already resolved. */\n placeholders: PptxIrPlaceholder[];\n}\n\nexport interface PptxIrSlideNumber {\n transform: PptxIrTransform;\n color?: PptxIrColor;\n /** Points. */\n fontSize?: number;\n}\n\n/**\n * A placeholder as the *master* declares it.\n *\n * Slide-side placeholder content is not a placeholder in the IR — it has\n * already been merged with the declaration and emitted as a normal element on\n * the slide. This entry exists so a master can still declare the region.\n */\nexport interface PptxIrPlaceholder {\n name: string;\n transform?: PptxIrTransform;\n}\n","/**\n * Unit and identity helpers for PptxIR construction.\n *\n * Authoring expresses geometry in inches (or percent strings); the IR expresses\n * it in EMU. The conversion is a single rounding step, done here so every\n * compile site agrees on it — and so the PptxGenJS adapter can invert it\n * exactly by dividing, since PptxGenJS applies the same `Math.round(in * EMU)`\n * on the way in.\n */\n\nimport { createHash } from 'node:crypto';\nimport { EMU_PER_INCH } from './types';\nimport type { PptxIrColor } from './types';\n\n/** Inches → EMU. */\nexport function inchesToEmu(inches: number): number {\n return Math.round(inches * EMU_PER_INCH);\n}\n\n/** EMU → inches. Lossless against `inchesToEmu` for realistic magnitudes. */\nexport function emuToInches(emu: number): number {\n return emu / EMU_PER_INCH;\n}\n\n/** Slide size in EMU, the frame percentages resolve against. */\nexport interface SlideExtentEmu {\n widthEmu: number;\n heightEmu: number;\n}\n\n/**\n * Resolve an authored dimension to EMU.\n *\n * This reproduces the authoring contract the pipeline has always had, quirks\n * included, because the numbers it produces are the numbers that end up in the\n * package:\n *\n * - a number below 100 is inches\n * - a number of 100 or more is already EMU (nobody authors a 100-inch slide,\n * and callers do pass EMU through)\n * - a percent string resolves against the slide extent *in EMU*, so the single\n * rounding step happens at the end\n * - a bare numeric string is treated as a number\n * - anything else is 0 rather than an error\n *\n * The rules are stated here once so no compile site has to re-derive them.\n */\nexport function resolveDimensionEmu(\n value: number | string,\n axis: 'X' | 'Y',\n extent: SlideExtentEmu\n): number {\n let size: number | string = value;\n if (\n typeof size === 'string' &&\n size.trim() !== '' &&\n !Number.isNaN(Number(size))\n ) {\n size = Number(size);\n }\n if (typeof size === 'number') {\n return size < 100 ? Math.round(EMU_PER_INCH * size) : size;\n }\n if (size.includes('%')) {\n const pct = Number.parseFloat(size);\n if (Number.isNaN(pct)) return 0;\n const axisEmu = axis === 'Y' ? extent.heightEmu : extent.widthEmu;\n return Math.round((pct / 100) * axisEmu);\n }\n return 0;\n}\n\n/**\n * Width used when an element does not state one.\n *\n * 75% of the slide width — the width the pipeline has always produced for an\n * element with no `w`. Materialising it here is what lets the IR promise an\n * explicit transform without changing any output.\n */\nexport function defaultWidthEmu(extent: SlideExtentEmu): number {\n return Math.round(0.75 * extent.widthEmu);\n}\n\n/**\n * Build an IR colour from an already-resolved bare hex string.\n *\n * `resolveColor` (utils/color.ts) is what turns theme tokens into hex; this\n * only normalises casing and attaches transparency, so an unresolved token can\n * never reach the IR by accident.\n */\nexport function irColor(bareHex: string, transparency?: number): PptxIrColor {\n const hex = bareHex.startsWith('#') ? bareHex.slice(1) : bareHex;\n return transparency === undefined\n ? { hex: hex.toUpperCase() }\n : { hex: hex.toUpperCase(), transparency };\n}\n\n/** Normalise degrees into [0, 360). */\nexport function normalizeDegrees(degrees: number): number {\n return ((degrees % 360) + 360) % 360;\n}\n\n/** Lowercase hex SHA-256, the identity used for inline resources. */\nexport function sha256Hex(bytes: Uint8Array): string {\n return createHash('sha256').update(bytes).digest('hex');\n}\n\n/**\n * Deterministic element id from its position in the tree.\n *\n * Ids are derived, never allocated from a counter, so two concurrent\n * generations of the same document produce the same ids and a single\n * generation's ids do not depend on evaluation order.\n */\nexport function elementId(\n slideIndex: number,\n indexPath: readonly number[]\n): string {\n return `s${slideIndex + 1}.${indexPath.map((i) => `e${i}`).join('.')}`;\n}\n","/**\n * PPTX renderer features.\n *\n * A feature is a capability a *backend* must have, not an authoring concept.\n * The compiler records one requirement per IR node that needs one; a renderer\n * declares the set it can satisfy. Anything required but not declared fails\n * before rendering, with the IR path attached.\n *\n * Names are chosen so the boundary is real: `gradient-fills` is separate from\n * `pattern-fills` because a backend can plausibly have one and not the other,\n * while `rich-text` covers multi-run bodies as a single indivisible ability.\n */\n\nexport const PPTX_FEATURES = [\n /** Slide masters compiled from authored templates. */\n 'masters',\n /** Named placeholder regions declared by a master. */\n 'placeholders',\n /** Multiple independently-formatted runs inside one text body. */\n 'rich-text',\n /**\n * Bullet glyphs outside PptxGenJS's single-BMP-character API: astral\n * characters and multi-code-point graphemes.\n */\n 'complex-bullet-glyphs',\n /** Text bodies at all (a single run, uniform formatting). */\n 'text',\n /** Preset-geometry shapes. */\n 'shapes',\n /** Raster and vector images. */\n 'images',\n /** SVG images specifically — many backends need a raster fallback. */\n 'svg',\n /**\n * Drawing only part of a picture: `cover`, `crop`, or a `contain` fit the\n * compiler could not resolve into the frame.\n *\n * A backend without it draws the whole picture into the frame, which is a\n * different image — the wrong region at the wrong scale — with nothing to\n * show that anything was lost.\n */\n 'image-crop',\n /** Masking a picture to rounded corners or a circle. */\n 'image-rounding',\n 'tables',\n /** Merged table cells (colSpan / rowSpan). */\n 'table-merged-cells',\n /**\n * Cell insets on a table.\n *\n * Separate from the inset on a text body: a reader takes a cell's padding\n * from `a:tcPr`, and a backend that can only write text-body insets puts the\n * numbers somewhere nothing reads them.\n */\n 'table-insets',\n /**\n * Rounded table corners.\n *\n * A separate ability because OOXML has no such property: a backend realises\n * it by drawing shapes behind the table, or it cannot realise it at all.\n */\n 'table-rounded-corners',\n /**\n * Flowing an over-long table onto further slides, header row included.\n *\n * Pagination is the backend's, not the IR's — the IR describes one table and\n * says it may split, so a backend that cannot split has to refuse rather than\n * emit a table running off the slide.\n */\n 'table-auto-page',\n /** Native OOXML charts with an embedded workbook. */\n 'charts',\n /*\n * Chart styling, split finer than `charts` itself.\n *\n * `charts` says a backend can draw a chart from data. It says nothing about\n * whether that backend honours the options the author styled it with, and one\n * coarse feature let a renderer accept a chart, draw it, and quietly ignore\n * half of what was asked for — an ignored axis maximum draws a different\n * chart from the authored one and the file says nothing about it.\n *\n * Each name below is required by the compiler *only when the matching prop\n * was authored*, at that prop's own path, so a default never demands a\n * capability and a refusal always names the line that caused it.\n */\n /** `barGapWidthPct`, `barOverlapPct`. */\n 'chart-bar-style',\n /** `firstSliceAng`, `holeSize`. */\n 'chart-pie-style',\n /** `lineSmooth`, `lineDataSymbol`, `lineSize`, `lineDataSymbolSize`. */\n 'chart-line-style',\n /** `radarStyle` — anything but the `standard` a backend may hardcode. */\n 'chart-radar-style',\n /** `showValue`, `showPercent`, `showLabel`, `showSerName`, `dataLabelPosition`. */\n 'chart-data-labels',\n /** `dataBorder`: an outline on bars, slices and areas. */\n 'chart-data-border',\n /** Value-axis bounds and number format: min, max, major unit, format code. */\n 'chart-axis-scale',\n /** Hiding an axis or its line. */\n 'chart-axis-visibility',\n /** Axis label rotation and grid lines. */\n 'chart-axis-style',\n /** Font family, size, weight and colour on any chart text. */\n 'chart-text-style',\n 'solid-fills',\n 'gradient-fills',\n 'pattern-fills',\n 'image-fills',\n 'lines',\n 'shadows',\n /** Slide backgrounds (solid or image). */\n 'backgrounds',\n 'speaker-notes',\n 'hidden-slides',\n 'transitions',\n /** Hyperlinks to an external URL. */\n 'external-links',\n /** Hyperlinks targeting another slide in the same deck. */\n 'internal-links',\n /** A link covering a text body — realisable on the runs inside it. */\n 'text-hyperlinks',\n /** A link on a shape or image as a whole, which runs cannot stand in for. */\n 'element-hyperlinks',\n /** Rotation on a shape, text box or table. */\n 'rotation',\n /**\n * Any transform on a picture — rotation or flip.\n *\n * One feature rather than three: a backend that cannot rotate a picture\n * generally cannot flip one either, because the option carrying both is\n * simply absent from its picture type.\n */\n 'image-transform',\n 'flip-horizontal',\n 'flip-vertical',\n /** Grouped elements sharing a transform. */\n 'groups',\n /** Per-run proofing language. */\n 'proofing-language',\n /** Right-to-left reading order. */\n 'rtl',\n] as const;\n\nexport type PptxFeature = (typeof PPTX_FEATURES)[number];\n\n/** Every feature, for an adapter that claims the full surface. */\nexport const ALL_PPTX_FEATURES: ReadonlySet<PptxFeature> = new Set(\n PPTX_FEATURES\n);\n\nexport function isPptxFeature(value: string): value is PptxFeature {\n return (PPTX_FEATURES as readonly string[]).includes(value);\n}\n","/**\n * Gradient and pattern fills for the PptxGenJS backend.\n *\n * PptxGenJS has no API for either. The workaround — render a sentinel\n * `<a:solidFill>` on a uniquely-named shape, then splice the real fill element\n * in while packaging — is a property of *this backend*, so it lives here and\n * never in PptxIR or in generic PPTX types. PptxIR describes the gradient\n * semantically; another adapter is free to emit it directly.\n *\n * Colours arriving here are already resolved to hex by the compiler, so\n * building the XML is a pure string operation.\n */\n\nimport type {\n PptxIrColor,\n PptxIrFill,\n PptxIrGradient,\n PptxIrRadialFocus,\n} from '../../ir/types';\n\n/** OOXML angle unit: 60000ths of a degree. */\nconst ANGLE_UNIT = 60000;\n/** OOXML percentage unit: 1000ths of a percent (0-100 → 0-100000). */\nconst PCT_UNIT = 1000;\n\n/** `fillToRect` edges (in 1000ths of a percent) per radial focus corner. */\nconst RADIAL_FOCUS_RECTS: Record<\n PptxIrRadialFocus,\n { l: number; t: number; r: number; b: number }\n> = {\n center: { l: 50000, t: 50000, r: 50000, b: 50000 },\n topLeft: { l: 0, t: 0, r: 100000, b: 100000 },\n topRight: { l: 100000, t: 0, r: 0, b: 100000 },\n bottomLeft: { l: 0, t: 100000, r: 100000, b: 0 },\n bottomRight: { l: 100000, t: 100000, r: 0, b: 0 },\n};\n\n/**\n * A fill to splice into slide XML during packaging.\n *\n * The shape that registered it carries `cNvPr name=\"{objectName}\"`.\n */\nexport interface PendingXmlFill {\n objectName: string;\n /** Complete replacement element, e.g. `<a:gradFill>…</a:gradFill>`. */\n xml: string;\n}\n\n/** Collects pending fills for one render. Never module-global. */\nexport type PendingFillSink = PendingXmlFill[];\n\n/**\n * A colour element that can carry an alpha child.\n *\n * Always paired, even with no alpha: gradient stops may gain one, and the\n * paired form is what the slide XML has always contained for them.\n */\nfunction colorXml(color: PptxIrColor): string {\n const alpha =\n color.transparency !== undefined\n ? `<a:alpha val=\"${Math.round((100 - color.transparency) * PCT_UNIT)}\"/>`\n : '';\n return `<a:srgbClr val=\"${color.hex.toUpperCase()}\">${alpha}</a:srgbClr>`;\n}\n\n/**\n * The compact colour element used inside a pattern fill.\n *\n * Pattern foreground/background carry no transparency, so the element has no\n * children and is written self-closing.\n */\nfunction opaqueColorXml(color: PptxIrColor): string {\n return `<a:srgbClr val=\"${color.hex.toUpperCase()}\"/>`;\n}\n\nexport function buildGradientFillXml(gradient: PptxIrGradient): string {\n const stops = gradient.stops\n .map(\n (stop) =>\n `<a:gs pos=\"${Math.round(stop.position * PCT_UNIT)}\">${colorXml(stop.color)}</a:gs>`\n )\n .join('');\n\n const shade =\n gradient.type === 'radial'\n ? radialShadeXml(gradient.focus)\n : `<a:lin ang=\"${Math.round(gradient.angleDegrees * ANGLE_UNIT)}\" scaled=\"1\"/>`;\n\n return `<a:gradFill rotWithShape=\"1\"><a:gsLst>${stops}</a:gsLst>${shade}</a:gradFill>`;\n}\n\nfunction radialShadeXml(focus: PptxIrRadialFocus): string {\n const rect = RADIAL_FOCUS_RECTS[focus] ?? RADIAL_FOCUS_RECTS.center;\n return `<a:path path=\"circle\"><a:fillToRect l=\"${rect.l}\" t=\"${rect.t}\" r=\"${rect.r}\" b=\"${rect.b}\"/></a:path>`;\n}\n\nexport function buildPatternFillXml(\n preset: string,\n foreground: PptxIrColor,\n background: PptxIrColor\n): string {\n return (\n `<a:pattFill prst=\"${preset}\">` +\n `<a:fgClr>${opaqueColorXml(foreground)}</a:fgClr>` +\n `<a:bgClr>${opaqueColorXml(background)}</a:bgClr>` +\n `</a:pattFill>`\n );\n}\n\n/**\n * Write a sentinel solid fill and register the real fill for splicing.\n *\n * Without a sink — a caller rendering outside the buffer pipeline — the shape\n * keeps the sentinel colour, so the deck still reads as authored instead of\n * falling back to a PptxGenJS default.\n */\nexport function registerAdvancedFill(\n opts: Record<string, unknown>,\n fill: Extract<PptxIrFill, { kind: 'gradient' | 'pattern' }>,\n elementPath: string,\n sink: PendingFillSink | undefined\n): void {\n const sentinel =\n fill.kind === 'gradient' ? fill.gradient.stops[0].color : fill.foreground;\n\n if (sink) {\n const xml =\n fill.kind === 'gradient'\n ? buildGradientFillXml(fill.gradient)\n : buildPatternFillXml(fill.preset, fill.foreground, fill.background);\n const objectName = `__jto_fill_${sink.length}__`;\n sink.push({ objectName, xml });\n opts.objectName = objectName;\n }\n\n void elementPath;\n opts.fill = { color: sentinel.hex };\n}\n","/**\n * PptxIR charts → PptxGenJS.\n *\n * Pure vocabulary translation. Every colour, font family, bold toggle and\n * palette entry was resolved by the compiler, so nothing here consults a theme\n * or decides a default.\n */\n\nimport type PptxGenJS from 'pptxgenjs';\nimport type {\n PptxIrChartAxis,\n PptxIrChartElement,\n PptxIrChartGridLine,\n PptxIrChartLabelFont,\n PptxIrChartValueAxis,\n} from '../../ir/types';\nimport { emuToInches } from '../../ir/units';\n\ntype Opts = Record<string, unknown>;\n\nexport function emitChart(\n slide: PptxGenJS.Slide,\n element: PptxIrChartElement\n): void {\n const data = element.series.map((series) => {\n const entry: Opts = {};\n if (series.name !== undefined) entry.name = series.name;\n if (series.labels) entry.labels = series.labels;\n if (series.values) entry.values = series.values;\n if (series.sizes) entry.sizes = series.sizes;\n return entry;\n });\n\n slide.addChart(\n element.chartType as never,\n data as never,\n chartOpts(element) as never\n );\n}\n\nfunction chartOpts(element: PptxIrChartElement): Opts {\n const { options: o, transform } = element;\n const opts: Opts = {\n x: emuToInches(transform.xEmu),\n y: emuToInches(transform.yEmu),\n w: emuToInches(transform.widthEmu),\n h: emuToInches(transform.heightEmu),\n };\n\n if (o.colors.length > 0) opts.chartColors = [...o.colors];\n\n assignDefined(opts, {\n showLegend: o.showLegend,\n showTitle: o.showTitle,\n showValue: o.showValue,\n showPercent: o.showPercent,\n showLabel: o.showLabel,\n showSerName: o.showSeriesName,\n title: o.title,\n legendPos: o.legendPosition,\n barDir: o.barDirection,\n barGrouping: o.barGrouping,\n barGapWidthPct: o.barGapWidthPercent,\n barOverlapPct: o.barOverlapPercent,\n lineSmooth: o.lineSmooth,\n lineDataSymbol: o.lineDataSymbol,\n lineSize: o.lineSize,\n lineDataSymbolSize: o.lineDataSymbolSize,\n firstSliceAng: o.firstSliceAngle,\n holeSize: o.holeSize,\n radarStyle: o.radarStyle,\n dataLabelPosition: o.dataLabelPosition,\n });\n\n applyLabelFont(opts, o.titleFont, {\n face: 'titleFontFace',\n bold: 'titleBold',\n size: 'titleFontSize',\n color: 'titleColor',\n });\n applyLabelFont(opts, o.legendFont, {\n face: 'legendFontFace',\n size: 'legendFontSize',\n color: 'legendColor',\n });\n applyLabelFont(opts, o.dataLabelFont, {\n face: 'dataLabelFontFace',\n bold: 'dataLabelFontBold',\n size: 'dataLabelFontSize',\n color: 'dataLabelColor',\n });\n\n applyAxis(opts, o.categoryAxis, {\n title: 'catAxisTitle',\n showTitle: 'showCatAxisTitle',\n hidden: 'catAxisHidden',\n labelRotate: 'catAxisLabelRotate',\n gridLine: 'catGridLine',\n showLine: 'catAxisLineShow',\n face: 'catAxisLabelFontFace',\n bold: 'catAxisLabelFontBold',\n size: 'catAxisLabelFontSize',\n color: 'catAxisLabelColor',\n });\n\n applyValueAxis(opts, o.valueAxis);\n\n if (o.dataBorder) {\n opts.dataBorder = {\n pt: o.dataBorder.widthPoints,\n color: o.dataBorder.color.hex,\n };\n }\n\n return opts;\n}\n\ninterface LabelFontKeys {\n face: string;\n /** Absent for the legend, which has no bold toggle in PowerPoint. */\n bold?: string;\n size: string;\n color: string;\n}\n\nfunction applyLabelFont(\n opts: Opts,\n font: PptxIrChartLabelFont,\n keys: LabelFontKeys\n): void {\n if (font.fontFamily !== undefined) opts[keys.face] = font.fontFamily;\n if (font.bold !== undefined && keys.bold) opts[keys.bold] = font.bold;\n if (font.fontSize !== undefined) opts[keys.size] = font.fontSize;\n if (font.color) opts[keys.color] = font.color.hex;\n}\n\ninterface AxisKeys extends LabelFontKeys {\n title: string;\n showTitle: string;\n hidden: string;\n labelRotate: string;\n gridLine: string;\n showLine: string;\n}\n\nfunction applyAxis(opts: Opts, axis: PptxIrChartAxis, keys: AxisKeys): void {\n if (axis.title !== undefined) {\n opts[keys.title] = axis.title;\n opts[keys.showTitle] = true;\n }\n if (axis.hidden !== undefined) opts[keys.hidden] = axis.hidden;\n if (axis.labelRotate !== undefined) opts[keys.labelRotate] = axis.labelRotate;\n if (axis.showLine !== undefined) opts[keys.showLine] = axis.showLine;\n if (axis.gridLine) opts[keys.gridLine] = gridLineOpts(axis.gridLine);\n applyLabelFont(opts, axis.labelFont, keys);\n}\n\nfunction applyValueAxis(opts: Opts, axis: PptxIrChartValueAxis): void {\n applyAxis(opts, axis, {\n title: 'valAxisTitle',\n showTitle: 'showValAxisTitle',\n hidden: 'valAxisHidden',\n labelRotate: 'valAxisLabelRotate',\n gridLine: 'valGridLine',\n showLine: 'valAxisLineShow',\n face: 'valAxisLabelFontFace',\n bold: 'valAxisLabelFontBold',\n size: 'valAxisLabelFontSize',\n color: 'valAxisLabelColor',\n });\n assignDefined(opts, {\n valAxisMinVal: axis.minValue,\n valAxisMaxVal: axis.maxValue,\n valAxisMajorUnit: axis.majorUnit,\n valAxisLabelFormatCode: axis.labelFormatCode,\n });\n}\n\nfunction gridLineOpts(gridLine: PptxIrChartGridLine): Opts {\n const opts: Opts = {};\n if (gridLine.style !== undefined) opts.style = gridLine.style;\n if (gridLine.size !== undefined) opts.size = gridLine.size;\n if (gridLine.color) opts.color = gridLine.color.hex;\n return opts;\n}\n\nfunction assignDefined(target: Opts, values: Opts): void {\n for (const [key, value] of Object.entries(values)) {\n if (value !== undefined) target[key] = value;\n }\n}\n","/**\n * PptxIR tables → PptxGenJS.\n *\n * Two things live here that are properties of *this backend* rather than of a\n * table:\n *\n * 1. **Units.** PptxGenJS's table path uses a different inch/EMU threshold from\n * the rest of its API (20 instead of 100) and does not run x/y/h through its\n * normal parser. Passing EMU directly sidesteps both: any real value is\n * above the threshold, so PptxGenJS uses it verbatim.\n * 2. **Rounded corners.** OOXML tables have no corner radius, and PptxGenJS\n * exposes none. The IR asks for one semantically; this module realises it by\n * drawing rounded rectangles behind the table and making the corner cells\n * transparent so they show through. That technique is not in the IR.\n */\n\nimport type PptxGenJS from 'pptxgenjs';\nimport type {\n PptxIrTableBorder,\n PptxIrTableCell,\n PptxIrTableElement,\n PptxIrTableFormatting,\n} from '../../ir/types';\nimport { emuToInches } from '../../ir/units';\n\ntype Opts = Record<string, unknown>;\n\nconst NO_BORDER = { type: 'none', pt: 0 } as const;\nconst NO_LINE = { type: 'none' } as const;\n\nexport function emitTable(\n slide: PptxGenJS.Slide,\n element: PptxIrTableElement,\n pptx: PptxGenJS\n): void {\n const rounded = roundedCornerPlan(element);\n // The IR always carries a resolved absolute origin, so the backdrop can\n // always be placed. The pre-IR pipeline drew it only when the author happened\n // to write x and y as plain numbers, which left a percentage-positioned\n // rounded table with square corners — see the recorded output differences.\n if (rounded) emitRoundedBackground(slide, element, rounded, pptx);\n\n const rows = element.rows.map((row, rowIndex) =>\n row.cells.map((cell, colIndex) =>\n emitCell(cell, {\n element,\n rounded,\n rowIndex,\n colIndex,\n columnCount: row.cells.length,\n })\n )\n );\n\n slide.addTable(rows as never, tableOpts(element, rounded) as never);\n}\n\n/* ------------------------------------------------------------------ *\n * Table-level options\n * ------------------------------------------------------------------ */\n\nfunction tableOpts(\n element: PptxIrTableElement,\n rounded: RoundedPlan | undefined\n): Opts {\n const opts: Opts = {\n // EMU passes through PptxGenJS's table path untouched — see the note above.\n x: element.transform.xEmu,\n y: element.transform.yEmu,\n };\n if (!element.transform.autoWidth) opts.w = element.transform.widthEmu;\n if (!element.transform.autoHeight) opts.h = element.transform.heightEmu;\n\n if (element.columnWidthsEmu.length > 0) {\n opts.colW = toInchList(element.columnWidthsEmu);\n }\n if (element.rowHeightsEmu.length > 0) {\n opts.rowH = toInchList(element.rowHeightsEmu);\n }\n\n // A rounded table draws its own outline through the background shapes, so\n // the table-level border is suppressed and the per-cell borders take over.\n if (element.border && !rounded) {\n opts.border = borderOpts(element.border);\n }\n if (element.fill) opts.fill = { color: element.fill.hex };\n\n Object.assign(opts, defaultsOpts(element.defaults));\n\n if (element.autoPage) opts.autoPage = true;\n if (element.autoPageRepeatHeader) {\n opts.autoPageRepeatHeader = true;\n opts.autoPageHeaderRows = 1;\n }\n\n if (rounded) {\n opts.w = rounded.widthEmu;\n opts.border = [\n NO_BORDER_TYPE,\n NO_BORDER_TYPE,\n NO_BORDER_TYPE,\n NO_BORDER_TYPE,\n ];\n }\n\n return opts;\n}\n\nconst NO_BORDER_TYPE = { type: 'none' } as const;\n\nfunction defaultsOpts(defaults: PptxIrTableFormatting): Opts {\n const opts: Opts = {\n fontSize: defaults.fontSize,\n fontFace: defaults.fontFamily,\n valign: defaults.verticalAlign,\n };\n if (defaults.bold !== undefined) opts.bold = defaults.bold;\n if (defaults.color) opts.color = defaults.color.hex;\n if (defaults.align) opts.align = defaults.align;\n if (defaults.insetPoints !== undefined) opts.margin = defaults.insetPoints;\n return opts;\n}\n\nfunction borderOpts(border: PptxIrTableBorder): Opts {\n const opts: Opts = { type: border.type };\n if (border.widthPoints !== undefined) opts.pt = border.widthPoints;\n if (border.color) opts.color = border.color.hex;\n return opts;\n}\n\nfunction toInchList(values: readonly number[]): number | number[] {\n const inches = values.map(emuToInches);\n return inches.length === 1 ? inches[0] : inches;\n}\n\n/* ------------------------------------------------------------------ *\n * Cells\n * ------------------------------------------------------------------ */\n\ninterface CellScope {\n element: PptxIrTableElement;\n rounded: RoundedPlan | undefined;\n rowIndex: number;\n colIndex: number;\n columnCount: number;\n}\n\nfunction emitCell(cell: PptxIrTableCell, scope: CellScope): Opts {\n const opts: Opts = {};\n const formatting = cell.formatting;\n\n if (formatting?.color) opts.color = formatting.color.hex;\n if (formatting?.fontSize !== undefined) opts.fontSize = formatting.fontSize;\n if (formatting?.fontFamily) opts.fontFace = formatting.fontFamily;\n if (formatting?.bold !== undefined) opts.bold = formatting.bold;\n if (formatting?.italic) opts.italic = true;\n if (formatting?.align) opts.align = formatting.align;\n if (formatting?.verticalAlign) opts.valign = formatting.verticalAlign;\n if (formatting?.insetPoints !== undefined) {\n opts.margin = formatting.insetPoints;\n }\n if (cell.colSpan !== undefined) opts.colspan = cell.colSpan;\n if (cell.rowSpan !== undefined) opts.rowspan = cell.rowSpan;\n\n if (scope.rounded) {\n applyRoundedCellStyling(opts, cell, scope, scope.rounded);\n } else if (cell.fill) {\n opts.fill = { color: cell.fill.hex };\n }\n\n return Object.keys(opts).length > 0\n ? { text: cell.text, options: opts }\n : { text: cell.text };\n}\n\n/* ------------------------------------------------------------------ *\n * Rounded corners\n * ------------------------------------------------------------------ */\n\ninterface RoundedPlan {\n radiusInches: number;\n bodyFill: string;\n headerFill: string;\n widthEmu: number;\n innerBorder: Opts;\n}\n\n/**\n * Work out whether a rounded table can be drawn, and with which colours.\n *\n * Needs at least a header row and a body row, and an absolute position: the\n * background shapes are placed at the table's own coordinates.\n */\nfunction roundedCornerPlan(\n element: PptxIrTableElement\n): RoundedPlan | undefined {\n if (element.cornerRadiusInches === undefined) return undefined;\n if (element.rows.length < 2) return undefined;\n\n const lastRow = element.rows[element.rows.length - 1];\n const bodyFill =\n element.fill?.hex ?? lastRow?.cells[0]?.fill?.hex ?? 'FFFFFF';\n const headerFill = element.rows[0]?.cells[0]?.fill?.hex ?? bodyFill;\n\n return {\n radiusInches: element.cornerRadiusInches,\n bodyFill,\n headerFill,\n widthEmu: roundedWidthEmu(element),\n innerBorder: element.border ? borderOpts(element.border) : { ...NO_BORDER },\n };\n}\n\n/**\n * Width the background shapes and the table must share.\n *\n * Derived from the column widths when they exist so the shapes line up with\n * the table exactly; otherwise the table's own width.\n */\nfunction roundedWidthEmu(element: PptxIrTableElement): number {\n // An explicit column list is summed as given — including a single-entry\n // list, which names one column rather than a width for every column. With no\n // list the table's own width applies, falling back to 5in when it has none.\n const columns = element.columnWidthsEmu;\n if (columns.length > 0) {\n return columns.reduce((sum, width) => sum + width, 0);\n }\n return element.transform.autoWidth\n ? Math.round(5 * 914400)\n : element.transform.widthEmu;\n}\n\n/**\n * Corner cells go transparent so the rounded shapes behind show through;\n * every other cell stays opaque so no seam appears between them.\n */\nfunction applyRoundedCellStyling(\n opts: Opts,\n cell: PptxIrTableCell,\n scope: CellScope,\n rounded: RoundedPlan\n): void {\n const isHeader = scope.rowIndex === 0;\n const isLastRow = scope.rowIndex === scope.element.rows.length - 1;\n const isCorner =\n (isHeader || isLastRow) &&\n (scope.colIndex === 0 || scope.colIndex === scope.columnCount - 1);\n\n if (!isCorner) {\n opts.fill = {\n color:\n cell.fill?.hex ?? (isHeader ? rounded.headerFill : rounded.bodyFill),\n };\n }\n opts.border = roundedCellBorders(scope, rounded);\n}\n\n/**\n * Per-cell borders for a rounded table: no outer edges (the shapes draw them)\n * and no seam between the header row and the body.\n */\nfunction roundedCellBorders(scope: CellScope, rounded: RoundedPlan): Opts[] {\n const { rowIndex, colIndex, columnCount, element } = scope;\n const isTop = rowIndex === 0;\n const isBottom = rowIndex === element.rows.length - 1;\n const isLeft = colIndex === 0;\n const isRight = colIndex === columnCount - 1;\n const inner = rounded.innerBorder;\n const none: Opts = { ...NO_BORDER };\n\n return [\n isTop || rowIndex === 1 ? none : inner,\n isRight ? none : inner,\n isBottom || rowIndex === 0 ? none : inner,\n isLeft ? none : inner,\n ];\n}\n\n/**\n * Draw the rounded background: a rounded header block with a flat patch over\n * its lower corners, and a rounded body block with a flat patch over its upper\n * corners, so only the outer four corners stay round.\n */\nfunction emitRoundedBackground(\n slide: PptxGenJS.Slide,\n element: PptxIrTableElement,\n rounded: RoundedPlan,\n pptx: PptxGenJS\n): void {\n const xInches = emuToInches(element.transform.xEmu);\n const yInches = emuToInches(element.transform.yEmu);\n const widthInches = emuToInches(rounded.widthEmu);\n\n const rowHeights = element.rowHeightsEmu;\n const headerInches =\n rowHeights.length > 0 ? emuToInches(rowHeights[0]) : 0.45;\n const totalInches =\n rowHeights.length > 1\n ? emuToInches(rowHeights.reduce((sum, h) => sum + h, 0))\n : rowHeights.length === 1\n ? emuToInches(rowHeights[0]) * element.rows.length\n : element.transform.autoHeight\n ? 2\n : emuToInches(element.transform.heightEmu);\n\n slide.addShape(pptx.ShapeType.roundRect, {\n x: xInches,\n y: yInches,\n w: widthInches,\n h: headerInches,\n fill: { color: rounded.headerFill },\n rectRadius: rounded.radiusInches,\n line: { ...NO_LINE },\n } as never);\n slide.addShape(pptx.ShapeType.rect, {\n x: xInches,\n y: yInches + headerInches - rounded.radiusInches,\n w: widthInches,\n h: rounded.radiusInches,\n fill: { color: rounded.headerFill },\n line: { ...NO_LINE },\n } as never);\n\n const bodyY = yInches + headerInches;\n slide.addShape(pptx.ShapeType.roundRect, {\n x: xInches,\n y: bodyY,\n w: widthInches,\n h: totalInches - headerInches,\n fill: { color: rounded.bodyFill },\n rectRadius: rounded.radiusInches,\n line: { ...NO_LINE },\n } as never);\n slide.addShape(pptx.ShapeType.rect, {\n x: xInches,\n y: bodyY,\n w: widthInches,\n h: rounded.radiusInches,\n fill: { color: rounded.bodyFill },\n line: { ...NO_LINE },\n } as never);\n}\n","/**\n * PptxIR → PptxGenJS calls.\n *\n * Each function here maps one IR node onto the option bag PptxGenJS expects.\n * They are deliberately small and free of policy: every cascade, default and\n * unit conversion already happened in the compiler, so this layer only\n * translates vocabulary.\n *\n * Unit note: the IR is in EMU, PptxGenJS takes inches. Dividing is exact\n * against the compiler's `Math.round(inches * 914400)` because PptxGenJS\n * applies the same rounding on the way in.\n */\n\nimport type PptxGenJS from 'pptxgenjs';\nimport { assertNever } from '@json-to-office/shared/rendering';\nimport type {\n PptxIrColor,\n PptxIrElement,\n PptxIrFill,\n PptxIrGeometry,\n PptxIrHyperlink,\n PptxIrImageElement,\n PptxIrLine,\n PptxIrResource,\n PptxIrShadow,\n PptxIrShapeElement,\n PptxIrTextBodyStyle,\n PptxIrTextBoxElement,\n PptxIrTextRun,\n PptxIrTransform,\n} from '../../ir/types';\nimport { emuToInches } from '../../ir/units';\nimport type { PipelineWarning } from '../../types';\nimport { W, warn } from '../../utils/warn';\nimport type { PendingFillSink } from './fills';\nimport { registerAdvancedFill } from './fills';\nimport { emitChart } from './chart';\nimport { emitTable } from './table';\n\ntype Opts = Record<string, unknown>;\n\n/** Resources by id, so an element's `resourceId` can be turned into a source. */\nexport type ResourceLookup = ReadonlyMap<string, PptxIrResource>;\n\nexport interface EmitContext {\n pptx: PptxGenJS;\n resources: ResourceLookup;\n /** Registry for fills PptxGenJS cannot express. Absent disables the splice. */\n pendingFills?: PendingFillSink;\n /** Sink for a shape this backend has no preset for. */\n warnings?: PipelineWarning[];\n}\n\n/* ------------------------------------------------------------------ *\n * Primitives\n * ------------------------------------------------------------------ */\n\nexport function transformOpts(transform: PptxIrTransform): Opts {\n const opts: Opts = {\n x: emuToInches(transform.xEmu),\n y: emuToInches(transform.yEmu),\n w: emuToInches(transform.widthEmu),\n h: emuToInches(transform.heightEmu),\n };\n if (transform.rotationDegrees !== undefined) {\n opts.rotate = transform.rotationDegrees;\n }\n if (transform.flipHorizontal) opts.flipH = true;\n if (transform.flipVertical) opts.flipV = true;\n return opts;\n}\n\n/** PptxGenJS wants bare hex; the IR already stores it that way. */\nexport function colorValue(color: PptxIrColor): string {\n return color.hex;\n}\n\nexport function lineOpts(line: PptxIrLine): Opts {\n const opts: Opts = {};\n if (line.color) opts.color = colorValue(line.color);\n if (line.widthPoints !== undefined) opts.width = line.widthPoints;\n if (line.dash) opts.dashType = line.dash;\n return opts;\n}\n\nexport function shadowOpts(shadow: PptxIrShadow): Opts {\n return {\n type: shadow.type,\n color: colorValue(shadow.color),\n blur: shadow.blurPoints,\n offset: shadow.offsetPoints,\n angle: shadow.angleDegrees,\n opacity: shadow.opacity,\n };\n}\n\nexport function hyperlinkOpts(link: PptxIrHyperlink): Opts {\n return link.kind === 'external'\n ? { url: link.url, tooltip: link.tooltip }\n : { slide: link.slideIndex, tooltip: link.tooltip };\n}\n\n/**\n * Apply a fill.\n *\n * Solid fills map directly. Gradients and patterns do not exist in the\n * PptxGenJS API, so they are registered for the post-generation splice and a\n * sentinel solid fill is written in their place — the workaround lives here,\n * never in the IR.\n */\nexport function applyFill(\n opts: Opts,\n fill: PptxIrFill,\n elementPath: string,\n ctx: EmitContext\n): void {\n switch (fill.kind) {\n case 'none':\n opts.fill = { type: 'none' };\n return;\n case 'solid': {\n const value: Opts = { color: colorValue(fill.color) };\n if (fill.color.transparency !== undefined) {\n value.transparency = fill.color.transparency;\n }\n opts.fill = value;\n return;\n }\n case 'gradient':\n case 'pattern':\n registerAdvancedFill(opts, fill, elementPath, ctx.pendingFills);\n return;\n case 'image':\n // Modelled in the IR; PptxGenJS has no shape image fill. Capability\n // checking rejects this before render, so reaching it is a bug.\n throw new Error(\n `PptxGenJS cannot apply an image fill (${elementPath}); this should have failed capability checking`\n );\n default:\n assertNever(fill, 'PptxIrFill');\n }\n}\n\n/* ------------------------------------------------------------------ *\n * Text\n * ------------------------------------------------------------------ */\n\nexport function textBodyOpts(style: PptxIrTextBodyStyle): Opts {\n const opts: Opts = { valign: style.verticalAlign };\n if (style.insetPoints !== undefined) {\n opts.margin = textBodyMargin(style.insetPoints);\n }\n if (style.align) opts.align = style.align;\n if (style.lineSpacingMultiple !== undefined) {\n opts.lineSpacingMultiple = style.lineSpacingMultiple;\n } else if (style.lineSpacingPoints !== undefined) {\n opts.lineSpacing = style.lineSpacingPoints;\n }\n if (style.spaceBeforePoints !== undefined) {\n opts.paraSpaceBefore = style.spaceBeforePoints;\n }\n if (style.spaceAfterPoints !== undefined) {\n opts.paraSpaceAfter = style.spaceAfterPoints;\n }\n if (style.bullet) opts.bullet = bulletOpt(style.bullet);\n if (style.autoFit) opts.isTextBox = true;\n return opts;\n}\n\n/**\n * A bullet in PptxGenJS's vocabulary.\n *\n * The backend reads three shapes and each has to be hit exactly:\n * - `false` is how it spells `<a:buNone/>`, and an object never reaches that\n * branch, so `type: 'none'` has to become the boolean;\n * - an object with `type: 'number'` becomes `<a:buAutoNum>`;\n * - a custom glyph goes through `characterCode`, a 4-digit hex code point —\n * PptxGenJS ignores `style` on a character bullet and writes no bullet at\n * all, so passing the glyph as `style` loses it silently.\n *\n * Anything else is the default glyph, which is what `true` asks for.\n */\nfunction bulletOpt(\n bullet: NonNullable<PptxIrTextBodyStyle['bullet']>\n): unknown {\n if (bullet.type === 'none') return false;\n if (bullet.type === 'number') {\n return {\n type: 'number',\n ...(bullet.style ? { style: bullet.style } : {}),\n ...(bullet.startAt !== undefined ? { startAt: bullet.startAt } : {}),\n };\n }\n if (bullet.style === undefined) return true;\n const characterCode = bmpCharacterCode(bullet.style);\n if (characterCode === undefined) {\n throw new Error(\n 'PptxGenJS cannot emit an astral or multi-code-point bullet glyph'\n );\n }\n return { characterCode };\n}\n\n/**\n * A glyph as the 4-digit hex code PptxGenJS validates against.\n *\n * Undefined for anything it would reject — an astral code point, or more than\n * one character. Capability preflight refuses those values before emission.\n */\nfunction bmpCharacterCode(glyph: string | undefined): string | undefined {\n if (glyph === undefined) return undefined;\n const points = [...glyph];\n if (points.length !== 1) return undefined;\n const code = points[0].codePointAt(0);\n if (code === undefined || code > 0xffff) return undefined;\n return code.toString(16).toUpperCase().padStart(4, '0');\n}\n\n/**\n * A text-body inset, in the order PptxGenJS's *text* path reads.\n *\n * The IR states `[top, right, bottom, left]`, which is what the authoring\n * schema documents and what PptxGenJS's table path reads. Its text path reads\n * the same four numbers as `[left, right, bottom, top]` — the two disagree\n * inside the library — so the tuple is reordered here rather than in the IR,\n * because it is a property of this backend and nothing else. A scalar is the\n * same on every side and passes through.\n */\nfunction textBodyMargin(\n inset: number | [number, number, number, number]\n): number | [number, number, number, number] {\n if (typeof inset === 'number') return inset;\n const [top, right, bottom, left] = inset;\n return [left, right, bottom, top];\n}\n\n/** Run-level options. Every value is already resolved; nothing cascades here. */\nexport function runOpts(run: PptxIrTextRun): Opts {\n const opts: Opts = {\n fontFace: run.fontFamily,\n fontSize: run.fontSize,\n color: colorValue(run.color),\n };\n if (run.bold !== undefined) opts.bold = run.bold;\n if (run.italic !== undefined) opts.italic = run.italic;\n if (run.strike !== undefined) opts.strike = run.strike;\n if (run.underline)\n opts.underline = run.underline.color\n ? { style: run.underline.style, color: colorValue(run.underline.color) }\n : { style: run.underline.style };\n if (run.superscript !== undefined) opts.superscript = run.superscript;\n if (run.subscript !== undefined) opts.subscript = run.subscript;\n if (run.characterSpacing !== undefined) {\n opts.charSpacing = run.characterSpacing;\n }\n if (run.language) opts.lang = run.language;\n if (run.breakAfter !== undefined) opts.breakLine = run.breakAfter;\n if (run.spaceBeforePoints !== undefined) {\n opts.paraSpaceBefore = run.spaceBeforePoints;\n }\n if (run.spaceAfterPoints !== undefined) {\n opts.paraSpaceAfter = run.spaceAfterPoints;\n }\n if (run.hyperlink) opts.hyperlink = hyperlinkOpts(run.hyperlink);\n return opts;\n}\n\n/**\n * Block-level options for a text body.\n *\n * These come from the body's own defaults, never from whichever run happens to\n * be first: PptxGenJS merges run options over block options, and it also uses\n * the block options for the trailing `endParaRPr`. Hoisting run 0's formatting\n * would leak it onto every later run that does not override it.\n */\nfunction bodyDefaultOpts(style: PptxIrTextBodyStyle): Opts {\n const defaults = style.defaults;\n const opts: Opts = {\n fontFace: defaults.fontFamily,\n fontSize: defaults.fontSize,\n color: colorValue(defaults.color),\n };\n if (defaults.bold !== undefined) opts.bold = defaults.bold;\n if (defaults.italic !== undefined) opts.italic = defaults.italic;\n if (defaults.language) opts.lang = defaults.language;\n return opts;\n}\n\nexport function emitTextBox(\n slide: PptxGenJS.Slide,\n element: PptxIrTextBoxElement,\n ctx: EmitContext\n): void {\n const opts: Opts = {\n ...transformOpts(element.transform),\n ...bodyDefaultOpts(element.style),\n ...textBodyOpts(element.style),\n };\n if (element.fill) applyFill(opts, element.fill, element.path, ctx);\n if (element.shadow) opts.shadow = shadowOpts(element.shadow);\n if (element.hyperlink) opts.hyperlink = hyperlinkOpts(element.hyperlink);\n if (element.altText) opts.altText = element.altText;\n\n emitRuns(slide, element.runs, opts);\n}\n\nfunction emitRuns(\n slide: PptxGenJS.Slide,\n runs: readonly PptxIrTextRun[],\n opts: Opts\n): void {\n if (runs.length === 1) {\n const [only] = runs;\n // A lone run's shared formatting is already hoisted into `opts` by\n // `bodyDefaultOpts`; anything run-specific still has to be applied.\n Object.assign(opts, runOpts(only));\n slide.addText(only.text, opts as never);\n return;\n }\n const segments = runs.map((run) => ({\n text: run.text,\n options: runOpts(run) as never,\n }));\n slide.addText(segments as never, opts as never);\n}\n\n/* ------------------------------------------------------------------ *\n * Shapes\n * ------------------------------------------------------------------ */\n\n/** Map an IR geometry name to a PptxGenJS `ShapeType` member. */\nexport function shapeType(\n geometry: PptxIrGeometry,\n pptx: PptxGenJS\n): unknown | undefined {\n const name = typeof geometry === 'string' ? geometry : geometry.custom;\n return (pptx.ShapeType as unknown as Record<string, unknown>)[name];\n}\n\nexport function emitShape(\n slide: PptxGenJS.Slide,\n element: PptxIrShapeElement,\n ctx: EmitContext\n): void {\n const type = shapeType(element.geometry, ctx.pptx);\n if (type === undefined) {\n // The IR carries any geometry name; only the backend knows which of them\n // it has a preset for. One unrecognised name costs that shape, not the\n // document.\n warn(\n ctx.warnings,\n W.UNKNOWN_SHAPE,\n `Unknown shape type: ${describeGeometry(element.geometry)}`,\n { component: 'shape' }\n );\n return;\n }\n\n const opts: Opts = { ...transformOpts(element.transform) };\n if (element.fill) applyFill(opts, element.fill, element.path, ctx);\n if (element.line) opts.line = lineOpts(element.line);\n if (element.shadow) opts.shadow = shadowOpts(element.shadow);\n if (element.cornerRadius !== undefined)\n opts.rectRadius = element.cornerRadius;\n if (element.angleRangeDegrees) opts.angleRange = element.angleRangeDegrees;\n if (element.hyperlink) opts.hyperlink = hyperlinkOpts(element.hyperlink);\n if (element.altText) opts.altText = element.altText;\n\n if (element.runs && element.runs.length > 0) {\n opts.shape = type;\n if (element.style) {\n Object.assign(opts, bodyDefaultOpts(element.style));\n Object.assign(opts, textBodyOpts(element.style));\n }\n emitRuns(slide, element.runs, opts);\n return;\n }\n\n slide.addShape(type as never, opts as never);\n}\n\nfunction describeGeometry(geometry: PptxIrGeometry): string {\n return typeof geometry === 'string' ? geometry : geometry.custom;\n}\n\n/* ------------------------------------------------------------------ *\n * Images\n * ------------------------------------------------------------------ */\n\n/**\n * Turn a resource into the `path`/`data` pair PptxGenJS expects.\n *\n * Inline bytes become a data URI; file and remote origins keep their location\n * so PptxGenJS streams them exactly as it did before the IR existed.\n */\nexport function imageSourceOpts(resource: PptxIrResource): Opts {\n switch (resource.origin.kind) {\n case 'inline': {\n const base64 = Buffer.from(resource.origin.bytes).toString('base64');\n const mediaType = resource.mediaType ?? 'image/png';\n return { data: `data:${mediaType};base64,${base64}` };\n }\n case 'file':\n return { path: resource.origin.path };\n case 'remote':\n return { path: resource.origin.url };\n default:\n return assertNever(resource.origin, 'PptxIrResourceOrigin');\n }\n}\n\nexport function emitImage(\n slide: PptxGenJS.Slide,\n element: PptxIrImageElement,\n ctx: EmitContext\n): void {\n const resource = ctx.resources.get(element.resourceId);\n if (!resource) {\n throw new Error(\n `Image ${element.path} references unknown resource \"${element.resourceId}\"`\n );\n }\n\n const opts: Opts = {\n ...imageSourceOpts(resource),\n ...transformOpts(element.transform),\n };\n // An extent the author did not state is left to the backend, which derives\n // it from the sizing box. Passing the IR's fallback would override that.\n if (element.transform.autoWidth) delete opts.w;\n if (element.transform.autoHeight) delete opts.h;\n if (element.sizing) {\n // EMU rather than inches: PptxGenJS reads these through the same parser as\n // positions, which treats anything at or above 100 as already-EMU, so\n // passing EMU is exact for any real box size.\n opts.sizing = {\n type: element.sizing.type,\n w: element.sizing.widthEmu,\n h: element.sizing.heightEmu,\n ...(element.sizing.xEmu !== undefined ? { x: element.sizing.xEmu } : {}),\n ...(element.sizing.yEmu !== undefined ? { y: element.sizing.yEmu } : {}),\n };\n }\n if (element.rounding) opts.rounding = true;\n if (element.shadow) opts.shadow = shadowOpts(element.shadow);\n if (element.hyperlink) opts.hyperlink = hyperlinkOpts(element.hyperlink);\n if (element.altText) opts.altText = element.altText;\n\n slide.addImage(opts as never);\n}\n\n/* ------------------------------------------------------------------ *\n * Dispatch\n * ------------------------------------------------------------------ */\n\nexport function emitElement(\n slide: PptxGenJS.Slide,\n element: PptxIrElement,\n ctx: EmitContext\n): void {\n switch (element.kind) {\n case 'textBox':\n emitTextBox(slide, element, ctx);\n return;\n case 'shape':\n emitShape(slide, element, ctx);\n return;\n case 'image':\n emitImage(slide, element, ctx);\n return;\n case 'table':\n emitTable(slide, element, ctx.pptx);\n return;\n case 'chart':\n emitChart(slide, element);\n return;\n case 'group':\n // Reachable only if capability checking let it through, which would be\n // a bug — never a silent drop.\n throw new Error(\n `The pptxgenjs renderer has no emitter for \"${element.kind}\" (${element.path})`\n );\n default:\n assertNever(element, 'PptxIrElement');\n }\n}\n","/**\n * Generic OOXML package finalization.\n *\n * Canonical chart identifiers, pinned core-metadata and ZIP timestamps, and a\n * stable zip encoding. Every one of those is a property of the package rather\n * than of the backend that produced it, so any renderer's output goes through\n * this and nothing here knows which one ran.\n *\n * Backend repairs — the sentinel gradient/pattern splice, the table-style\n * GUID, the SVG preview fix — live with the backend that needs them, in\n * `renderers/pptxgenjs/packaging.ts`. Both halves share one `JSZip` so the\n * package is still read once and written once.\n */\n\nimport JSZip from 'jszip';\n\n/** Stable default shared by package entries and OOXML core metadata. */\nexport const DEFAULT_GENERATED_AT = '2000-01-01T00:00:00.000Z';\n\n/** What a caller may say about how the package is stamped. */\nexport interface PresentationPackagingOptions {\n /** Normalize metadata and ZIP timestamps. Defaults to true. */\n deterministic?: boolean;\n /** Clock used when deterministic packaging is enabled. */\n generatedAt?: Date | string;\n}\n\nexport async function readPackage(buffer: Buffer): Promise<JSZip> {\n return JSZip.loadAsync(buffer);\n}\n\nexport async function writePackage(zip: JSZip): Promise<Buffer> {\n return generateZip(zip);\n}\n\nexport function resolveGeneratedAt(value?: Date | string): Date {\n const date =\n value === undefined ? new Date(DEFAULT_GENERATED_AT) : new Date(value);\n if (Number.isNaN(date.getTime())) {\n throw new Error(`Invalid generatedAt value: ${String(value)}`);\n }\n if (date.getUTCFullYear() < 1980) {\n throw new Error(\n 'generatedAt must be on or after 1980-01-01 for ZIP compatibility'\n );\n }\n return date;\n}\n\n/**\n * Finalize a package in place: canonical chart ids, then pinned timestamps.\n *\n * In place rather than buffer-in/buffer-out so an adapter that has already\n * opened the zip for its own repairs does not pay for a second pass.\n */\nexport async function finalizePackage(\n zip: JSZip,\n generatedAt: Date\n): Promise<void> {\n await canonicalizeChartIds(zip);\n await canonicalizePackage(zip, generatedAt);\n}\n\n/** Finalize a package a caller holds only as bytes. */\nexport async function finalizePackageBuffer(\n buffer: Buffer,\n options: { generatedAt?: Date | string } = {}\n): Promise<Buffer> {\n const zip = await readPackage(buffer);\n await finalizePackage(zip, resolveGeneratedAt(options.generatedAt));\n return writePackage(zip);\n}\n\nfunction replaceCoreTimestamp(\n xml: string,\n tag: 'created' | 'modified',\n value: string\n): string {\n const expression = new RegExp(\n `(<dcterms:${tag}\\\\b[^>]*>)[^<]*(</dcterms:${tag}>)`,\n 'g'\n );\n return xml.replace(expression, `$1${value}$2`);\n}\n\nconst EMBEDDED_OFFICE_PACKAGE = /\\.(?:docx|pptx|xlsx|xlsm)$/i;\n\nfunction remapChartReferences(\n value: string,\n chartIds: ReadonlyMap<number, number>\n): string {\n return value\n .replace(/chart(\\d+)\\.xml/g, (match, rawId: string) => {\n const id = chartIds.get(Number(rawId));\n return id === undefined ? match : `chart${id}.xml`;\n })\n .replace(\n /Microsoft_Excel_Worksheet(\\d+)\\.xlsx/g,\n (match, rawId: string) => {\n const id = chartIds.get(Number(rawId));\n return id === undefined ? match : `Microsoft_Excel_Worksheet${id}.xlsx`;\n }\n );\n}\n\nasync function canonicalizeChartIds(zip: JSZip): Promise<void> {\n const sourceIds = Object.keys(zip.files)\n .map((path) => path.match(/^ppt\\/charts\\/chart(\\d+)\\.xml$/)?.[1])\n .filter((value): value is string => value !== undefined)\n .map(Number)\n .sort((a, b) => a - b);\n const chartIds = new Map(sourceIds.map((id, index) => [id, index + 1]));\n if (chartIds.size === 0) return;\n\n // Rewrite relationship/content-type targets using one mapping pass so\n // overlapping IDs (2→1, 3→2) cannot cascade into each other.\n for (const [path, entry] of Object.entries(zip.files)) {\n if (entry.dir || (!path.endsWith('.xml') && !path.endsWith('.rels'))) {\n continue;\n }\n const xml = await entry.async('string');\n const remapped = remapChartReferences(xml, chartIds);\n if (remapped !== xml) zip.file(path, remapped);\n }\n\n const renames: Array<{\n from: string;\n to: string;\n data: Buffer;\n date: Date;\n }> = [];\n for (const [path, entry] of Object.entries(zip.files)) {\n if (entry.dir) continue;\n const remappedPath = remapChartReferences(path, chartIds);\n if (remappedPath === path) continue;\n renames.push({\n from: path,\n to: remappedPath,\n data: await entry.async('nodebuffer'),\n date: entry.date,\n });\n }\n\n // Remove every source before adding destinations to avoid overwriting a\n // source path that another chart still needs.\n for (const entry of renames) zip.remove(entry.from);\n for (const entry of renames) {\n zip.file(entry.to, entry.data, { date: entry.date });\n }\n}\n\nasync function generateZip(zip: JSZip): Promise<Buffer> {\n return (await zip.generateAsync({\n type: 'nodebuffer',\n compression: 'DEFLATE',\n compressionOptions: { level: 6 },\n platform: 'DOS',\n streamFiles: false,\n })) as Buffer;\n}\n\nasync function canonicalizePackage(\n zip: JSZip,\n generatedAt: Date,\n depth = 0\n): Promise<void> {\n const timestamp = generatedAt.toISOString().replace(/\\.\\d{3}Z$/, 'Z');\n const coreEntry = zip.file('docProps/core.xml');\n if (coreEntry) {\n let coreXml = await coreEntry.async('string');\n coreXml = replaceCoreTimestamp(coreXml, 'created', timestamp);\n coreXml = replaceCoreTimestamp(coreXml, 'modified', timestamp);\n zip.file('docProps/core.xml', coreXml);\n }\n\n // Native charts contain generated XLSX packages with their own volatile\n // core.xml and ZIP timestamps. Normalize those recursively as well, or an\n // otherwise-stable outer PPTX still changes bytes on every build.\n if (depth < 3) {\n for (const [path, entry] of Object.entries(zip.files)) {\n if (entry.dir || !EMBEDDED_OFFICE_PACKAGE.test(path)) continue;\n try {\n const nested = await JSZip.loadAsync(await entry.async('nodebuffer'));\n await canonicalizePackage(nested, generatedAt, depth + 1);\n zip.file(path, await generateZip(nested));\n } catch {\n // Opaque/encrypted user-provided packages cannot be normalized safely.\n }\n }\n }\n\n for (const entry of Object.values(zip.files)) {\n entry.date = generatedAt;\n }\n}\n","/**\n * Raster fallbacks for inline SVG pictures (PPTX)\n *\n * An SVG picture ships as two media parts: the SVG itself, referenced by\n * `<asvg:svgBlip>` inside the blip's `<a:extLst>`, plus a PNG preview\n * referenced by the `<a:blip r:embed>` that every consumer understands.\n * PptxGenJS builds that preview with a browser canvas, so under Node it\n * writes its hardcoded broken-image placeholder instead\n * (gitbrent/PptxGenJS#401) and every viewer without svgBlip support —\n * LibreOffice <= 7.x, Google Slides, Office < 2016 — draws a red X.\n *\n * This pass rasterizes each SVG part and overwrites its paired PNG. It is a\n * best-effort repair: any failure leaves the placeholder in place and reports\n * a warning, because a broken preview still beats a package that failed to\n * build.\n */\nimport path from 'node:path';\nimport type JSZip from 'jszip';\nimport type { PipelineWarning } from '../../types';\nimport { W, warn } from '../../utils/warn';\n\ntype ResvgModule = typeof import('@resvg/resvg-js');\ntype FitTo = { mode: 'width' | 'height'; value: number };\n\nconst EMU_PER_INCH = 914400;\n/** 3x of PowerPoint's 96 DPI baseline — ~288 DPI, sharp when projected. */\nconst RASTER_SCALE = 3;\nconst MAX_EDGE_PX = 4096;\nconst MIN_EDGE_PX = 16;\n/** Used when a picture carries no `<a:xfrm>` extent to size against. */\nconst DEFAULT_EDGE_PX = 1024;\n\nconst PART_PATTERNS = [\n /^ppt\\/slides\\/slide\\d+\\.xml$/,\n /^ppt\\/slideLayouts\\/[^/]+\\.xml$/,\n /^ppt\\/slideMasters\\/[^/]+\\.xml$/,\n];\n\nconst SVG_BLIP = /<asvg:svgBlip\\b[^>]*r:embed=\"([^\"]+)\"/g;\nconst BLIP = /<a:blip\\b[^>]*r:embed=\"([^\"]+)\"/g;\nconst EXTENT = /<a:ext\\s+cx=\"(\\d+)\"\\s+cy=\"(\\d+)\"/;\nconst RELATIONSHIP = /<Relationship\\b([^>]*)>/g;\n\ninterface WorkItem {\n svgPart: string;\n cx?: number;\n cy?: number;\n}\n\nlet resvgModule: Promise<ResvgModule> | undefined;\n\nfunction loadResvg(): Promise<ResvgModule> {\n resvgModule ??= import('@resvg/resvg-js');\n return resvgModule;\n}\n\n/** Map `Id` -> package-absolute part path for one part's sibling .rels file. */\nasync function readRelationships(\n zip: JSZip,\n partPath: string\n): Promise<Map<string, string>> {\n const dir = path.posix.dirname(partPath);\n const relsPath = `${dir}/_rels/${path.posix.basename(partPath)}.rels`;\n const targets = new Map<string, string>();\n const entry = zip.file(relsPath);\n if (!entry) return targets;\n\n const xml = await entry.async('string');\n for (const match of xml.matchAll(RELATIONSHIP)) {\n const attrs = match[1];\n if (/\\bTargetMode=\"External\"/.test(attrs)) continue;\n const id = /\\bId=\"([^\"]+)\"/.exec(attrs)?.[1];\n const target = /\\bTarget=\"([^\"]+)\"/.exec(attrs)?.[1];\n if (!id || !target) continue;\n targets.set(\n id,\n target.startsWith('/')\n ? target.slice(1)\n : path.posix.normalize(path.posix.join(dir, target))\n );\n }\n return targets;\n}\n\n/**\n * Collect the svg/png part pairs referenced by one slide-family part. The\n * preview rId is the `<a:blip r:embed>` immediately preceding the svgBlip —\n * the svgBlip lives inside that blip's own `<a:extLst>` — and the placed size\n * is the `<a:ext cx cy>` that follows it inside the same `<p:pic>`.\n */\nfunction collectWorkItems(\n xml: string,\n rels: ReadonlyMap<string, string>,\n items: Map<string, WorkItem>\n): void {\n const blips = [...xml.matchAll(BLIP)];\n\n for (const svgBlip of xml.matchAll(SVG_BLIP)) {\n const at = svgBlip.index ?? 0;\n const preview = blips.filter((blip) => (blip.index ?? 0) < at).pop();\n if (!preview) continue;\n\n const pngPart = rels.get(preview[1]);\n const svgPart = rels.get(svgBlip[1]);\n if (!pngPart || !svgPart) continue;\n\n const picEnd = xml.indexOf('</p:pic>', at);\n const extent = EXTENT.exec(picEnd === -1 ? '' : xml.slice(at, picEnd));\n const cx = extent ? Number(extent[1]) : undefined;\n const cy = extent ? Number(extent[2]) : undefined;\n\n // PptxGenJS can point two pictures at one preview part; size it for the\n // largest box it has to cover. The axes max independently on purpose:\n // resvg scales uniformly, so one bitmap covers every box that shares the\n // part only when its width clears the widest and its height the tallest.\n // Keeping whichever single box is largest by area undersizes the other.\n const existing = items.get(pngPart);\n items.set(pngPart, {\n svgPart,\n cx: Math.max(cx ?? 0, existing?.cx ?? 0) || undefined,\n cy: Math.max(cy ?? 0, existing?.cy ?? 0) || undefined,\n });\n }\n}\n\nfunction toPixels(emu: number): number {\n const px = Math.round((emu / EMU_PER_INCH) * 96 * RASTER_SCALE);\n return Math.min(MAX_EDGE_PX, Math.max(MIN_EDGE_PX, px));\n}\n\n/**\n * Pick the axis to scale by so the bitmap covers the placed box on both axes:\n * an SVG wider than its box has to be sized by height, anything else by width.\n */\nfunction resolveFitTo(\n intrinsicAspect: number,\n cx: number | undefined,\n cy: number | undefined\n): FitTo {\n if (!cx || !cy) return { mode: 'width', value: DEFAULT_EDGE_PX };\n\n const wide = intrinsicAspect > cx / cy;\n const mode = wide ? 'height' : 'width';\n let value = wide ? toPixels(cy) : toPixels(cx);\n\n const other = wide\n ? Math.round(value * intrinsicAspect)\n : Math.round(value / intrinsicAspect);\n const longest = Math.max(value, other);\n if (longest > MAX_EDGE_PX) {\n value = Math.max(MIN_EDGE_PX, Math.floor((value * MAX_EDGE_PX) / longest));\n }\n return { mode, value };\n}\n\n/**\n * Replace the broken-image placeholders PptxGenJS writes for inline SVG\n * pictures with real rasterizations of those SVGs. Never throws: a missing\n * native binding or an SVG resvg rejects degrades to a warning and leaves the\n * package as generated.\n *\n * @returns whether any part of the zip was rewritten.\n */\nexport async function repairSvgRasterFallbacks(\n zip: JSZip,\n warnings?: PipelineWarning[]\n): Promise<boolean> {\n const pending = new Map<string, WorkItem>();\n\n for (const [partPath, entry] of Object.entries(zip.files)) {\n if (entry.dir || !PART_PATTERNS.some((rule) => rule.test(partPath))) {\n continue;\n }\n const xml = await entry.async('string');\n if (!xml.includes('asvg:svgBlip')) continue;\n\n collectWorkItems(xml, await readRelationships(zip, partPath), pending);\n }\n\n if (pending.size === 0) return false;\n\n let Resvg: ResvgModule['Resvg'];\n try {\n ({ Resvg } = await loadResvg());\n } catch (error) {\n warn(\n warnings,\n W.IMAGE_SVG_RASTER_FAILED,\n `Could not load the SVG rasterizer, so inline SVG images keep PowerPoint's broken-image fallback: ${String(error)}`,\n { component: 'image' }\n );\n return false;\n }\n\n const rendered = new Map<string, Buffer>();\n let changed = false;\n\n for (const [pngPart, item] of pending) {\n try {\n // Repair only a preview that is really there: a dangling relationship\n // target would otherwise have this pass author a brand new media part.\n if (!zip.file(pngPart)) {\n throw new Error(`missing preview part ${pngPart}`);\n }\n const source = zip.file(item.svgPart);\n if (!source) throw new Error(`missing part ${item.svgPart}`);\n const svg = await source.async('string');\n\n const probe = new Resvg(svg);\n const fitTo = resolveFitTo(probe.width / probe.height, item.cx, item.cy);\n const key = `${fitTo.mode}:${fitTo.value}\\n${svg}`;\n\n let png = rendered.get(key);\n if (!png) {\n png = Buffer.from(new Resvg(svg, { fitTo }).render().asPng());\n rendered.set(key, png);\n }\n\n // Timestamps are normalized afterwards by canonicalizePackage.\n zip.file(pngPart, png);\n changed = true;\n } catch (error) {\n warn(\n warnings,\n W.IMAGE_SVG_RASTER_FAILED,\n `Could not rasterize ${item.svgPart}, so it keeps PowerPoint's broken-image fallback: ${String(error)}`,\n { component: 'image' }\n );\n }\n }\n\n return changed;\n}\n","/**\n * Packaging for PptxGenJS output.\n *\n * Everything here exists because of what PptxGenJS emits, and would be wrong\n * to apply to another backend's bytes:\n *\n * - **Gradient and pattern fills.** The library has no API for either, so the\n * emitter registers the fill XML against a sentinel shape name and this pass\n * splices it in, restoring a normal name on the way out.\n * - **The table style GUID.** PptxGenJS hard-codes Medium Style 2 Accent 1 on\n * every table, which paints banding and accent borders the author never\n * asked for. Swapping it for No Style No Grid leaves the explicit borders\n * the emitter already wrote.\n * - **SVG previews.** The library builds them with a browser canvas, so under\n * Node it writes a broken-image placeholder — see `svgRasterFallback.ts`.\n *\n * Deterministic timestamps, canonical chart ids and the zip encoding are not\n * repairs; they are properties of an OOXML package. Those live in\n * `core/finalizePackage.ts` and run on the same open zip, so the package is\n * still read once and written once — which is what the byte-stable corpus was\n * recorded against.\n */\n\nimport {\n finalizePackage,\n readPackage,\n resolveGeneratedAt,\n writePackage,\n} from '../../core/finalizePackage';\nimport { repairSvgRasterFallbacks } from './svgRasterFallback';\nimport type { PendingXmlFill, PipelineWarning } from '../../types';\n\n/** PptxGenJS hard-codes this on every table it writes. */\nconst MEDIUM_STYLE_2_ACCENT_1 = '{5C22544A-7EE6-4342-B048-85BDC9FD1C3A}';\nconst NO_STYLE_NO_GRID = '{2D5ABB26-0587-4C30-8999-92F81FD0307C}';\n\nconst SLIDE_PART = /^ppt\\/slides\\/slide\\d+\\.xml$/;\n\nexport interface PptxGenJsPackagingOptions {\n /**\n * Gradient/pattern fills registered during rendering. Each entry names a\n * shape (via its sentinel `cNvPr name`) whose `<a:solidFill>` is swapped for\n * the registered fill XML.\n */\n pendingFills?: readonly PendingXmlFill[];\n /** Normalize metadata and ZIP timestamps. Defaults to true. */\n deterministic?: boolean;\n /** Clock used when deterministic packaging is enabled. */\n generatedAt?: Date | string;\n /**\n * Sink for repairs that need to report, e.g. an SVG that cannot rasterize.\n * When omitted their failures go to `console.warn`.\n */\n warnings?: PipelineWarning[];\n}\n\n/**\n * Splice registered gradient/pattern fills into a slide XML string. For every\n * pending fill whose sentinel objectName appears in this slide, the first\n * `<a:solidFill>` inside that shape's `<p:sp>` (its shape fill — line and run\n * fills come later in the element) is replaced with the registered fill XML,\n * and the sentinel marker name is swapped for a normal shape name.\n */\nfunction applyPendingFills(\n xml: string,\n pendingFills: readonly PendingXmlFill[]\n): string {\n let out = xml;\n for (const [index, fill] of pendingFills.entries()) {\n const marker = `name=\"${fill.objectName}\"`;\n const markerIdx = out.indexOf(marker);\n if (markerIdx === -1) continue;\n\n const spEnd = out.indexOf('</p:sp>', markerIdx);\n const solidStart = out.indexOf('<a:solidFill>', markerIdx);\n const solidEndTag = '</a:solidFill>';\n const solidEnd = out.indexOf(solidEndTag, solidStart);\n if (\n solidStart !== -1 &&\n solidEnd !== -1 &&\n spEnd !== -1 &&\n solidStart < spEnd\n ) {\n out =\n out.slice(0, solidStart) +\n fill.xml +\n out.slice(solidEnd + solidEndTag.length);\n }\n\n // Restore a normal name attribute so the sentinel never ships.\n out =\n out.slice(0, markerIdx) +\n `name=\"Fill ${index + 1}\"` +\n out.slice(markerIdx + marker.length);\n }\n return out;\n}\n\n/**\n * Apply the backend repairs, then hand the same zip to generic finalization.\n *\n * Returns the input buffer untouched when nothing needed doing, which only\n * happens with `deterministic: false` — PptxGenJS stamps both `core.xml` and\n * its ZIP entries with the wall clock, so a deterministic build always\n * rewrites something.\n */\nexport async function packagePptxGenJsBuffer(\n buffer: Buffer,\n options: PptxGenJsPackagingOptions = {}\n): Promise<Buffer> {\n const zip = await readPackage(buffer);\n let changed = false;\n\n for (const [path, entry] of Object.entries(zip.files)) {\n if (!SLIDE_PART.test(path)) continue;\n let xml = await entry.async('string');\n let fileChanged = false;\n if (xml.includes(MEDIUM_STYLE_2_ACCENT_1)) {\n xml = xml.replaceAll(MEDIUM_STYLE_2_ACCENT_1, NO_STYLE_NO_GRID);\n fileChanged = true;\n }\n if (options.pendingFills?.length) {\n const withFills = applyPendingFills(xml, options.pendingFills);\n if (withFills !== xml) {\n xml = withFills;\n fileChanged = true;\n }\n }\n if (fileChanged) {\n zip.file(path, xml);\n changed = true;\n }\n }\n\n changed = (await repairSvgRasterFallbacks(zip, options.warnings)) || changed;\n\n if (options.deterministic !== false) {\n await finalizePackage(zip, resolveGeneratedAt(options.generatedAt));\n changed = true;\n }\n\n if (!changed) return buffer;\n\n return writePackage(zip);\n}\n","/**\n * The PptxGenJS renderer.\n *\n * This is the only place in `core-pptx` production code allowed to import\n * `pptxgenjs`. It consumes PptxIR and nothing else — no author JSON, no\n * `ProcessedPresentation`, no theme lookups.\n */\n\nimport PptxGenJS from 'pptxgenjs';\nimport { ALL_PPTX_FEATURES, type PptxFeature } from '../../ir/features';\nimport type {\n PptxIR,\n PptxIrBackground,\n PptxIrMaster,\n PptxIrResource,\n PptxIrSlide,\n} from '../../ir/types';\nimport { emuToInches } from '../../ir/units';\nimport type { PipelineWarning } from '../../types';\nimport type { PptxRenderOptions, PptxRenderer, PptxRendererId } from '../types';\nimport { emitElement, imageSourceOpts, type EmitContext } from './emit';\nimport type { PendingFillSink } from './fills';\nimport { packagePptxGenJsBuffer } from './packaging';\n\nexport const PPTXGENJS_RENDERER_ID: PptxRendererId = 'pptxgenjs';\n\n/**\n * Everything the PptxGenJS backend can express.\n *\n * The exclusions are real gaps, not omissions:\n * - `image-fills` — no shape image-fill API\n * - `transitions` — no transition API (and none in the pre-IR pipeline either)\n * - `groups` — no grouping API; groups are flattened upstream or rejected\n * - `complex-bullet-glyphs` — the API accepts only a four-digit BMP code\n */\n/**\n * Everything except four verified gaps.\n *\n * Every `chart-*` styling capability is declared: `emitChart` forwards all of\n * them to pptxgenjs — the data labels, the data border, the axis bounds,\n * visibility, grid lines and rotation, the bar, line, pie and radar options and\n * every label font — so declaring them costs no existing deck a render.\n */\nconst PPTXGENJS_CAPABILITIES: ReadonlySet<PptxFeature> = new Set(\n [...ALL_PPTX_FEATURES].filter(\n (feature) =>\n feature !== 'image-fills' &&\n feature !== 'transitions' &&\n feature !== 'groups' &&\n feature !== 'complex-bullet-glyphs'\n )\n);\n\nexport function createPptxGenJsRenderer(): PptxRenderer {\n return {\n id: PPTXGENJS_RENDERER_ID,\n format: 'pptx',\n capabilities: PPTXGENJS_CAPABILITIES,\n async render(ir: PptxIR, options?: PptxRenderOptions): Promise<Uint8Array> {\n const pendingFills: PendingFillSink = [];\n const pptx = buildPresentation(ir, pendingFills, options?.warnings);\n const raw = (await pptx.write({\n outputType: 'nodebuffer',\n })) as Buffer;\n const packaged = await packagePptxGenJsBuffer(raw, {\n pendingFills,\n deterministic: options?.deterministic,\n generatedAt: options?.generatedAt,\n warnings: options?.warnings,\n });\n return new Uint8Array(packaged);\n },\n };\n}\n\n/**\n * Build the PptxGenJS object graph for an IR document.\n *\n * Exported for tests: it is the interesting half of the adapter, and asserting\n * on the object graph is far cheaper than unzipping a package.\n */\nexport function buildPresentation(\n ir: PptxIR,\n pendingFills?: PendingFillSink,\n warnings?: PipelineWarning[]\n): PptxGenJS {\n const pptx = new PptxGenJS();\n\n if (ir.metadata.title) pptx.title = ir.metadata.title;\n if (ir.metadata.author) pptx.author = ir.metadata.author;\n if (ir.metadata.subject) pptx.subject = ir.metadata.subject;\n if (ir.metadata.company) pptx.company = ir.metadata.company;\n\n pptx.defineLayout({\n name: 'CUSTOM',\n width: emuToInches(ir.size.widthEmu),\n height: emuToInches(ir.size.heightEmu),\n });\n pptx.layout = 'CUSTOM';\n\n if (ir.rtl) pptx.rtlMode = true;\n\n pptx.theme = {\n headFontFace: ir.theme.headingFont,\n bodyFontFace: ir.theme.bodyFont,\n };\n\n const resources = new Map<string, PptxIrResource>(\n ir.resources.map((resource) => [resource.id, resource])\n );\n const ctx: EmitContext = { pptx, resources, pendingFills, warnings };\n\n for (const master of ir.masters) {\n pptx.defineSlideMaster(masterProps(master, resources) as never);\n }\n\n for (const slide of ir.slides) {\n emitSlide(pptx, slide, ctx);\n }\n\n return pptx;\n}\n\n/**\n * Master properties PptxGenJS understands.\n *\n * A master's fixed decoration is *not* passed as `objects`: the pipeline draws\n * template objects onto each slide instead, which is what the IR records, and\n * doing both would double them.\n */\nfunction masterProps(\n master: PptxIrMaster,\n resources: ReadonlyMap<string, PptxIrResource>\n): Record<string, unknown> {\n const props: Record<string, unknown> = { title: master.name };\n\n const background = backgroundProps(master.background, resources);\n if (background) props.background = background;\n if (master.margin !== undefined) props.margin = master.margin;\n\n if (master.slideNumber) {\n const slideNumber: Record<string, unknown> = {\n x: emuToInches(master.slideNumber.transform.xEmu),\n y: emuToInches(master.slideNumber.transform.yEmu),\n w: emuToInches(master.slideNumber.transform.widthEmu),\n h: emuToInches(master.slideNumber.transform.heightEmu),\n };\n if (master.slideNumber.color) {\n slideNumber.color = master.slideNumber.color.hex;\n }\n if (master.slideNumber.fontSize !== undefined) {\n slideNumber.fontSize = master.slideNumber.fontSize;\n }\n props.slideNumber = slideNumber;\n }\n\n return props;\n}\n\nfunction backgroundProps(\n background: PptxIrBackground | undefined,\n resources: ReadonlyMap<string, PptxIrResource>\n): Record<string, unknown> | undefined {\n if (!background) return undefined;\n if (background.kind === 'solid') return { color: background.color.hex };\n\n const resource = resources.get(background.resourceId);\n if (!resource) return undefined;\n return imageSourceOpts(resource);\n}\n\nfunction emitSlide(\n pptx: PptxGenJS,\n slideIr: PptxIrSlide,\n ctx: EmitContext\n): void {\n const slide = slideIr.masterName\n ? pptx.addSlide({ masterName: slideIr.masterName })\n : pptx.addSlide();\n\n const background = backgroundProps(slideIr.background, ctx.resources);\n if (background) slide.background = background as never;\n\n if (slideIr.hidden) slide.hidden = true;\n\n for (const element of slideIr.elements) {\n emitElement(slide, element, ctx);\n }\n\n if (slideIr.notes) slide.addNotes(slideIr.notes);\n}\n","/**\n * Packaging a native chart's missing half, for PPTX.\n *\n * The repairs themselves are format-neutral and live in `chart-parts` in\n * `@json-to-office/shared/rendering`; a `c:chartSpace` is DrawingML and the\n * docx sibling of this file makes the same edits. What differs is how much is\n * missing. `@office-open/pptx` hands its whole options object to\n * `chartSpaceDesc`, so the chart title and the legend position survive the trip\n * — verified against the package — where the docx sibling loses both. Every\n * other repair is needed on this side too: the cell references, the series\n * colours, the axis titles, the bar grouping and `c:externalData`. The shared\n * splice guards each on what the XML actually lacks, so the same function does\n * both jobs without writing anything twice.\n *\n * What is genuinely pptx's own is the packaging. The backend writes\n * `ppt/charts/chartN.xml` and nothing else: no rels part, no workbook, no\n * content-type override for one. Two conventions have to be matched exactly:\n *\n * - The workbook is `ppt/embeddings/Microsoft_Excel_Worksheet{N}.xlsx`, which\n * is what pptxgenjs writes, so a deck's two backends produce packages of the\n * same shape.\n * - `canonicalizeChartIds` in `finalizePackage` renumbers chart parts to 1..n\n * and rewrites `Microsoft_Excel_Worksheet{N}.xlsx` references through the\n * *same* index map. So the workbook's number must match the chart part it\n * belongs to, and this pass must run before finalization — otherwise the\n * rename walks a reference that is not there yet.\n */\n\nimport JSZip from 'jszip';\nimport {\n CHART_WORKBOOK_CONTENT_TYPE,\n chartWorkbookParts,\n chartWorkbookRelsXml,\n matchChartParts,\n spliceChartXml,\n type ChartAxisEdits,\n type ChartPartInput,\n type ChartTextStyle,\n} from '@json-to-office/shared/rendering';\nimport type {\n PptxIrChartAxis,\n PptxIrChartElement,\n PptxIrChartLabelFont,\n PptxIrChartValueAxis,\n} from '../../ir/types';\n\n/** The workbook name pptxgenjs uses, and therefore the one this must use too. */\nconst workbookName = (ordinal: number): string =>\n `Microsoft_Excel_Worksheet${ordinal}.xlsx`;\n\n/**\n * One chart element, in the shared splice's vocabulary.\n *\n * The pptx IR carries a far richer options bag than the splice needs — four\n * label fonts, per-family tuning, axis bounds — and all of it reaches the\n * backend through the emitter. Only the handful the backend drops is projected\n * here.\n *\n * A series missing `labels` or `values` cannot occur: the compiler warns\n * `CHART_INVALID_SERIES` and drops the whole chart before it reaches the IR.\n * The empty fallbacks keep this total rather than relying on that from a\n * distance.\n */\nfunction spliceInput(element: PptxIrChartElement): ChartPartInput {\n return {\n chartType: element.chartType,\n series: element.series.map((series) => ({\n ...(series.name !== undefined ? { name: series.name } : {}),\n labels: series.labels ?? [],\n values: series.values ?? [],\n })),\n colors: element.options.colors,\n ...(element.options.barGrouping\n ? { barGrouping: element.options.barGrouping }\n : {}),\n // Spliced rather than emitted: see `chartChild`, which cannot pass `axes`\n // without also inventing the axis ids the plot area references.\n categoryAxis: axisEdits(element.options.categoryAxis),\n valueAxis: axisEdits(element.options.valueAxis),\n // Three the backend has nowhere to put: `ChartSeriesCommon` has no line\n // width, no data-element outline, and `c:radarStyle` is written from a\n // literal rather than an option.\n ...(element.options.lineSize !== undefined\n ? { lineWidthPoints: element.options.lineSize }\n : {}),\n ...(element.options.dataBorder\n ? {\n dataBorder: {\n widthPoints: element.options.dataBorder.widthPoints,\n color: element.options.dataBorder.color.hex,\n },\n }\n : {}),\n ...(element.options.radarStyle\n ? { radarStyle: element.options.radarStyle }\n : {}),\n // Fonts: `c:txPr` and `a:defRPr` on four different elements, none of which\n // the backend exposes an option for.\n ...(textStyle(element.options.titleFont)\n ? { titleFont: textStyle(element.options.titleFont) }\n : {}),\n ...(textStyle(element.options.legendFont)\n ? { legendFont: textStyle(element.options.legendFont) }\n : {}),\n ...(textStyle(element.options.dataLabelFont)\n ? { dataLabelFont: textStyle(element.options.dataLabelFont) }\n : {}),\n };\n}\n\n/** One resolved label font, or nothing if it carries no styling. */\nfunction textStyle(\n font: PptxIrChartLabelFont | undefined\n): ChartTextStyle | undefined {\n if (!font) return undefined;\n const style: ChartTextStyle = {\n ...(font.fontFamily !== undefined ? { fontFamily: font.fontFamily } : {}),\n ...(font.fontSize !== undefined ? { fontSize: font.fontSize } : {}),\n ...(font.bold !== undefined ? { bold: font.bold } : {}),\n ...(font.color ? { color: font.color.hex } : {}),\n };\n return Object.keys(style).length > 0 ? style : undefined;\n}\n\n/** One authored axis, in the shared splice's vocabulary. */\nfunction axisEdits(\n axis: PptxIrChartAxis | PptxIrChartValueAxis\n): ChartAxisEdits {\n const value = axis as PptxIrChartValueAxis;\n return {\n ...(axis.title !== undefined ? { title: axis.title } : {}),\n ...(axis.hidden !== undefined ? { hidden: axis.hidden } : {}),\n ...(axis.showLine !== undefined ? { lineVisible: axis.showLine } : {}),\n ...(axis.labelRotate !== undefined\n ? { labelRotation: axis.labelRotate }\n : {}),\n ...(textStyle(axis.labelFont)\n ? { labelFont: textStyle(axis.labelFont) }\n : {}),\n ...(axis.gridLine\n ? {\n gridLine: {\n ...(textStyle(axis.labelFont)\n ? { labelFont: textStyle(axis.labelFont) }\n : {}),\n ...(axis.gridLine.style !== undefined\n ? { style: axis.gridLine.style }\n : {}),\n ...(textStyle(axis.labelFont)\n ? { labelFont: textStyle(axis.labelFont) }\n : {}),\n ...(axis.gridLine.size !== undefined\n ? { size: axis.gridLine.size }\n : {}),\n ...(textStyle(axis.labelFont)\n ? { labelFont: textStyle(axis.labelFont) }\n : {}),\n ...(axis.gridLine.color ? { color: axis.gridLine.color.hex } : {}),\n },\n }\n : {}),\n ...(value.minValue !== undefined ? { min: value.minValue } : {}),\n ...(value.maxValue !== undefined ? { max: value.maxValue } : {}),\n ...(value.majorUnit !== undefined ? { majorUnit: value.majorUnit } : {}),\n ...(value.labelFormatCode !== undefined\n ? { numberFormat: value.labelFormatCode }\n : {}),\n };\n}\n\n/**\n * Register the xlsx content type once, if the package does not have it.\n *\n * Fails loudly rather than open. `String.replace` returns its input unchanged\n * when the needle is absent, so a backend that reformatted or reordered that\n * `Default` element would turn this into a silent no-op — and the package would\n * then hold `.xlsx` parts no `Default` and no `Override` covers, which is an\n * OPC violation a reader offers to repair. Nothing else in this pass would\n * notice: the chart XML still looks right.\n */\nfunction declareWorkbookContentType(zip: JSZip, xml: string): void {\n if (xml.includes(`Extension=\"xlsx\"`)) return;\n const patched = xml.replace(\n '<Default Extension=\"xml\"',\n `<Default Extension=\"xlsx\" ContentType=\"${CHART_WORKBOOK_CONTENT_TYPE}\"/><Default Extension=\"xml\"`\n );\n if (patched === xml) {\n throw new Error(\n 'Could not declare the embedded workbook content type: ' +\n '[Content_Types].xml has no `<Default Extension=\"xml\"` to anchor on. ' +\n 'The package would ship an .xlsx part no content type covers.'\n );\n }\n zip.file('[Content_Types].xml', patched, { createFolders: false });\n}\n\n/**\n * Build one chart's workbook as a nested zip.\n *\n * `finalizePackage` walks embedded `.xlsx` entries and normalizes their\n * timestamps recursively, so no clock is pinned here — unlike the docx side,\n * whose package pass does not recurse.\n */\nasync function workbookBytes(chart: ChartPartInput): Promise<Uint8Array> {\n const book = new JSZip();\n for (const [path, content] of chartWorkbookParts(chart.series)) {\n // `createFolders` defaults to true and would add 0-length directory\n // entries no other Office package carries.\n book.file(path, content, { createFolders: false });\n }\n return book.generateAsync({\n type: 'uint8array',\n compression: 'DEFLATE',\n compressionOptions: { level: 6 },\n });\n}\n\n/**\n * Give every chart in the package the cell references, colours and workbook the\n * backend leaves out.\n *\n * Parts are matched to IR elements by content rather than by position: the\n * emitter fills its array while *building* the backend's options object and the\n * backend numbers its parts while *stringifying* that object, and the two walks\n * need not agree. Pairing by position is what handed docx charts another\n * chart's workbook.\n */\nexport async function spliceChartParts(\n zip: JSZip,\n charts: readonly PptxIrChartElement[]\n): Promise<void> {\n if (charts.length === 0) return;\n\n const inputs = charts.map(spliceInput);\n const parts: Array<readonly [number, string]> = [];\n for (const path of Object.keys(zip.files)) {\n const match = path.match(/^ppt\\/charts\\/chart(\\d+)\\.xml$/);\n if (!match) continue;\n parts.push([Number(match[1]), await zip.file(path)!.async('string')]);\n }\n parts.sort(([a], [b]) => a - b);\n\n for (const { ordinal, xml, chart } of matchChartParts(parts, inputs)) {\n const workbook = workbookName(ordinal);\n\n zip.file(`ppt/charts/chart${ordinal}.xml`, spliceChartXml(xml, chart), {\n createFolders: false,\n });\n zip.file(`ppt/embeddings/${workbook}`, await workbookBytes(chart), {\n binary: true,\n createFolders: false,\n });\n zip.file(\n `ppt/charts/_rels/chart${ordinal}.xml.rels`,\n chartWorkbookRelsXml(workbook),\n { createFolders: false }\n );\n }\n\n const contentTypes = zip.file('[Content_Types].xml');\n if (contentTypes) {\n declareWorkbookContentType(zip, await contentTypes.async('string'));\n }\n}\n","/**\n * PptxIR → `@office-open/pptx` options.\n *\n * The mapping is unusually direct because the two models agree on units: EMU\n * for geometry, points for font sizes, degrees for angles, percent for gradient\n * stops. Bare numbers reach the backend in exactly those units — the\n * `UniversalMeasure` string form is never used here, because a value that has\n * already been resolved has no business being re-parsed.\n *\n * Backend gaps are handled by *not declaring the capability* in `index.ts`, so\n * anything this module cannot express has already been rejected before it is\n * called. Reaching a `throw` here is a bug, not a user error.\n */\n\nimport { assertNever } from '@json-to-office/shared/rendering';\nimport type {\n PptxIrBackground,\n PptxIrColor,\n PptxIrElement,\n PptxIrFill,\n PptxIrGeometry,\n PptxIrGroupElement,\n PptxIrHyperlink,\n PptxIrImageElement,\n PptxIrLine,\n PptxIrResource,\n PptxIrShadow,\n PptxIrShapeElement,\n PptxIrTableBorder,\n PptxIrTableElement,\n PptxIrChartElement,\n PptxIrChartOptions,\n PptxIrTextBodyStyle,\n PptxIrTextBoxElement,\n PptxIrTextRun,\n PptxIrTransform,\n} from '../../ir/types';\n\ntype Opts = Record<string, unknown>;\n\nexport type ResourceLookup = ReadonlyMap<string, PptxIrResource>;\n\nexport interface OfficeOpenEmitContext {\n resources: ResourceLookup;\n /** Bytes for file and remote resources, fetched before rendering. */\n resourceBytes: ReadonlyMap<string, Uint8Array>;\n /**\n * Allocates the drawing id for the next element on the current slide.\n *\n * The backend numbers elements from a counter that lives for the life of the\n * process, so a second render of the same deck produces different ids and\n * different bytes. Numbering them here, per slide, makes a render depend only\n * on its input.\n */\n nextId: () => number;\n /**\n * Charts, in the order they were emitted.\n *\n * The post-generation splice reads this to give each chart part the cell\n * references and series colours the backend leaves out. Matched to parts by\n * content rather than by this order — see `chart-parts` in\n * `@json-to-office/shared/rendering`.\n */\n charts?: PptxIrChartElement[];\n}\n\n/* ------------------------------------------------------------------ *\n * Primitives\n * ------------------------------------------------------------------ */\n\n/** Geometry: a bare `prst` name, which is what the backend interpolates. */\nfunction geometryName(geometry: PptxIrGeometry): string {\n return typeof geometry === 'string' ? geometry : geometry.custom;\n}\n\nfunction frame(transform: PptxIrTransform): Opts {\n return {\n x: transform.xEmu,\n y: transform.yEmu,\n width: transform.widthEmu,\n height: transform.heightEmu,\n };\n}\n\n/**\n * A colour.\n *\n * `FillOptions` accepts a bare hex string for the common opaque case; anything\n * with transparency needs the object form with an `alpha` transform.\n */\nfunction color(value: PptxIrColor): unknown {\n if (value.transparency === undefined) return value.hex;\n return {\n type: 'srgb',\n value: value.hex,\n transforms: { alpha: 100 - value.transparency },\n };\n}\n\n/**\n * OOXML `prst` pattern names → the backend's friendly names.\n *\n * `PresetPattern` spells `pct25` as `percent25`; the IR carries the OOXML name,\n * so the mapping happens here rather than in the IR.\n */\nconst PATTERN_NAMES: Readonly<Record<string, string>> = {\n pct5: 'percent5',\n pct10: 'percent10',\n pct20: 'percent20',\n pct25: 'percent25',\n pct30: 'percent30',\n pct40: 'percent40',\n pct50: 'percent50',\n pct60: 'percent60',\n pct70: 'percent70',\n pct75: 'percent75',\n pct80: 'percent80',\n pct90: 'percent90',\n horz: 'horizontal',\n vert: 'vertical',\n ltHorz: 'lightHorizontal',\n ltVert: 'lightVertical',\n dkHorz: 'darkHorizontal',\n dkVert: 'darkVertical',\n narHorz: 'narrowHorizontal',\n narVert: 'narrowVertical',\n cross: 'cross',\n diagCross: 'diagonalCross',\n upDiag: 'upwardDiagonal',\n dnDiag: 'downwardDiagonal',\n ltUpDiag: 'lightUpwardDiagonal',\n ltDnDiag: 'lightDownwardDiagonal',\n dkUpDiag: 'darkUpwardDiagonal',\n dkDnDiag: 'darkDownwardDiagonal',\n wdUpDiag: 'wideUpwardDiagonal',\n wdDnDiag: 'wideDownwardDiagonal',\n smGrid: 'smallGrid',\n lgGrid: 'largeGrid',\n dotGrid: 'dottedGrid',\n smCheck: 'smallCheckerBoard',\n lgCheck: 'largeCheckerBoard',\n trellis: 'trellis',\n divot: 'divot',\n shingle: 'shingle',\n weave: 'weave',\n plaid: 'plaid',\n sphere: 'sphere',\n zigZag: 'zigZag',\n wave: 'wave',\n};\n\nexport function fill(value: PptxIrFill, ctx: OfficeOpenEmitContext): unknown {\n switch (value.kind) {\n case 'none':\n return { type: 'none' };\n case 'solid':\n return { type: 'solid', color: color(value.color) };\n case 'gradient': {\n const stops = value.gradient.stops.map((stop) => ({\n position: stop.position,\n color: color(stop.color),\n }));\n return value.gradient.type === 'radial'\n ? { type: 'gradient', path: 'circle', stops }\n : { type: 'gradient', angle: value.gradient.angleDegrees, stops };\n }\n case 'pattern':\n return {\n type: 'pattern',\n pattern: PATTERN_NAMES[value.preset] ?? value.preset,\n foregroundColor: color(value.foreground),\n backgroundColor: color(value.background),\n };\n case 'image': {\n const bytes = ctx.resourceBytes.get(value.resourceId);\n const resource = ctx.resources.get(value.resourceId);\n if (!bytes || !resource) {\n throw new Error(\n `image fill references unresolved resource \"${value.resourceId}\"`\n );\n }\n return { type: 'blip', data: bytes, imageType: pictureType(resource) };\n }\n default:\n return assertNever(value, 'PptxIrFill');\n }\n}\n\nfunction outline(line: PptxIrLine): Opts {\n const opts: Opts = {};\n if (line.color) opts.fill = { type: 'solid', color: color(line.color) };\n // Outline width is EMU; the IR keeps stroke width in points.\n if (line.widthPoints !== undefined) {\n opts.width = Math.round(line.widthPoints * 12700);\n }\n if (line.dash) opts.dash = line.dash;\n return opts;\n}\n\nfunction effects(shadow: PptxIrShadow): Opts {\n return {\n outerShadow: {\n blurRadius: Math.round(shadow.blurPoints * 12700),\n distance: Math.round(shadow.offsetPoints * 12700),\n direction: shadow.angleDegrees,\n color: {\n type: 'srgb',\n value: shadow.color.hex,\n transforms: { alpha: Math.round(shadow.opacity * 100) },\n },\n },\n };\n}\n\nfunction hyperlink(link: PptxIrHyperlink): Opts {\n return link.kind === 'external'\n ? { url: link.url, ...(link.tooltip ? { tooltip: link.tooltip } : {}) }\n : {\n slide: link.slideIndex,\n ...(link.tooltip ? { tooltip: link.tooltip } : {}),\n };\n}\n\n/* ------------------------------------------------------------------ *\n * Text\n * ------------------------------------------------------------------ */\n\nconst ALIGNMENT: Readonly<Record<string, string>> = {\n left: 'left',\n center: 'center',\n right: 'right',\n justify: 'justify',\n};\n\nconst ANCHOR: Readonly<Record<string, string>> = {\n top: 't',\n middle: 'ctr',\n bottom: 'b',\n};\n\nfunction runProperties(run: PptxIrTextRun): Opts {\n const opts: Opts = {\n size: run.fontSize,\n font: run.fontFamily,\n fill: { type: 'solid', color: color(run.color) },\n };\n if (run.bold !== undefined) opts.bold = run.bold;\n if (run.italic !== undefined) opts.italic = run.italic;\n if (run.strike) opts.strike = 'single';\n if (run.underline) opts.underline = 'single';\n if (run.superscript) opts.baseline = 30;\n if (run.subscript) opts.baseline = -25;\n if (run.characterSpacing !== undefined) opts.spacing = run.characterSpacing;\n if (run.language) opts.lang = run.language;\n if (run.hyperlink) opts.hyperlink = hyperlink(run.hyperlink);\n return opts;\n}\n\n/**\n * Build a text body.\n *\n * `breakAfter` on a run starts a new paragraph, which is how the IR expresses a\n * hard break inside a body.\n */\nexport function textBody(\n runs: readonly PptxIrTextRun[],\n style: PptxIrTextBodyStyle | undefined\n): Opts {\n const paragraphs: Opts[] = [];\n let current: Opts[] = [];\n\n const flush = () => {\n paragraphs.push({\n ...(style ? { properties: paragraphProperties(style) } : {}),\n children: current,\n });\n current = [];\n };\n\n for (const run of runs) {\n current.push({ text: run.text, ...runProperties(run) });\n if (run.breakAfter) flush();\n }\n if (current.length > 0 || paragraphs.length === 0) flush();\n\n const body: Opts = { paragraphs };\n if (style) {\n body.anchor = ANCHOR[style.verticalAlign] ?? 't';\n if (style.autoFit) body.autoFit = 'shape';\n if (style.insetPoints !== undefined) {\n body.margins = insetMargins(style.insetPoints);\n }\n }\n return body;\n}\n\n/**\n * A body or cell inset, in the backend's per-side form.\n *\n * The four-value tuple is CSS-ordered — `[top, right, bottom, left]` — which is\n * what the authoring schema states and what the default backend reads. Naming\n * the sides here rather than positionally is what keeps the two adapters\n * agreeing on which edge a value belongs to.\n */\nfunction insetMargins(inset: number | [number, number, number, number]): Opts {\n const toEmu = (points: number) => Math.round(points * 12700);\n if (typeof inset === 'number') {\n const value = toEmu(inset);\n return { left: value, top: value, right: value, bottom: value };\n }\n const [top, right, bottom, left] = inset;\n return {\n left: toEmu(left),\n top: toEmu(top),\n right: toEmu(right),\n bottom: toEmu(bottom),\n };\n}\n\nfunction paragraphProperties(style: PptxIrTextBodyStyle): Opts {\n const opts: Opts = {};\n if (style.align) opts.alignment = ALIGNMENT[style.align] ?? style.align;\n if (style.lineSpacingMultiple !== undefined) {\n opts.lineSpacingPercent = style.lineSpacingMultiple * 100;\n } else if (style.lineSpacingPoints !== undefined) {\n opts.lineSpacingPoints = style.lineSpacingPoints;\n }\n if (style.spaceBeforePoints !== undefined) {\n opts.spaceBefore = style.spaceBeforePoints;\n }\n if (style.spaceAfterPoints !== undefined) {\n opts.spaceAfter = style.spaceAfterPoints;\n }\n if (style.bullet) opts.bullet = bulletOption(style.bullet);\n return opts;\n}\n\n/**\n * A bullet in the backend's vocabulary.\n *\n * The discriminants are the backend's own — `char`, `autoNum`, `none` — and it\n * writes nothing at all for a value it does not recognise, so a near-miss here\n * is a silent loss rather than a type error.\n */\nfunction bulletOption(\n bullet: NonNullable<PptxIrTextBodyStyle['bullet']>\n): Opts {\n if (bullet.type === 'none') return { type: 'none' };\n if (bullet.type === 'number') {\n return {\n type: 'autoNum',\n ...(bullet.style ? { format: bullet.style } : {}),\n ...(bullet.startAt !== undefined ? { startAt: bullet.startAt } : {}),\n };\n }\n return { type: 'char', char: bullet.style ?? '•' };\n}\n\n/* ------------------------------------------------------------------ *\n * Elements\n * ------------------------------------------------------------------ */\n\nfunction textBoxChild(\n element: PptxIrTextBoxElement,\n ctx: OfficeOpenEmitContext\n): Opts {\n // A shape cannot carry a link here, so a body-level link is pushed onto the\n // runs it covers — which is what the link means anyway.\n const runs = element.hyperlink\n ? element.runs.map((run) => ({ ...run, hyperlink: element.hyperlink }))\n : element.runs;\n\n const shape: Opts = {\n id: ctx.nextId(),\n ...frame(element.transform),\n geometry: 'rect',\n textBody: textBody(runs, element.style),\n };\n if (element.fill) shape.fill = fill(element.fill, ctx);\n else shape.fill = { type: 'none' };\n if (element.line) shape.outline = outline(element.line);\n if (element.shadow) shape.effects = effects(element.shadow);\n if (element.transform.rotationDegrees !== undefined) {\n shape.rotation = element.transform.rotationDegrees;\n }\n if (element.altText) shape.description = element.altText;\n return { shape };\n}\n\nfunction shapeChild(\n element: PptxIrShapeElement,\n ctx: OfficeOpenEmitContext\n): Opts {\n const shape: Opts = {\n id: ctx.nextId(),\n ...frame(element.transform),\n geometry: geometryName(element.geometry),\n };\n if (element.fill) shape.fill = fill(element.fill, ctx);\n if (element.line) shape.outline = outline(element.line);\n if (element.shadow) shape.effects = effects(element.shadow);\n if (element.transform.rotationDegrees !== undefined) {\n shape.rotation = element.transform.rotationDegrees;\n }\n if (element.transform.flipHorizontal) shape.flipHorizontal = true;\n if (element.runs && element.runs.length > 0) {\n shape.textBody = textBody(element.runs, element.style);\n }\n if (element.altText) shape.description = element.altText;\n return { shape };\n}\n\n/** Media type → the backend's picture `type` discriminator. */\nfunction pictureType(resource: PptxIrResource): string {\n switch (resource.mediaType) {\n case 'image/jpeg':\n return 'jpg';\n case 'image/gif':\n return 'gif';\n case 'image/bmp':\n return 'bmp';\n case 'image/png':\n return 'png';\n default:\n // Guessing would label an SVG — or anything else — as a PNG and ship a\n // broken image. Capability checking rejects the types this backend\n // cannot take, so an unknown one here means the media type could not be\n // determined at all.\n throw new Error(\n `cannot determine the picture type for resource \"${resource.id}\"` +\n (resource.mediaType ? ` (media type ${resource.mediaType})` : '')\n );\n }\n}\n\nfunction pictureChild(\n element: PptxIrImageElement,\n ctx: OfficeOpenEmitContext\n): Opts {\n const resource = ctx.resources.get(element.resourceId);\n const bytes = ctx.resourceBytes.get(element.resourceId);\n if (!resource || !bytes) {\n throw new Error(\n `image ${element.path} references unresolved resource \"${element.resourceId}\"`\n );\n }\n const picture: Opts = {\n id: ctx.nextId(),\n ...frame(element.transform),\n data: bytes,\n type: pictureType(resource),\n };\n if (element.shadow) picture.effects = effects(element.shadow);\n if (element.altText) picture.description = element.altText;\n return { picture };\n}\n\n/**\n * A table.\n *\n * Cells carry `children` (paragraphs), not a text body, and cell formatting is\n * flattened onto the single run each cell holds — the authoring surface gives a\n * cell one string, so one run is the whole of it.\n *\n * Table-level border, fill and inset are cell properties here. The backend's\n * own `TableOptions.borders` distributes only to the *edge* cells, which is a\n * frame rather than the grid the IR describes, and it has no table-level fill\n * at all — so both are pushed onto every cell that does not override them,\n * which is the same thing the default backend's table options mean.\n *\n * Merged cells, rounded corners and pagination are deliberately absent from\n * this adapter's capabilities: the backend expresses a merge as\n * `restart`/`continue` markers on the covered cells whereas the IR carries span\n * counts, OOXML has no table corner radius, and nothing here can flow a table\n * onto a second slide.\n */\nfunction tableChild(\n element: PptxIrTableElement,\n ctx: OfficeOpenEmitContext\n): Opts {\n const columnCount = Math.max(\n ...element.rows.map((row) => row.cells.length),\n 1\n );\n const columnWidths =\n element.columnWidthsEmu.length === columnCount\n ? [...element.columnWidthsEmu]\n : evenColumns(element, columnCount);\n\n const rows = element.rows.map((row, rowIndex) => {\n const out: Opts = {\n cells: row.cells.map((cell) => tableCell(cell, element)),\n };\n const height = element.rowHeightsEmu[rowIndex];\n if (height !== undefined) out.height = height;\n return out;\n });\n\n return {\n table: {\n id: ctx.nextId(),\n ...frame(element.transform),\n columnWidths,\n rows,\n },\n };\n}\n\nfunction tableCell(\n cell: PptxIrTableElement['rows'][number]['cells'][number],\n element: PptxIrTableElement\n): Opts {\n const formatting = cell.formatting;\n const defaults = element.defaults;\n\n const runProps: Opts = {\n size: formatting?.fontSize ?? defaults.fontSize,\n font: formatting?.fontFamily ?? defaults.fontFamily,\n };\n const cellColor = formatting?.color ?? defaults.color;\n if (cellColor) runProps.fill = { type: 'solid', color: color(cellColor) };\n const bold = formatting?.bold ?? defaults.bold;\n if (bold !== undefined) runProps.bold = bold;\n if (formatting?.italic !== undefined) runProps.italic = formatting.italic;\n\n const align = formatting?.align ?? defaults.align;\n const paragraph: Opts = {\n children: [{ text: cell.text, ...runProps }],\n };\n if (align) {\n paragraph.properties = { alignment: ALIGNMENT[align] ?? align };\n }\n\n const out: Opts = {\n children: [paragraph],\n verticalAlign: ANCHOR[formatting?.verticalAlign ?? defaults.verticalAlign],\n };\n\n // Cell first, table second — the table's value is the default a cell may\n // override, exactly as `tblPr` layers under `tcPr`.\n const fill = cell.fill ?? element.fill;\n if (fill) out.fill = { type: 'solid', color: color(fill) };\n\n // No cell inset. `TableCellOptions.margins` writes `lIns`/`tIns` onto the\n // cell's own `a:bodyPr`, and a reader takes a cell's padding from\n // `a:tcPr/@marL` — a LibreOffice render moves not one point for a 40pt\n // margin written that way. `table-insets` is therefore not declared, and a\n // table with one is refused before any of this runs.\n\n const borders = cellBorders(cell, element);\n if (borders) out.borders = borders;\n\n return out;\n}\n\n/** OOXML dash names for the IR's border vocabulary. `none` draws nothing. */\nconst BORDER_DASH: Record<string, string | undefined> = {\n solid: 'solid',\n dash: 'dash',\n dot: 'sysDot',\n};\n\n/**\n * A cell's four edges.\n *\n * Per-side borders win where the IR carries them; otherwise the table's uniform\n * border applies to every edge of every cell, which is what \"uniform\" means and\n * what the default backend draws.\n */\nfunction cellBorders(\n cell: PptxIrTableElement['rows'][number]['cells'][number],\n element: PptxIrTableElement\n): Opts | undefined {\n if (cell.borders) {\n const [top, right, bottom, left] = cell.borders;\n const out: Opts = {};\n if (top.type !== 'none') out.top = borderLine(top);\n if (right.type !== 'none') out.right = borderLine(right);\n if (bottom.type !== 'none') out.bottom = borderLine(bottom);\n if (left.type !== 'none') out.left = borderLine(left);\n return Object.keys(out).length > 0 ? out : undefined;\n }\n\n const border = element.border;\n if (!border || border.type === 'none') return undefined;\n const line = borderLine(border);\n return { top: line, right: line, bottom: line, left: line };\n}\n\nfunction borderLine(border: PptxIrTableBorder): Opts {\n const dashStyle = BORDER_DASH[border.type];\n return {\n // Points → EMU: a bare number is EMU to this backend, and a border stated\n // in points would otherwise be drawn 12,700 times too thin.\n ...(border.widthPoints !== undefined\n ? { width: Math.round(border.widthPoints * 12700) }\n : {}),\n ...(border.color ? { color: color(border.color) } : {}),\n ...(dashStyle ? { dashStyle } : {}),\n };\n}\n\n/** Even column widths when the IR did not carry a matching set. */\nfunction evenColumns(\n element: PptxIrTableElement,\n columnCount: number\n): number[] {\n const each = Math.floor(element.transform.widthEmu / columnCount);\n return Array.from({ length: columnCount }, () => each);\n}\n\nfunction groupChild(\n element: PptxIrGroupElement,\n ctx: OfficeOpenEmitContext\n): Opts {\n const group: Opts = {\n id: ctx.nextId(),\n ...frame(element.transform),\n childOffset: { x: element.transform.xEmu, y: element.transform.yEmu },\n childExtents: {\n width: element.transform.widthEmu,\n height: element.transform.heightEmu,\n },\n children: element.children.map((child) => slideChild(child, ctx)),\n };\n if (element.transform.rotationDegrees !== undefined) {\n group.rotation = element.transform.rotationDegrees;\n }\n return { group };\n}\n\n/**\n * A chart, in the vocabulary `@office-open/pptx` actually reads.\n *\n * Unlike its docx sibling this backend hands the whole options object to\n * `chartSpaceDesc`, so the title and the legend position survive. Passing them\n * here rather than splicing them is the cheaper half of the same job.\n *\n * `axes` is the exception, and is deliberately *not* passed. Supplying it\n * replaces the backend's default axis pair wholesale rather than adding to it,\n * and `AxisOptions` requires an `id` and a `crossAxisId` this adapter has no\n * way to allocate that the plot area would agree with. Passing a partial one\n * emitted literal `<undefined>` elements and six `val=\"undefined\"` attributes,\n * dropping `c:catAx`, `c:axPos`, `c:scaling` and `c:crosses` with them —\n * tolerated by LibreOffice, a repair prompt in PowerPoint. Axis titles are\n * spliced into the backend's own valid axes instead, which is the path the\n * docx side already takes.\n */\nfunction chartChild(\n element: PptxIrChartElement,\n ctx: OfficeOpenEmitContext\n): Opts {\n const { options, transform } = element;\n const series = element.series;\n const dataLabels = dataLabelOptions(options);\n const marker = markerOptions(options);\n\n // Unreachable through validation, which refuses bubble charts on this\n // renderer by name. Stated here too because a caller can bypass validation,\n // and the backend's own failure is a TypeError raised from inside its\n // bundle — see `collectPptxRendererErrors`.\n if (element.chartType === 'bubble') {\n throw new Error(\n `the office-open renderer does not draw bubble charts (${element.path}); ` +\n 'use the pptxgenjs renderer for this chart'\n );\n }\n\n return {\n // Stated, never left to the backend: `_nextChartId` in\n // `@office-open/pptx` is module-level and never resets, so an unnamed\n // chart is numbered differently on every render in the same process.\n id: ctx.nextId(),\n ...chartTypeOptions(element),\n categories: series[0]?.labels ?? [],\n series: series.map((entry, index) => ({\n name: entry.name ?? `Series ${index + 1}`,\n values: entry.values ?? [],\n // Every series, not just the first: PowerPoint labels each one, and a\n // chart that labelled only its first series would be a different chart.\n ...(dataLabels ? { dataLabels } : {}),\n ...(options.lineSmooth !== undefined\n ? { smooth: options.lineSmooth }\n : {}),\n ...(marker ? { marker } : {}),\n })),\n ...(options.title && options.showTitle !== false\n ? { title: options.title }\n : {}),\n ...(options.showLegend !== undefined\n ? { showLegend: options.showLegend }\n : {}),\n ...chartFamilyOptions(options),\n ...(options.legendPosition\n ? { legendPosition: options.legendPosition }\n : {}),\n x: transform.xEmu,\n y: transform.yEmu,\n width: transform.widthEmu,\n height: transform.heightEmu,\n ...(element.altText ? { description: element.altText } : {}),\n };\n}\n\n/**\n * Per-family tuning that `ChartSpaceOptions` carries directly.\n *\n * Bar gap and overlap, and the pie/doughnut geometry. Each is only forwarded\n * when authored — the backend has its own defaults and writing a value it did\n * not ask for is how a chart drifts from the one that was designed.\n */\nfunction chartFamilyOptions(options: PptxIrChartOptions): Opts {\n return {\n ...(options.barGapWidthPercent !== undefined\n ? { gapWidth: options.barGapWidthPercent }\n : {}),\n ...(options.barOverlapPercent !== undefined\n ? { overlap: options.barOverlapPercent }\n : {}),\n ...(options.holeSize !== undefined ? { holeSize: options.holeSize } : {}),\n ...(options.firstSliceAngle !== undefined\n ? { firstSliceAngle: options.firstSliceAngle }\n : {}),\n };\n}\n\n/**\n * The data labels a series carries, or nothing if none were authored.\n *\n * Every flag is written once any of them is, and that is not tidiness. A\n * `CT_Boolean` in DrawingML has an *optional* `val` that defaults to **true**,\n * so `<c:dLbls><c:showVal/></c:dLbls>` does not mean \"show the value\": it means\n * show the value, the category name, the series name, the percentage and the\n * legend key, because every flag left out defaults to on. A chart authored with\n * `showValue: true` came out labelled `Q1; Revenue; 120`. pptxgenjs writes all\n * six for the same reason.\n *\n * So an unauthored flag is written `false` rather than omitted — but only once\n * the author has asked for labels at all. A chart that said nothing about them\n * gets no `c:dLbls`, and keeps the backend's own defaults.\n */\nfunction dataLabelOptions(options: PptxIrChartOptions): Opts | undefined {\n const authored =\n options.showValue !== undefined ||\n options.showPercent !== undefined ||\n options.showLabel !== undefined ||\n options.showSeriesName !== undefined ||\n options.dataLabelPosition !== undefined;\n if (!authored) return undefined;\n\n return {\n showVal: options.showValue ?? false,\n showPercent: options.showPercent ?? false,\n showCatName: options.showLabel ?? false,\n showSerName: options.showSeriesName ?? false,\n showBubbleSize: false,\n showLegendKey: false,\n ...(options.dataLabelPosition\n ? { position: options.dataLabelPosition }\n : {}),\n };\n}\n\n/**\n * The marker a line series draws at each point, or nothing if unstyled.\n *\n * `lineSize` is deliberately absent: `ChartSeriesCommon` has no line-width\n * field at all, so the series line's width is spliced into `c:ser/c:spPr/a:ln`\n * afterwards.\n */\nfunction markerOptions(options: PptxIrChartOptions): Opts | undefined {\n const marker: Opts = {\n ...(options.lineDataSymbol ? { symbol: options.lineDataSymbol } : {}),\n ...(options.lineDataSymbolSize !== undefined\n ? { size: options.lineDataSymbolSize }\n : {}),\n };\n return Object.keys(marker).length > 0 ? marker : undefined;\n}\n\n/**\n * The backend's chart type, and the 3-D flag that goes with it.\n *\n * The two vocabularies disagree in one place each way. PowerPoint spells a\n * vertical bar chart as `bar` with `barDir: \"col\"` — which is the *default* —\n * while `@office-open` gives it its own type name, `column`. And the IR's\n * `bar3D` has no counterpart at all: it is a bar chart with the depth flag set.\n * Reading `barDirection` here is what keeps a deck's columns from coming out on\n * their side.\n */\nfunction chartTypeOptions(element: PptxIrChartElement): Opts {\n const horizontal = element.options.barDirection === 'bar';\n switch (element.chartType) {\n case 'bar':\n return { type: horizontal ? 'bar' : 'column' };\n case 'bar3D':\n return { type: horizontal ? 'bar' : 'column', threeD: true };\n default:\n return { type: element.chartType };\n }\n}\n\nexport function slideChild(\n element: PptxIrElement,\n ctx: OfficeOpenEmitContext\n): Opts {\n switch (element.kind) {\n case 'textBox':\n return textBoxChild(element, ctx);\n case 'shape':\n return shapeChild(element, ctx);\n case 'image':\n return pictureChild(element, ctx);\n case 'table':\n return tableChild(element, ctx);\n case 'group':\n return groupChild(element, ctx);\n case 'chart':\n ctx.charts?.push(element);\n return { chart: chartChild(element, ctx) };\n default:\n return assertNever(element, 'PptxIrElement');\n }\n}\n\nexport function background(\n value: PptxIrBackground,\n ctx: OfficeOpenEmitContext\n): Opts {\n if (value.kind === 'solid') {\n return { fill: { type: 'solid', color: color(value.color) } };\n }\n return { fill: fill({ kind: 'image', resourceId: value.resourceId }, ctx) };\n}\n","/**\n * The experimental `@office-open/pptx` renderer.\n *\n * Selecting it is explicit and opt-in; `pptxgenjs` stays the default. The\n * backend is an optional peer dependency, resolved at call time so a missing\n * package surfaces as an install hint rather than a module-resolution failure.\n *\n * The capability set below is deliberately narrow. A feature is listed only\n * when it has been proven against the real package, never from its README, and\n * a gap in the backend is expressed by *omitting* the capability — which makes\n * the compiler reject the document before any bytes exist, instead of shipping\n * a deck with content quietly missing.\n */\n\nimport { readFile } from 'node:fs/promises';\nimport {\n finalizePackage,\n readPackage,\n writePackage,\n resolveGeneratedAt,\n} from '../../core/finalizePackage';\nimport { spliceChartParts } from './chartParts';\nimport { ALL_PPTX_FEATURES, type PptxFeature } from '../../ir/features';\nimport type {\n PptxIR,\n PptxIrChartElement,\n PptxIrResource,\n} from '../../ir/types';\nimport type { PptxRenderOptions, PptxRenderer, PptxRendererId } from '../types';\nimport { background, slideChild, type OfficeOpenEmitContext } from './emit';\n\nexport const OFFICE_OPEN_PPTX_RENDERER_ID: PptxRendererId = 'office-open';\n\n/**\n * Module specifier held in a variable so TypeScript does not resolve the\n * optional dependency at build time and the failure lands at selection time.\n */\nconst OFFICE_OPEN_PPTX = '@office-open/pptx';\n\n/**\n * What this adapter does *not* declare, and why. Each is a verified gap, not\n * an unfinished mapping:\n *\n * - `svg` — `PictureOptions.type` excludes SVG and no code path creates an SVG\n * media entry, so an SVG would ship as a broken image.\n * - `image-transform` — `PictureOptions` carries neither `rotation` nor a flip,\n * so any transform on a picture would be silently discarded.\n * - `image-crop`, `image-rounding` — `PictureOptions` is `{data, type}` plus a\n * frame and effects: no source rectangle, no geometry. A cropped picture\n * would be drawn whole into the frame and a circular one would come out\n * rectangular, neither with anything to show for it.\n * - `flip-vertical` — no pptx option type carries it, on any element.\n * - `element-hyperlinks` — `NonVisualDrawingPropertiesOptions` is\n * `{name, description, title, hidden}`: a shape or picture cannot carry a\n * link. Only runs can, which is why `text-hyperlinks` *is* declared and is\n * realised by putting the link on the runs inside the body.\n * - `masters`, `placeholders` — layout and master generation are supported by\n * the backend but not yet mapped here, and an unmapped master would lose\n * every template object.\n * - `table-merged-cells` — the backend marks merges as `restart`/`continue` on\n * the covered cells while the IR carries span counts; the translation is\n * real work and is not yet proven by a test.\n * - `table-rounded-corners` — OOXML tables have no corner radius. The default\n * backend fakes one with shapes drawn behind the table; that technique is\n * not in the IR and is not reproduced here.\n * - `table-auto-page` — nothing in this backend flows a table onto a second\n * slide, so an over-long table would run off the bottom of the first.\n * - `table-insets` — `TableCellOptions.margins` writes the insets onto the\n * cell's own `a:bodyPr`, and a reader takes a cell's padding from\n * `a:tcPr/@marL`: rendering the same table with a 0pt and a 40pt margin puts\n * the text in exactly the same place.\n * - `image-fills` on a shape are supported and declared; the resource bytes are\n * fetched before rendering.\n *\n * Table border and fill *are* declared: the backend has no table-level form of\n * either, but both are cell properties there and the adapter pushes them onto\n * every cell — see `tableChild` in `emit.ts`.\n *\n * The ten `chart-*` capabilities are the styling half of `charts`, and all ten\n * are declared: the emitter forwards what `ChartSpaceOptions` and\n * `ChartSeriesCommon` carry, and `chartParts.ts` splices in the rest. Each was\n * declared only once its mapping landed and was tested, never before — an\n * ignored `valAxisMaxVal` draws a different chart from the authored one with\n * nothing in the file to say so, which is what the split exists to prevent.\n *\n * `charts` *is* declared, and used to not be. The backend writes chart XML\n * whose `<c:f>` references are empty and which has no workbook behind them, so\n * \"Edit Data\" failed and a chart you cannot edit is not the chart that was\n * asked for. Rather than refuse, the adapter now writes the missing half\n * itself — see `chartParts.ts`.\n */\nconst UNSUPPORTED: ReadonlySet<PptxFeature> = new Set<PptxFeature>([\n 'svg',\n 'image-transform',\n 'image-crop',\n 'image-rounding',\n 'flip-vertical',\n 'element-hyperlinks',\n 'masters',\n 'placeholders',\n 'table-merged-cells',\n 'table-rounded-corners',\n 'table-auto-page',\n 'table-insets',\n]);\n\nconst OFFICE_OPEN_CAPABILITIES: ReadonlySet<PptxFeature> = new Set(\n [...ALL_PPTX_FEATURES].filter((feature) => !UNSUPPORTED.has(feature))\n);\n\ninterface OfficeOpenBackend {\n generatePresentation: (\n options: Record<string, unknown>,\n packerOptions?: { type?: string }\n ) => Promise<Uint8Array>;\n}\n\nexport async function createOfficeOpenPptxRenderer(): Promise<PptxRenderer> {\n // Throws `Cannot find package '@office-open/pptx'` when the optional\n // dependency is absent; the registry rewrites that into an install hint.\n const backend = (await import(\n /* @vite-ignore */ OFFICE_OPEN_PPTX\n )) as unknown as OfficeOpenBackend;\n\n if (typeof backend.generatePresentation !== 'function') {\n throw new Error(\n `${OFFICE_OPEN_PPTX} does not export generatePresentation(); the installed version is not compatible with this adapter.`\n );\n }\n\n return {\n id: OFFICE_OPEN_PPTX_RENDERER_ID,\n format: 'pptx',\n capabilities: OFFICE_OPEN_CAPABILITIES,\n async render(ir: PptxIR, options?: PptxRenderOptions): Promise<Uint8Array> {\n const charts: PptxIrChartElement[] = [];\n const presentation = await buildPresentationOptions(ir, charts);\n const bytes = await backend.generatePresentation(presentation, {\n type: 'uint8array',\n });\n const raw = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);\n\n // One zip, opened once: the chart repairs and the generic finalization\n // both need it, and a round-trip between them would cost a full\n // re-compress for nothing. This mirrors the pptxgenjs path, which also\n // applies its backend repairs and then calls `finalizePackage` on the\n // same open zip.\n //\n // The splice has to happen even when finalization is skipped — a chart\n // without its workbook is a broken chart, not an undeterministic one —\n // and it has to happen *before* finalization, because\n // `canonicalizeChartIds` renumbers chart parts and rewrites the\n // `Microsoft_Excel_Worksheet{N}.xlsx` references through the same map.\n if (charts.length === 0 && options?.deterministic === false) return raw;\n\n const zip = await readPackage(Buffer.from(raw));\n await spliceChartParts(zip, charts);\n\n if (options?.deterministic === false) {\n return new Uint8Array(await writePackage(zip));\n }\n // Generic package finalization. The backend stamps core metadata and ZIP\n // entries with the wall clock, so the same deck rendered twice differs.\n // Pinning those is a property of an OOXML package rather than of this\n // backend, which is why the same pass runs over the default backend's\n // output too.\n await finalizePackage(zip, resolveGeneratedAt(options?.generatedAt));\n return new Uint8Array(await writePackage(zip));\n },\n };\n}\n\n/**\n * Build the backend's document object for an IR presentation.\n *\n * Exported for tests: asserting on this object is far cheaper, and far more\n * legible, than unzipping a package.\n */\nexport async function buildPresentationOptions(\n ir: PptxIR,\n charts: PptxIrChartElement[] = []\n): Promise<Record<string, unknown>> {\n // Drawing ids restart at 2 on each slide — 1 is the slide's own group — so\n // they depend on position in the deck and nothing else.\n let nextDrawingId = 2;\n const ctx: OfficeOpenEmitContext = {\n resources: new Map(ir.resources.map((r) => [r.id, r])),\n resourceBytes: await loadResourceBytes(ir.resources),\n nextId: () => nextDrawingId++,\n charts,\n };\n\n const presentation: Record<string, unknown> = {\n size: { width: ir.size.widthEmu, height: ir.size.heightEmu },\n slides: ir.slides.map((slide) => {\n nextDrawingId = 2;\n const out: Record<string, unknown> = {\n children: slide.elements.map((element) => slideChild(element, ctx)),\n };\n if (slide.background) {\n out.background = background(slide.background, ctx);\n }\n if (slide.notes) out.notes = slide.notes;\n if (slide.hidden) out.hidden = true;\n if (slide.transition) {\n out.transition = {\n type: slide.transition.type,\n ...(slide.transition.speed ? { speed: slide.transition.speed } : {}),\n };\n }\n return out;\n }),\n };\n\n if (ir.rtl) presentation.rtl = true;\n if (ir.metadata.title) presentation.title = ir.metadata.title;\n if (ir.metadata.author) presentation.creator = ir.metadata.author;\n if (ir.metadata.subject) presentation.subject = ir.metadata.subject;\n // `company` is an *extended* property — `docProps/app.xml`, not `core.xml` —\n // which is why it is not a sibling of the three above (#262).\n if (ir.metadata.company) {\n presentation.appProperties = { company: ir.metadata.company };\n }\n\n const theme = themeOptions(ir);\n if (theme) {\n // A theme belongs to a master, and the backend generates a default master\n // when none is declared. Declaring one here is what gives the deck a\n // `theme1.xml` carrying the authored fonts and palette rather than\n // PowerPoint's Office defaults (#258).\n presentation.masters = [{ name: ir.theme.name || 'Default', theme }];\n }\n\n return presentation;\n}\n\n/**\n * The authored theme, as the backend's `ThemeOptions`.\n *\n * Only what survives IR theme resolution: the major/minor font faces, which\n * are set on the presentation rather than on any element, and the resolved\n * palette. Element colours are already literal hex by this point, so the\n * scheme is not what draws the deck — it is what PowerPoint offers when\n * someone edits it, and what newly inserted content picks up.\n */\nfunction themeOptions(ir: PptxIR): Record<string, unknown> | undefined {\n const { headingFont, bodyFont, palette, name } = ir.theme;\n const colorScheme = colorSchemeOptions(palette);\n if (!headingFont && !bodyFont && !colorScheme) return undefined;\n\n return {\n ...(name ? { name } : {}),\n fontScheme: {\n ...(name ? { name } : {}),\n ...(headingFont\n ? { majorFont: { latin: { typeface: headingFont } } }\n : {}),\n ...(bodyFont ? { minorFont: { latin: { typeface: bodyFont } } } : {}),\n },\n ...(colorScheme ? { colorScheme } : {}),\n };\n}\n\n/**\n * OOXML scheme slot ← the IR palette's project-owned slot.\n *\n * `PptxIrTheme.palette` is keyed by the project's own vocabulary, so an adapter\n * that writes a real `<a:clrScheme>` has to know which of those names each\n * OOXML slot holds. The pairing is the one the authoring surface already\n * accepts as aliases — see `SEMANTIC_TO_THEME_KEY` in `utils/color.ts`, which\n * resolves `accent1`, `tx1` and friends against the same slots.\n *\n * A palette entry with no OOXML counterpart is left out rather than invented\n * into a spare accent.\n */\nconst SCHEME_SLOTS: ReadonlyArray<readonly [string, string]> = [\n ['dark1', 'text'],\n ['light1', 'background'],\n ['dark2', 'text2'],\n ['light2', 'background2'],\n ['accent1', 'primary'],\n ['accent2', 'secondary'],\n ['accent3', 'accent'],\n ['accent4', 'accent4'],\n ['accent5', 'accent5'],\n ['accent6', 'accent6'],\n];\n\nfunction colorSchemeOptions(\n palette: Readonly<Record<string, string>>\n): Record<string, string> | undefined {\n const scheme: Record<string, string> = {};\n for (const [slot, key] of SCHEME_SLOTS) {\n const value = palette[key];\n if (value) scheme[slot] = value;\n }\n return Object.keys(scheme).length > 0 ? scheme : undefined;\n}\n\n/**\n * Read the bytes for every resource.\n *\n * The backend embeds media by value, so file and remote resources — which the\n * IR deliberately keeps as locations, so a large deck is not held in memory by\n * the default path — are materialised here, in the adapter that needs them.\n */\nasync function loadResourceBytes(\n resources: readonly PptxIrResource[]\n): Promise<Map<string, Uint8Array>> {\n const entries = await Promise.all(\n resources.map(async (resource) => {\n switch (resource.origin.kind) {\n case 'inline':\n return [resource.id, resource.origin.bytes] as const;\n case 'file':\n return [\n resource.id,\n new Uint8Array(await readFile(resource.origin.path)),\n ] as const;\n case 'remote': {\n const response = await fetch(resource.origin.url);\n if (!response.ok) {\n throw new Error(\n `failed to fetch image ${resource.origin.url}: ${response.status} ${response.statusText}`\n );\n }\n return [\n resource.id,\n new Uint8Array(await response.arrayBuffer()),\n ] as const;\n }\n }\n })\n );\n return new Map(entries);\n}\n","/**\n * Presentation generation entry points.\n *\n * Every path here compiles the authoring tree to PptxIR and hands it to a\n * renderer adapter; nothing in this module knows which backend that is. The\n * default is `pptxgenjs`, which reproduces the output this pipeline has always\n * produced — see `src/__tests__/corpus-goldens.test.ts`.\n */\n\nimport { writeFileSync } from 'fs';\nimport type {\n PipelineWarning,\n PresentationComponentDefinition,\n} from '../types';\nimport { generateBufferViaIr } from './generateFromIr';\n\nexport {\n PresentationValidationError,\n assertNoContentConflicts,\n assertValidPresentation,\n isPresentationComponentDefinition,\n} from './generationOptions';\nexport type {\n GenerationOptions,\n GenerationResult,\n GenerationValidationOptions,\n} from './generationOptions';\n\nimport {\n isPresentationComponentDefinition,\n type GenerationOptions,\n type GenerationResult,\n} from './generationOptions';\n\n/**\n * Generate a `.pptx` buffer from a presentation definition.\n */\nexport async function generateBufferFromJson(\n jsonConfig: string | PresentationComponentDefinition,\n options?: GenerationOptions\n): Promise<Buffer> {\n const result = await generateBufferWithWarnings(jsonConfig, options);\n return result.buffer;\n}\n\n/**\n * Generate a `.pptx` buffer, returning the pipeline warnings alongside it.\n */\nexport async function generateBufferWithWarnings(\n jsonConfig: string | PresentationComponentDefinition,\n options?: GenerationOptions\n): Promise<GenerationResult> {\n const { buffer, warnings } = await generateBufferViaIr(jsonConfig, options);\n return { buffer, warnings };\n}\n\n/**\n * Generate and save a `.pptx` file from a presentation definition.\n */\nexport async function generateAndSaveFromJson(\n jsonConfig: string | PresentationComponentDefinition,\n outputPath: string,\n options?: GenerationOptions\n): Promise<void> {\n const buffer = await generateBufferFromJson(jsonConfig, options);\n writeFileSync(outputPath, buffer);\n}\n\n/**\n * Generate from a JSON file path.\n */\nexport async function generateFromFile(\n filePath: string,\n outputPath: string,\n options?: GenerationOptions\n): Promise<void> {\n const { readFileSync } = await import('fs');\n const json = readFileSync(filePath, 'utf-8');\n await generateAndSaveFromJson(json, outputPath, options);\n}\n\nexport type { PipelineWarning };\n\n/**\n * The main API surface.\n *\n * Buffer- and file-oriented only: no member returns a renderer-native object.\n */\nexport const PresentationGenerator = {\n generateBufferFromJson,\n generateBufferWithWarnings,\n generateAndSaveFromJson,\n generateFromFile,\n isPresentationComponentDefinition,\n};\n","/**\n * The IR-based PPTX generation path.\n *\n * Same prologue as `generateBufferWithWarnings` — props defaulting, inline\n * theme normalisation, theme resolution, export-mode pre-pass, font\n * resolution — and then, instead of calling PptxGenJS directly, it compiles to\n * PptxIR, checks the selected renderer can express it, and hands the IR to an\n * adapter.\n *\n * Not yet the default. It becomes the default when every component the legacy\n * path renders is lowered by the compiler and the parity fixtures pass through\n * it; until then `compilePresentation` reports anything it cannot lower and\n * this function refuses rather than shipping a deck with content missing.\n */\n\nimport { assertRendererSupports } from '@json-to-office/shared/rendering';\nimport { PPTX_RENDERER_IDS } from '@json-to-office/shared-pptx';\nimport { runWithBaseDir } from '../utils/baseDirContext';\nimport { compilePresentation } from '../ir/compiler';\nimport type { PptxIR } from '../ir/types';\nimport { resolvePptxRenderer } from '../renderers/registry';\nimport type {\n PipelineWarning,\n PresentationComponentDefinition,\n ProcessedPresentation,\n} from '../types';\nimport { isPresentationComponent } from '../types';\nimport { resolveDocumentFonts } from './fontResolution';\nimport { resolveThemeContext } from './generationContext';\nimport {\n assertNoContentConflicts,\n assertValidPresentationForGeneration,\n type GenerationOptions,\n} from './generationOptions';\nimport { expandHighchartsComponents } from './expandHighcharts';\nimport { resolveImageLayout } from './resolveImageLayout';\nimport { processPresentation } from './structure';\n\n/** Alias kept for readability at call sites inside the IR pipeline. */\nexport type IrGenerationOptions = GenerationOptions;\n\nexport interface IrGenerationResult {\n buffer: Buffer;\n warnings: PipelineWarning[];\n}\n\n/**\n * Thrown when the compiler meets a component it does not lower yet.\n *\n * Silently dropping the component would be worse than failing: the deck would\n * look complete and not be. This disappears when the compiler covers every\n * component kind.\n */\nexport class UncompiledComponentError extends Error {\n public readonly code = 'UNCOMPILED_COMPONENT';\n public readonly components: ReadonlyArray<{ name: string; path: string }>;\n\n constructor(components: ReadonlyArray<{ name: string; path: string }>) {\n const names = [...new Set(components.map((c) => c.name))]\n .map((n) => `\"${n}\"`)\n .join(', ');\n super(\n `The PptxIR compiler does not lower ${names} yet, so the IR path would ` +\n `drop ${components.length} component(s):\\n` +\n components.map((c) => ` - ${c.name} at ${c.path}`).join('\\n')\n );\n this.name = 'UncompiledComponentError';\n this.components = [...components];\n }\n}\n\n/**\n * Compile a presentation document to PptxIR without rendering it.\n *\n * Runs the same pre-passes as generation, so what comes back is the IR that\n * would be rendered — not a near-miss that omits image fitting.\n */\nexport async function compileDocumentToIr(\n jsonConfig: string | PresentationComponentDefinition,\n options?: IrGenerationOptions\n): Promise<{\n ir: PptxIR;\n warnings: PipelineWarning[];\n required: ReturnType<typeof compilePresentation>['required'];\n unsupported: ReturnType<typeof compilePresentation>['unsupported'];\n}> {\n const component = parseDocument(jsonConfig);\n const selectedRenderer = options?.renderer ?? component.renderer;\n assertValidPresentationForGeneration(\n selectedRenderer && PPTX_RENDERER_IDS.includes(selectedRenderer)\n ? { ...component, renderer: selectedRenderer }\n : component,\n options?.validation\n );\n const warnings: PipelineWarning[] = [];\n\n const context = resolveThemeContext(component, {\n customThemes: options?.customThemes,\n fonts: options?.fonts,\n warnings,\n });\n\n assertNoContentConflicts(context.document);\n\n const result = await runWithBaseDir(options?.baseDir, async () => {\n const processed = processPresentation(context.document, {\n ...options,\n theme: context.theme,\n });\n const expansion = await expandHighchartsComponents(\n processed,\n options?.services?.highcharts,\n warnings\n );\n const laidOut = await resolveImageLayout(expansion.presentation, warnings);\n const compiled = compilePresentation(laidOut, warnings);\n return {\n ...compiled,\n unsupported: [...compiled.unsupported, ...expansion.unexpanded],\n };\n });\n\n return {\n ir: result.ir,\n warnings: result.warnings,\n required: result.required,\n unsupported: result.unsupported,\n };\n}\n\n/** Generate a `.pptx` buffer through PptxIR and the selected renderer. */\nexport async function generateBufferViaIr(\n jsonConfig: string | PresentationComponentDefinition,\n options?: IrGenerationOptions\n): Promise<IrGenerationResult> {\n const component = parseDocument(jsonConfig);\n const selectedRenderer = options?.renderer ?? component.renderer;\n const effectiveOptions = selectedRenderer\n ? { ...options, renderer: selectedRenderer }\n : options;\n assertValidPresentationForGeneration(\n selectedRenderer && PPTX_RENDERER_IDS.includes(selectedRenderer)\n ? { ...component, renderer: selectedRenderer }\n : component,\n options?.validation\n );\n const warnings: PipelineWarning[] = [];\n\n const context = resolveThemeContext(component, {\n customThemes: options?.customThemes,\n fonts: options?.fonts,\n warnings,\n });\n\n assertNoContentConflicts(context.document);\n\n // Fires `fonts.onResolved` for the preview stager, exactly as the legacy\n // path does. The PPTX itself never embeds font bytes.\n await resolveDocumentFonts(\n context.document,\n context.theme,\n warnings,\n options?.fonts\n );\n\n // Relative asset paths are resolved during compilation, so the base-directory\n // scope has to span it (#142).\n const buffer = await runWithBaseDir(options?.baseDir, () =>\n renderProcessedViaIr(\n processPresentation(context.document, {\n ...effectiveOptions,\n theme: context.theme,\n }),\n warnings,\n effectiveOptions\n )\n );\n\n return { buffer, warnings };\n}\n\n/**\n * Compile a processed presentation and render it with the selected backend.\n *\n * Shared by both entry points — the core buffer API and the plugin generator —\n * so the two cannot drift in which expansions run, which capabilities are\n * checked, or how the package is finalised.\n *\n * The caller is responsible for the base-directory scope: relative asset paths\n * are resolved during compilation (#142).\n */\nexport async function renderProcessedViaIr(\n processed: ProcessedPresentation,\n warnings: PipelineWarning[],\n options?: IrRenderOptions\n): Promise<Buffer> {\n // `highcharts` fetches a PNG from an export server; resolving it before\n // compilation keeps the IR free of any service dependency.\n const expansion = await expandHighchartsComponents(\n processed,\n options?.services?.highcharts,\n warnings\n );\n // Fitting an image needs its intrinsic size, which needs I/O; resolving it\n // here keeps the compiler synchronous and free of file access.\n const laidOut = await resolveImageLayout(expansion.presentation, warnings);\n const compiled = compilePresentation(laidOut, warnings);\n\n const missing = [...compiled.unsupported, ...expansion.unexpanded];\n if (missing.length > 0) {\n throw new UncompiledComponentError(missing);\n }\n\n const renderer = await resolvePptxRenderer(options?.renderer);\n assertRendererSupports(compiled.required, renderer);\n\n const bytes = await renderer.render(compiled.ir, {\n ...(options?.deterministic !== undefined\n ? { deterministic: options.deterministic }\n : {}),\n ...(options?.generatedAt !== undefined\n ? { generatedAt: toDate(options.generatedAt) }\n : {}),\n // Post-render repairs report into the same list as the rest of the\n // pipeline, so a caller sees one set of warnings.\n warnings,\n });\n\n return Buffer.from(bytes);\n}\n\n/** The subset of options `renderProcessedViaIr` reads. */\nexport type IrRenderOptions = Pick<\n GenerationOptions,\n 'renderer' | 'services' | 'deterministic' | 'generatedAt'\n>;\n\nfunction parseDocument(\n jsonConfig: string | PresentationComponentDefinition\n): PresentationComponentDefinition {\n if (typeof jsonConfig !== 'string') return jsonConfig;\n const parsed = JSON.parse(jsonConfig);\n if (!isPresentationComponent(parsed)) {\n throw new Error('Parsed JSON must be a presentation component');\n }\n return parsed;\n}\n\nfunction toDate(value: Date | string): Date {\n return value instanceof Date ? value : new Date(value);\n}\n","import { AsyncLocalStorage } from 'node:async_hooks';\nimport { isAbsolute, resolve } from 'node:path';\n\nconst baseDirStorage = new AsyncLocalStorage<string>();\n\n/**\n * Scope the document base directory for a generation run, so relative asset\n * paths (`image.props.path`, slide background images) resolve against the\n * document's own location rather than `process.cwd()` (#142). No baseDir →\n * plain callback, preserving the historical cwd-relative behavior. Mirrors\n * core-docx/src/utils/generationContext.ts.\n */\nexport function runWithBaseDir<T>(\n baseDir: string | undefined,\n callback: () => T\n): T {\n return baseDir === undefined\n ? callback()\n : baseDirStorage.run(resolve(baseDir), callback);\n}\n\n/** The active document base directory, if a generation scope set one. */\nexport function getBaseDir(): string | undefined {\n return baseDirStorage.getStore();\n}\n\n/**\n * Resolve a relative file path against the active base directory. Absolute\n * paths pass through; with no active baseDir the path is returned as-is,\n * which pptxgenjs / `fs` resolve against cwd — the legacy behavior. The\n * rewrite must happen eagerly at render time: pptxgenjs reads `path` entries\n * later, during `write()`, outside any generation scope.\n */\nexport function resolveFromBaseDir(filePath: string): string {\n const base = baseDirStorage.getStore();\n if (!base || isAbsolute(filePath)) return filePath;\n return resolve(base, filePath);\n}\n","/**\n * Compile a processed presentation into PptxIR.\n *\n * The input is `ProcessedPresentation` — the authoring tree after schema\n * validation, custom-component expansion, theme resolution and component\n * defaults. What remains, and what this module does, is the last mile of\n * resolution: grid cells become EMU transforms, placeholder content is merged\n * with its declaration, theme colour tokens become hex, the font cascade is\n * flattened onto every run, and page-number placeholders are substituted.\n *\n * No renderer is imported here, and none may be. The output is plain data.\n *\n * Scope: this is the Phase 2 vertical slice — metadata, slide size, slides,\n * solid backgrounds, text bodies (single and rich-run), images and preset\n * shapes. Component kinds outside that slice are reported through\n * `unsupported`, so a caller can tell \"not yet compiled\" from \"compiled to\n * nothing\".\n */\n\nimport {\n FeatureRequirementCollector,\n type FeatureRequirement,\n} from '@json-to-office/shared/rendering';\nimport type { TextSegment } from '@json-to-office/shared-pptx';\nimport { PATTERN_FILL_PRESETS } from '@json-to-office/shared-pptx';\nimport type {\n GridConfig,\n PipelineWarning,\n PptxComponentInput,\n PptxThemeConfig,\n ProcessedPresentation,\n ProcessedSlide,\n SlideContext,\n StyleName,\n TemplateSlideDefinition,\n} from '../types';\nimport { definedChartColorTokens, resolveColor } from '../utils/color';\nimport { applyFontWeight } from '../utils/fontAliasContext';\nimport { getDefaultsForType } from '../utils/componentDefaults';\nimport { resolveComponentDefaults } from '../utils/resolveComponentTree';\nimport { resolveImageSource, safeLocalPath } from '../utils/imageSource';\nimport {\n HYPERLINK_SLIDE_UNRESOLVED,\n type HyperlinkProps,\n} from '../utils/hyperlink';\nimport { mergeGridConfigs, resolveComponentGridPosition } from '../core/grid';\nimport { mergeWithDefaults } from '@json-to-office/shared';\nimport { W, warn } from '../utils/warn';\nimport type { PptxFeature } from './features';\nimport {\n ResourceTable,\n mediaTypeFromLocation,\n parseDataUri,\n} from './resources';\nimport {\n PPTX_IR_GEOMETRY,\n PPTX_IR_SCHEMA_VERSION,\n type PptxIR,\n type PptxIrBackground,\n type PptxIrBullet,\n type PptxIrColor,\n type PptxIrElement,\n type PptxIrFill,\n type PptxIrGeometry,\n type PptxIrGradient,\n type PptxIrHyperlink,\n type PptxIrImageSizing,\n type PptxIrKnownGeometry,\n type PptxIrLine,\n type PptxIrMaster,\n type PptxIrPlaceholder,\n type PptxIrRunFormatting,\n type PptxIrChartGridLine,\n type PptxIrChartLabelFont,\n type PptxIrChartOptions,\n type PptxIrChartType,\n type PptxIrShadow,\n type PptxIrTableBorder,\n type PptxIrTableCell,\n type PptxIrTableCellFormatting,\n type PptxIrTableElement,\n type PptxIrTableFormatting,\n type PptxIrTableRow,\n type PptxIrSlide,\n type PptxIrTextBodyStyle,\n type PptxIrTextRun,\n type PptxIrTransform,\n type PptxIrTransition,\n} from './types';\nimport {\n defaultWidthEmu,\n elementId,\n inchesToEmu,\n irColor,\n normalizeDegrees,\n resolveDimensionEmu,\n type SlideExtentEmu,\n} from './units';\n\n/** A component kind the compiler does not yet lower into IR. */\nexport interface UnsupportedComponent {\n name: string;\n path: string;\n}\n\nexport interface PptxCompileResult {\n ir: PptxIR;\n /** Backend capabilities the IR needs, with the IR path that needs them. */\n required: readonly FeatureRequirement<PptxFeature>[];\n warnings: PipelineWarning[];\n /**\n * Components the compiler could not lower. Empty once the migration is\n * complete; until then this is what keeps the legacy path authoritative\n * instead of silently dropping content.\n */\n unsupported: UnsupportedComponent[];\n}\n\n/** Shared mutable state for one compilation. Never module-global. */\ninterface CompileContext {\n theme: PptxThemeConfig;\n warnings: PipelineWarning[];\n features: FeatureRequirementCollector<PptxFeature>;\n resources: ResourceTable;\n unsupported: UnsupportedComponent[];\n slideWidthInches: number;\n slideHeightInches: number;\n /** Slide extent in EMU — what percentage dimensions resolve against. */\n extent: SlideExtentEmu;\n}\n\nexport function compilePresentation(\n processed: ProcessedPresentation,\n warnings: PipelineWarning[] = []\n): PptxCompileResult {\n const ctx: CompileContext = {\n theme: processed.theme,\n warnings,\n features: new FeatureRequirementCollector<PptxFeature>(),\n resources: new ResourceTable(),\n unsupported: [],\n slideWidthInches: processed.slideWidth,\n slideHeightInches: processed.slideHeight,\n extent: {\n widthEmu: inchesToEmu(processed.slideWidth),\n heightEmu: inchesToEmu(processed.slideHeight),\n },\n };\n\n const masters = (processed.templates ?? []).map((template, index) =>\n compileMaster(template, index, processed, ctx)\n );\n if (masters.length > 0) {\n ctx.features.require('masters', 'masters');\n }\n\n const slides = processed.slides.map((slide, index) =>\n compileSlide(slide, index, processed, ctx)\n );\n\n if (processed.rtlMode) ctx.features.require('rtl', 'rtl');\n\n const ir: PptxIR = {\n schemaVersion: PPTX_IR_SCHEMA_VERSION,\n metadata: { ...processed.metadata },\n size: { ...ctx.extent },\n theme: {\n name: processed.theme.name,\n headingFont: processed.theme.fonts.heading,\n bodyFont: processed.theme.fonts.body,\n palette: resolvePalette(processed.theme),\n },\n rtl: processed.rtlMode,\n ...(processed.language ? { language: processed.language } : {}),\n resources: ctx.resources.list(),\n masters,\n slides,\n };\n\n return {\n ir,\n required: ctx.features.list(),\n warnings: ctx.warnings,\n unsupported: ctx.unsupported,\n };\n}\n\n/* ------------------------------------------------------------------ *\n * Theme\n * ------------------------------------------------------------------ */\n\n/**\n * Resolve every theme colour slot to hex.\n *\n * Slots may name other slots; `resolveColor` walks those chains. Resolution\n * runs without a warning sink because an unset optional slot is normal here —\n * it only matters when an element actually references it, and that call site\n * reports it.\n */\nfunction resolvePalette(theme: PptxThemeConfig): Record<string, string> {\n const palette: Record<string, string> = {};\n for (const [slot, value] of Object.entries(theme.colors)) {\n if (typeof value !== 'string' || value.length === 0) continue;\n palette[slot] = resolveColor(value, theme).toUpperCase();\n }\n return palette;\n}\n\n/* ------------------------------------------------------------------ *\n * Masters\n * ------------------------------------------------------------------ */\n\nfunction compileMaster(\n template: TemplateSlideDefinition,\n templateIndex: number,\n processed: ProcessedPresentation,\n ctx: CompileContext\n): PptxIrMaster {\n const path = `masters[${templateIndex}]`;\n const background = compileBackground(\n template.background,\n `${path}.background`,\n ctx\n );\n\n // A template's fixed objects are drawn onto every slide that uses it, not\n // into the master part — that is what the pipeline has always done, and it\n // is what `compileSlide` records. Compiling them here as well would put the\n // same content in the IR twice. The field stays on the master for a backend\n // that supports genuine master-level decoration.\n const elements: PptxIrElement[] = [];\n\n const placeholders: PptxIrPlaceholder[] = (template.placeholders ?? []).map(\n (placeholder) => {\n const transform = optionalTransform(\n placeholder.x,\n placeholder.y,\n placeholder.w,\n placeholder.h,\n ctx\n );\n return transform\n ? { name: placeholder.name, transform }\n : { name: placeholder.name };\n }\n );\n if (placeholders.length > 0) {\n ctx.features.require('placeholders', `${path}.placeholders`);\n }\n\n const master: PptxIrMaster = {\n name: template.name,\n ...(background ? { background } : {}),\n ...(template.margin !== undefined ? { margin: template.margin } : {}),\n elements,\n placeholders,\n };\n\n if (template.slideNumber) {\n const sn = template.slideNumber;\n master.slideNumber = {\n transform: {\n xEmu: inchesToEmu(sn.x),\n yEmu: inchesToEmu(sn.y),\n widthEmu: inchesToEmu(sn.w ?? 1),\n heightEmu: inchesToEmu(sn.h ?? 0.3),\n },\n ...(sn.color\n ? { color: irColor(resolveColor(sn.color, ctx.theme, ctx.warnings)) }\n : {}),\n ...(sn.fontSize !== undefined ? { fontSize: sn.fontSize } : {}),\n };\n }\n\n // A template gradient background is not a background: it compiles to a\n // full-bleed shape at the back of every slide that uses the template. The\n // slide compiler emits it, because that is where slide element order lives.\n void processed;\n\n return master;\n}\n\n/* ------------------------------------------------------------------ *\n * Slides\n * ------------------------------------------------------------------ */\n\nfunction compileSlide(\n slide: ProcessedSlide,\n slideIndex: number,\n processed: ProcessedPresentation,\n ctx: CompileContext\n): PptxIrSlide {\n const path = `slides[${slideIndex}]`;\n const templates = new Map(\n (processed.templates ?? []).map((template) => [template.name, template])\n );\n const template = slide.template ? templates.get(slide.template) : undefined;\n if (slide.template && !template) {\n warn(\n ctx.warnings,\n W.MISSING_TEMPLATE,\n `Unknown template \"${slide.template}\". Available: ${[...templates.keys()].join(', ')}`,\n { slide: slideIndex }\n );\n }\n\n const elements: PptxIrElement[] = [];\n let nextIndex = 0;\n const push = (element: PptxIrElement | undefined) => {\n if (element) elements.push(element);\n nextIndex += 1;\n };\n\n // A gradient background renders as a full-bleed rectangle added first, so it\n // sits behind everything else. The slide's own background wins over the\n // template's, matching the pre-IR pipeline.\n const gradientSource =\n slide.background?.gradient ??\n (slide.background ? undefined : template?.background?.gradient);\n let background: PptxIrBackground | undefined;\n if (gradientSource) {\n const gradient = compileGradient(\n gradientSource,\n `${path}.background.gradient`,\n ctx\n );\n if (gradient) {\n ctx.features.require('gradient-fills', `${path}.background`);\n elements.push({\n kind: 'shape',\n id: elementId(slideIndex, [nextIndex]),\n path: `${path}.elements[${nextIndex}]`,\n transform: {\n xEmu: 0,\n yEmu: 0,\n widthEmu: inchesToEmu(ctx.slideWidthInches),\n heightEmu: inchesToEmu(ctx.slideHeightInches),\n },\n geometry: 'rect',\n fill: { kind: 'gradient', gradient },\n });\n ctx.features.require('shapes', `${path}.elements[${nextIndex}]`);\n nextIndex += 1;\n }\n } else {\n background = compileBackground(slide.background, `${path}.background`, ctx);\n }\n\n const effectiveGrid = mergeGridConfigs(processed.grid, template?.grid);\n\n // Template fixed objects draw beneath slide content.\n // Template objects are drawn onto this slide, so they see this slide's\n // context: a `{PAGE_NUMBER}` in a template header has to resolve, and its\n // runs inherit the deck language like any other.\n for (const object of template?.objects ?? []) {\n push(\n compileComponent(object, {\n ctx,\n path: `${path}.elements[${nextIndex}]`,\n id: elementId(slideIndex, [nextIndex]),\n slideCtx: slideContextFor(slideIndex, processed),\n })\n );\n }\n\n for (const component of slide.components) {\n const resolved = resolveComponentGridPosition(\n component,\n effectiveGrid,\n ctx.slideWidthInches,\n ctx.slideHeightInches,\n ctx.warnings\n );\n push(\n compileComponent(resolved, {\n ctx,\n path: `${path}.elements[${nextIndex}]`,\n id: elementId(slideIndex, [nextIndex]),\n slideCtx: slideContextFor(slideIndex, processed),\n })\n );\n }\n\n for (const component of compilePlaceholderComponents(\n slide,\n template,\n effectiveGrid,\n slideIndex,\n ctx\n )) {\n push(\n compileComponent(component, {\n ctx,\n path: `${path}.elements[${nextIndex}]`,\n id: elementId(slideIndex, [nextIndex]),\n slideCtx: slideContextFor(slideIndex, processed),\n })\n );\n }\n\n if (slide.notes) ctx.features.require('speaker-notes', `${path}.notes`);\n if (slide.hidden) ctx.features.require('hidden-slides', `${path}.hidden`);\n if (background) ctx.features.require('backgrounds', `${path}.background`);\n\n const transition = compileTransition(slide.transition);\n if (transition) ctx.features.require('transitions', `${path}.transition`);\n\n return {\n id: `slide${slideIndex + 1}`,\n path,\n ...(slide.template ? { masterName: slide.template } : {}),\n ...(background ? { background } : {}),\n elements,\n ...(slide.notes ? { notes: slide.notes } : {}),\n hidden: slide.hidden === true,\n ...(transition ? { transition } : {}),\n };\n}\n\n/**\n * An authored transition.\n *\n * `none` is an authored transition too — it says \"do not inherit one\" — but\n * OOXML expresses that by omitting `<p:transition>`, so it lowers to nothing\n * and asks nothing of the backend.\n */\nfunction compileTransition(\n transition: ProcessedSlide['transition']\n): PptxIrTransition | undefined {\n const type = transition?.type;\n if (!type || type === 'none') return undefined;\n return {\n type,\n ...(transition?.speed\n ? { speed: transition.speed as PptxIrTransition['speed'] }\n : {}),\n };\n}\n\nfunction slideContextFor(\n slideIndex: number,\n processed: ProcessedPresentation\n): SlideContext {\n return {\n slideNumber: slideIndex + 1,\n totalSlides: processed.slides.length,\n pageNumberFormat: processed.pageNumberFormat,\n language: processed.language,\n };\n}\n\n/**\n * Merge slide-side placeholder content with its master declaration.\n *\n * Precedence matches the pre-IR renderer: componentDefaults < declared\n * position < declared defaults < the component's own props.\n */\nfunction compilePlaceholderComponents(\n slide: ProcessedSlide,\n template: TemplateSlideDefinition | undefined,\n effectiveGrid: GridConfig | undefined,\n slideIndex: number,\n ctx: CompileContext\n): PptxComponentInput[] {\n if (!slide.placeholders) return [];\n const out: PptxComponentInput[] = [];\n\n if (!template) {\n // No template: a placeholder is only renderable if it positions itself.\n for (const [name, component] of Object.entries(slide.placeholders)) {\n const defaulted = resolveComponentDefaults(component, ctx.theme);\n const positioned =\n defaulted.props.x != null ||\n defaulted.props.y != null ||\n defaulted.props.grid;\n if (!positioned) {\n warn(\n ctx.warnings,\n W.PLACEHOLDER_NO_POSITION,\n `Placeholder \"${name}\" has no template and no explicit position — skipped`,\n { slide: slideIndex }\n );\n continue;\n }\n out.push(\n resolveComponentGridPosition(\n defaulted,\n effectiveGrid,\n ctx.slideWidthInches,\n ctx.slideHeightInches,\n ctx.warnings\n )\n );\n }\n return out;\n }\n\n const declared = new Map(\n (template.placeholders ?? []).map((placeholder) => [\n placeholder.name,\n placeholder,\n ])\n );\n\n for (const [name, component] of Object.entries(slide.placeholders)) {\n const definition = declared.get(name);\n if (!definition) {\n warn(\n ctx.warnings,\n W.UNKNOWN_PLACEHOLDER,\n `Unknown placeholder \"${name}\" in template \"${slide.template}\". Available: ${[...declared.keys()].join(', ')}`,\n { slide: slideIndex }\n );\n continue;\n }\n\n const gridResolved = resolveComponentGridPosition(\n component,\n effectiveGrid,\n ctx.slideWidthInches,\n ctx.slideHeightInches,\n ctx.warnings\n );\n\n const typeDefaults = getDefaultsForType(component.name, ctx.theme);\n const positionDefaults: Record<string, unknown> = {};\n if (definition.x != null) positionDefaults.x = definition.x;\n if (definition.y != null) positionDefaults.y = definition.y;\n if (definition.w != null) positionDefaults.w = definition.w;\n if (definition.h != null) positionDefaults.h = definition.h;\n\n let props = mergeWithDefaults(positionDefaults, typeDefaults);\n props = mergeWithDefaults(definition.defaults?.props ?? {}, props);\n props = mergeWithDefaults(gridResolved.props, props);\n\n out.push({ ...gridResolved, props });\n }\n\n return out;\n}\n\n/* ------------------------------------------------------------------ *\n * Components\n * ------------------------------------------------------------------ */\n\ninterface ComponentScope {\n ctx: CompileContext;\n path: string;\n id: string;\n slideCtx?: SlideContext;\n}\n\nfunction compileComponent(\n component: PptxComponentInput,\n scope: ComponentScope\n): PptxIrElement | undefined {\n if (component.enabled === false) return undefined;\n\n switch (component.name) {\n case 'text':\n return compileText(component, scope);\n case 'shape':\n return compileShape(component, scope);\n case 'image':\n return compileImage(component, scope);\n case 'table':\n return compileTable(component, scope);\n case 'chart':\n return compileChart(component, scope);\n case 'highcharts':\n // Modelled in the IR, not yet lowered. Recorded rather than dropped.\n scope.ctx.unsupported.push({ name: component.name, path: scope.path });\n return undefined;\n default:\n warn(\n scope.ctx.warnings,\n W.UNKNOWN_COMPONENT,\n `Unknown PPTX component type: ${component.name}`,\n { component: component.name }\n );\n return undefined;\n }\n}\n\n/* ------------------------------------------------------------------ *\n * Text\n * ------------------------------------------------------------------ */\n\ninterface TextRunProps {\n text: string;\n color?: string;\n bold?: boolean;\n fontWeight?: number;\n italic?: boolean;\n underline?: boolean | { style?: string; color?: string };\n strike?: boolean;\n fontSize?: number;\n fontFace?: string;\n superscript?: boolean;\n subscript?: boolean;\n charSpacing?: number;\n breakLine?: boolean;\n}\n\nfunction compileText(\n component: PptxComponentInput,\n scope: ComponentScope\n): PptxIrElement | undefined {\n const { ctx, path } = scope;\n const props = component.props as Record<string, any>;\n const runProps: TextRunProps[] | undefined =\n Array.isArray(props.runs) && props.runs.length > 0 ? props.runs : undefined;\n\n if (props.text === undefined && !runProps) {\n warn(\n ctx.warnings,\n W.TEXT_NO_CONTENT,\n 'Text component has neither \"text\" nor \"runs\" — skipped',\n { component: 'text' }\n );\n return undefined;\n }\n\n const named = namedStyle(props.style, ctx.theme);\n // Component override wins over the deck default; with neither set the\n // renderer falls back to its own default, so nothing is recorded.\n const cascade = fontCascade(\n props,\n named,\n ctx,\n (props.language as string | undefined) ?? scope.slideCtx?.language\n );\n\n const lineCount = runProps\n ? runProps.reduce(\n (count, run) =>\n count +\n (run.breakLine ? 1 : 0) +\n (run.text.match(/\\n/g)?.length ?? 0),\n 1\n )\n : ((props.text as string).match(/\\n/g)?.length ?? 0) + 1;\n\n // The derived height has always been sized from the component's own font\n // size or the theme default — not from the named style's size. Using\n // `cascade.fontSize` here would silently resize every styled text box that\n // omits an explicit height.\n const heightFontSize =\n (props.fontSize as number | undefined) ?? ctx.theme.defaults.fontSize ?? 18;\n const transform = textTransform(props, heightFontSize, lineCount, ctx);\n const autoFit = props.h === undefined;\n\n const hyperlink = compileHyperlink(props.hyperlink, 'text', ctx, path);\n // The link belongs to the text box, not to each run: attaching it per run\n // emits one identical external relationship per run.\n const runs: PptxIrTextRun[] = runProps\n ? runProps.map((run) =>\n compileRichRun(run, cascade, undefined, scope.slideCtx, ctx)\n )\n : [\n {\n text: substitutePageNumbers(props.text as string, scope.slideCtx),\n ...baseRunFormatting(cascade),\n ...(cascade.strike != null ? { strike: cascade.strike } : {}),\n ...(cascade.underline ? { underline: cascade.underline } : {}),\n ...(cascade.language ? { language: cascade.language } : {}),\n ...(props.breakLine ? { breakAfter: true } : {}),\n },\n ];\n\n ctx.features.require('text', path);\n if (runs.length > 1) ctx.features.require('rich-text', path);\n if (cascade.language) ctx.features.require('proofing-language', path);\n if (hyperlink) ctx.features.require('text-hyperlinks', path);\n\n const fill = props.fill\n ? compileSolidFillFromProps(props.fill, `${path}.fill`, ctx)\n : undefined;\n if (fill) ctx.features.require('solid-fills', `${path}.fill`);\n\n const shadow = compileShadow(props.shadow, ctx);\n if (shadow) ctx.features.require('shadows', `${path}.shadow`);\n\n const bodyStyle = textBodyStyle(props, named, cascade, {\n autoFit,\n // Text boxes have always defaulted their inset to 0 so the text lines up\n // exactly with the position the author (or the grid) gave it.\n defaultInsetPoints: 0,\n });\n requireBulletFeatures(bodyStyle.bullet, path, ctx);\n\n return {\n kind: 'textBox',\n id: scope.id,\n path,\n transform,\n runs,\n style: bodyStyle,\n ...(fill ? { fill } : {}),\n ...(shadow ? { shadow } : {}),\n ...(hyperlink ? { hyperlink } : {}),\n };\n}\n\ninterface FontCascade {\n fontFamily: string;\n /** The family before weight aliasing, used to resolve per-run aliases. */\n baseFamily: string;\n fontSize: number;\n color: PptxIrColor;\n bold?: boolean;\n italic?: boolean;\n fontWeight?: number;\n characterSpacing?: number;\n underline?: PptxIrTextRun['underline'];\n strike?: boolean;\n language?: string;\n}\n\nfunction namedStyle(\n style: unknown,\n theme: PptxThemeConfig\n): { style?: ReturnType<typeof pickStyle>; isHeading: boolean } {\n const name = typeof style === 'string' ? (style as StyleName) : undefined;\n return {\n style: name ? pickStyle(theme, name) : undefined,\n isHeading: name !== undefined && /^(title|heading)/.test(name),\n };\n}\n\nfunction pickStyle(theme: PptxThemeConfig, name: StyleName) {\n return theme.styles?.[name];\n}\n\n/**\n * Flatten component props → named style → theme defaults into one set of run\n * formatting values, applying weight aliasing exactly once.\n */\nfunction fontCascade(\n props: Record<string, any>,\n named: ReturnType<typeof namedStyle>,\n ctx: CompileContext,\n /**\n * Proofing language for the runs. Text bodies inherit the deck default when\n * they do not name one; shapes never carry a language, so they pass nothing.\n */\n language?: string\n): FontCascade {\n const style = named.style;\n const fontSize =\n props.fontSize ?? style?.fontSize ?? ctx.theme.defaults.fontSize;\n const baseFamily =\n props.fontFace ??\n style?.fontFace ??\n (named.isHeading ? ctx.theme.fonts.heading : ctx.theme.fonts.body);\n const color = irColor(\n resolveColor(\n props.color ??\n props.fontColor ??\n style?.fontColor ??\n ctx.theme.defaults.fontColor,\n ctx.theme,\n ctx.warnings\n )\n );\n\n const bold = props.bold ?? style?.bold;\n const italic = props.italic ?? style?.italic;\n const fontWeight = props.fontWeight ?? style?.fontWeight;\n const characterSpacing = props.charSpacing ?? style?.charSpacing;\n\n let fontFamily = baseFamily;\n let effectiveBold = bold;\n let effectiveItalic = italic;\n if (fontWeight != null || bold === true) {\n const aliased = applyFontWeight({\n family: baseFamily,\n fontWeight,\n italic,\n bold,\n });\n if (aliased.fontFace !== undefined) fontFamily = aliased.fontFace;\n if (aliased.bold !== undefined) effectiveBold = aliased.bold;\n if (aliased.italic !== undefined) effectiveItalic = aliased.italic;\n }\n\n return {\n fontFamily,\n baseFamily,\n fontSize,\n color,\n ...(effectiveBold != null ? { bold: effectiveBold } : {}),\n ...(effectiveItalic != null ? { italic: effectiveItalic } : {}),\n ...(fontWeight != null ? { fontWeight } : {}),\n ...(characterSpacing != null ? { characterSpacing } : {}),\n ...(props.underline !== undefined\n ? { underline: compileUnderline(props.underline, ctx) }\n : {}),\n ...(props.strike != null ? { strike: props.strike as boolean } : {}),\n ...(language ? { language } : {}),\n };\n}\n\nfunction baseRunFormatting(\n cascade: FontCascade\n): Pick<\n PptxIrTextRun,\n 'fontFamily' | 'fontSize' | 'color' | 'bold' | 'italic' | 'characterSpacing'\n> {\n return {\n fontFamily: cascade.fontFamily,\n fontSize: cascade.fontSize,\n color: cascade.color,\n ...(cascade.bold != null ? { bold: cascade.bold } : {}),\n ...(cascade.italic != null ? { italic: cascade.italic } : {}),\n ...(cascade.characterSpacing != null\n ? { characterSpacing: cascade.characterSpacing }\n : {}),\n };\n}\n\nfunction compileRichRun(\n run: TextRunProps,\n cascade: FontCascade,\n hyperlink: PptxIrHyperlink | undefined,\n slideCtx: SlideContext | undefined,\n ctx: CompileContext\n): PptxIrTextRun {\n const effectiveWeight = run.fontWeight ?? cascade.fontWeight;\n const effectiveBold = run.bold ?? cascade.bold;\n const effectiveItalic = run.italic ?? cascade.italic;\n\n let fontFamily = run.fontFace ?? cascade.fontFamily;\n let bold = effectiveBold;\n let italic = effectiveItalic;\n\n // Only alias when the run inherits the component family. A run that names\n // its own face has already chosen it; re-aliasing would double the suffix.\n if (\n run.fontFace == null &&\n (effectiveWeight != null || effectiveBold === true)\n ) {\n const aliased = applyFontWeight({\n family: cascade.baseFamily,\n fontWeight: effectiveWeight,\n italic: effectiveItalic,\n bold: effectiveBold,\n });\n if (aliased.fontFace !== undefined) fontFamily = aliased.fontFace;\n if (aliased.bold !== undefined) bold = aliased.bold;\n if (aliased.italic !== undefined) italic = aliased.italic;\n }\n\n // Component-level underline and strike cascade into every run, exactly as\n // size, family and colour do. Reading only the run's own value silently drops\n // formatting the author set once for the whole body.\n const underline =\n run.underline !== undefined\n ? compileUnderline(run.underline, ctx)\n : cascade.underline;\n const strike = run.strike ?? cascade.strike;\n\n return {\n text: substitutePageNumbers(run.text, slideCtx),\n fontFamily,\n fontSize: run.fontSize ?? cascade.fontSize,\n color:\n run.color != null\n ? irColor(resolveColor(run.color, ctx.theme, ctx.warnings))\n : cascade.color,\n ...(bold != null ? { bold } : {}),\n ...(italic != null ? { italic } : {}),\n ...(strike != null ? { strike } : {}),\n ...(underline ? { underline } : {}),\n ...(run.superscript != null ? { superscript: run.superscript } : {}),\n ...(run.subscript != null ? { subscript: run.subscript } : {}),\n ...(run.charSpacing != null\n ? { characterSpacing: run.charSpacing }\n : cascade.characterSpacing != null\n ? { characterSpacing: cascade.characterSpacing }\n : {}),\n ...(cascade.language ? { language: cascade.language } : {}),\n ...(run.breakLine != null ? { breakAfter: run.breakLine } : {}),\n ...(hyperlink ? { hyperlink } : {}),\n };\n}\n\nfunction compileUnderline(\n underline: boolean | { style?: string; color?: string },\n ctx: CompileContext\n): PptxIrTextRun['underline'] {\n if (typeof underline === 'boolean') {\n return underline ? { style: 'sng' } : undefined;\n }\n return {\n style: underline.style ?? 'sng',\n ...(underline.color\n ? {\n color: irColor(\n resolveColor(underline.color, ctx.theme, ctx.warnings)\n ),\n }\n : {}),\n };\n}\n\nfunction substitutePageNumbers(\n text: string,\n slideCtx: SlideContext | undefined\n): string {\n if (!slideCtx) return text;\n const { slideNumber, totalSlides, pageNumberFormat } = slideCtx;\n const format = (n: number) =>\n pageNumberFormat === '09'\n ? String(n).padStart(String(totalSlides).length, '0')\n : String(n);\n return text\n .replace(/\\{PAGE_NUMBER\\}/g, format(slideNumber))\n .replace(/\\{PAGE_COUNT\\}/g, format(totalSlides));\n}\n\ninterface TextBodyStyleOptions {\n autoFit?: boolean;\n /**\n * Inset to state when the component does not set `margin`. A text box\n * defaults to 0 so it aligns exactly to its position; a shape states\n * nothing and keeps the format's own padding.\n */\n defaultInsetPoints?: number;\n}\n\nfunction textBodyStyle(\n props: Record<string, any>,\n named: ReturnType<typeof namedStyle>,\n cascade: FontCascade,\n options: TextBodyStyleOptions = {}\n): PptxIrTextBodyStyle {\n const style = named.style;\n const align = props.align ?? style?.align;\n const lineSpacing = props.lineSpacing ?? style?.lineSpacing;\n const spaceAfter = props.paraSpaceAfter ?? style?.paraSpaceAfter;\n const inset = props.margin ?? options.defaultInsetPoints;\n\n return {\n ...(align ? { align: align as PptxIrTextBodyStyle['align'] } : {}),\n verticalAlign: (props.valign ??\n 'top') as PptxIrTextBodyStyle['verticalAlign'],\n ...(props.lineSpacingMultiple !== undefined\n ? { lineSpacingMultiple: props.lineSpacingMultiple }\n : lineSpacing !== undefined\n ? { lineSpacingPoints: lineSpacing }\n : {}),\n ...(props.paraSpaceBefore !== undefined\n ? { spaceBeforePoints: props.paraSpaceBefore }\n : {}),\n ...(spaceAfter !== undefined ? { spaceAfterPoints: spaceAfter } : {}),\n ...(props.bullet !== undefined\n ? { bullet: compileBullet(props.bullet) }\n : {}),\n ...(inset !== undefined\n ? { insetPoints: inset as PptxIrTextBodyStyle['insetPoints'] }\n : {}),\n ...(options.autoFit ? { autoFit: true } : {}),\n defaults: bodyDefaults(cascade),\n };\n}\n\n/** The body-level formatting an empty paragraph inherits. */\nfunction bodyDefaults(cascade: FontCascade): PptxIrRunFormatting {\n return {\n fontFamily: cascade.fontFamily,\n fontSize: cascade.fontSize,\n color: cascade.color,\n ...(cascade.bold != null ? { bold: cascade.bold } : {}),\n ...(cascade.italic != null ? { italic: cascade.italic } : {}),\n ...(cascade.language ? { language: cascade.language } : {}),\n };\n}\n\n/**\n * An authored bullet value, as the IR states it.\n *\n * `false` is a statement, not an absence: it has to reach the backend as an\n * explicit \"no bullet\", because the paragraph may be inheriting one from a\n * named style or from the format's own list style. Compiling it to an enabled\n * bullet is what #254 was.\n */\nfunction compileBullet(\n bullet: boolean | { type?: string; style?: string; startAt?: number }\n): PptxIrBullet {\n if (typeof bullet === 'boolean') {\n return { type: bullet ? 'bullet' : 'none' };\n }\n return {\n type: bullet.type === 'number' ? 'number' : 'bullet',\n ...(bullet.style ? { style: bullet.style } : {}),\n ...(bullet.startAt !== undefined ? { startAt: bullet.startAt } : {}),\n };\n}\n\n/** Record glyphs the default backend cannot represent without substitution. */\nfunction requireBulletFeatures(\n bullet: PptxIrBullet | undefined,\n path: string,\n ctx: CompileContext\n): void {\n if (bullet?.type !== 'bullet' || bullet.style === undefined) return;\n const points = [...bullet.style];\n const codePoint = points[0]?.codePointAt(0);\n if (points.length !== 1 || codePoint === undefined || codePoint > 0xffff) {\n ctx.features.require('complex-bullet-glyphs', `${path}.bullet.style`);\n }\n}\n\n/**\n * Position a text box, reproducing the pre-IR default height.\n *\n * When no height is authored, the renderer used to derive one from the font\n * size and line count so LibreOffice — which draws `cy=\"0\"` as blank — still\n * showed the text. That derivation is layout, so it belongs here.\n */\nfunction textTransform(\n props: Record<string, any>,\n fontSize: number,\n lineCount: number,\n ctx: CompileContext\n): PptxIrTransform {\n // With no authored height, derive one from the font size and line count —\n // LibreOffice draws `cy=\"0\"` as blank, so the pipeline has always supplied a\n // height here rather than letting it default to zero.\n const heightEmu =\n props.h !== undefined\n ? resolveDimensionEmu(props.h, 'Y', ctx.extent)\n : inchesToEmu(Math.max(0.5, (fontSize / 72) * 1.6 * lineCount));\n\n return {\n xEmu:\n props.x !== undefined ? resolveDimensionEmu(props.x, 'X', ctx.extent) : 0,\n yEmu:\n props.y !== undefined ? resolveDimensionEmu(props.y, 'Y', ctx.extent) : 0,\n widthEmu:\n props.w !== undefined\n ? resolveDimensionEmu(props.w, 'X', ctx.extent)\n : defaultWidthEmu(ctx.extent),\n heightEmu,\n ...rotationProperty(props.rotate),\n };\n}\n\n/* ------------------------------------------------------------------ *\n * Shapes\n * ------------------------------------------------------------------ */\n\nconst GEOMETRY_ALIASES: Record<string, PptxIrKnownGeometry> = {\n arrow: 'rightArrow',\n lightning: 'lightningBolt',\n};\n\nfunction compileShape(\n component: PptxComponentInput,\n scope: ComponentScope\n): PptxIrElement | undefined {\n const { ctx, path } = scope;\n const props = component.props as Record<string, any>;\n\n // A geometry outside the known preset set is carried as `{ custom }` rather\n // than rejected: the backends do not agree on which presets exist, so only\n // an adapter can tell an arc from a typo.\n const geometry = compileGeometry(props.type);\n const named = namedStyle(props.style, ctx.theme);\n\n const fill = compileFill(props.fill, `${path}.fill`, ctx);\n if (fill) requireFillFeature(fill, `${path}.fill`, ctx);\n\n const line = compileLine(props.line, ctx);\n if (line) ctx.features.require('lines', `${path}.line`);\n\n const shadow = compileShadow(props.shadow, ctx);\n if (shadow) ctx.features.require('shadows', `${path}.shadow`);\n\n const hasText =\n props.text !== undefined &&\n (!Array.isArray(props.text) || props.text.length > 0);\n\n let runs: PptxIrTextRun[] | undefined;\n let style: PptxIrTextBodyStyle | undefined;\n if (hasText) {\n const cascade = fontCascade(props, named, ctx);\n runs = Array.isArray(props.text)\n ? (props.text as TextSegment[]).map((segment) =>\n compileTextSegment(segment, cascade, ctx)\n )\n : [{ text: props.text as string, ...baseRunFormatting(cascade) }];\n style = textBodyStyle(props, named, cascade);\n requireBulletFeatures(style.bullet, path, ctx);\n ctx.features.require('text', path);\n if (runs.length > 1) ctx.features.require('rich-text', path);\n }\n\n const hyperlink = compileHyperlink(props.hyperlink, 'shape', ctx, path);\n\n ctx.features.require('shapes', path);\n if (hyperlink) ctx.features.require('element-hyperlinks', path);\n const transform = shapeTransform(props, ctx);\n requireTransformFeatures(transform, path, 'shape', ctx);\n\n return {\n kind: 'shape',\n id: scope.id,\n path,\n transform,\n geometry,\n ...(fill ? { fill } : {}),\n ...(line ? { line } : {}),\n ...(shadow ? { shadow } : {}),\n ...(props.rectRadius !== undefined\n ? { cornerRadius: props.rectRadius as number }\n : {}),\n ...(props.angleRange !== undefined\n ? { angleRangeDegrees: props.angleRange as [number, number] }\n : {}),\n ...(runs ? { runs } : {}),\n ...(style ? { style } : {}),\n ...(hyperlink ? { hyperlink } : {}),\n };\n}\n\nfunction compileGeometry(type: unknown): PptxIrGeometry {\n const name = typeof type === 'string' ? type : '';\n const aliased = GEOMETRY_ALIASES[name] ?? name;\n return (PPTX_IR_GEOMETRY as readonly string[]).includes(aliased)\n ? (aliased as PptxIrKnownGeometry)\n : { custom: name };\n}\n\nfunction compileTextSegment(\n segment: TextSegment,\n cascade: FontCascade,\n ctx: CompileContext\n): PptxIrTextRun {\n const segmentWeight = (segment as TextSegment & { fontWeight?: number })\n .fontWeight;\n const effectiveWeight = segmentWeight ?? cascade.fontWeight;\n const effectiveBold = segment.bold ?? cascade.bold;\n const effectiveItalic = segment.italic ?? cascade.italic;\n\n let fontFamily = segment.fontFace ?? cascade.fontFamily;\n let bold = effectiveBold;\n let italic = effectiveItalic;\n\n if (\n segment.fontFace == null &&\n (effectiveWeight != null || effectiveBold === true)\n ) {\n const aliased = applyFontWeight({\n family: cascade.baseFamily,\n fontWeight: effectiveWeight,\n italic: effectiveItalic,\n bold: effectiveBold,\n });\n if (aliased.fontFace !== undefined) fontFamily = aliased.fontFace;\n if (aliased.bold !== undefined) bold = aliased.bold;\n if (aliased.italic !== undefined) italic = aliased.italic;\n }\n\n return {\n text: segment.text,\n fontFamily,\n fontSize: segment.fontSize ?? cascade.fontSize,\n color:\n segment.color != null\n ? irColor(resolveColor(segment.color, ctx.theme, ctx.warnings))\n : cascade.color,\n ...(bold != null ? { bold } : {}),\n ...(italic != null ? { italic } : {}),\n ...(segment.charSpacing != null\n ? { characterSpacing: segment.charSpacing }\n : cascade.characterSpacing != null\n ? { characterSpacing: cascade.characterSpacing }\n : {}),\n ...(segment.breakLine != null ? { breakAfter: segment.breakLine } : {}),\n ...(segment.spaceBefore != null\n ? { spaceBeforePoints: segment.spaceBefore }\n : {}),\n ...(segment.spaceAfter != null\n ? { spaceAfterPoints: segment.spaceAfter }\n : {}),\n };\n}\n\n/**\n * Position any absolutely-placed element.\n *\n * Unstated x, y and h are zero; unstated width falls back to\n * `defaultWidthEmu`, which is the width such an element has always been given.\n */\nfunction shapeTransform(\n props: Record<string, any>,\n ctx: CompileContext,\n options: { markAuto?: boolean } = {}\n): PptxIrTransform {\n const autoWidth = options.markAuto && props.w === undefined;\n const autoHeight = options.markAuto && props.h === undefined;\n return {\n ...(autoWidth ? { autoWidth: true } : {}),\n ...(autoHeight ? { autoHeight: true } : {}),\n xEmu:\n props.x !== undefined ? resolveDimensionEmu(props.x, 'X', ctx.extent) : 0,\n yEmu:\n props.y !== undefined ? resolveDimensionEmu(props.y, 'Y', ctx.extent) : 0,\n widthEmu:\n props.w !== undefined\n ? resolveDimensionEmu(props.w, 'X', ctx.extent)\n : defaultWidthEmu(ctx.extent),\n heightEmu:\n props.h !== undefined ? resolveDimensionEmu(props.h, 'Y', ctx.extent) : 0,\n ...rotationProperty(props.rotate),\n ...(props.flipH ? { flipHorizontal: true } : {}),\n ...(props.flipV ? { flipVertical: true } : {}),\n };\n}\n\n/** Omit full-turn rotations: they are identity, not a backend requirement. */\nfunction rotationProperty(\n value: unknown\n): Pick<PptxIrTransform, 'rotationDegrees'> {\n if (typeof value !== 'number' || value % 360 === 0) return {};\n return { rotationDegrees: value };\n}\n\n/**\n * Record the transform abilities an element actually uses.\n *\n * Rotation is split by element kind because backends differ: one may rotate a\n * shape but not a picture. Flips are separate for the same reason.\n */\nfunction requireTransformFeatures(\n transform: PptxIrTransform,\n path: string,\n kind: 'shape' | 'image',\n ctx: CompileContext\n): void {\n const transformed =\n transform.rotationDegrees !== undefined ||\n transform.flipHorizontal === true ||\n transform.flipVertical === true;\n if (!transformed) return;\n\n if (kind === 'image') {\n // A picture type that carries no rotation generally carries no flip\n // either, so one requirement covers both.\n ctx.features.require('image-transform', path);\n return;\n }\n\n if (transform.rotationDegrees !== undefined) {\n ctx.features.require('rotation', path);\n }\n if (transform.flipHorizontal) ctx.features.require('flip-horizontal', path);\n if (transform.flipVertical) ctx.features.require('flip-vertical', path);\n}\n\n/* ------------------------------------------------------------------ *\n * Images\n * ------------------------------------------------------------------ */\n\nfunction compileImage(\n component: PptxComponentInput,\n scope: ComponentScope\n): PptxIrElement | undefined {\n const { ctx, path } = scope;\n const props = component.props as Record<string, any>;\n\n const source = resolveImageSource(props);\n if (!source) {\n warn(\n ctx.warnings,\n W.IMAGE_NO_SOURCE,\n 'Image component missing path, base64, and svg',\n { component: 'image' }\n );\n return undefined;\n }\n\n const resourceId = internImageSource(source, path, ctx);\n if (resourceId === undefined) return undefined;\n\n const resource = ctx.resources.get(resourceId);\n ctx.features.require('images', path);\n if (resource?.mediaType === 'image/svg+xml') {\n ctx.features.require('svg', path);\n }\n\n const shadow = compileShadow(props.shadow, ctx);\n if (shadow) ctx.features.require('shadows', `${path}.shadow`);\n\n const hyperlink = compileHyperlink(props.hyperlink, 'image', ctx, path);\n if (hyperlink) ctx.features.require('element-hyperlinks', path);\n\n // An image with a sizing box and no stated extent takes its size from that\n // box; materialising a default width here would override it.\n const transform = shapeTransform(props, ctx, { markAuto: true });\n requireTransformFeatures(transform, path, 'image', ctx);\n\n const sizing = compileImageSizing(props.sizing, ctx);\n if (sizing) ctx.features.require('image-crop', `${path}.sizing`);\n if (props.rounding)\n ctx.features.require('image-rounding', `${path}.rounding`);\n\n return {\n kind: 'image',\n id: scope.id,\n path,\n transform,\n resourceId,\n ...(sizing ? { sizing } : {}),\n ...(props.rounding ? { rounding: true } : {}),\n ...(shadow ? { shadow } : {}),\n ...(hyperlink ? { hyperlink } : {}),\n ...(props.alt ? { altText: props.alt as string } : {}),\n };\n}\n\n/**\n * Turn a resolved image source string into a resource id.\n *\n * Data URIs are decoded to bytes here so identical inline images collapse to a\n * single resource. File paths keep the same allowed-root policy the pre-IR\n * pipeline enforced, and are rejected — with a warning, not silently — when\n * they escape it.\n */\nfunction internImageSource(\n source: string,\n path: string,\n ctx: CompileContext\n): string | undefined {\n const inline = parseDataUri(source);\n if (inline) {\n return ctx.resources.intern({\n kind: 'inline',\n bytes: inline.bytes,\n mediaType: inline.mediaType,\n });\n }\n\n if (/^https?:\\/\\//.test(source)) {\n return ctx.resources.intern({\n kind: 'remote',\n url: source,\n ...(mediaTypeFromLocation(source)\n ? { mediaType: mediaTypeFromLocation(source) }\n : {}),\n });\n }\n\n const resolved = safeLocalPath(source);\n if (resolved === undefined) {\n warn(\n ctx.warnings,\n W.IMAGE_PATH_OUTSIDE_ROOTS,\n `Image path resolves outside the document base directory: ${source}`,\n { component: 'image' }\n );\n return undefined;\n }\n void path;\n return ctx.resources.intern({\n kind: 'file',\n path: resolved,\n ...(mediaTypeFromLocation(resolved)\n ? { mediaType: mediaTypeFromLocation(resolved) }\n : {}),\n });\n}\n\n/**\n * Carry an image's sizing through to the IR.\n *\n * `contain` never reaches here: `resolveImageLayout` fits and centres the\n * element itself and drops the sizing, because the box has already been\n * honoured by the transform.\n */\nfunction compileImageSizing(\n sizing:\n | {\n type?: string;\n w?: number | string;\n h?: number | string;\n x?: number | string;\n y?: number | string;\n }\n | undefined,\n ctx: CompileContext\n): PptxIrImageSizing | undefined {\n if (!sizing?.type) return undefined;\n const type =\n sizing.type === 'cover'\n ? 'cover'\n : sizing.type === 'contain'\n ? 'contain'\n : 'crop';\n return {\n type,\n widthEmu: resolveDimensionEmu(sizing.w ?? 0, 'X', ctx.extent),\n heightEmu: resolveDimensionEmu(sizing.h ?? 0, 'Y', ctx.extent),\n ...(sizing.x !== undefined\n ? { xEmu: resolveDimensionEmu(sizing.x, 'X', ctx.extent) }\n : {}),\n ...(sizing.y !== undefined\n ? { yEmu: resolveDimensionEmu(sizing.y, 'Y', ctx.extent) }\n : {}),\n };\n}\n\n/* ------------------------------------------------------------------ *\n * Tables\n * ------------------------------------------------------------------ */\n\n/**\n * Characters PowerPoint may promote to colour emoji.\n *\n * Appending VS15 (U+FE0E) forces text presentation. This is a property of how\n * the *format* is rendered, not of any one backend, so it belongs here rather\n * than in an adapter.\n */\nconst EMOJI_PRONE_CHARS = /[✓✔✗✘☐☑☒★☆●○■□▶◀▲▼⚡⚠❌❓❗]/gu;\n\nfunction forceTextPresentation(text: string): string {\n return text.replace(EMOJI_PRONE_CHARS, (char) => `${char}\\uFE0E`);\n}\n\ninterface AuthoredTableCell {\n text: string;\n color?: string;\n fill?: string;\n fontSize?: number;\n fontFace?: string;\n bold?: boolean;\n fontWeight?: number;\n italic?: boolean;\n align?: string;\n valign?: string;\n colspan?: number;\n rowspan?: number;\n margin?: number | number[];\n}\n\nfunction compileTable(\n component: PptxComponentInput,\n scope: ComponentScope\n): PptxIrElement | undefined {\n const { ctx, path } = scope;\n const props = component.props as Record<string, any>;\n const authoredRows = (props.rows ?? []) as Array<\n Array<string | AuthoredTableCell>\n >;\n\n const defaults = compileTableDefaults(props, ctx);\n const rows: PptxIrTableRow[] = authoredRows.map((row) => ({\n cells: row.map((cell) => compileTableCell(cell, props, ctx)),\n }));\n\n const border = compileTableBorder(props.border, ctx);\n const cornerRadius =\n typeof props.borderRadius === 'number' && props.borderRadius > 0\n ? props.borderRadius\n : undefined;\n\n ctx.features.require('tables', path);\n if (\n rows.some((row) =>\n row.cells.some((cell) => cell.colSpan != null || cell.rowSpan != null)\n )\n ) {\n ctx.features.require('table-merged-cells', path);\n }\n if (cornerRadius !== undefined) {\n ctx.features.require('table-rounded-corners', `${path}.borderRadius`);\n }\n if (props.autoPage) {\n ctx.features.require('table-auto-page', `${path}.autoPage`);\n }\n if (props.autoPageRepeatHeader) {\n ctx.features.require('table-auto-page', `${path}.autoPageRepeatHeader`);\n }\n if (defaults.insetPoints !== undefined) {\n ctx.features.require('table-insets', `${path}.margin`);\n }\n rows.forEach((row, rowIndex) =>\n row.cells.forEach((cell, cellIndex) => {\n if (cell.formatting?.insetPoints !== undefined) {\n ctx.features.require(\n 'table-insets',\n `${path}.rows[${rowIndex}][${cellIndex}].margin`\n );\n }\n })\n );\n\n const element: PptxIrTableElement = {\n kind: 'table',\n id: scope.id,\n path,\n transform: tableTransform(props, ctx),\n rows,\n columnWidthsEmu: toEmuList(props.colW, 'X', ctx),\n rowHeightsEmu: toEmuList(props.rowH, 'Y', ctx),\n defaults,\n ...(border ? { border } : {}),\n ...(props.fill\n ? { fill: irColor(resolveColor(props.fill, ctx.theme, ctx.warnings)) }\n : {}),\n ...(cornerRadius !== undefined ? { cornerRadiusInches: cornerRadius } : {}),\n ...(props.autoPage ? { autoPage: true } : {}),\n ...(props.autoPageRepeatHeader ? { autoPageRepeatHeader: true } : {}),\n };\n return element;\n}\n\n/**\n * Table geometry.\n *\n * Width and height are marked auto when the author states neither, because an\n * OOXML table sizes from its columns and rows. Position resolves through the\n * same rule every other element uses — the pre-IR pipeline applied a different\n * inch/EMU threshold to tables than to shapes, which is a backend detail, not\n * an authoring rule (see docs/architecture/office-renderer-ir.md).\n */\nfunction tableTransform(\n props: Record<string, any>,\n ctx: CompileContext\n): PptxIrTransform {\n const hasWidth = props.w !== undefined;\n const hasHeight = props.h !== undefined;\n return {\n xEmu:\n props.x !== undefined ? resolveDimensionEmu(props.x, 'X', ctx.extent) : 0,\n yEmu:\n props.y !== undefined ? resolveDimensionEmu(props.y, 'Y', ctx.extent) : 0,\n widthEmu: hasWidth\n ? resolveDimensionEmu(props.w, 'X', ctx.extent)\n : defaultWidthEmu(ctx.extent),\n heightEmu: hasHeight ? resolveDimensionEmu(props.h, 'Y', ctx.extent) : 0,\n ...(hasWidth ? {} : { autoWidth: true }),\n ...(hasHeight ? {} : { autoHeight: true }),\n };\n}\n\nfunction toEmuList(\n value: number | number[] | undefined,\n axis: 'X' | 'Y',\n ctx: CompileContext\n): number[] {\n if (value === undefined) return [];\n const values = Array.isArray(value) ? value : [value];\n return values.map((v) => resolveDimensionEmu(v, axis, ctx.extent));\n}\n\nfunction compileTableDefaults(\n props: Record<string, any>,\n ctx: CompileContext\n): PptxIrTableFormatting {\n const family = (props.fontFace as string | undefined) ?? ctx.theme.fonts.body;\n let fontFamily = family;\n let bold: boolean | undefined;\n\n if (props.fontWeight != null) {\n const aliased = applyFontWeight({\n family,\n fontWeight: props.fontWeight as number,\n });\n if (aliased.fontFace !== undefined) fontFamily = aliased.fontFace;\n // Only ever true: a table-level `bold: false` is inert, because the cell\n // cascade ignores falsy table options.\n if (aliased.bold === true) bold = true;\n }\n\n return {\n fontFamily,\n fontSize:\n (props.fontSize as number | undefined) ?? ctx.theme.defaults.fontSize,\n ...(bold !== undefined ? { bold } : {}),\n ...(props.color\n ? { color: irColor(resolveColor(props.color, ctx.theme, ctx.warnings)) }\n : {}),\n ...(props.align\n ? { align: props.align as PptxIrTableFormatting['align'] }\n : {}),\n verticalAlign: (props.valign ??\n 'middle') as PptxIrTableFormatting['verticalAlign'],\n ...(props.margin !== undefined\n ? { insetPoints: props.margin as PptxIrTableFormatting['insetPoints'] }\n : {}),\n };\n}\n\nfunction compileTableCell(\n cell: string | AuthoredTableCell,\n tableProps: Record<string, any>,\n ctx: CompileContext\n): PptxIrTableCell {\n if (typeof cell === 'string') {\n return { text: forceTextPresentation(cell) };\n }\n\n const formatting: PptxIrTableCellFormatting = {};\n if (cell.color) {\n formatting.color = irColor(\n resolveColor(cell.color, ctx.theme, ctx.warnings)\n );\n }\n if (cell.fontSize) formatting.fontSize = cell.fontSize;\n if (cell.fontFace) formatting.fontFamily = cell.fontFace;\n // `!== undefined`, not truthiness: a table-level weight sets bold on every\n // cell that stays silent, so a cell meaning `false` has to say so.\n if (cell.bold !== undefined) formatting.bold = cell.bold;\n if (cell.italic) formatting.italic = true;\n\n if (cell.fontWeight != null || cell.bold !== undefined) {\n const aliased = applyFontWeight({\n family:\n cell.fontFace ??\n (tableProps.fontFace as string | undefined) ??\n ctx.theme.fonts.body,\n fontWeight: cell.fontWeight,\n italic: cell.italic,\n bold: cell.bold,\n });\n if (aliased.fontFace !== undefined)\n formatting.fontFamily = aliased.fontFace;\n if (aliased.bold !== undefined) formatting.bold = aliased.bold;\n if (aliased.italic !== undefined) formatting.italic = aliased.italic;\n }\n\n if (cell.align) {\n formatting.align = cell.align as PptxIrTableCellFormatting['align'];\n }\n if (cell.valign) {\n formatting.verticalAlign =\n cell.valign as PptxIrTableCellFormatting['verticalAlign'];\n }\n if (cell.margin !== undefined) {\n formatting.insetPoints =\n cell.margin as PptxIrTableCellFormatting['insetPoints'];\n }\n\n return {\n text: forceTextPresentation(cell.text),\n ...(Object.keys(formatting).length > 0 ? { formatting } : {}),\n ...(cell.fill\n ? { fill: irColor(resolveColor(cell.fill, ctx.theme, ctx.warnings)) }\n : {}),\n ...(cell.colspan !== undefined && cell.colspan > 1\n ? { colSpan: cell.colspan }\n : {}),\n ...(cell.rowspan !== undefined && cell.rowspan > 1\n ? { rowSpan: cell.rowspan }\n : {}),\n };\n}\n\nfunction compileTableBorder(\n border: { type?: string; pt?: number; color?: string } | undefined,\n ctx: CompileContext\n): PptxIrTableBorder | undefined {\n if (!border) return undefined;\n return {\n type: (border.type ?? 'solid') as PptxIrTableBorder['type'],\n widthPoints: border.pt ?? 1,\n color: irColor(\n resolveColor(border.color ?? '000000', ctx.theme, ctx.warnings)\n ),\n };\n}\n\n/* ------------------------------------------------------------------ *\n * Charts\n * ------------------------------------------------------------------ */\n\nconst CHART_TYPES: readonly PptxIrChartType[] = [\n 'area',\n 'bar',\n 'bar3D',\n 'bubble',\n 'doughnut',\n 'line',\n 'pie',\n 'radar',\n 'scatter',\n];\n\ninterface AuthoredChartSeries {\n name?: string;\n labels?: string[];\n values?: number[];\n sizes?: number[];\n}\n\n/**\n * Which capability each styling prop demands of a backend.\n *\n * Keyed by the *authored* prop name rather than by anything on the compiled\n * IR, and that is the whole point. `compileChartLabelFont` falls back to\n * `ctx.theme.fonts?.body` when a weight is authored without a face, so a\n * compiled font object can hold a family the author never wrote; asking the IR\n * \"was a font set here?\" would demand `chart-text-style` of a chart that only\n * styled its weight. The authored props are the only place the question has a\n * straight answer.\n *\n * Props absent from this table are ones every backend already honours — `type`,\n * `data`, `title`, `showLegend`, `legendPos`, `chartColors`, the axis titles,\n * `barDir`, `barGrouping` and the geometry.\n */\nconst CHART_STYLE_FEATURES: Readonly<Record<string, PptxFeature>> = {\n showValue: 'chart-data-labels',\n showPercent: 'chart-data-labels',\n showLabel: 'chart-data-labels',\n showSerName: 'chart-data-labels',\n dataLabelPosition: 'chart-data-labels',\n\n dataBorder: 'chart-data-border',\n\n catAxisHidden: 'chart-axis-visibility',\n valAxisHidden: 'chart-axis-visibility',\n catAxisLineShow: 'chart-axis-visibility',\n valAxisLineShow: 'chart-axis-visibility',\n\n catAxisLabelRotate: 'chart-axis-style',\n catGridLine: 'chart-axis-style',\n valGridLine: 'chart-axis-style',\n\n valAxisMinVal: 'chart-axis-scale',\n valAxisMaxVal: 'chart-axis-scale',\n valAxisMajorUnit: 'chart-axis-scale',\n valAxisLabelFormatCode: 'chart-axis-scale',\n\n barGapWidthPct: 'chart-bar-style',\n barOverlapPct: 'chart-bar-style',\n\n firstSliceAng: 'chart-pie-style',\n holeSize: 'chart-pie-style',\n\n lineSmooth: 'chart-line-style',\n lineDataSymbol: 'chart-line-style',\n lineSize: 'chart-line-style',\n lineDataSymbolSize: 'chart-line-style',\n\n radarStyle: 'chart-radar-style',\n\n titleFontSize: 'chart-text-style',\n titleColor: 'chart-text-style',\n titleFontFace: 'chart-text-style',\n titleFontWeight: 'chart-text-style',\n legendFontSize: 'chart-text-style',\n legendFontFace: 'chart-text-style',\n legendFontWeight: 'chart-text-style',\n legendColor: 'chart-text-style',\n catAxisLabelFontSize: 'chart-text-style',\n catAxisLabelColor: 'chart-text-style',\n catAxisLabelFontFace: 'chart-text-style',\n catAxisLabelFontWeight: 'chart-text-style',\n valAxisLabelFontSize: 'chart-text-style',\n valAxisLabelColor: 'chart-text-style',\n valAxisLabelFontFace: 'chart-text-style',\n valAxisLabelFontWeight: 'chart-text-style',\n dataLabelColor: 'chart-text-style',\n dataLabelFontSize: 'chart-text-style',\n dataLabelFontFace: 'chart-text-style',\n dataLabelFontWeight: 'chart-text-style',\n dataLabelFontBold: 'chart-text-style',\n};\n\n/**\n * Record what this chart's styling demands of a backend.\n *\n * One requirement per authored prop, at that prop's own path, so a renderer\n * that cannot express it refuses naming the line rather than the chart. A prop\n * set to `undefined` is not authored; a prop set to `false` is — an author who\n * turns a data label off means it, and a backend that ignores the instruction\n * draws a label they asked not to see.\n */\nfunction requireChartStyleFeatures(\n props: Record<string, unknown>,\n ctx: CompileContext,\n path: string\n): void {\n for (const [prop, feature] of Object.entries(CHART_STYLE_FEATURES)) {\n if (props[prop] === undefined) continue;\n ctx.features.require(feature, `${path}.${prop}`);\n }\n}\n\nfunction compileChart(\n component: PptxComponentInput,\n scope: ComponentScope\n): PptxIrElement | undefined {\n const { ctx, path } = scope;\n const props = component.props as Record<string, any>;\n\n const chartType = (CHART_TYPES as readonly string[]).includes(props.type)\n ? (props.type as PptxIrChartType)\n : undefined;\n if (!chartType) {\n warn(\n ctx.warnings,\n W.UNKNOWN_CHART_TYPE,\n `Unknown chart type: ${props.type}`,\n {\n component: 'chart',\n }\n );\n return undefined;\n }\n\n const authored = (props.data ?? []) as AuthoredChartSeries[];\n if (authored.length === 0) {\n warn(ctx.warnings, W.CHART_NO_DATA, 'Chart component has no data series', {\n component: 'chart',\n });\n return undefined;\n }\n for (const series of authored) {\n if (!series.labels || !series.values) {\n warn(\n ctx.warnings,\n W.CHART_INVALID_SERIES,\n `Chart series \"${series.name ?? '(unnamed)'}\" missing labels or values`,\n { component: 'chart' }\n );\n return undefined;\n }\n }\n if (\n (chartType === 'pie' || chartType === 'doughnut') &&\n authored.length > 1\n ) {\n warn(\n ctx.warnings,\n W.CHART_MULTI_SERIES,\n `${props.type} chart has ${authored.length} series — only the first will render`,\n { component: 'chart' }\n );\n }\n\n ctx.features.require('charts', path);\n requireChartStyleFeatures(props, ctx, path);\n\n return {\n kind: 'chart',\n id: scope.id,\n path,\n transform: shapeTransform(props, ctx),\n chartType,\n series: authored.map((series) => ({\n ...(series.name !== undefined ? { name: series.name } : {}),\n ...(series.labels ? { labels: series.labels } : {}),\n ...(series.values ? { values: series.values } : {}),\n ...(series.sizes ? { sizes: series.sizes } : {}),\n })),\n options: compileChartOptions(props, ctx),\n };\n}\n\n/**\n * Resolve a chart label font.\n *\n * PowerPoint chart labels carry no numeric weight, so a non-RIBBI weight only\n * survives as a synthesized sub-family (\"Inter\" at 300 → \"Inter Light\");\n * 400/700 stay on the family and use the slot's bold toggle. `hasBoldToggle`\n * is false for the legend, which has none — a weight that would need one is\n * reported rather than silently rendered as Regular.\n */\nfunction compileChartLabelFont(\n ctx: CompileContext,\n slot: string,\n face: string | undefined,\n weight: number | undefined,\n hasBoldToggle: boolean,\n extra: {\n fontSize?: number;\n color?: PptxIrColor;\n /** Bold set alongside the weight; an explicit weight overrides it. */\n boldFallback?: boolean;\n } = {}\n): PptxIrChartLabelFont {\n const { boldFallback, ...rest } = extra;\n const font: PptxIrChartLabelFont = { ...rest };\n if (boldFallback !== undefined) font.bold = boldFallback;\n\n if (weight === undefined) {\n if (face !== undefined) font.fontFamily = face;\n return font;\n }\n\n const aliased = applyFontWeight({\n family: face ?? ctx.theme.fonts?.body,\n fontWeight: weight,\n });\n if (aliased.fontFace !== undefined) font.fontFamily = aliased.fontFace;\n if (hasBoldToggle) {\n // Assign even when false: an explicit weight has to win over a bold\n // toggle set alongside it.\n font.bold = aliased.bold === true;\n } else if (aliased.bold === true) {\n warn(\n ctx.warnings,\n W.CHART_FONT_WEIGHT_DROPPED,\n `Chart ${slot} weight ${weight} renders as Regular — PowerPoint gives the legend no bold toggle, and only non-RIBBI weights resolve to a sub-family face`,\n { component: 'chart' }\n );\n }\n return font;\n}\n\nfunction compileChartOptions(\n props: Record<string, any>,\n ctx: CompileContext\n): PptxIrChartOptions {\n // Author-supplied colours keep the loud fallback for an undefined token; the\n // implicit palette skips tokens the theme leaves unset or unresolvable, which\n // is what DOCX does too. An empty list stays empty so the backend uses its\n // own — a zero-length palette would paint every series black.\n const colorSources: string[] =\n props.chartColors ?? definedChartColorTokens(ctx.theme);\n const colors = colorSources.map((color) =>\n resolveColor(color, ctx.theme, ctx.warnings).toUpperCase()\n );\n\n const themeTextColor = irColor(resolveColor('text', ctx.theme, ctx.warnings));\n const resolved = (value: string | undefined): PptxIrColor =>\n value\n ? irColor(resolveColor(value, ctx.theme, ctx.warnings))\n : themeTextColor;\n\n return {\n colors,\n\n ...pick(props, {\n showLegend: 'showLegend',\n showTitle: 'showTitle',\n showValue: 'showValue',\n showPercent: 'showPercent',\n showLabel: 'showLabel',\n showSeriesName: 'showSerName',\n }),\n\n ...(props.title !== undefined ? { title: props.title as string } : {}),\n titleFont: compileChartLabelFont(\n ctx,\n 'titleFontFace',\n props.titleFontFace,\n props.titleFontWeight,\n true,\n {\n ...(props.titleFontSize !== undefined\n ? { fontSize: props.titleFontSize as number }\n : {}),\n color: resolved(props.titleColor),\n }\n ),\n\n ...(props.legendPos !== undefined\n ? { legendPosition: props.legendPos as string }\n : {}),\n legendFont: compileChartLabelFont(\n ctx,\n 'legendFontFace',\n props.legendFontFace,\n props.legendFontWeight,\n false,\n {\n ...(props.legendFontSize !== undefined\n ? { fontSize: props.legendFontSize as number }\n : {}),\n color: resolved(props.legendColor),\n }\n ),\n\n categoryAxis: {\n ...(props.catAxisTitle !== undefined\n ? { title: props.catAxisTitle as string }\n : {}),\n ...(props.catAxisHidden !== undefined\n ? { hidden: props.catAxisHidden as boolean }\n : {}),\n ...(props.catAxisLabelRotate !== undefined\n ? { labelRotate: props.catAxisLabelRotate as number }\n : {}),\n ...(props.catAxisLineShow !== undefined\n ? { showLine: props.catAxisLineShow as boolean }\n : {}),\n ...(props.catGridLine !== undefined\n ? { gridLine: compileGridLine(props.catGridLine, ctx) }\n : {}),\n labelFont: compileChartLabelFont(\n ctx,\n 'catAxisLabelFontFace',\n props.catAxisLabelFontFace,\n props.catAxisLabelFontWeight,\n true,\n {\n ...(props.catAxisLabelFontSize !== undefined\n ? { fontSize: props.catAxisLabelFontSize as number }\n : {}),\n color: resolved(props.catAxisLabelColor),\n }\n ),\n },\n\n valueAxis: {\n ...(props.valAxisTitle !== undefined\n ? { title: props.valAxisTitle as string }\n : {}),\n ...(props.valAxisHidden !== undefined\n ? { hidden: props.valAxisHidden as boolean }\n : {}),\n ...(props.valAxisMinVal !== undefined\n ? { minValue: props.valAxisMinVal as number }\n : {}),\n ...(props.valAxisMaxVal !== undefined\n ? { maxValue: props.valAxisMaxVal as number }\n : {}),\n ...(props.valAxisMajorUnit !== undefined\n ? { majorUnit: props.valAxisMajorUnit as number }\n : {}),\n ...(props.valAxisLabelFormatCode !== undefined\n ? { labelFormatCode: props.valAxisLabelFormatCode as string }\n : {}),\n ...(props.valAxisLineShow !== undefined\n ? { showLine: props.valAxisLineShow as boolean }\n : {}),\n ...(props.valGridLine !== undefined\n ? { gridLine: compileGridLine(props.valGridLine, ctx) }\n : {}),\n labelFont: compileChartLabelFont(\n ctx,\n 'valAxisLabelFontFace',\n props.valAxisLabelFontFace,\n props.valAxisLabelFontWeight,\n true,\n {\n ...(props.valAxisLabelFontSize !== undefined\n ? { fontSize: props.valAxisLabelFontSize as number }\n : {}),\n color: resolved(props.valAxisLabelColor),\n }\n ),\n },\n\n ...(props.dataBorder !== undefined\n ? {\n dataBorder: {\n widthPoints: props.dataBorder.pt as number,\n color: irColor(\n resolveColor(props.dataBorder.color, ctx.theme, ctx.warnings)\n ),\n },\n }\n : {}),\n dataLabelFont: compileChartLabelFont(\n ctx,\n 'dataLabelFontFace',\n props.dataLabelFontFace,\n props.dataLabelFontWeight,\n true,\n {\n ...(props.dataLabelFontSize !== undefined\n ? { fontSize: props.dataLabelFontSize as number }\n : {}),\n color: resolved(props.dataLabelColor),\n ...(props.dataLabelFontBold !== undefined\n ? { boldFallback: props.dataLabelFontBold as boolean }\n : {}),\n }\n ),\n ...(props.dataLabelPosition !== undefined\n ? { dataLabelPosition: props.dataLabelPosition as string }\n : {}),\n\n ...pick(props, {\n barDirection: 'barDir',\n barGrouping: 'barGrouping',\n barGapWidthPercent: 'barGapWidthPct',\n barOverlapPercent: 'barOverlapPct',\n lineSmooth: 'lineSmooth',\n lineDataSymbol: 'lineDataSymbol',\n lineSize: 'lineSize',\n lineDataSymbolSize: 'lineDataSymbolSize',\n firstSliceAngle: 'firstSliceAng',\n holeSize: 'holeSize',\n radarStyle: 'radarStyle',\n }),\n };\n}\n\n/** Copy authored props onto IR names, skipping anything the author omitted. */\nfunction pick(\n props: Record<string, any>,\n mapping: Record<string, string>\n): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const [irName, authoredName] of Object.entries(mapping)) {\n if (props[authoredName] !== undefined) out[irName] = props[authoredName];\n }\n return out;\n}\n\nfunction compileGridLine(\n gridLine: { style?: string; size?: number; color?: string },\n ctx: CompileContext\n): PptxIrChartGridLine {\n return {\n ...(gridLine.style !== undefined ? { style: gridLine.style } : {}),\n ...(gridLine.size !== undefined ? { size: gridLine.size } : {}),\n ...(gridLine.color !== undefined\n ? {\n color: irColor(resolveColor(gridLine.color, ctx.theme, ctx.warnings)),\n }\n : {}),\n };\n}\n\n/* ------------------------------------------------------------------ *\n * Shared: fills, lines, shadows, hyperlinks, backgrounds\n * ------------------------------------------------------------------ */\n\nfunction compileBackground(\n background:\n | {\n color?: string;\n gradient?: unknown;\n image?: { path?: string; base64?: string };\n }\n | undefined,\n path: string,\n ctx: CompileContext\n): PptxIrBackground | undefined {\n if (!background) return undefined;\n\n if (background.color) {\n return {\n kind: 'solid',\n color: irColor(resolveColor(background.color, ctx.theme, ctx.warnings)),\n };\n }\n\n if (background.image) {\n const source = resolveImageSource(background.image);\n if (!source) return undefined;\n const resourceId = internImageSource(source, path, ctx);\n return resourceId === undefined ? undefined : { kind: 'image', resourceId };\n }\n\n return undefined;\n}\n\nfunction compileFill(\n fill:\n | {\n color?: string;\n transparency?: number;\n gradient?: unknown;\n pattern?: { preset: string; foreground: string; background: string };\n }\n | undefined,\n path: string,\n ctx: CompileContext\n): PptxIrFill | undefined {\n if (!fill) return undefined;\n\n let gradient = fill.gradient;\n let pattern = fill.pattern;\n\n if (gradient && pattern) {\n warn(\n ctx.warnings,\n W.ADVANCED_FILL_FALLBACK,\n 'Shape fill sets both \"gradient\" and \"pattern\" — using the gradient',\n { component: 'shape' }\n );\n pattern = undefined;\n }\n\n let unknownPresetForeground: string | undefined;\n if (\n pattern &&\n !(PATTERN_FILL_PRESETS as readonly string[]).includes(pattern.preset)\n ) {\n warn(\n ctx.warnings,\n W.UNKNOWN_PATTERN_PRESET,\n `Unknown pattern preset \"${pattern.preset}\" — falling back to solid foreground`,\n { component: 'shape' }\n );\n unknownPresetForeground = pattern.foreground;\n pattern = undefined;\n }\n\n if (gradient) {\n const compiled = compileGradient(gradient, path, ctx);\n if (compiled) return { kind: 'gradient', gradient: compiled };\n }\n\n if (pattern) {\n return {\n kind: 'pattern',\n preset: pattern.preset,\n foreground: irColor(\n resolveColor(pattern.foreground, ctx.theme, ctx.warnings)\n ),\n background: irColor(\n resolveColor(pattern.background, ctx.theme, ctx.warnings)\n ),\n };\n }\n\n const solid = fill.color ?? unknownPresetForeground;\n if (solid === undefined) return undefined;\n return {\n kind: 'solid',\n color: irColor(\n resolveColor(solid, ctx.theme, ctx.warnings),\n fill.transparency\n ),\n };\n}\n\nfunction compileSolidFillFromProps(\n fill: { color: string; transparency?: number },\n path: string,\n ctx: CompileContext\n): PptxIrFill | undefined {\n void path;\n return {\n kind: 'solid',\n color: irColor(\n resolveColor(fill.color, ctx.theme, ctx.warnings),\n fill.transparency\n ),\n };\n}\n\nfunction requireFillFeature(\n fill: PptxIrFill,\n path: string,\n ctx: CompileContext\n): void {\n switch (fill.kind) {\n case 'solid':\n ctx.features.require('solid-fills', path);\n return;\n case 'gradient':\n ctx.features.require('gradient-fills', path);\n return;\n case 'pattern':\n ctx.features.require('pattern-fills', path);\n return;\n case 'image':\n ctx.features.require('image-fills', path);\n return;\n case 'none':\n return;\n }\n}\n\nfunction compileGradient(\n gradient: unknown,\n path: string,\n ctx: CompileContext\n): PptxIrGradient | undefined {\n if (!gradient || typeof gradient !== 'object') return undefined;\n const source = gradient as {\n type?: string;\n angle?: number;\n focus?: string;\n stops?: Array<{ color: string; pos: number; transparency?: number }>;\n };\n const stops = (source.stops ?? []).map((stop) => ({\n position: stop.pos,\n color: irColor(\n resolveColor(stop.color, ctx.theme, ctx.warnings),\n stop.transparency\n ),\n }));\n if (stops.length === 0) {\n warn(\n ctx.warnings,\n W.ADVANCED_FILL_FALLBACK,\n `Gradient at ${path} has no stops — ignored`,\n { component: 'shape' }\n );\n return undefined;\n }\n\n if (source.type === 'radial') {\n return {\n type: 'radial',\n focus: (source.focus ?? 'center') as PptxIrGradient extends {\n focus: infer F;\n }\n ? F\n : never,\n stops,\n } as PptxIrGradient;\n }\n\n return {\n type: 'linear',\n angleDegrees: normalizeDegrees(source.angle ?? 0),\n stops,\n };\n}\n\nfunction compileLine(\n line: { color?: string; width?: number; dashType?: string } | undefined,\n ctx: CompileContext\n): PptxIrLine | undefined {\n if (!line) return undefined;\n const compiled: PptxIrLine = {};\n if (line.color) {\n compiled.color = irColor(resolveColor(line.color, ctx.theme, ctx.warnings));\n }\n if (line.width !== undefined) compiled.widthPoints = line.width;\n if (line.dashType) compiled.dash = line.dashType as PptxIrLine['dash'];\n // An empty `line: {}` is an authored request for the format's default\n // outline, which is not the same as no outline at all.\n return compiled;\n}\n\nfunction compileShadow(\n shadow:\n | {\n type?: string;\n color?: string;\n blur?: number;\n offset?: number;\n angle?: number;\n opacity?: number;\n }\n | undefined,\n ctx: CompileContext\n): PptxIrShadow | undefined {\n if (!shadow) return undefined;\n return {\n type: (shadow.type ?? 'outer') as PptxIrShadow['type'],\n color: irColor(\n resolveColor(shadow.color ?? '000000', ctx.theme, ctx.warnings)\n ),\n blurPoints: shadow.blur ?? 3,\n offsetPoints: shadow.offset ?? 3,\n angleDegrees: shadow.angle ?? 45,\n opacity: shadow.opacity ?? 0.5,\n };\n}\n\n/**\n * Compile a hyperlink, dropping unresolvable slide refs with a warning.\n *\n * An unresolved ref must never reach a renderer: it would emit a relationship\n * to a slide part that is not in the archive, which PowerPoint reports as a\n * damaged file.\n */\nfunction compileHyperlink(\n hyperlink: HyperlinkProps | undefined,\n componentName: string,\n ctx: CompileContext,\n path: string\n): PptxIrHyperlink | undefined {\n if (!hyperlink) return undefined;\n\n if (hyperlink.url) {\n ctx.features.require('external-links', path);\n return {\n kind: 'external',\n url: hyperlink.url,\n ...(hyperlink.tooltip ? { tooltip: hyperlink.tooltip } : {}),\n };\n }\n\n if (hyperlink.unresolvedSlideRef != null) {\n // HYPERLINK_SLIDE_UNRESOLVED lives outside the `W` registry (it is owned by\n // utils/hyperlink.ts), so push it the same way `applyHyperlink` does.\n ctx.warnings.push({\n code: HYPERLINK_SLIDE_UNRESOLVED,\n message:\n `hyperlink.slide ${hyperlink.unresolvedSlideRef} matches no slide in the generated ` +\n `presentation (slide disabled, or index out of range) — hyperlink dropped`,\n component: componentName,\n });\n return undefined;\n }\n\n if (hyperlink.slide) {\n ctx.features.require('internal-links', path);\n return {\n kind: 'slide',\n slideIndex: hyperlink.slide,\n ...(hyperlink.tooltip ? { tooltip: hyperlink.tooltip } : {}),\n };\n }\n\n return undefined;\n}\n\nfunction optionalTransform(\n x: number | undefined,\n y: number | undefined,\n w: number | undefined,\n h: number | undefined,\n ctx: CompileContext\n): PptxIrTransform | undefined {\n if (x == null && y == null && w == null && h == null) return undefined;\n return {\n xEmu: inchesToEmu(x ?? 0),\n yEmu: inchesToEmu(y ?? 0),\n widthEmu: w != null ? inchesToEmu(w) : defaultWidthEmu(ctx.extent),\n heightEmu: h != null ? inchesToEmu(h) : 0,\n };\n}\n","/**\n * Color utilities for PPTX generation.\n * pptxgenjs expects bare 6-char hex (e.g. 'FF0000'), but our theme\n * convention uses '#'-prefixed values (e.g. '#FF0000').\n */\n\nimport type { PptxThemeConfig, PipelineWarning } from '../types';\nimport { SEMANTIC_COLOR_NAMES } from '@json-to-office/shared-pptx';\nimport { DEFAULT_CHART_THEME_COLORS } from '@json-to-office/shared';\nimport { warn, W } from './warn';\n\n// Build identity entries from the shared source of truth, then add aliases\nconst SEMANTIC_TO_THEME_KEY: Record<string, keyof PptxThemeConfig['colors']> = {\n ...Object.fromEntries(SEMANTIC_COLOR_NAMES.map((n) => [n, n])),\n // Aliases (PowerPoint XML compat)\n accent1: 'primary',\n accent2: 'secondary',\n accent3: 'accent',\n tx1: 'text',\n tx2: 'text2',\n bg1: 'background',\n bg2: 'background2',\n};\n\n/**\n * Default series-color tokens for charts, used by the native `chart` component\n * and the `highcharts` component. Defined in @json-to-office/shared so the DOCX\n * `highcharts` component resolves the same tokens; re-exported here because\n * every PPTX call site already imports colors from this module.\n */\nexport { DEFAULT_CHART_THEME_COLORS };\n\n/**\n * Follow a stored theme color value to bare hex, or undefined when it never\n * reaches one. The theme schema lets a slot name another slot\n * (`\"accent4\": \"primary\"`), so a stored value is only a color once the\n * reference chain has been walked — without this, `accent4` resolved to the\n * literal string `primary` and pptxgenjs silently painted the series black.\n *\n * Mirrors DOCX `toChartColor`/`resolveColor` (core-docx colorUtils) on casing:\n * the stored value passes through verbatim when it is already hex, and anything\n * reached by following a reference is normalized to uppercase. Two deliberate\n * divergences: `seen` turns a reference cycle into \"unresolvable\" instead of the\n * stack overflow the DOCX version would hit, and 3-char shorthand is expanded\n * here but not by DOCX, so `\"accent4\": \"#abc\"` fills the slot in a deck and\n * drops it in a document.\n */\nfunction chainToHex(\n value: string,\n theme: PptxThemeConfig,\n seen: Set<string>\n): string | undefined {\n const bare = value.startsWith('#') ? value.slice(1) : value;\n if (/^[0-9A-Fa-f]{6}$/.test(bare)) return bare;\n // Expand 3-char hex shorthand (e.g. 'FFF' → 'FFFFFF')\n if (/^[0-9A-Fa-f]{3}$/.test(bare)) {\n return bare[0] + bare[0] + bare[1] + bare[1] + bare[2] + bare[2];\n }\n const themeKey = SEMANTIC_TO_THEME_KEY[value];\n if (!themeKey || seen.has(themeKey)) return undefined;\n seen.add(themeKey);\n const next = theme?.colors?.[themeKey];\n if (typeof next !== 'string' || next.length === 0) return undefined;\n return chainToHex(next, theme, seen)?.toUpperCase();\n}\n\n/**\n * The default chart palette narrowed to the tokens this theme actually defines\n * *and* can resolve to a color. Both PPTX chart paths build their implicit\n * palette from this, so an unset accent4-6 is skipped — matching DOCX — instead\n * of resolving to `primary` six times over, and a slot holding an unresolvable\n * value is dropped rather than posted as `#primary`. Author-supplied colors must\n * NOT go through here: naming an undefined token stays a loud `resolveColor`\n * fallback + warning.\n */\nexport function definedChartColorTokens(theme: PptxThemeConfig): string[] {\n const colors = theme?.colors as\n | Record<string, string | undefined>\n | undefined;\n if (!colors) return [];\n return DEFAULT_CHART_THEME_COLORS.filter((token) => {\n const themeKey = SEMANTIC_TO_THEME_KEY[token] ?? token;\n const value = colors[themeKey];\n if (typeof value !== 'string' || value.length === 0) return false;\n return chainToHex(value, theme, new Set([themeKey])) !== undefined;\n });\n}\n\n/**\n * Resolve a color value to bare hex (no '#' prefix).\n * Accepts hex colors (with or without '#') or semantic theme color names.\n */\nexport function resolveColor(\n color: string,\n theme: PptxThemeConfig,\n warnings?: PipelineWarning[]\n): string {\n const themeKey = SEMANTIC_TO_THEME_KEY[color];\n if (themeKey) {\n const resolved = theme.colors[themeKey];\n if (resolved) {\n const hex = chainToHex(resolved, theme, new Set([themeKey]));\n if (hex) return hex;\n // Defined but not a color (e.g. a name reference that goes nowhere).\n // Never hand the literal on to pptxgenjs — it renders black in silence.\n warn(\n warnings,\n W.UNKNOWN_COLOR,\n `Theme color \"${themeKey}\" is \"${resolved}\", which is not a hex color or a theme color name; falling back to primary`\n );\n return resolvePrimary(theme);\n }\n // Fall back to primary for unset optional colors\n warn(\n warnings,\n W.THEME_COLOR_FALLBACK,\n `Theme color \"${themeKey}\" not defined, falling back to primary`\n );\n return resolvePrimary(theme);\n }\n // Not a semantic name — treat as literal hex\n const bare = color.startsWith('#') ? color.slice(1) : color;\n // Expand 3-char hex shorthand (e.g. 'FFF' → 'FFFFFF')\n if (/^[0-9A-Fa-f]{3}$/.test(bare)) {\n return bare[0] + bare[0] + bare[1] + bare[1] + bare[2] + bare[2];\n }\n if (!/^[0-9A-Fa-f]{6}$/.test(bare)) {\n warn(\n warnings,\n W.UNKNOWN_COLOR,\n `Unknown color value: \"${color}\", treating as literal`\n );\n }\n return bare;\n}\n\n/** The `primary` fallback, itself chain-resolved so it can't leak a token name. */\nfunction resolvePrimary(theme: PptxThemeConfig): string {\n const primary = theme.colors.primary;\n return (\n chainToHex(primary, theme, new Set(['primary'])) ??\n (primary.startsWith('#') ? primary.slice(1) : primary)\n );\n}\n","/**\n * Resolve (family, weight, italic) into the PPTX run's final `(fontFace,\n * bold, italic)` triple. Non-RIBBI weights are rewritten to synthetic\n * sub-family names (e.g. \"Inter Light\") so PowerPoint / LibreOffice can\n * resolve the matching installed face; RIBBI stays on the canonical\n * family and uses native bold/italic toggles.\n *\n * Mirrors the DOCX `applyFontWeightAlias` helper so both cores coerce\n * fontWeight identically.\n */\n\nimport { synthesizeFamilyName } from '@json-to-office/shared';\n\nexport function applyFontWeight(params: {\n family?: string;\n fontWeight?: number;\n italic?: boolean;\n bold?: boolean;\n}): { fontFace?: string; bold?: boolean; italic?: boolean } {\n if (!params.family) {\n const weight =\n params.fontWeight ?? (params.bold === true ? 700 : undefined);\n return {\n bold: weight != null ? weight >= 600 : params.bold,\n italic: params.italic,\n };\n }\n const weight = params.fontWeight ?? (params.bold === true ? 700 : undefined);\n const synth = synthesizeFamilyName(\n params.family,\n weight,\n params.italic === true\n );\n return { fontFace: synth.family, bold: synth.bold, italic: synth.italic };\n}\n","/**\n * PPTX Component Default Resolution System\n * Provides theme-based default configurations for components\n */\n\nimport type { PptxThemeConfig } from '../types';\nimport type {\n PptxComponentDefaults,\n TextComponentDefaults,\n ImageComponentDefaults,\n ShapeComponentDefaults,\n TableComponentDefaults,\n HighchartsComponentDefaults,\n ChartComponentDefaults,\n TextProps,\n PptxImageProps,\n ShapeProps,\n PptxTableProps,\n PptxHighchartsProps,\n PptxChartProps,\n} from '@json-to-office/shared-pptx';\nimport { mergeWithDefaults } from '@json-to-office/shared';\n\n// ── Getters ──────────────────────────────────────────────────────────\n\nexport function getComponentDefaults(\n theme: PptxThemeConfig\n): PptxComponentDefaults {\n return theme.componentDefaults || {};\n}\n\nexport function getTextDefaults(theme: PptxThemeConfig): TextComponentDefaults {\n return getComponentDefaults(theme).text || {};\n}\n\nexport function getImageDefaults(\n theme: PptxThemeConfig\n): ImageComponentDefaults {\n return getComponentDefaults(theme).image || {};\n}\n\nexport function getShapeDefaults(\n theme: PptxThemeConfig\n): ShapeComponentDefaults {\n return getComponentDefaults(theme).shape || {};\n}\n\nexport function getTableDefaults(\n theme: PptxThemeConfig\n): TableComponentDefaults {\n return getComponentDefaults(theme).table || {};\n}\n\nexport function getHighchartsDefaults(\n theme: PptxThemeConfig\n): HighchartsComponentDefaults {\n return getComponentDefaults(theme).highcharts || {};\n}\n\nexport function getChartDefaults(\n theme: PptxThemeConfig\n): ChartComponentDefaults {\n return getComponentDefaults(theme).chart || {};\n}\n\nexport function getCustomComponentDefaults(\n theme: PptxThemeConfig,\n componentName: string\n): Record<string, unknown> {\n const defaults = getComponentDefaults(theme);\n return ((defaults as any)?.[componentName] as Record<string, unknown>) || {};\n}\n\n// ── Resolvers ────────────────────────────────────────────────────────\n\nexport function resolveTextProps(\n props: TextProps,\n theme: PptxThemeConfig\n): TextProps {\n return mergeWithDefaults(props, getTextDefaults(theme));\n}\n\nexport function resolveImageProps(\n props: PptxImageProps,\n theme: PptxThemeConfig\n): PptxImageProps {\n return mergeWithDefaults(props, getImageDefaults(theme));\n}\n\nexport function resolveShapeProps(\n props: ShapeProps,\n theme: PptxThemeConfig\n): ShapeProps {\n return mergeWithDefaults(props, getShapeDefaults(theme));\n}\n\nexport function resolveTableProps(\n props: PptxTableProps,\n theme: PptxThemeConfig\n): PptxTableProps {\n return mergeWithDefaults(props, getTableDefaults(theme));\n}\n\nexport function resolveHighchartsProps(\n props: PptxHighchartsProps,\n theme: PptxThemeConfig\n): PptxHighchartsProps {\n return mergeWithDefaults(props, getHighchartsDefaults(theme));\n}\n\nexport function resolveChartProps(\n props: PptxChartProps,\n theme: PptxThemeConfig\n): PptxChartProps {\n return mergeWithDefaults(props, getChartDefaults(theme));\n}\n\nexport function resolveCustomComponentProps<T extends Record<string, unknown>>(\n props: T,\n theme: PptxThemeConfig,\n componentName: string\n): T {\n const defaults = getCustomComponentDefaults(theme, componentName);\n return mergeWithDefaults(props, defaults as Partial<T>);\n}\n\n// ── Generic lookup ───────────────────────────────────────────────────\n\nconst TYPE_GETTERS: Record<\n string,\n (t: PptxThemeConfig) => Record<string, unknown>\n> = {\n text: getTextDefaults,\n image: getImageDefaults,\n shape: getShapeDefaults,\n table: getTableDefaults,\n highcharts: getHighchartsDefaults,\n chart: getChartDefaults,\n};\n\n/**\n * Get the flat componentDefaults object for a given component type.\n * Use this when you need the raw defaults without merging into props\n * (e.g. for injecting into a multi-layer shallow spread).\n */\nexport function getDefaultsForType(\n componentName: string,\n theme: PptxThemeConfig\n): Record<string, unknown> {\n const getter = TYPE_GETTERS[componentName];\n return getter\n ? getter(theme)\n : getCustomComponentDefaults(theme, componentName);\n}\n","/**\n * Centralized Component Defaults Resolution\n * Walks the component tree and resolves theme componentDefaults\n * on every component before any rendering or structure processing.\n */\n\nimport type { PptxComponentInput, PptxThemeConfig } from '../types';\nimport {\n resolveTextProps,\n resolveImageProps,\n resolveShapeProps,\n resolveTableProps,\n resolveHighchartsProps,\n resolveChartProps,\n resolveCustomComponentProps,\n} from './componentDefaults';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- resolver map needs wide input to accept all prop types\ntype Resolver = (props: any, theme: PptxThemeConfig) => Record<string, unknown>;\n\nconst RESOLVER_MAP: Record<string, Resolver> = {\n text: resolveTextProps,\n image: resolveImageProps,\n shape: resolveShapeProps,\n table: resolveTableProps,\n highcharts: resolveHighchartsProps,\n chart: resolveChartProps,\n};\n\n/**\n * Resolve componentDefaults for a single component.\n * Known components use their typed resolver; unknown names\n * fall back to resolveCustomComponentProps.\n */\nexport function resolveComponentDefaults(\n component: PptxComponentInput,\n theme: PptxThemeConfig\n): PptxComponentInput {\n const resolver = RESOLVER_MAP[component.name];\n const resolvedProps = resolver\n ? resolver(component.props, theme)\n : resolveCustomComponentProps(\n component.props as Record<string, unknown>,\n theme,\n component.name\n );\n\n return { ...component, props: resolvedProps };\n}\n\n/**\n * Recursively walk the component tree and resolve componentDefaults\n * on every component. Returns a new tree (no mutation).\n */\nexport function resolveComponentTree(\n components: PptxComponentInput[],\n theme: PptxThemeConfig\n): PptxComponentInput[] {\n return components.map((component) => {\n const resolved = resolveComponentDefaults(component, theme);\n\n if (resolved.children && resolved.children.length > 0) {\n return {\n ...resolved,\n children: resolveComponentTree(resolved.children, theme),\n };\n }\n\n return resolved;\n });\n}\n","/**\n * Image source resolution (PPTX)\n *\n * Resolves the three mutually-exclusive image sources into a single string that\n * can be probed and handed to pptxgenjs. Precedence mirrors core-docx:\n * `svg > base64 > path`. Raw SVG markup is wrapped into an `image/svg+xml`\n * data URI so it embeds as a vector (PowerPoint 2016+).\n */\nimport path from 'node:path';\nimport { getBaseDir, resolveFromBaseDir } from './baseDirContext';\n\n/** A source field counts only when it carries a non-empty (non-whitespace) value. */\nconst hasValue = (v?: string): v is string =>\n typeof v === 'string' && v.trim().length > 0;\n\nexport function resolveImageSource(props: {\n svg?: string;\n base64?: string;\n path?: string;\n}): string | undefined {\n if (hasValue(props.svg)) {\n const encoded = Buffer.from(props.svg, 'utf-8').toString('base64');\n return `data:image/svg+xml;base64,${encoded}`;\n }\n // Mirror the conflict-validator predicate: blank base64/path are treated as\n // absent, so a whitespace-only value can't shadow a real later source.\n if (hasValue(props.base64)) return props.base64;\n if (hasValue(props.path)) return props.path;\n return undefined;\n}\n\n/**\n * Local files must live under the document base directory (when set) or CWD —\n * path-traversal guard (#142). `resolved` must already be absolute.\n */\nexport function isAllowedLocalPath(resolved: string): boolean {\n const baseDir = getBaseDir();\n const allowedRoots = baseDir ? [baseDir, process.cwd()] : [process.cwd()];\n return allowedRoots.some(\n (root) => resolved.startsWith(root + path.sep) || resolved === root\n );\n}\n\n/**\n * Resolve a source string that may be a URL, data URI, or local file path:\n * URLs and data URIs pass through; local paths resolve against the active\n * document base directory when the generation scope set one, eagerly —\n * pptxgenjs reads `path` entries during write(), outside the generation\n * scope. Returns `undefined` when a local path escapes the allowed roots, so\n * out-of-root paths never reach pptxgenjs (#142).\n */\nexport function safeLocalPath(source: string): string | undefined {\n if (/^(https?:\\/\\/|data:)/.test(source)) return source;\n const resolved = path.resolve(resolveFromBaseDir(source));\n return isAllowedLocalPath(resolved) ? resolved : undefined;\n}\n","/**\n * Slide-targeted hyperlinks\n *\n * `hyperlink.slide` is 1-based over the slides *as authored* in the JSON —\n * slides carrying `enabled: false` still count. Structure processing remaps\n * every ref to the position its target ends up at in the generated deck, so\n * toggling one slide off never silently retargets the links after it.\n *\n * A ref that cannot be resolved — target dropped, or index outside the\n * authored range — is marked unresolved here and dropped by the writer with a\n * warning. It must never reach pptxgenjs: it would emit a relationship to a\n * `slideN.xml` part that is not in the archive, which PowerPoint reports as a\n * damaged file.\n */\n\nimport type { PipelineWarning, PptxComponentInput } from '../types';\n\nexport const HYPERLINK_SLIDE_UNRESOLVED = 'HYPERLINK_SLIDE_UNRESOLVED';\n\nexport interface HyperlinkProps {\n url?: string;\n slide?: number;\n tooltip?: string;\n /** Internal: authored `slide` ref that resolves to no rendered slide. */\n unresolvedSlideRef?: number;\n}\n\n/** Authored 1-based slide number -> rendered 1-based slide number. */\nexport type SlideIndexMap = ReadonlyMap<number, number>;\n\nfunction remapHyperlink(\n hyperlink: HyperlinkProps,\n map: SlideIndexMap\n): HyperlinkProps {\n // `url` wins over `slide` at write time, so leave those refs alone.\n if (hyperlink.url || hyperlink.slide == null) return hyperlink;\n\n const rendered = map.get(hyperlink.slide);\n if (rendered === undefined) {\n const { slide, ...rest } = hyperlink;\n return { ...rest, unresolvedSlideRef: slide };\n }\n return rendered === hyperlink.slide\n ? hyperlink\n : { ...hyperlink, slide: rendered };\n}\n\n/**\n * Rewrite `hyperlink.slide` in a bare props bag. Template placeholder\n * `defaults` are merged into a component at render time without ever being a\n * component themselves, so they need rebasing on their own — otherwise a\n * `defaults.props.hyperlink.slide` reaches the writer as a raw authored index.\n */\nexport function remapHyperlinkProps<T extends Record<string, unknown>>(\n props: T,\n map: SlideIndexMap\n): T {\n const hyperlink = props.hyperlink as HyperlinkProps | undefined;\n if (!hyperlink || typeof hyperlink !== 'object') return props;\n\n const remapped = remapHyperlink(hyperlink, map);\n return remapped === hyperlink ? props : { ...props, hyperlink: remapped };\n}\n\n/** Rewrite every `hyperlink.slide` in a component subtree. Returns a new tree. */\nexport function remapHyperlinkSlideRefs(\n component: PptxComponentInput,\n map: SlideIndexMap\n): PptxComponentInput {\n const hyperlink = component.props?.hyperlink as HyperlinkProps | undefined;\n let next = component;\n\n if (hyperlink && typeof hyperlink === 'object') {\n const remapped = remapHyperlink(hyperlink, map);\n if (remapped !== hyperlink) {\n next = { ...next, props: { ...next.props, hyperlink: remapped } };\n }\n }\n\n if (next.children && next.children.length > 0) {\n next = {\n ...next,\n children: next.children.map((child) =>\n remapHyperlinkSlideRefs(child, map)\n ),\n };\n }\n\n return next;\n}\n\n/**\n * Write the pptxgenjs `hyperlink` option, dropping unresolvable slide refs.\n * Shared by every component that accepts a hyperlink.\n */\nexport function applyHyperlink(\n opts: Record<string, unknown>,\n hyperlink: HyperlinkProps | undefined,\n componentName: string,\n warnings?: PipelineWarning[]\n): void {\n if (!hyperlink) return;\n\n if (hyperlink.url) {\n opts.hyperlink = { url: hyperlink.url, tooltip: hyperlink.tooltip };\n return;\n }\n\n if (hyperlink.unresolvedSlideRef != null) {\n const message =\n `hyperlink.slide ${hyperlink.unresolvedSlideRef} matches no slide in the generated ` +\n `presentation (slide disabled, or index out of range) — hyperlink dropped`;\n if (warnings) {\n warnings.push({\n code: HYPERLINK_SLIDE_UNRESOLVED,\n message,\n component: componentName,\n });\n } else {\n console.warn(message);\n }\n return;\n }\n\n if (hyperlink.slide) {\n opts.hyperlink = { slide: hyperlink.slide, tooltip: hyperlink.tooltip };\n }\n}\n","/**\n * Grid Layout Resolution\n * Converts grid coordinates to absolute x/y/w/h positions\n */\n\nimport type { GridConfig, GridPosition, PptxComponentInput, PipelineWarning } from '../types';\nimport { warn, W } from '../utils/warn';\n\nexport const DEFAULT_GRID_CONFIG: Required<{\n columns: number;\n rows: number;\n margin: { top: number; right: number; bottom: number; left: number };\n gutter: { column: number; row: number };\n}> = {\n columns: 12,\n rows: 6,\n margin: { top: 0.5, right: 0.5, bottom: 0.5, left: 0.5 },\n gutter: { column: 0.2, row: 0.2 },\n};\n\nfunction resolveMargin(margin: GridConfig['margin']) {\n if (margin == null) return DEFAULT_GRID_CONFIG.margin;\n if (typeof margin === 'number') return { top: margin, right: margin, bottom: margin, left: margin };\n return margin;\n}\n\nfunction resolveGutter(gutter: GridConfig['gutter']) {\n if (gutter == null) return DEFAULT_GRID_CONFIG.gutter;\n if (typeof gutter === 'number') return { column: gutter, row: gutter };\n return gutter;\n}\n\n/**\n * Merge a template-level grid override on top of the presentation grid.\n * Template fields take precedence; nested margin/gutter objects are shallow-merged.\n * Both sides are normalized to object form before merging so that a shorthand\n * base (e.g. margin: 0.5) combined with a partial override (e.g. { top: 1.1 })\n * doesn't lose the other sides.\n */\nexport function mergeGridConfigs(\n base: GridConfig | undefined,\n override: GridConfig | undefined\n): GridConfig | undefined {\n if (!override) return base;\n if (!base) return override;\n\n const merged: GridConfig = {\n columns: override.columns ?? base.columns,\n rows: override.rows ?? base.rows,\n };\n\n // Merge margin — normalize both to object form first\n if (override.margin !== undefined) {\n if (typeof override.margin === 'number') {\n merged.margin = override.margin;\n } else {\n merged.margin = { ...resolveMargin(base.margin), ...override.margin };\n }\n } else {\n merged.margin = base.margin;\n }\n\n // Merge gutter — same normalization\n if (override.gutter !== undefined) {\n if (typeof override.gutter === 'number') {\n merged.gutter = override.gutter;\n } else {\n merged.gutter = { ...resolveGutter(base.gutter), ...override.gutter };\n }\n } else {\n merged.gutter = base.gutter;\n }\n\n return merged;\n}\n\nexport function resolveGridPosition(\n gridPos: GridPosition,\n gridConfig: GridConfig | undefined,\n slideWidth: number,\n slideHeight: number,\n warnings?: PipelineWarning[]\n): { x: number; y: number; w: number; h: number } {\n const cols = Math.max(1, gridConfig?.columns ?? DEFAULT_GRID_CONFIG.columns);\n const rows = Math.max(1, gridConfig?.rows ?? DEFAULT_GRID_CONFIG.rows);\n const margin = resolveMargin(gridConfig?.margin);\n const gutter = resolveGutter(gridConfig?.gutter);\n\n const col = Math.max(0, Math.min(gridPos.column, cols - 1));\n const row = Math.max(0, Math.min(gridPos.row, rows - 1));\n const colSpan = Math.max(1, Math.min(gridPos.columnSpan ?? 1, cols - col));\n const rowSpan = Math.max(1, Math.min(gridPos.rowSpan ?? 1, rows - row));\n\n if (gridPos.column !== col || gridPos.row !== row) {\n warn(warnings, W.GRID_POSITION_CLAMPED,\n `Grid position clamped: column ${gridPos.column}→${col}, row ${gridPos.row}→${row} (grid: ${cols}×${rows})`\n );\n }\n\n const availableW = slideWidth - margin.left - margin.right;\n const availableH = slideHeight - margin.top - margin.bottom;\n const trackW = (availableW - (cols - 1) * gutter.column) / cols;\n const trackH = (availableH - (rows - 1) * gutter.row) / rows;\n\n const x = margin.left + col * (trackW + gutter.column);\n const y = margin.top + row * (trackH + gutter.row);\n const w = colSpan * trackW + (colSpan - 1) * gutter.column;\n const h = rowSpan * trackH + (rowSpan - 1) * gutter.row;\n\n return { x, y, w, h };\n}\n\nexport function resolveComponentGridPosition(\n component: PptxComponentInput,\n gridConfig: GridConfig | undefined,\n slideWidth: number,\n slideHeight: number,\n warnings?: PipelineWarning[]\n): PptxComponentInput {\n const gridPos = component.props.grid as GridPosition | undefined;\n if (!gridPos) return component;\n\n const resolved = resolveGridPosition(gridPos, gridConfig, slideWidth, slideHeight, warnings);\n\n const { grid: _grid, ...restProps } = component.props; // eslint-disable-line no-unused-vars, @typescript-eslint/no-unused-vars\n const newProps = { ...restProps };\n\n // When explicit values use percentage strings, convert grid-resolved inches\n // to percentages too so pptxgenjs receives consistent units per element.\n const hasPercentX = typeof newProps.x === 'string' || typeof newProps.w === 'string';\n const hasPercentY = typeof newProps.y === 'string' || typeof newProps.h === 'string';\n\n const toPercX = (v: number) => `${+((v / slideWidth) * 100).toFixed(2)}%`;\n const toPercY = (v: number) => `${+((v / slideHeight) * 100).toFixed(2)}%`;\n\n // Grid sets x/y/w/h, but explicit values on the element override individually\n if (newProps.x == null) newProps.x = hasPercentX ? toPercX(resolved.x) : resolved.x;\n if (newProps.y == null) newProps.y = hasPercentY ? toPercY(resolved.y) : resolved.y;\n if (newProps.w == null) newProps.w = hasPercentX ? toPercX(resolved.w) : resolved.w;\n if (newProps.h == null) newProps.h = hasPercentY ? toPercY(resolved.h) : resolved.h;\n\n return { ...component, props: newProps };\n}\n","/**\n * Resource table used while compiling a presentation to PptxIR.\n *\n * One table per compilation — never module-global — so concurrent generations\n * cannot share ids or entries.\n *\n * Identity depends on where the bytes come from. Inline sources (authored\n * base64, raw SVG) are decoded once and keyed by content hash, so the same\n * image authored twice becomes one resource. File and remote sources keep\n * their location and are keyed by it, because reading every file at compile\n * time would change when I/O happens and how much of a large deck is resident\n * in memory.\n */\n\nimport type {\n PptxIrPixelSize,\n PptxIrResource,\n PptxIrResourceOrigin,\n} from './types';\nimport { sha256Hex } from './units';\n\nexport interface InlineResourceInput {\n kind: 'inline';\n bytes: Uint8Array;\n mediaType?: string;\n}\n\nexport interface FileResourceInput {\n kind: 'file';\n path: string;\n mediaType?: string;\n}\n\nexport interface RemoteResourceInput {\n kind: 'remote';\n url: string;\n mediaType?: string;\n}\n\nexport type ResourceInput =\n | InlineResourceInput\n | FileResourceInput\n | RemoteResourceInput;\n\nexport class ResourceTable {\n private readonly byKey = new Map<string, PptxIrResource>();\n private readonly order: PptxIrResource[] = [];\n\n /**\n * Add a resource (or return the existing one with matching identity) and\n * return its id.\n */\n intern(input: ResourceInput, intrinsic?: PptxIrPixelSize): string {\n const origin = toOrigin(input);\n const key = identity(origin);\n const existing = this.byKey.get(key);\n if (existing) {\n // A later reference may have probed dimensions the first one skipped.\n if (!existing.intrinsic && intrinsic) existing.intrinsic = intrinsic;\n return existing.id;\n }\n\n const resource: PptxIrResource = {\n id: `res${this.order.length + 1}`,\n kind: 'image',\n origin,\n ...(input.mediaType ? { mediaType: input.mediaType } : {}),\n ...(intrinsic ? { intrinsic } : {}),\n };\n this.byKey.set(key, resource);\n this.order.push(resource);\n return resource.id;\n }\n\n /** Every resource, in first-use order. */\n list(): PptxIrResource[] {\n return this.order;\n }\n\n get(id: string): PptxIrResource | undefined {\n return this.order.find((r) => r.id === id);\n }\n}\n\nfunction toOrigin(input: ResourceInput): PptxIrResourceOrigin {\n switch (input.kind) {\n case 'inline':\n return {\n kind: 'inline',\n bytes: input.bytes,\n byteLength: input.bytes.byteLength,\n sha256: sha256Hex(input.bytes),\n };\n case 'file':\n return { kind: 'file', path: input.path };\n case 'remote':\n return { kind: 'remote', url: input.url };\n }\n}\n\nfunction identity(origin: PptxIrResourceOrigin): string {\n switch (origin.kind) {\n case 'inline':\n return `sha256:${origin.sha256}`;\n case 'file':\n return `file:${origin.path}`;\n case 'remote':\n return `remote:${origin.url}`;\n }\n}\n\n/**\n * Split a `data:` URI into its media type and decoded bytes.\n *\n * Returns `undefined` for anything that is not a base64 data URI, so callers\n * can fall back to treating the string as a location.\n */\nexport function parseDataUri(\n source: string\n): { mediaType: string; bytes: Uint8Array } | undefined {\n const match = /^data:([^;,]+)(;[^,]*)?,(.*)$/s.exec(source);\n if (!match) return undefined;\n const [, mediaType, params, payload] = match;\n const isBase64 = (params ?? '').includes(';base64');\n const bytes = isBase64\n ? new Uint8Array(Buffer.from(payload, 'base64'))\n : new Uint8Array(Buffer.from(decodeURIComponent(payload), 'utf-8'));\n return { mediaType, bytes };\n}\n\n/** Guess a media type from a file extension or URL path. */\nexport function mediaTypeFromLocation(location: string): string | undefined {\n const withoutQuery = location.split(/[?#]/)[0];\n const ext = withoutQuery\n .slice(withoutQuery.lastIndexOf('.') + 1)\n .toLowerCase();\n switch (ext) {\n case 'png':\n return 'image/png';\n case 'jpg':\n case 'jpeg':\n return 'image/jpeg';\n case 'gif':\n return 'image/gif';\n case 'svg':\n return 'image/svg+xml';\n case 'webp':\n return 'image/webp';\n case 'bmp':\n return 'image/bmp';\n case 'tif':\n case 'tiff':\n return 'image/tiff';\n default:\n return undefined;\n }\n}\n","/**\n * PPTX renderer registry.\n *\n * Adapters are registered as async factories so an optional backend is only\n * imported when it is actually selected — choosing `pptxgenjs` never loads\n * `@office-open/pptx`, and a missing optional dependency surfaces as an\n * actionable install hint rather than a bare module-resolution failure.\n */\n\nimport { RendererRegistry } from '@json-to-office/shared/rendering';\nimport type { PptxFeature } from '../ir/features';\nimport type { PptxIR } from '../ir/types';\nimport {\n DEFAULT_PPTX_RENDERER_ID,\n type PptxRenderer,\n type PptxRendererId,\n} from './types';\n\nconst registry = new RendererRegistry<PptxIR, PptxFeature, PptxRendererId>(\n 'pptx',\n DEFAULT_PPTX_RENDERER_ID\n);\n\nregistry.register('pptxgenjs', async () => {\n const { createPptxGenJsRenderer } = await import('./pptxgenjs/index');\n return createPptxGenJsRenderer();\n});\n\nregistry.register('office-open', async () => {\n const { createOfficeOpenPptxRenderer } = await import('./office-open/index');\n return createOfficeOpenPptxRenderer();\n});\n\n/** Resolve a renderer by id, defaulting to `pptxgenjs`. */\nexport function resolvePptxRenderer(\n id?: PptxRendererId\n): Promise<PptxRenderer> {\n return registry.resolve(id);\n}\n\n/** Renderer ids registered for PPTX. */\nexport function pptxRendererIds(): readonly PptxRendererId[] {\n return registry.ids();\n}\n\nexport function isPptxRendererId(value: string): value is PptxRendererId {\n return registry.has(value);\n}\n","/**\n * PPTX renderer contracts.\n *\n * Format-specific bindings of the shared `OfficeRenderer` contract. Nothing in\n * this file imports a backend; the adapters under `pptxgenjs/` and\n * `office-open/` do, and they are the only places allowed to.\n */\n\nimport type {\n OfficeRenderer,\n RenderOptions,\n} from '@json-to-office/shared/rendering';\nimport type { PptxFeature } from '../ir/features';\nimport type { PptxIR } from '../ir/types';\nimport type { PipelineWarning } from '../types';\nimport {\n DEFAULT_PPTX_RENDERER_ID,\n type PptxRendererId,\n} from '@json-to-office/shared-pptx';\n\n/**\n * Renderer ids available for PPTX.\n *\n * `pptxgenjs` is the default and must keep producing today's output.\n * `office-open` is experimental and opt-in.\n */\nexport { DEFAULT_PPTX_RENDERER_ID };\nexport type { PptxRendererId };\n\n/**\n * Render options for PPTX.\n *\n * Adds a warning sink to the shared contract. Post-render repairs — the SVG\n * preview fix, for one — can find problems that the author should hear about,\n * and those have to reach the same structured warning list the rest of the\n * pipeline uses rather than `console.warn`.\n */\nexport interface PptxRenderOptions extends RenderOptions {\n warnings?: PipelineWarning[];\n}\n\nexport interface PptxRenderer\n extends OfficeRenderer<PptxIR, PptxFeature, PptxRendererId> {\n render(document: PptxIR, options?: PptxRenderOptions): Promise<Uint8Array>;\n}\n\nexport type { RenderOptions };\n","/**\n * PPTX Core Types\n */\n\nimport type {\n ServicesConfig,\n FontRegistryDefinition,\n} from '@json-to-office/shared';\nimport type {\n GradientFill,\n PptxComponentDefaults,\n PptxRendererId,\n} from '@json-to-office/shared-pptx';\n\nexport interface PptxComponentInput {\n name: string;\n id?: string;\n enabled?: boolean;\n props: Record<string, any>;\n children?: PptxComponentInput[];\n}\n\nexport interface PresentationComponentDefinition {\n name: 'pptx';\n $schema?: string;\n /** Renderer backend. Omitted defaults to pptxgenjs. */\n renderer?: PptxRendererId;\n id?: string;\n props: {\n title?: string;\n author?: string;\n subject?: string;\n company?: string;\n theme?: string;\n fontRegistry?: FontRegistryDefinition;\n slideWidth?: number;\n slideHeight?: number;\n rtlMode?: boolean;\n language?: string;\n pageNumberFormat?: '9' | '09';\n componentDefaults?: PptxComponentDefaults;\n grid?: GridConfig;\n templates?: TemplateSlideDefinition[];\n };\n children?: PptxComponentInput[];\n}\n\n/** A presentation explicitly targeted at one renderer profile. */\nexport type PresentationComponentDefinitionFor<R extends PptxRendererId> = Omit<\n PresentationComponentDefinition,\n 'renderer'\n> &\n (R extends 'pptxgenjs' ? { renderer?: R } : { renderer: R });\n\nexport interface SlideComponentDefinition {\n name: 'slide';\n id?: string;\n /** Optional: every slide prop is optional, so validation accepts a slide with none. */\n props?: {\n background?: {\n color?: string;\n gradient?: GradientFill;\n image?: { path?: string; base64?: string };\n };\n transition?: {\n type?: string;\n speed?: string;\n };\n notes?: string;\n layout?: string;\n hidden?: boolean;\n template?: string;\n placeholders?: Record<string, PptxComponentInput>;\n };\n children?: PptxComponentInput[];\n}\n\nexport interface ProcessedPresentation {\n metadata: {\n title?: string;\n author?: string;\n subject?: string;\n company?: string;\n };\n theme: PptxThemeConfig;\n grid?: GridConfig;\n slideWidth: number;\n slideHeight: number;\n rtlMode: boolean;\n /** Default presentation language (BCP-47) for spell-checking */\n language?: string;\n pageNumberFormat: '9' | '09';\n slides: ProcessedSlide[];\n templates?: TemplateSlideDefinition[];\n services?: ServicesConfig;\n}\n\nexport interface ProcessedSlide {\n components: PptxComponentInput[];\n background?: {\n color?: string;\n gradient?: GradientFill;\n image?: { path?: string; base64?: string };\n };\n /**\n * Slide transition, as authored.\n *\n * Carried through processing rather than dropped there: a backend without a\n * transition API has to be told the deck wants one so it can refuse, and a\n * backend with one has to be able to write it (#257).\n */\n transition?: { type?: string; speed?: string };\n notes?: string;\n layout?: string;\n hidden?: boolean;\n template?: string;\n placeholders?: Record<string, PptxComponentInput>;\n}\n\nexport interface GridConfig {\n columns?: number;\n rows?: number;\n margin?:\n | number\n | { top: number; right: number; bottom: number; left: number };\n gutter?: number | { column: number; row: number };\n}\n\nexport interface GridPosition {\n column: number;\n row: number;\n columnSpan?: number;\n rowSpan?: number;\n}\n\nexport interface TextStyle {\n fontSize?: number;\n fontFace?: string;\n fontColor?: string;\n bold?: boolean;\n /**\n * Per-style weight (100–900). Overrides `bold` when set — renderer picks\n * the closest embedded variant via CSS font-matching and emits the run\n * under a synthetic family alias (e.g. \"Inter Light\" for weight 300).\n */\n fontWeight?: number;\n italic?: boolean;\n align?: string;\n lineSpacing?: number;\n charSpacing?: number;\n paraSpaceAfter?: number;\n}\n\nexport type StyleName =\n | 'title'\n | 'subtitle'\n | 'heading1'\n | 'heading2'\n | 'heading3'\n | 'body'\n | 'caption';\n\nexport interface PptxThemeConfig {\n name: string;\n colors: {\n primary: string;\n secondary: string;\n accent: string;\n background: string;\n text: string;\n text2?: string;\n background2?: string;\n accent4?: string;\n accent5?: string;\n accent6?: string;\n };\n fonts: {\n heading: string;\n body: string;\n };\n fontRegistry?: FontRegistryDefinition;\n defaults: {\n fontSize: number;\n fontColor: string;\n };\n styles?: Partial<Record<StyleName, TextStyle>>;\n componentDefaults?: PptxComponentDefaults;\n}\n\nexport interface PlaceholderDefinition {\n name: string;\n x?: number;\n y?: number;\n w?: number;\n h?: number;\n grid?: GridPosition;\n defaults?: PptxComponentInput;\n}\n\nexport interface TemplateSlideDefinition {\n name: string;\n background?: {\n color?: string;\n gradient?: GradientFill;\n image?: { path?: string; base64?: string };\n };\n margin?: number | [number, number, number, number];\n slideNumber?: {\n x: number;\n y: number;\n w?: number;\n h?: number;\n color?: string;\n fontSize?: number;\n };\n objects?: PptxComponentInput[];\n placeholders?: PlaceholderDefinition[];\n grid?: GridConfig;\n}\n\nexport interface SlideContext {\n slideNumber: number;\n totalSlides: number;\n pageNumberFormat: '9' | '09';\n /** Default presentation language (BCP-47); text runs inherit it unless overridden */\n language?: string;\n}\n\nexport interface SlideRenderContext {\n slideCtx?: SlideContext;\n services?: ServicesConfig;\n slideWidth: number;\n slideHeight: number;\n /**\n * Per-generation registry of fills (gradient/pattern) that pptxgenjs cannot\n * express. Components render a sentinel solid fill tagged with a unique\n * objectName; the PptxGenJS packaging pass swaps the sentinel for the real\n * fill XML after generation.\n */\n pendingFills?: PendingXmlFill[];\n}\n\n/**\n * A fill to be spliced into the slide XML during packaging. The component that\n * registered it rendered a sentinel `<a:solidFill>` on a shape whose\n * `cNvPr name` equals `objectName`.\n */\nexport interface PendingXmlFill {\n objectName: string;\n /** Complete replacement fill element (e.g. `<a:gradFill>…</a:gradFill>`). */\n xml: string;\n}\n\nexport interface PipelineWarning {\n code: string; // WarningCode at call sites; string here to avoid circular import\n message: string;\n component?: string;\n slide?: number;\n}\n\nexport function isPresentationComponent(\n component: unknown\n): component is PresentationComponentDefinition {\n return (\n typeof component === 'object' &&\n component !== null &&\n (component as any).name === 'pptx'\n );\n}\n\nexport function isSlideComponent(\n component: unknown\n): component is SlideComponentDefinition {\n return (\n typeof component === 'object' &&\n component !== null &&\n (component as any).name === 'slide'\n );\n}\n","/**\n * Shared font-resolution helper used by BOTH entry paths into renderPresentation:\n *\n * - core/generator.ts → generateBufferWithWarnings (non-plugin)\n * - plugin/createPresentationGenerator.ts → generate (plugin-aware)\n *\n * Keeping it in one place ensures both paths validate, materialize, and fire\n * the `onResolved` side-channel consumed by the LibreOffice preview stager.\n */\n\nimport type { FontRuntimeOpts, ResolvedFont } from '@json-to-office/shared';\nimport {\n collectFontNamesFromPptx,\n validateFontReferences,\n FontRegistry,\n documentFontRegistry,\n themeFontRegistry,\n mergeFontRegistries,\n} from '@json-to-office/shared';\nimport {\n loadFileFontSource,\n FontDiskCache,\n fetchVariableFontSource,\n} from '@json-to-office/shared/fonts/node';\nimport type {\n PipelineWarning,\n PresentationComponentDefinition,\n} from '../types';\nimport type { PptxThemeConfig } from '../types';\nimport { warn, W } from '../utils/warn';\n\nexport async function resolveDocumentFonts(\n document: PresentationComponentDefinition,\n theme: PptxThemeConfig,\n warnings: PipelineWarning[],\n fonts?: FontRuntimeOpts\n): Promise<ResolvedFont[]> {\n const names = new Set<string>();\n for (const n of collectFontNamesFromPptx(document)) names.add(n);\n for (const n of collectFontNamesFromPptx(theme as unknown)) names.add(n);\n if (names.size === 0) return [];\n\n // Merge the declared registries with runtime overrides. Precedence:\n // theme < document < fonts.extraEntries (see registry.ts's resolution\n // rules). This MUST run before validation, not after the `onResolved`\n // short-circuit below: a presentation with a valid registry and no preview\n // listener would otherwise still report every registered family as\n // FONT_UNRESOLVED.\n const registryEntries = mergeFontRegistries(\n themeFontRegistry(theme),\n documentFontRegistry(document),\n fonts?.extraEntries\n );\n\n // Validate unconditionally — strict mode must fire even when no consumer\n // is listening via onResolved (CLI / library callers that just want\n // build-time validation of font references).\n const validation = validateFontReferences({\n referencedNames: names,\n registeredEntries: registryEntries,\n });\n if (validation.warnings.length > 0) {\n if (fonts?.strict) {\n throw new Error(\n `Unresolved font references (strict mode):\\n` +\n validation.warnings.map((w) => ` - ${w.message}`).join('\\n')\n );\n }\n for (const w of validation.warnings) {\n warn(warnings, W.FONT_UNRESOLVED, w.message, {\n component: 'fontRegistry',\n });\n }\n }\n\n // Registry resolution (Google/URL/file fetches) only runs when a consumer\n // is listening via onResolved — typically the LibreOffice preview stager.\n // Office output never embeds bytes, so skipping fetches when nobody cares\n // keeps library callers from paying network cost.\n if (!fonts?.onResolved) return [];\n\n const registry = new FontRegistry({\n // Spread keeps baseDir/googleFonts/mode/substitution intact for\n // materializeSource; extraEntries carries the merged registry.\n opts: { ...fonts, extraEntries: registryEntries },\n fileLoader: loadFileFontSource,\n variableLoader: fetchVariableFontSource,\n diskCache: fonts?.googleFonts?.cacheDir\n ? new FontDiskCache(fonts.googleFonts.cacheDir)\n : undefined,\n });\n const resolved = await registry.resolveMany(names);\n for (const r of resolved) {\n for (const msg of r.warnings) {\n warn(warnings, W.FONT_UNRESOLVED, msg, {\n component: 'fontRegistry',\n });\n }\n }\n // Fire the side-channel here so callers never have to remember. The\n // short-circuit above guarantees we only reach this point when a\n // listener is registered.\n fonts.onResolved(resolved);\n return resolved;\n}\n","/**\n * Shared generation prologue.\n *\n * Both entry points — `generateBufferWithWarnings` (core) and\n * `createPresentationGenerator` (plugin) — must resolve the same theme, run\n * the same export-mode pre-pass before slide processing runs. Keeping two\n * copies of that is how DOCX silently dropped a\n * root-level prop from one path (#133); this module is the single definition\n * so the next root-level prop cannot diverge (#134). Mirrors\n * core-docx/src/core/generationContext.ts.\n *\n * The prologue deliberately stops before font resolution: the core path\n * resolves fonts straight after this, while the plugin path must first expand\n * custom components (which can introduce new families). The export-mode\n * pre-pass runs here, BEFORE expansion, so custom components reading\n * `theme.fonts.*` during render see substituted names, not the original\n * non-safe ones.\n */\n\nimport type {\n PresentationComponentDefinition,\n PptxThemeConfig,\n PipelineWarning,\n} from '../types';\nimport type { FontRuntimeOpts } from '@json-to-office/shared';\nimport { applyExportMode } from '@json-to-office/shared';\nimport { getPptxTheme } from '../themes/defaults';\n\nexport interface ThemeContextOptions {\n customThemes?: Record<string, PptxThemeConfig>;\n fonts?: FontRuntimeOpts;\n warnings?: PipelineWarning[];\n /**\n * Base theme name when the document doesn't name one. The plugin builder\n * passes its constructor-supplied string theme; defaults to 'default'.\n */\n defaultThemeName?: string;\n /**\n * Theme lookup for the base `props.theme` name. The plugin builder passes\n * its own (customThemes → doc-named built-in → constructor theme object →\n * built-in); omit it to use customThemes → built-in. `authored` is true\n * when the name came from the document's own `props.theme` (as opposed to\n * `defaultThemeName` or the 'default' fallback), so the lookup can honor\n * an explicitly doc-named built-in without the constructor object\n * swallowing the default name too (#141).\n */\n resolveNamedTheme?: (name: string, authored: boolean) => PptxThemeConfig;\n}\n\nexport interface GenerationThemeContext {\n /**\n * The document after the export-mode pre-pass rewrote font references.\n * `props.theme` stays as authored (name or inline object) — callers hand\n * `theme` to `processPresentation` by value instead of round-tripping it\n * through a name lookup (#135).\n */\n document: PresentationComponentDefinition;\n theme: PptxThemeConfig;\n}\n\nexport function resolveThemeContext(\n documentIn: PresentationComponentDefinition,\n options: ThemeContextOptions = {}\n): GenerationThemeContext {\n const { customThemes, fonts, warnings, defaultThemeName, resolveNamedTheme } =\n options;\n\n // A root written without a `props` key is defaulted here — otherwise the\n // first downstream `document.props.*` read throws a raw TypeError. Only\n // `undefined` is defaulted: `props: null` is malformed and must be rejected\n // rather than quietly rewritten into a valid shape. Both entry points\n // validate before reaching here when validation is enabled (the PPTX\n // validator rejects a missing `props`); this covers the\n // `validation: { enabled: false }` route. Matches DOCX.\n if (documentIn.props === null) {\n throw new Error(\n 'Document `props` is null. Omit it, or provide an object — ' +\n 'a null props cannot carry a theme.'\n );\n }\n let document =\n documentIn.props === undefined ? { ...documentIn, props: {} } : documentIn;\n\n // An inline theme object (self-contained document) resolves directly and\n // wins over any customThemes entry sharing its name, on both paths. The\n // document keeps the authored object — nothing downstream resolves the\n // theme by name anymore.\n let inlineTheme: PptxThemeConfig | undefined;\n if (\n typeof document.props.theme === 'object' &&\n document.props.theme !== null\n ) {\n inlineTheme = document.props.theme as PptxThemeConfig;\n }\n\n const authoredThemeName =\n typeof document.props.theme === 'string' ? document.props.theme : undefined;\n const baseThemeName = inlineTheme\n ? inlineTheme.name || 'inline-theme'\n : authoredThemeName ?? defaultThemeName ?? 'default';\n let theme =\n inlineTheme ??\n (resolveNamedTheme\n ? resolveNamedTheme(baseThemeName, authoredThemeName !== undefined)\n : customThemes?.[baseThemeName] ?? getPptxTheme(baseThemeName));\n\n // Export-mode pre-pass: substitute rewrites non-safe families in place;\n // custom leaves refs untouched and resolution short-circuits to empty.\n const mode = applyExportMode({ doc: document, theme, fonts });\n document = mode.doc;\n theme = mode.theme;\n for (const w of mode.warnings) {\n warnings?.push({\n code: w.code,\n message: w.message,\n component: 'fontRegistry',\n });\n }\n\n return {\n document,\n theme,\n };\n}\n","/**\n * PPTX Theme Defaults\n */\n\nimport type { PptxThemeConfig, TextStyle, StyleName } from '../types';\n\nconst DEFAULT_STYLES: Partial<Record<StyleName, TextStyle>> = {\n title: { fontSize: 36, bold: true, fontColor: 'text', align: 'center' },\n subtitle: { fontSize: 20, italic: true, fontColor: 'text2', align: 'center' },\n heading1: { fontSize: 28, bold: true, fontColor: 'primary' },\n heading2: { fontSize: 22, bold: true, fontColor: 'primary' },\n heading3: { fontSize: 18, bold: true, fontColor: 'text' },\n body: { fontSize: 14 },\n caption: { fontSize: 10, italic: true, fontColor: 'text2' },\n};\n\nexport const DEFAULT_PPTX_THEME: PptxThemeConfig = {\n name: 'default',\n colors: {\n primary: '#4472C4',\n secondary: '#ED7D31',\n accent: '#70AD47',\n background: '#FFFFFF',\n text: '#333333',\n text2: '#44546A',\n background2: '#E7E6E6',\n accent4: '#FFC000',\n accent5: '#5B9BD5',\n accent6: '#70AD47',\n },\n fonts: {\n heading: 'Arial',\n body: 'Arial',\n },\n defaults: {\n fontSize: 18,\n fontColor: '#333333',\n },\n styles: DEFAULT_STYLES,\n};\n\nconst PPTX_THEMES: Record<string, PptxThemeConfig> = {\n default: DEFAULT_PPTX_THEME,\n dark: {\n name: 'dark',\n colors: {\n primary: '#5B9BD5',\n secondary: '#FF6F61',\n accent: '#6BCB77',\n background: '#2D2D2D',\n text: '#FFFFFF',\n text2: '#CCCCCC',\n background2: '#3D3D3D',\n accent4: '#FFB347',\n accent5: '#77DD77',\n accent6: '#AEC6CF',\n },\n fonts: {\n heading: 'Arial',\n body: 'Arial',\n },\n defaults: {\n fontSize: 18,\n fontColor: '#FFFFFF',\n },\n styles: DEFAULT_STYLES,\n },\n minimal: {\n name: 'minimal',\n colors: {\n primary: '#000000',\n secondary: '#666666',\n accent: '#999999',\n background: '#FFFFFF',\n text: '#000000',\n text2: '#444444',\n background2: '#F5F5F5',\n accent4: '#BBBBBB',\n accent5: '#DDDDDD',\n accent6: '#888888',\n },\n fonts: {\n heading: 'Helvetica',\n body: 'Helvetica',\n },\n defaults: {\n fontSize: 18,\n fontColor: '#000000',\n },\n styles: DEFAULT_STYLES,\n },\n};\n\nexport function getPptxTheme(name: string): PptxThemeConfig {\n return PPTX_THEMES[name] || DEFAULT_PPTX_THEME;\n}\n\n/**\n * Whether `name` is a known built-in theme. `getPptxTheme` never misses (it\n * falls back to the default theme), so callers that need to distinguish \"a\n * real built-in\" from \"an unknown name\" must check here first.\n */\nexport function hasPptxTheme(name: string): boolean {\n return Object.prototype.hasOwnProperty.call(PPTX_THEMES, name);\n}\n\nexport const pptxThemes = PPTX_THEMES;\n","/**\n * Generation options and the pre-generation gates.\n *\n * Extracted from `generator.ts` so the IR pipeline can use them without\n * importing the module that now delegates to it.\n */\n\nimport type { ServicesConfig, FontRuntimeOpts } from '@json-to-office/shared';\nimport {\n collectImageSourceConflicts,\n collectTextContentConflicts,\n validateJsonPresentationDocument,\n validatePresentationDocument,\n type ValidationError,\n} from '@json-to-office/shared-pptx';\nimport type {\n PipelineWarning,\n PptxThemeConfig,\n PresentationComponentDefinition,\n} from '../types';\nimport type { PresentationPackagingOptions } from './finalizePackage';\nimport type { PptxRendererId } from '../renderers/types';\n\nexport interface GenerationValidationOptions {\n /** Validate the complete component tree before rendering. Defaults to true. */\n enabled?: boolean;\n /** Accept unknown props while still enforcing required fields and types. */\n allowUnknownFields?: boolean;\n}\n\nexport interface GenerationOptions extends PresentationPackagingOptions {\n customThemes?: Record<string, PptxThemeConfig>;\n /**\n * Fully resolved theme, set by the generation prologue after the\n * export-mode pre-pass. Wins over the `props.theme` name/inline lookup in\n * `processPresentation` — omit it (direct callers) to fall back to that.\n */\n theme?: PptxThemeConfig;\n services?: ServicesConfig;\n fonts?: FontRuntimeOpts;\n validation?: GenerationValidationOptions;\n /**\n * Directory that relative asset paths (image `path` props, slide\n * background images) resolve against. Defaults to `process.cwd()` when\n * absent (#142).\n */\n baseDir?: string;\n /**\n * Backend that turns the compiled presentation into bytes.\n *\n * Defaults to `pptxgenjs`, which is what every existing caller gets.\n * `office-open` is experimental and opt-in: it declares a subset of\n * features and fails before rendering on anything outside it.\n */\n renderer?: PptxRendererId;\n}\n\n/** Result from `generateBufferWithWarnings`. */\nexport interface GenerationResult {\n buffer: Buffer;\n warnings: PipelineWarning[];\n}\n\n/** Error thrown when a presentation fails the generation validation gate. */\nexport class PresentationValidationError extends Error {\n public readonly errors: ValidationError[];\n\n constructor(errors: ValidationError[]) {\n super(\n `Presentation validation failed:\\n${errors\n .map((error) => ` - ${error.path}: ${error.message}`)\n .join('\\n')}`\n );\n this.name = 'PresentationValidationError';\n this.errors = errors;\n }\n}\n\nexport function assertValidPresentation(\n input: string | unknown,\n validation?: GenerationValidationOptions\n): void {\n assertValidPresentationInternal(input, validation, false);\n}\n\n/** Keep compiler capability diagnostics authoritative during generation. */\nexport function assertValidPresentationForGeneration(\n input: string | unknown,\n validation?: GenerationValidationOptions\n): void {\n assertValidPresentationInternal(input, validation, true);\n}\n\nfunction assertValidPresentationInternal(\n input: string | unknown,\n validation: GenerationValidationOptions | undefined,\n deferRendererProfileErrors: boolean\n): void {\n if (validation?.enabled === false) return;\n\n const options = {\n allowUnknownFields: validation?.allowUnknownFields,\n };\n const result =\n typeof input === 'string'\n ? validateJsonPresentationDocument(input, options)\n : validatePresentationDocument(input, options);\n\n const errors = deferRendererProfileErrors\n ? result.errors.filter(\n (error) => error.code !== 'unsupported_renderer_feature'\n )\n : result.errors;\n if (errors.length > 0) {\n throw new PresentationValidationError(errors);\n }\n}\n\n/**\n * Structural rules the per-component schema can't express: image sources\n * (path/base64/svg) are mutually exclusive, and text components carry\n * exactly one of text/runs. Reject conflicting payloads before rendering so\n * they can't be silently resolved by runtime precedence. Matches core-docx,\n * which fails generation on the same image conflict.\n *\n * Runs unconditionally — the validators also collect these conflicts, so this\n * is the net for `validation: { enabled: false }`. Shared with the plugin\n * path, which checks the expanded tree (custom components can emit\n * conflicting payloads too).\n */\nexport function assertNoContentConflicts(document: unknown): void {\n const sourceConflicts = [\n ...collectImageSourceConflicts(document),\n ...collectTextContentConflicts(document),\n ];\n if (sourceConflicts.length > 0) {\n throw new Error(\n `Document validation failed:\\n${sourceConflicts\n .map((e) => ` - ${e.path}: ${e.message}`)\n .join('\\n')}`\n );\n }\n}\n\n/** Type guard for a presentation component definition. */\nexport function isPresentationComponentDefinition(\n definition: unknown\n): definition is PresentationComponentDefinition {\n if (typeof definition !== 'object' || definition === null) return false;\n const def = definition as Record<string, unknown>;\n return def.name === 'pptx' && 'props' in def;\n}\n","/**\n * Environment detection utilities\n */\n\n/**\n * Check if the current environment is Node.js\n */\nexport function isNodeEnvironment(): boolean {\n return (\n typeof process !== 'undefined' &&\n process.versions != null &&\n process.versions.node != null &&\n typeof process.versions.node === 'string'\n );\n}\n","/**\n * Highcharts → image, before compilation.\n *\n * A `highcharts` component is authoring sugar: it describes a chart that an\n * export server renders to a PNG. That fetch is I/O, and the result is just an\n * image, so it is resolved here — an authoring-only expansion — rather than in\n * the compiler or an adapter. By the time PptxIR exists there is no chart\n * service left to depend on.\n *\n * This mirrors how the DOCX pipeline pre-rasterizes `visual` components.\n */\n\nimport type { HighchartsServiceConfig } from '@json-to-office/shared';\nimport type { PptxHighchartsProps } from '@json-to-office/shared-pptx';\nimport type {\n PipelineWarning,\n PptxComponentInput,\n PptxThemeConfig,\n ProcessedPresentation,\n} from '../types';\nimport { definedChartColorTokens, resolveColor } from '../utils/color';\nimport { isNodeEnvironment } from '../utils/environment';\n\n/** Screen pixels per inch, the unit the export server reports sizes in. */\nconst PX_PER_INCH = 96;\nconst DEFAULT_EXPORT_SERVER_URL = 'http://localhost:7801';\n\nexport interface HighchartsExpansionResult {\n presentation: ProcessedPresentation;\n /**\n * Highcharts components this pass did not reach.\n *\n * Placeholder content is merged with its declaration during compilation, so\n * expanding it here would use pre-merge dimensions. Rather than render a\n * chart at the wrong size, those are reported and the caller refuses.\n */\n unexpanded: Array<{ name: string; path: string }>;\n}\n\n/**\n * Replace every `highcharts` component with the `image` it renders to.\n *\n * Slide components and template objects are expanded in place. The presentation\n * is copied rather than mutated so a caller's tree is never altered.\n */\nexport async function expandHighchartsComponents(\n presentation: ProcessedPresentation,\n services: HighchartsServiceConfig | undefined,\n warnings: PipelineWarning[]\n): Promise<HighchartsExpansionResult> {\n const unexpanded: HighchartsExpansionResult['unexpanded'] = [];\n\n const templates = presentation.templates\n ? await Promise.all(\n presentation.templates.map(async (template, index) => ({\n ...template,\n objects: template.objects\n ? await expandList(\n template.objects,\n `masters[${index}].elements`,\n presentation.theme,\n services,\n warnings\n )\n : template.objects,\n }))\n )\n : presentation.templates;\n\n const slides = await Promise.all(\n presentation.slides.map(async (slide, index) => {\n for (const [name, component] of Object.entries(\n slide.placeholders ?? {}\n )) {\n if (component.name === 'highcharts') {\n unexpanded.push({\n name: 'highcharts',\n path: `slides[${index}].placeholders.${name}`,\n });\n }\n }\n return {\n ...slide,\n components: await expandList(\n slide.components,\n `slides[${index}].elements`,\n presentation.theme,\n services,\n warnings\n ),\n };\n })\n );\n\n return {\n presentation: { ...presentation, slides, templates },\n unexpanded,\n };\n}\n\nasync function expandList(\n components: PptxComponentInput[],\n path: string,\n theme: PptxThemeConfig,\n services: HighchartsServiceConfig | undefined,\n warnings: PipelineWarning[]\n): Promise<PptxComponentInput[]> {\n const out: PptxComponentInput[] = [];\n for (const [index, component] of components.entries()) {\n out.push(\n component.name === 'highcharts'\n ? await expandOne(\n component,\n `${path}[${index}]`,\n theme,\n services,\n warnings\n )\n : component\n );\n }\n return out;\n}\n\nasync function expandOne(\n component: PptxComponentInput,\n path: string,\n theme: PptxThemeConfig,\n services: HighchartsServiceConfig | undefined,\n warnings: PipelineWarning[]\n): Promise<PptxComponentInput> {\n const props = component.props as unknown as PptxHighchartsProps;\n const chart = await renderChart(\n withThemeColors(props, theme, warnings),\n services\n );\n\n void path;\n return {\n ...component,\n name: 'image',\n props: {\n base64: chart.dataUri,\n x: props.x ?? 0,\n y: props.y ?? 0,\n w: props.w ?? chart.widthPx / PX_PER_INCH,\n h: props.h ?? chart.heightPx / PX_PER_INCH,\n },\n };\n}\n\ninterface RenderedChart {\n dataUri: string;\n widthPx: number;\n heightPx: number;\n}\n\nasync function renderChart(\n config: PptxHighchartsProps,\n services: HighchartsServiceConfig | undefined\n): Promise<RenderedChart> {\n if (!isNodeEnvironment()) {\n throw new Error(\n 'Highcharts export server requires a Node.js environment. ' +\n 'Chart generation is not available in browser environments.'\n );\n }\n\n const serverUrl = exportServerUrl(config.serverUrl, services?.serverUrl);\n const requestBody = {\n infile: config.options,\n type: 'png',\n b64: true,\n scale: config.scale,\n // Forwarded verbatim only when present, so the payload stays byte-identical\n // for callers that omit it.\n ...(config.resources ? { resources: config.resources } : {}),\n };\n\n const resolvedHeaders =\n typeof services?.headers === 'function'\n ? await services.headers(requestBody)\n : services?.headers;\n\n const response = await fetch(`${serverUrl}/export`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', ...resolvedHeaders },\n body: JSON.stringify(requestBody),\n }).catch((error) => {\n throw new Error(\n `Highcharts Export Server is not running at ${serverUrl}. ` +\n 'Start it with: npx highcharts-export-server --enableServer true\\n' +\n `Cause: ${error instanceof Error ? error.message : String(error)}`\n );\n });\n\n if (!response.ok) {\n throw new Error(\n `Highcharts export server returned ${response.status}: ${response.statusText}`\n );\n }\n\n return {\n dataUri: `data:image/png;base64,${await response.text()}`,\n widthPx: config.options.chart?.width ?? 960,\n heightPx: config.options.chart?.height ?? 720,\n };\n}\n\nfunction exportServerUrl(propsUrl?: string, servicesUrl?: string): string {\n const raw = propsUrl || servicesUrl || DEFAULT_EXPORT_SERVER_URL;\n return raw.startsWith('http') ? raw : `http://${raw}`;\n}\n\n/**\n * Inject the theme's chart palette when the config sets no top-level `colors`.\n *\n * Without it, series render in the Highcharts default palette and ignore the\n * document theme. Slots the theme leaves unset are skipped — the same rule the\n * native chart component and DOCX both follow — so the palette never repeats\n * `primary`. An explicit `colors` always wins.\n */\nfunction withThemeColors(\n props: PptxHighchartsProps,\n theme: PptxThemeConfig,\n warnings: PipelineWarning[]\n): PptxHighchartsProps {\n if (!props.options || props.options.colors || !theme?.colors) return props;\n const palette = definedChartColorTokens(theme).map(\n (token) => `#${resolveColor(token, theme, warnings)}`\n );\n if (palette.length === 0) return props;\n return { ...props, options: { ...props.options, colors: palette } };\n}\n","/**\n * Image layout resolution, before compilation.\n *\n * Fitting an image needs its intrinsic pixel size, and getting that means I/O —\n * reading a file, or fetching a URL. That makes it a pre-pass rather than part\n * of the compiler, which stays synchronous and pure. What arrives at the\n * compiler is an image component whose `w`/`h` (and `sizing`, where it\n * survives) are already decided.\n *\n * Three cases need the intrinsic size:\n *\n * - exactly one of `w`/`h` given, no `sizing` — the other is derived from the\n * aspect ratio\n * - `sizing.type === 'contain'` — the image is fitted inside the box and\n * centred here, because the backend's own `contain` produces negative crop\n * values when the aspect ratios differ\n * - `sizing.type === 'cover'` — the backend crops correctly once it is given\n * the real intrinsic dimensions\n */\n\nimport path from 'node:path';\nimport probe from 'probe-image-size';\nimport type {\n PipelineWarning,\n PptxComponentInput,\n ProcessedPresentation,\n} from '../types';\nimport { resolveFromBaseDir } from '../utils/baseDirContext';\nimport { isAllowedLocalPath, resolveImageSource } from '../utils/imageSource';\nimport { W, warn } from '../utils/warn';\n\ninterface ImageSizing {\n type: string;\n w?: number | string;\n h?: number | string;\n}\n\n/** Resolve every image component's geometry across the presentation. */\nexport async function resolveImageLayout(\n presentation: ProcessedPresentation,\n warnings: PipelineWarning[]\n): Promise<ProcessedPresentation> {\n const resolve = (components: PptxComponentInput[]) =>\n resolveList(components, presentation, warnings);\n\n const [slides, templates] = await Promise.all([\n Promise.all(\n presentation.slides.map(async (slide) => ({\n ...slide,\n components: await resolve(slide.components),\n ...(slide.placeholders\n ? {\n placeholders: Object.fromEntries(\n await Promise.all(\n Object.entries(slide.placeholders).map(\n async ([name, component]) =>\n [name, (await resolve([component]))[0]] as const\n )\n )\n ),\n }\n : {}),\n }))\n ),\n presentation.templates\n ? Promise.all(\n presentation.templates.map(async (template) => ({\n ...template,\n ...(template.objects\n ? { objects: await resolve(template.objects) }\n : {}),\n }))\n )\n : Promise.resolve(presentation.templates),\n ]);\n\n return { ...presentation, slides, templates };\n}\n\nasync function resolveList(\n components: PptxComponentInput[],\n presentation: ProcessedPresentation,\n warnings: PipelineWarning[]\n): Promise<PptxComponentInput[]> {\n const out: PptxComponentInput[] = [];\n for (const component of components) {\n out.push(\n component.name === 'image'\n ? await resolveOne(component, presentation, warnings)\n : component\n );\n }\n return out;\n}\n\nasync function resolveOne(\n component: PptxComponentInput,\n presentation: ProcessedPresentation,\n warnings: PipelineWarning[]\n): Promise<PptxComponentInput> {\n const props = component.props as Record<string, unknown>;\n const source = resolveImageSource(\n props as Parameters<typeof resolveImageSource>[0]\n );\n if (!source) return component;\n\n const sizing = props.sizing as ImageSizing | undefined;\n const hasWidth = props.w !== undefined;\n const hasHeight = props.h !== undefined;\n const slideWidth = presentation.slideWidth;\n const slideHeight = presentation.slideHeight;\n\n const needsIntrinsic =\n (hasWidth !== hasHeight && !sizing) ||\n sizing?.type === 'contain' ||\n sizing?.type === 'cover';\n const intrinsic = needsIntrinsic\n ? await probeIntrinsicSize(source, warnings)\n : undefined;\n\n const next: Record<string, unknown> = { ...props };\n\n // Derive the missing dimension from the aspect ratio.\n if (hasWidth !== hasHeight && !sizing) {\n if (intrinsic && intrinsic.width > 0 && intrinsic.height > 0) {\n const aspect = intrinsic.width / intrinsic.height;\n if (hasWidth) {\n const width = toInches(props.w as number | string, slideWidth);\n next.w = width;\n next.h = width / aspect;\n } else {\n const height = toInches(props.h as number | string, slideHeight);\n next.h = height;\n next.w = height * aspect;\n }\n }\n return { ...component, props: next };\n }\n\n if (!sizing) return component;\n\n if (sizing.type !== 'contain' && sizing.type !== 'cover') {\n next.sizing = {\n ...sizing,\n w: toInches((sizing.w ?? props.w ?? 0) as number | string, slideWidth),\n h: toInches((sizing.h ?? props.h ?? 0) as number | string, slideHeight),\n };\n return { ...component, props: next };\n }\n\n const boxWidth = toInches(\n (sizing.w ?? props.w ?? 0) as number | string,\n slideWidth\n );\n const boxHeight = toInches(\n (sizing.h ?? props.h ?? 0) as number | string,\n slideHeight\n );\n\n if (boxWidth <= 0 || boxHeight <= 0) {\n warn(\n warnings,\n W.IMAGE_ZERO_BOX,\n `Image sizing box resolved to zero (${boxWidth}x${boxHeight})`,\n { component: 'image' }\n );\n }\n\n const usable =\n intrinsic &&\n intrinsic.width > 0 &&\n intrinsic.height > 0 &&\n boxWidth > 0 &&\n boxHeight > 0;\n\n if (!usable) {\n next.sizing = { ...sizing, w: boxWidth, h: boxHeight };\n return { ...component, props: next };\n }\n\n const imageAspect = intrinsic.width / intrinsic.height;\n\n if (sizing.type === 'contain') {\n // Fit inside the box, preserving the aspect ratio, centred. The element\n // ends up exactly the fitted size, so no sizing is passed on.\n const boxAspect = boxWidth / boxHeight;\n const fitWidth =\n imageAspect > boxAspect ? boxWidth : boxHeight * imageAspect;\n const fitHeight =\n imageAspect > boxAspect ? boxWidth / imageAspect : boxHeight;\n const baseX = toInches((props.x ?? 0) as number | string, slideWidth);\n const baseY = toInches((props.y ?? 0) as number | string, slideHeight);\n\n next.x = baseX + (boxWidth - fitWidth) / 2;\n next.y = baseY + (boxHeight - fitHeight) / 2;\n next.w = fitWidth;\n next.h = fitHeight;\n delete next.sizing;\n return { ...component, props: next };\n }\n\n // Cover: the backend crops correctly once given the real intrinsic size.\n next.w = intrinsic.width;\n next.h = intrinsic.height;\n next.sizing = { type: 'cover', w: boxWidth, h: boxHeight };\n return { ...component, props: next };\n}\n\n/**\n * Resolve a dimension to inches.\n *\n * Deliberately the plain rule — a number is inches, a percent resolves against\n * the axis — because these values feed the fitting arithmetic, where \"inches\"\n * is the only interpretation that makes sense.\n */\nfunction toInches(value: number | string, axisInches: number): number {\n if (typeof value === 'number') return value;\n if (value.endsWith('%')) {\n const pct = Number.parseFloat(value);\n return !Number.isNaN(pct) && pct >= 0 ? (pct / 100) * axisInches : 0;\n }\n const n = Number(value);\n return Number.isNaN(n) ? 0 : n;\n}\n\n/** Block requests to private, loopback and link-local hosts. */\nfunction isPrivateUrl(urlString: string): boolean {\n try {\n const { hostname } = new URL(urlString);\n if (\n hostname === 'localhost' ||\n hostname === '127.0.0.1' ||\n hostname === '::1' ||\n hostname === '[::1]' ||\n hostname.startsWith('10.') ||\n hostname.startsWith('192.168.') ||\n hostname.startsWith('169.254.') ||\n hostname.endsWith('.local') ||\n hostname.endsWith('.internal')\n ) {\n return true;\n }\n if (hostname.startsWith('172.')) {\n const second = Number.parseInt(hostname.split('.')[1], 10);\n if (second >= 16 && second <= 31) return true;\n }\n return false;\n } catch {\n return true;\n }\n}\n\nasync function probeIntrinsicSize(\n source: string,\n warnings: PipelineWarning[]\n): Promise<{ width: number; height: number } | undefined> {\n try {\n if (/^data:image\\//.test(source)) {\n const base64Data = source.split(',')[1];\n if (!base64Data) return undefined;\n const result = probe.sync(Buffer.from(base64Data, 'base64'));\n return result\n ? { width: result.width, height: result.height }\n : undefined;\n }\n\n if (/^https?:\\/\\//.test(source)) {\n if (isPrivateUrl(source)) return undefined;\n const result = await probe(source, { timeout: 5000 });\n return { width: result.width, height: result.height };\n }\n\n // Local file — restricted to the document base directory (or CWD) to\n // prevent path traversal (#142).\n const resolved = path.resolve(resolveFromBaseDir(source));\n if (!isAllowedLocalPath(resolved)) return undefined;\n const { createReadStream } = await import('fs');\n const result = await probe(createReadStream(resolved));\n return result ? { width: result.width, height: result.height } : undefined;\n } catch (error) {\n warn(\n warnings,\n W.IMAGE_PROBE_FAILED,\n `Image probe failed: ${error instanceof Error ? error.message : String(error)}`,\n { component: 'image' }\n );\n return undefined;\n }\n}\n","/**\n * Structure Processing\n * JSON -> internal model\n */\n\nimport type {\n PptxComponentInput,\n PptxThemeConfig,\n PresentationComponentDefinition,\n ProcessedPresentation,\n ProcessedSlide,\n SlideComponentDefinition,\n TemplateSlideDefinition,\n} from '../types';\nimport { isSlideComponent } from '../types';\nimport {\n resolveGridPosition,\n resolveComponentGridPosition,\n mergeGridConfigs,\n} from './grid';\nimport { getPptxTheme } from '../themes';\nimport type { GenerationOptions } from './generator';\nimport { resolveComponentTree } from '../utils/resolveComponentTree';\nimport {\n remapHyperlinkProps,\n remapHyperlinkSlideRefs,\n} from '../utils/hyperlink';\nimport { mergeWithDefaults } from '@json-to-office/shared';\n\n/** A slide child is rendered unless it carries `enabled: false`. */\nfunction isSlideEnabled(child: object): boolean {\n return !(\n 'enabled' in child && (child as { enabled?: boolean }).enabled === false\n );\n}\n\n/**\n * Map authored 1-based slide numbers (disabled slides included) to their\n * position in the generated deck. Dropped slides are absent from the map, so\n * hyperlinks pointing at them resolve to nothing instead of to whichever slide\n * happened to shift into that number.\n */\nfunction buildSlideIndexMap(\n children: PptxComponentInput[]\n): Map<number, number> {\n const map = new Map<number, number>();\n let authored = 0;\n let rendered = 0;\n for (const child of children) {\n if (!isSlideComponent(child)) continue;\n authored++;\n if (isSlideEnabled(child)) map.set(authored, ++rendered);\n }\n return map;\n}\n\nexport function processPresentation(\n document: PresentationComponentDefinition,\n options?: GenerationOptions\n): ProcessedPresentation {\n const { props, children = [] } = document;\n\n // The generation prologue hands the resolved theme over directly — after\n // the export-mode pre-pass, so a name lookup here would resurrect\n // pre-substitute font families. The `props.theme` resolution below (a name,\n // or an inline theme config object embedded in the document itself —\n // self-contained documents-as-data) is the fallback for direct callers.\n const baseTheme =\n options?.theme ??\n (typeof props.theme === 'object' && props.theme !== null\n ? (props.theme as PptxThemeConfig)\n : options?.customThemes?.[props.theme ?? 'default'] ??\n getPptxTheme(props.theme ?? 'default'));\n\n // Merge presentation-level componentDefaults on top of theme-level ones\n const presDefaults = props.componentDefaults;\n const theme = presDefaults\n ? {\n ...baseTheme,\n componentDefaults: mergeWithDefaults(\n presDefaults,\n baseTheme.componentDefaults || {}\n ),\n }\n : baseTheme;\n\n const slideWidth = props.slideWidth ?? 10;\n const slideHeight = props.slideHeight ?? 7.5;\n\n const slideIndexMap = buildSlideIndexMap(children);\n\n // Process template slide definitions\n let templates: TemplateSlideDefinition[] | undefined;\n if (props.templates && props.templates.length > 0) {\n templates = props.templates.map((m: TemplateSlideDefinition) => {\n const effectiveGrid = mergeGridConfigs(props.grid, m.grid);\n\n // Rebase slide refs in placeholder `defaults`, then resolve grid\n // positions. `defaults.props` is merged into the rendered component by\n // core/render.ts, so it reaches the writer just like a component's own\n // props and needs the same remapping.\n const resolvedPhs = m.placeholders?.map((ph) => {\n const phDefaults = ph.defaults;\n const defaultProps = phDefaults?.props\n ? remapHyperlinkProps(phDefaults.props, slideIndexMap)\n : undefined;\n const base =\n phDefaults && defaultProps && defaultProps !== phDefaults.props\n ? { ...ph, defaults: { ...phDefaults, props: defaultProps } }\n : ph;\n\n if (!base.grid) return base;\n const abs = resolveGridPosition(\n base.grid,\n effectiveGrid,\n slideWidth,\n slideHeight\n );\n return {\n ...base,\n x: base.x ?? abs.x,\n y: base.y ?? abs.y,\n w: base.w ?? abs.w,\n h: base.h ?? abs.h,\n grid: undefined,\n };\n });\n\n // Resolve componentDefaults then grid positions on fixed objects\n const defaultedObjects = m.objects\n ? resolveComponentTree(m.objects, theme)\n : undefined;\n const resolvedObjects = defaultedObjects?.map((obj) =>\n remapHyperlinkSlideRefs(\n resolveComponentGridPosition(\n obj,\n effectiveGrid,\n slideWidth,\n slideHeight\n ),\n slideIndexMap\n )\n );\n\n return { ...m, placeholders: resolvedPhs, objects: resolvedObjects };\n });\n }\n\n const slides: ProcessedSlide[] = [];\n\n for (const child of children) {\n if (isSlideComponent(child)) {\n // `enabled: false` drops the slide entirely; absent means enabled\n if (!isSlideEnabled(child)) continue;\n\n const slideComponents: PptxComponentInput[] = [];\n if (child.children) {\n for (const slideChild of child.children) {\n slideComponents.push(slideChild);\n }\n }\n\n // Resolve componentDefaults on all slide components, then rebase\n // slide-targeted hyperlinks onto the generated slide numbering\n const resolvedComponents = resolveComponentTree(\n slideComponents,\n theme\n ).map((component) => remapHyperlinkSlideRefs(component, slideIndexMap));\n\n // Every slide prop is optional, so validation accepts a slide with no\n // `props` at all (the deep validator checks an empty object in that\n // case). Generation has to accept the same documents validation does.\n const slideProps: NonNullable<SlideComponentDefinition['props']> =\n child.props ?? {};\n\n const placeholders = slideProps.placeholders as\n | Record<string, PptxComponentInput>\n | undefined;\n\n slides.push({\n components: resolvedComponents,\n background: slideProps.background,\n transition: slideProps.transition,\n notes: slideProps.notes,\n layout: slideProps.layout,\n hidden: slideProps.hidden,\n template: slideProps.template,\n placeholders: placeholders\n ? Object.fromEntries(\n Object.entries(placeholders).map(([name, component]) => [\n name,\n remapHyperlinkSlideRefs(component, slideIndexMap),\n ])\n )\n : undefined,\n });\n }\n }\n\n return {\n metadata: {\n title: props.title,\n author: props.author,\n subject: props.subject,\n company: props.company,\n },\n theme,\n grid: props.grid,\n slideWidth,\n slideHeight,\n rtlMode: props.rtlMode ?? false,\n language: props.language,\n pageNumberFormat: props.pageNumberFormat ?? '9',\n slides,\n templates,\n services: options?.services,\n };\n}\n","// Version information\nexport function getPptxCoreVersion(): string {\n return 'PptxCore v1.0.0';\n}\n\n// Core API — buffer and file oriented; no member exposes a renderer object.\nexport {\n generateBufferFromJson,\n generateBufferWithWarnings,\n generateAndSaveFromJson,\n generateFromFile,\n isPresentationComponentDefinition,\n PresentationValidationError,\n PresentationGenerator,\n} from './core/generator';\n\nexport type {\n GenerationOptions,\n GenerationResult,\n GenerationValidationOptions,\n} from './core/generator';\n\n// Renderer selection. The IR itself stays internal to this package for now.\nexport type { PptxRendererId } from './renderers/types';\nexport { DEFAULT_PPTX_RENDERER_ID } from './renderers/types';\nexport { isPptxRendererId, pptxRendererIds } from './renderers/registry';\nexport { UncompiledComponentError } from './core/generateFromIr';\nexport { DEFAULT_GENERATED_AT } from './core/finalizePackage';\nexport type { PresentationPackagingOptions } from './core/finalizePackage';\n\n// Types\nexport type {\n PptxComponentInput,\n PresentationComponentDefinition,\n PresentationComponentDefinitionFor,\n SlideComponentDefinition,\n ProcessedPresentation,\n ProcessedSlide,\n PptxThemeConfig,\n PipelineWarning,\n SlideContext,\n SlideRenderContext,\n} from './types';\n\nexport { isPresentationComponent, isSlideComponent } from './types';\n\n// Warning utilities\nexport { W as WarningCodes } from './utils/warn';\nexport type { WarningCode } from './utils/warn';\n\n// Themes\nexport { DEFAULT_PPTX_THEME, getPptxTheme, pptxThemes } from './themes';\n\n// Plugin system\nexport {\n createComponent,\n createVersion,\n createPresentationGenerator,\n resolveComponentVersion,\n validateComponentProps,\n validatePresentation,\n cleanComponentProps,\n ComponentValidationError,\n DuplicateComponentError,\n generatePluginPresentationSchema,\n exportPluginSchema,\n} from './plugin';\n\nexport type {\n CustomComponent,\n ComponentVersion,\n ComponentVersionMap,\n RenderFunction,\n RenderContext,\n PresentationGeneratorOptions,\n PresentationGenerator as PluginPresentationGenerator,\n PresentationGeneratorBuilder,\n BufferGenerationResult as PluginBufferGenerationResult,\n FileGenerationResult as PluginFileGenerationResult,\n GenerateFileOptions as PluginGenerateFileOptions,\n GenerateOptions as PluginGenerateOptions,\n GenerationValidationOptions as PluginGenerationValidationOptions,\n ValidationResult as PluginValidationResult,\n ExtractCustomComponentType,\n CustomComponentUnion,\n ExtendedPptxComponentInput,\n ExtendedPresentationComponent,\n InferBuilderComponents,\n InferDocumentType,\n InferComponentDefinition,\n ComponentValidationResult,\n ValidationError as PluginValidationError,\n} from './plugin';\n","/**\n * Plugin system for json-to-pptx\n *\n * @example\n * ```typescript\n * import { createComponent, createVersion, createPresentationGenerator } from '@json-to-office/core-pptx/plugin';\n * import { Type } from '@sinclair/typebox';\n *\n * const bannerComponent = createComponent({\n * name: 'banner' as const,\n * versions: {\n * '1.0.0': createVersion({\n * propsSchema: Type.Object({ title: Type.String() }),\n * render: async ({ props }) => [{\n * name: 'text',\n * props: { text: props.title, x: 0.5, y: 0.5, w: 9, h: 1 }\n * }]\n * })\n * }\n * });\n *\n * const generator = createPresentationGenerator()\n * .addComponent(bannerComponent);\n * ```\n */\n\n// Component creation (from shared)\nexport {\n createComponent,\n createVersion,\n type CustomComponent,\n type ComponentVersion,\n type ComponentVersionMap,\n type RenderFunction,\n type RenderContext,\n} from '@json-to-office/shared/plugin';\n\n// Generator\nexport {\n createPresentationGenerator,\n type PresentationGeneratorOptions,\n} from './createPresentationGenerator';\n\n// Types\nexport {\n type PresentationGenerator,\n type PresentationGeneratorBuilder,\n type BufferGenerationResult,\n type FileGenerationResult,\n type GenerateFileOptions,\n type GenerateOptions,\n type GenerationValidationOptions,\n type ValidationResult,\n type ExtractCustomComponentType,\n type CustomComponentUnion,\n type ExtendedPptxComponentInput,\n type ExtendedPresentationComponent,\n type InferBuilderComponents,\n type InferDocumentType,\n type InferComponentDefinition,\n} from './types';\n\n// Validation\nexport {\n validateComponentProps,\n validatePresentation,\n cleanComponentProps,\n ComponentValidationError,\n DuplicateComponentError,\n type ValidationError,\n type ComponentValidationResult,\n} from './validation';\n\n// Schema\nexport { generatePluginPresentationSchema, exportPluginSchema } from './schema';\n\n// Version resolution (from shared)\nexport { resolveComponentVersion } from '@json-to-office/shared/plugin';\n","import type { TSchema } from '@sinclair/typebox';\nimport type { CustomComponent } from '@json-to-office/shared/plugin';\nimport {\n resolveComponentVersion,\n DuplicateComponentError,\n ComponentValidationError,\n} from '@json-to-office/shared/plugin';\nimport type {\n PptxComponentInput,\n PresentationComponentDefinition,\n PipelineWarning,\n PptxThemeConfig,\n} from '../types';\nimport type {\n ExtendedPresentationComponent,\n PresentationGeneratorBuilder,\n BufferGenerationResult,\n FileGenerationResult,\n GenerateFileOptions,\n GenerateOptions,\n GenerationValidationOptions,\n ValidationResult,\n} from './types';\nimport { validatePresentation, cleanComponentProps } from './validation';\nimport { generatePluginPresentationSchema, exportPluginSchema } from './schema';\nimport { processPresentation } from '../core/structure';\nimport type { PresentationPackagingOptions } from '../core/finalizePackage';\nimport { renderProcessedViaIr } from '../core/generateFromIr';\nimport type { PptxRendererId } from '../renderers/types';\nimport { getPptxTheme, hasPptxTheme } from '../themes';\nimport type { ServicesConfig, FontRuntimeOpts } from '@json-to-office/shared';\nimport { resolveDocumentFonts } from '../core/fontResolution';\nimport { resolveThemeContext } from '../core/generationContext';\nimport { runWithBaseDir } from '../utils/baseDirContext';\nimport { assertNoContentConflicts } from '../core/generator';\n\n/**\n * Options for creating a presentation generator\n */\nexport interface PresentationGeneratorOptions\n extends PresentationPackagingOptions {\n /** Theme configuration or theme name */\n theme?: PptxThemeConfig | string;\n /** Custom themes map */\n customThemes?: Record<string, PptxThemeConfig>;\n /** Enable debug logging */\n debug?: boolean;\n /** External service configuration (e.g. Highcharts export server) */\n services?: ServicesConfig;\n /** Font resolution options — extraEntries, Google Fonts config, onResolved hook. */\n fonts?: FontRuntimeOpts;\n /** Default validation behavior; per-call options take precedence. */\n validation?: GenerationValidationOptions;\n /**\n * Directory that relative asset paths (image `path` props, slide\n * background images) resolve against. Per-call `options.baseDir`\n * overrides it; defaults to `process.cwd()` when neither is set (#142).\n */\n baseDir?: string;\n /**\n * Backend that turns the compiled presentation into bytes. Per-call\n * `options.renderer` overrides it; defaults to `pptxgenjs`.\n */\n renderer?: PptxRendererId;\n}\n\n/**\n * Internal state held by each builder instance\n */\ninterface BuilderState {\n components: readonly CustomComponent<any, any, any>[];\n componentNames: Set<string>;\n theme?: PptxThemeConfig | string;\n customThemes?: Record<string, PptxThemeConfig>;\n debug: boolean;\n services?: ServicesConfig;\n fonts?: FontRuntimeOpts;\n validation?: GenerationValidationOptions;\n packaging: PresentationPackagingOptions;\n baseDir?: string;\n renderer?: PptxRendererId;\n}\n\ntype ValidateEmitted = (\n emitted: PptxComponentInput[],\n componentLabel: string,\n parentName?: string\n) => void;\n\n/**\n * Create the builder implementation with the given state\n */\nfunction createBuilderImpl<\n TComponents extends readonly CustomComponent<any, any, any>[],\n>(state: BuilderState): PresentationGeneratorBuilder<TComponents> {\n const componentMap = new Map(state.components.map((c) => [c.name, c]));\n\n /**\n * Process custom components in slide children, recursively resolving them\n * to standard PptxComponentInput elements.\n */\n async function processSlideComponents(\n components: PptxComponentInput[],\n warningsCollector: PipelineWarning[],\n theme: PptxThemeConfig,\n validateEmitted: ValidateEmitted | undefined,\n parentName?: string,\n depth = 0\n ): Promise<PptxComponentInput[]> {\n if (depth > 20) {\n throw new Error(\n 'Maximum component nesting depth exceeded (20). Check for circular component references.'\n );\n }\n const processed: PptxComponentInput[] = [];\n\n for (const componentData of components) {\n const customComponent = componentMap.get(componentData.name);\n\n if (customComponent) {\n try {\n if (!componentData.props) {\n throw new Error(\n `Custom component '${componentData.name}' must have a 'props' property. ` +\n `Use format: { name: '${componentData.name}', props: {...} }`\n );\n }\n\n const componentWithVersion = componentData as {\n name: string;\n version?: string;\n props: Record<string, any>;\n children?: PptxComponentInput[];\n };\n\n // Resolve version\n const versionEntry = resolveComponentVersion(\n customComponent.name,\n customComponent.versions,\n componentWithVersion.version\n );\n\n // Validate and clean props\n const cleanedProps = cleanComponentProps(\n versionEntry,\n componentWithVersion.props\n );\n\n // Process nested children if container\n let nestedChildren: unknown[] | undefined;\n if (\n componentWithVersion.children &&\n Array.isArray(componentWithVersion.children)\n ) {\n nestedChildren = await processSlideComponents(\n componentWithVersion.children,\n warningsCollector,\n theme,\n validateEmitted,\n undefined,\n depth + 1\n );\n }\n\n // Create addWarning callback\n const versionLabel = componentWithVersion.version\n ? `${customComponent.name}@${componentWithVersion.version}`\n : customComponent.name;\n\n const addWarning = (\n message: string,\n context?: Record<string, unknown>\n ) => {\n warningsCollector.push({\n code: (context?.code as string) ?? 'PLUGIN_WARNING',\n message,\n component: versionLabel,\n slide: context?.slide as number | undefined,\n });\n };\n\n // Call render\n const result = await versionEntry.render({\n props: cleanedProps,\n theme,\n addWarning,\n children: nestedChildren,\n });\n\n const resultComponents = (\n Array.isArray(result) ? result : [result]\n ) as PptxComponentInput[];\n\n validateEmitted?.(resultComponents, versionLabel, parentName);\n\n // Recursively process in case result contains more custom components\n const processedResult = await processSlideComponents(\n resultComponents,\n warningsCollector,\n theme,\n validateEmitted,\n parentName,\n depth + 1\n );\n processed.push(...processedResult);\n\n if (state.debug) {\n console.log(\n `Processed custom component '${versionLabel}':`,\n processedResult\n );\n }\n } catch (error) {\n if (error instanceof ComponentValidationError) {\n throw error;\n }\n throw new Error(\n `Error processing custom component '${customComponent.name}': ${\n error instanceof Error ? error.message : String(error)\n }`\n );\n }\n } else {\n // Standard component — process children recursively\n if (componentData.children && Array.isArray(componentData.children)) {\n const processedChildren = await processSlideComponents(\n componentData.children,\n warningsCollector,\n theme,\n validateEmitted,\n componentData.name,\n depth + 1\n );\n processed.push({\n ...componentData,\n children: processedChildren,\n });\n } else {\n processed.push(componentData);\n }\n }\n }\n\n return processed;\n }\n\n /**\n * Add a custom component to the generator\n */\n function addComponent<TNewComponent extends CustomComponent<any, any, any>>(\n component: TNewComponent\n ): PresentationGeneratorBuilder<readonly [...TComponents, TNewComponent]> {\n if (!component.name) {\n throw new Error('Component name is required');\n }\n\n if (state.componentNames.has(component.name)) {\n throw new DuplicateComponentError(component.name);\n }\n\n const newComponentNames = new Set(state.componentNames);\n newComponentNames.add(component.name);\n\n const newState: BuilderState = {\n components: [...state.components, component],\n componentNames: newComponentNames,\n theme: state.theme,\n customThemes: state.customThemes,\n debug: state.debug,\n services: state.services,\n fonts: state.fonts,\n validation: state.validation,\n packaging: state.packaging,\n baseDir: state.baseDir,\n renderer: state.renderer,\n };\n\n return createBuilderImpl<readonly [...TComponents, TNewComponent]>(\n newState\n );\n }\n\n /**\n * Generate a presentation buffer\n */\n async function generate(\n document: ExtendedPresentationComponent<TComponents>,\n options?: GenerateOptions\n ): Promise<BufferGenerationResult> {\n try {\n let internalDocument =\n document as unknown as PresentationComponentDefinition;\n const renderer =\n options?.renderer ?? state.renderer ?? internalDocument.renderer;\n const validationDocument =\n renderer === undefined\n ? internalDocument\n : { ...internalDocument, renderer };\n\n const validationOptions: GenerationValidationOptions = {\n ...state.validation,\n ...options?.validation,\n };\n if (validationOptions.enabled !== false) {\n const result = validatePresentation(\n validationDocument,\n state.components as unknown as CustomComponent<TSchema>[],\n { allowUnknownFields: validationOptions.allowUnknownFields }\n );\n if (!result.valid) {\n throw new ComponentValidationError(result.errors, internalDocument);\n }\n } else if (!internalDocument || internalDocument.name !== 'pptx') {\n throw new Error('Top-level component must be a pptx component');\n }\n\n const warnings: PipelineWarning[] = [];\n\n // Props defaulting, inline-theme normalization, theme resolution\n // (customThemes → constructor theme → built-in) and export-mode pre-pass\n // — shared with the core pipeline so the two\n // cannot drift (see core/generationContext.ts). The pre-pass runs\n // BEFORE custom-component expansion so any component that reads\n // `theme.fonts.*` during render sees the substituted names, not the\n // original non-safe ones.\n //\n // Theme precedence: customThemes[name] → doc-named built-in →\n // constructor `state.theme` object → built-in, with the lookup name\n // taken from doc-level `props.theme` (or `defaultThemeName` when the\n // doc names none). A document explicitly naming a known built-in gets\n // it; the constructor object fills in when the doc names nothing or\n // names something nothing recognizes (#141). The `authored` guard on\n // the built-in step matters twice over: an unauthored default name\n // must not shadow the constructor object, and an authored UNKNOWN name\n // must still reach the constructor object (getPptxTheme never misses —\n // a doc naming \"wiseair\" must render the app's theme, not silently\n // fall back to default). Matches the DOCX plugin\n // (resolveDocumentTheme) exactly.\n const context = resolveThemeContext(internalDocument, {\n customThemes: state.customThemes,\n fonts: state.fonts,\n warnings,\n defaultThemeName:\n typeof state.theme === 'string' ? state.theme : undefined,\n resolveNamedTheme: (name, authored) =>\n state.customThemes?.[name] ??\n (authored && hasPptxTheme(name) ? getPptxTheme(name) : undefined) ??\n (typeof state.theme === 'object' && state.theme !== null\n ? state.theme\n : getPptxTheme(name)),\n });\n const modedRoot = context.document;\n const resolvedTheme = context.theme;\n\n // A custom render() creates a new, previously unseen boundary in the\n // component tree. Validate its output in the authored parent context so\n // dead props and illegal placement cannot reach the renderer silently.\n const validateEmitted: ValidateEmitted | undefined =\n validationOptions.enabled === false\n ? undefined\n : (emitted, componentLabel, parentName) => {\n let validationDocument: PresentationComponentDefinition;\n if (parentName === 'pptx') {\n validationDocument = {\n ...modedRoot,\n ...(renderer !== undefined ? { renderer } : {}),\n children: emitted,\n };\n } else if (parentName === 'slide') {\n validationDocument = {\n ...modedRoot,\n ...(renderer !== undefined ? { renderer } : {}),\n children: [{ name: 'slide', props: {}, children: emitted }],\n };\n } else {\n // Custom container semantics are plugin-defined. The complete\n // expanded-tree pass below validates the final standard tree.\n return;\n }\n\n const result = validatePresentation(\n validationDocument,\n state.components as unknown as CustomComponent<TSchema>[],\n { allowUnknownFields: validationOptions.allowUnknownFields }\n );\n if (!result.valid) {\n throw new ComponentValidationError(\n result.errors.map((error) => ({\n ...error,\n message: `custom component '${componentLabel}' emitted invalid output — ${error.message}`,\n })),\n emitted\n );\n }\n };\n\n // Process custom components in all slide children\n const processedChildren = modedRoot.children\n ? await processAllSlides(\n modedRoot.children,\n warnings,\n resolvedTheme,\n validateEmitted\n )\n : [];\n\n const processedDocument: PresentationComponentDefinition = {\n ...modedRoot,\n children: processedChildren,\n };\n\n // Validate the fully expanded tree once more. This covers output from\n // nested custom containers whose intermediate parent semantics are\n // plugin-defined and therefore cannot be checked at render time.\n if (validationOptions.enabled !== false) {\n const result = validatePresentation(\n {\n ...processedDocument,\n ...(renderer !== undefined ? { renderer } : {}),\n },\n [],\n {\n allowUnknownFields: validationOptions.allowUnknownFields,\n }\n );\n if (!result.valid) {\n throw new ComponentValidationError(\n result.errors.map((error) => ({\n ...error,\n message: `expanded plugin output failed validation — ${error.message}`,\n })),\n processedDocument\n );\n }\n }\n\n // resolveDocumentFonts fires `fonts.onResolved` internally when a\n // listener is registered (LibreOffice preview stager). The PPTX\n // itself never embeds bytes.\n await resolveDocumentFonts(\n processedDocument,\n resolvedTheme,\n warnings,\n state.fonts\n );\n\n // Unconditional conflict gate on the expanded tree — the tree that\n // reaches the renderer, so it also covers payloads emitted by custom\n // components. The validators above collect the same conflicts with\n // richer paths when validation is enabled; this is the net for\n // `validation: { enabled: false }`, where the core path already threw\n // and this path silently resolved by runtime precedence.\n assertNoContentConflicts(processedDocument);\n\n // processPresentation takes the resolved (post-substitute) theme by\n // value — the document's `props.theme` stays as authored and is not\n // consulted again.\n // Scope the document base directory over process+render: relative\n // asset paths are rewritten eagerly there — pptxgenjs reads them\n // later, during write() (#142). Matches the core pipeline.\n const buffer = await runWithBaseDir(\n options?.baseDir ?? state.baseDir,\n () =>\n renderProcessedViaIr(\n processPresentation(processedDocument, {\n theme: resolvedTheme,\n services: state.services,\n }),\n warnings,\n {\n renderer,\n services: state.services,\n deterministic:\n options?.deterministic ?? state.packaging.deterministic,\n generatedAt: options?.generatedAt ?? state.packaging.generatedAt,\n }\n )\n );\n\n return { buffer, warnings };\n } catch (error) {\n if (state.debug) {\n console.error('Presentation generation error:', error);\n }\n throw error;\n }\n }\n\n /**\n * Process custom components inside all slides.\n * Walks the top-level children (slides), then processes each slide's children.\n */\n async function processAllSlides(\n children: PptxComponentInput[],\n warnings: PipelineWarning[],\n theme: PptxThemeConfig,\n validateEmitted: ValidateEmitted | undefined\n ): Promise<PptxComponentInput[]> {\n const result: PptxComponentInput[] = [];\n\n for (const child of children) {\n if (child.name === 'slide' && child.children) {\n const processedSlideChildren = await processSlideComponents(\n child.children,\n warnings,\n theme,\n validateEmitted,\n 'slide'\n );\n result.push({ ...child, children: processedSlideChildren });\n } else {\n // Non-slide top-level children — process in case they're custom\n const processedTopLevel = await processSlideComponents(\n [child],\n warnings,\n theme,\n validateEmitted,\n 'pptx'\n );\n result.push(...processedTopLevel);\n }\n }\n\n return result;\n }\n\n /**\n * Generate and save to file\n */\n async function generateFile(\n document: ExtendedPresentationComponent<TComponents>,\n outputPath: string,\n options?: GenerateFileOptions\n ): Promise<FileGenerationResult> {\n const { buffer, warnings } = await generate(document, options);\n const fs = await import('fs/promises');\n await fs.writeFile(outputPath, new Uint8Array(buffer));\n return { warnings };\n }\n\n /**\n * Get registered component names\n */\n function getComponentNames(): string[] {\n return Array.from(state.componentNames);\n }\n\n /**\n * Validate a document without generating it\n */\n function validate(\n document: ExtendedPresentationComponent<TComponents>\n ): ValidationResult {\n try {\n const internalDocument =\n document as unknown as PresentationComponentDefinition;\n const result = validatePresentation(\n internalDocument,\n state.components as unknown as CustomComponent<TSchema>[]\n );\n if (!result.valid) {\n return {\n valid: false,\n errors: result.errors.map((e) => ({\n path: e.path,\n message: e.message,\n })),\n };\n }\n return { valid: true };\n } catch (error) {\n if (error instanceof ComponentValidationError) {\n return {\n valid: false,\n errors: error.errors.map((e) => ({\n path: e.path,\n message: e.message,\n })),\n };\n }\n return {\n valid: false,\n errors: [\n {\n path: 'document',\n message: error instanceof Error ? error.message : String(error),\n },\n ],\n };\n }\n }\n\n /**\n * Generate the extended JSON schema\n */\n function generateSchema(): TSchema {\n return generatePluginPresentationSchema(\n state.components as unknown as CustomComponent<TSchema>[]\n );\n }\n\n /**\n * Export the schema to a file\n */\n async function exportSchemaToFile(\n outputPath: string,\n options?: { prettyPrint?: boolean }\n ): Promise<void> {\n await exportPluginSchema(\n state.components as unknown as CustomComponent<TSchema>[],\n outputPath,\n options\n );\n }\n\n return Object.freeze({\n addComponent,\n generate,\n generateBuffer: generate,\n generateFile,\n getComponentNames,\n validate,\n generateSchema,\n exportSchema: exportSchemaToFile,\n });\n}\n\n/**\n * Create a presentation generator with chainable component registration.\n */\nexport function createPresentationGenerator(\n options: PresentationGeneratorOptions = {}\n): PresentationGeneratorBuilder<readonly []> {\n const initialState: BuilderState = {\n components: [],\n componentNames: new Set(),\n theme: options.theme,\n customThemes: options.customThemes,\n debug: options.debug ?? false,\n services: options.services,\n fonts: options.fonts,\n validation: options.validation,\n packaging: {\n deterministic: options.deterministic,\n generatedAt: options.generatedAt,\n },\n baseDir: options.baseDir,\n renderer: options.renderer,\n };\n\n return createBuilderImpl<readonly []>(initialState);\n}\n","import type { TSchema, Static } from '@sinclair/typebox';\nimport type { CustomComponent } from '@json-to-office/shared/plugin';\nimport type { PresentationComponentDefinition } from '../types';\nimport {\n resolveComponentVersion,\n validateCustomComponentProps,\n ComponentValidationError,\n type ComponentValidationResult,\n} from '@json-to-office/shared/plugin';\nimport type { ValidationError } from '@json-to-office/shared';\nimport { validatePresentationDocument } from '@json-to-office/shared-pptx';\n\n// Re-export errors from shared\nexport {\n DuplicateComponentError,\n ComponentValidationError,\n} from '@json-to-office/shared/plugin';\nexport type { ComponentValidationResult } from '@json-to-office/shared/plugin';\nexport type { ValidationError } from '@json-to-office/shared';\n\n/**\n * Validate component props against a schema.\n */\nexport function validateComponentProps<TPropsSchema extends TSchema>(\n schema: { propsSchema: TPropsSchema },\n props: unknown,\n componentName?: string,\n opts?: { clean?: boolean; applyDefaults?: boolean }\n): ComponentValidationResult<TPropsSchema> {\n return validateCustomComponentProps<TPropsSchema>(schema.propsSchema, props, {\n // Render-time cleaning remains the default. The document-validation path\n // passes clean:false so unknown custom props are rejected when the custom\n // schema declares additionalProperties:false.\n clean: opts?.clean ?? true,\n applyDefaults: opts?.applyDefaults ?? true,\n componentName,\n });\n}\n\n/**\n * Validate presentation and all custom components (version-aware).\n *\n * Standard nodes and tree structure are checked by the shared deep validator;\n * custom component props are then checked against their resolved version.\n */\nexport function validatePresentation(\n document: PresentationComponentDefinition,\n customComponents: CustomComponent<any, any, any>[],\n options?: { allowUnknownFields?: boolean }\n): { valid: boolean; errors: ValidationError[] } {\n const knownCustomNames = new Set(customComponents.map((c) => c.name));\n\n // Validate all standard nodes and tree structure. Registered custom nodes\n // are deferred to the version-aware pass below, while their descendants are\n // still walked by the unified validator.\n const documentResult = validatePresentationDocument(document, {\n knownCustomNames,\n allowUnknownFields: options?.allowUnknownFields,\n });\n const errors: ValidationError[] = [...documentResult.errors];\n\n function validateComponents(components: any[], pathPrefix = 'children') {\n components.forEach((componentData, index) => {\n if (\n !componentData ||\n typeof componentData !== 'object' ||\n Array.isArray(componentData)\n ) {\n return;\n }\n\n const customComponent = customComponents.find(\n (cc) => cc.name === componentData.name\n );\n\n if (customComponent) {\n const versionEntry = resolveComponentVersion(\n customComponent.name,\n customComponent.versions,\n componentData.version\n );\n\n const validation = validateComponentProps(\n versionEntry,\n componentData.props,\n customComponent.name,\n { clean: options?.allowUnknownFields === true }\n );\n\n if (!validation.valid && validation.errors) {\n const indexedErrors = validation.errors.map(\n (error: ValidationError) => ({\n ...error,\n path: `${pathPrefix}[${index}].${error.path}`,\n })\n );\n errors.push(...indexedErrors);\n }\n }\n\n // Recurse into children (slides, containers, etc.)\n if (componentData.children && Array.isArray(componentData.children)) {\n validateComponents(\n componentData.children,\n `${pathPrefix}[${index}].children`\n );\n }\n });\n }\n\n if (document && Array.isArray(document.children)) {\n validateComponents(document.children);\n }\n\n return errors.length > 0\n ? { valid: false, errors }\n : { valid: true, errors: [] };\n}\n\n/**\n * Validates component props and returns typed props or throws.\n */\nexport function getValidatedProps<TPropsSchema extends TSchema>(\n schema: { propsSchema: TPropsSchema },\n props: unknown\n): Static<TPropsSchema> {\n const validation = validateComponentProps(schema, props);\n\n if (!validation.valid) {\n throw new ComponentValidationError(validation.errors || [], props);\n }\n\n return validation.data!;\n}\n\nexport const cleanComponentProps = getValidatedProps;\n","import type { TSchema } from '@sinclair/typebox';\nimport type { CustomComponent } from '@json-to-office/shared/plugin';\nimport {\n generateUnifiedDocumentSchema,\n type CustomComponentInfo,\n} from '@json-to-office/shared-pptx';\n\n/**\n * Generate a JSON schema for plugin-enhanced presentations at RUNTIME.\n */\nexport function generatePluginPresentationSchema(\n customComponents: CustomComponent<any, any, any>[]\n): TSchema {\n const customComponentInfos: CustomComponentInfo[] = customComponents.map(\n (component) => {\n const versionKeys = Object.keys(component.versions);\n\n const versions = versionKeys.map((v) => ({\n version: v,\n propsSchema: component.versions[v].propsSchema,\n hasChildren: component.versions[v].hasChildren === true,\n description: component.versions[v].description,\n }));\n\n return {\n name: component.name,\n versions,\n };\n }\n );\n\n return generateUnifiedDocumentSchema({\n customComponents: customComponentInfos,\n });\n}\n\n/**\n * Export a plugin-enhanced JSON schema to a file at RUNTIME\n */\nexport async function exportPluginSchema(\n customComponents: CustomComponent<any, any, any>[],\n outputPath: string,\n options: { prettyPrint?: boolean } = {}\n): Promise<void> {\n const { prettyPrint = true } = options;\n\n const { convertToJsonSchema, exportSchemaToFile } = await import(\n '@json-to-office/shared'\n );\n\n const schema = generatePluginPresentationSchema(customComponents);\n\n const jsonSchema = convertToJsonSchema(schema, {\n $schema: 'http://json-schema.org/draft-07/schema#',\n });\n\n await exportSchemaToFile(jsonSchema, outputPath, { prettyPrint });\n}\n"],"mappings":";;;;;;;;;;;AA6BO,SAAS,KACd,UACA,MACA,SACA,OACM;AACN,MAAI,UAAU;AACZ,aAAS,KAAK,EAAE,MAAM,SAAS,GAAG,MAAM,CAAC;AAAA,EAC3C,OAAO;AACL,YAAQ,KAAK,OAAO;AAAA,EACtB;AACF;AAxCA,IAEa;AAFb;AAAA;AAAA;AAEO,IAAM,IAAI;AAAA,MACf,mBAAmB;AAAA,MACnB,oBAAoB;AAAA,MACpB,eAAe;AAAA,MACf,eAAe;AAAA,MACf,sBAAsB;AAAA,MACtB,oBAAoB;AAAA,MACpB,2BAA2B;AAAA,MAC3B,iBAAiB;AAAA,MACjB,oBAAoB;AAAA,MACpB,0BAA0B;AAAA,MAC1B,yBAAyB;AAAA,MACzB,kBAAkB;AAAA,MAClB,qBAAqB;AAAA,MACrB,yBAAyB;AAAA,MACzB,sBAAsB;AAAA,MACtB,eAAe;AAAA,MACf,uBAAuB;AAAA,MACvB,iBAAiB;AAAA,MACjB,wBAAwB;AAAA,MACxB,wBAAwB;AAAA,MACxB,gBAAgB;AAAA,MAChB,iBAAiB;AAAA,IACnB;AAAA;AAAA;;;ACzBA,IAuBa,cAEA,eAEA,wBA0aA;AArcb;AAAA;AAAA;AAuBO,IAAM,eAAe;AAErB,IAAM,gBAAgB,eAAe;AAErC,IAAM,yBAAyB;AA0a/B,IAAM,mBAAmB;AAAA,MAC9B;AAAA,MACA;AAAA,MACA;AAAA,MACA;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;AAAA,EACpB;AAEA,SAAO,kBAA+B,YAAY;AACpD;;;AD9jBA,SAAS,2BAAAG,gCAA+B;;;AD5EjC,SAAS,qBAA6B;AAC3C,SAAO;AACT;","names":["color","background","fill","color","fill","path","path","EMU_PER_INCH","probe","fill","path","background","JSZip","path","assertNever","fill","init_emit","init_emit","color","weight","hyperlink","mergeWithDefaults","path","background","template","mergeWithDefaults","hyperlink","fill","color","createPptxGenJsRenderer","createOfficeOpenPptxRenderer","registry","path","path","resolve","result","path","mergeWithDefaults","slideChild","resolveComponentVersion","DuplicateComponentError","ComponentValidationError","validatePresentationDocument","ComponentValidationError","resolveComponentVersion","ComponentValidationError","DuplicateComponentError","validationDocument","resolveComponentVersion"]}
|