@json-to-office/core-pptx 5.3.0 → 6.0.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.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/utils/warn.ts","../src/ir/types.ts","../src/ir/units.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/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/generationOptions.ts","../src/core/expandHighcharts.ts","../src/utils/environment.ts","../src/core/resolveImageLayout.ts","../src/quality/facts.ts","../src/core/generationContext.ts","../src/themes/consulting.pptx.theme.json","../src/themes/consulting.ts","../src/themes/vermilion.pptx.theme.json","../src/themes/devportal.pptx.theme.json","../src/themes/alternates.ts","../src/themes/defaults.ts","../src/themes/design-system.ts","../src/utils/componentDefaults.ts","../src/utils/resolveComponentTree.ts","../src/core/structure.ts","../src/core/dimensions.ts","../src/core/layout.ts","../src/core/fit.ts","../src/utils/textMetrics.ts","../src/blocks/document.ts","../src/index.ts","../src/blueprints/index.ts","../src/templates/blueprints/consulting-deck.pptx.blueprint.json","../src/quality/preflight.ts","../src/quality/rules.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 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 TEXT_OVERLAP_UNPOSITIONED: 'TEXT_OVERLAP_UNPOSITIONED',\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 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\n * ------------------------------------------------------------------ */\n\nexport interface PptxIrSlide {\n /** Deterministic: `slide${n}`, 1-based in generated order. */\n id: string;\n path: 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","/**\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 * 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 type { PptxFeature } from '../../ir/features';\nimport type {\n PptxIR,\n PptxIrBackground,\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 * Explicit allowlist with four verified gaps. A new `PptxFeature` stays\n * unsupported until this adapter deliberately adds and tests it.\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 'rich-text',\n 'text',\n 'shapes',\n 'images',\n 'svg',\n 'image-crop',\n 'image-rounding',\n 'tables',\n 'table-merged-cells',\n 'table-insets',\n 'table-rounded-corners',\n 'table-auto-page',\n 'charts',\n 'chart-bar-style',\n 'chart-pie-style',\n 'chart-line-style',\n 'chart-radar-style',\n 'chart-data-labels',\n 'chart-data-border',\n 'chart-axis-scale',\n 'chart-axis-visibility',\n 'chart-axis-style',\n 'chart-text-style',\n 'solid-fills',\n 'gradient-fills',\n 'pattern-fills',\n 'lines',\n 'shadows',\n 'backgrounds',\n 'speaker-notes',\n 'hidden-slides',\n 'external-links',\n 'internal-links',\n 'text-hyperlinks',\n 'element-hyperlinks',\n 'rotation',\n 'image-transform',\n 'flip-horizontal',\n 'flip-vertical',\n 'proofing-language',\n 'rtl',\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 slide of ir.slides) {\n emitSlide(pptx, slide, ctx);\n }\n\n return pptx;\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 = 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 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 * This adapter uses an explicit allowlist: a new `PptxFeature` stays\n * unsupported until the adapter deliberately adds and tests it. What it does\n * not declare, and why — each is a verified gap or an explicit mapping\n * boundary:\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 * - `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 OFFICE_OPEN_CAPABILITIES: ReadonlySet<PptxFeature> = new Set([\n 'rich-text',\n 'complex-bullet-glyphs',\n 'text',\n 'shapes',\n 'images',\n 'tables',\n 'charts',\n 'chart-bar-style',\n 'chart-pie-style',\n 'chart-line-style',\n 'chart-radar-style',\n 'chart-data-labels',\n 'chart-data-border',\n 'chart-axis-scale',\n 'chart-axis-visibility',\n 'chart-axis-style',\n 'chart-text-style',\n 'solid-fills',\n 'gradient-fills',\n 'pattern-fills',\n 'image-fills',\n 'lines',\n 'shadows',\n 'backgrounds',\n 'speaker-notes',\n 'hidden-slides',\n 'transitions',\n 'external-links',\n 'internal-links',\n 'text-hyperlinks',\n 'rotation',\n 'flip-horizontal',\n 'groups',\n 'proofing-language',\n 'rtl',\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 { toChartFontFaces } from '@json-to-office/shared/fonts/node';\nimport type { RasterizeFontFace } from '@json-to-office/shared';\nimport {\n assertNoContentConflicts,\n assertValidPresentationForGeneration,\n type GenerationOptions,\n} from './generationOptions';\nimport { expandHighchartsComponents } from './expandHighcharts';\nimport { resolveImageLayout } from './resolveImageLayout';\nimport { preparePptxQualityDocument } from '../quality/facts';\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 assertNoContentConflicts(component);\n const warnings: PipelineWarning[] = [];\n\n const prepared =\n options?.prepared ??\n preparePptxQualityDocument(component, {\n customThemes: options?.customThemes,\n fonts: options?.fonts,\n warnings,\n services: options?.services,\n renderer: selectedRenderer,\n });\n\n const result = await runWithBaseDir(options?.baseDir, async () => {\n const expansion = await expandHighchartsComponents(\n prepared.model.processed,\n options?.services?.highcharts,\n warnings\n );\n const laidOut = await resolveImageLayout(expansion.presentation, warnings);\n return compilePresentation(laidOut, warnings);\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 assertNoContentConflicts(component);\n const warnings: PipelineWarning[] = [];\n\n const prepared =\n options?.prepared ??\n preparePptxQualityDocument(component, {\n customThemes: options?.customThemes,\n fonts: options?.fonts,\n warnings,\n services: options?.services,\n renderer: selectedRenderer,\n });\n\n // Fires `fonts.onResolved` for the preview stager, exactly as the legacy\n // path does. The PPTX itself never embeds font bytes; a `highcharts` is\n // drawn by an export server's browser, though, which needs the bytes of any\n // registered face to set the chart in the deck's type, so a chart-bearing\n // deck materialises them for that.\n const hasHighcharts = containsHighcharts(prepared.model.processed);\n const resolvedFonts = await resolveDocumentFonts(\n prepared.model.document,\n prepared.model.theme,\n warnings,\n options?.fonts,\n hasHighcharts\n );\n const chartFonts = hasHighcharts ? toChartFontFaces(resolvedFonts) : [];\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(prepared.model.processed, warnings, {\n ...effectiveOptions,\n ...(chartFonts.length > 0 ? { chartFonts } : {}),\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 options?.chartFonts\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 if (compiled.unsupported.length > 0) {\n throw new UncompiledComponentError(compiled.unsupported);\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 /** Staged faces a chart's export server is handed as inline `@font-face`. */\n chartFonts?: readonly RasterizeFontFace[];\n};\n\n/** Whether any slide carries an enabled `highcharts`, groups included. */\nexport function containsHighcharts(\n presentation: ProcessedPresentation\n): boolean {\n const named = (\n components:\n | readonly {\n name: string;\n enabled?: boolean;\n children?: readonly unknown[];\n }[]\n | undefined\n ): boolean =>\n components?.some(\n (component) =>\n component.enabled !== false &&\n (component.name === 'highcharts' ||\n named(component.children as typeof components))\n ) ?? false;\n return presentation.slides.some((slide) => named(slide.components));\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, block and custom-component expansion, theme resolution,\n * component defaults, layout and fit. What remains, and what this module\n * does, is the last mile of resolution: inches become EMU transforms, groups\n * flatten into slide elements, theme colour tokens become hex, the font\n * cascade is flattened onto every run, and page-number placeholders are\n * 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 PipelineWarning,\n PptxComponentInput,\n PptxThemeConfig,\n ProcessedPresentation,\n ProcessedSlide,\n SlideContext,\n StyleName,\n} from '../types';\nimport { definedChartColorTokens, resolveColor } from '../utils/color';\nimport { applyFontWeight } from '../utils/fontAliasContext';\nimport { resolveImageSource, safeLocalPath } from '../utils/imageSource';\nimport {\n HYPERLINK_SLIDE_UNRESOLVED,\n type HyperlinkProps,\n} from '../utils/hyperlink';\nimport { resolveComponentGridPosition } from '../core/grid';\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 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 * Text boxes on the slide being compiled that stated no coordinates at all.\n *\n * Reset per slide by `compileSlide`. A named style now lands each role in a\n * band of its own, but two boxes sharing a style still share a band, and the\n * IR alone cannot tell a deliberate overlay from two elements nobody\n * positioned — so authored-ness is recorded here while it is still known.\n */\n positionlessText: Array<{ path: string; transform: PptxIrTransform }>;\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 positionlessText: [],\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 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 * 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\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 // Per slide: two boxes only collide with each other if they share one.\n ctx.positionlessText = [];\n\n // A gradient background renders as a full-bleed rectangle added first, so it\n // sits behind everything else.\n const gradientSource = slide.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 // A `group` is transparent: layout already resolved its children to\n // absolute boxes, so the compiler draws them in order as slide elements.\n // Grid placement was resolved by layout too; resolving it again is a no-op\n // that keeps the compiler correct on a tree that skipped that pass.\n const visit = (components: readonly PptxComponentInput[]): void => {\n for (const component of components) {\n if (component.name === 'group') {\n if (component.enabled !== false) visit(component.children ?? []);\n continue;\n }\n const resolved = resolveComponentGridPosition(\n component,\n processed.grid,\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 visit(slide.components);\n\n warnOverlappingText(slideIndex, ctx);\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 ...(background ? { background } : {}),\n elements,\n ...(slide.notes ? { notes: slide.notes } : {}),\n hidden: slide.hidden === true,\n ...(transition ? { transition } : {}),\n };\n}\n\n/**\n * Report text boxes nobody positioned that landed on top of each other.\n *\n * Only boxes that stated neither `x` nor `y` are compared: an overlap between\n * two authored positions is a composition, and one between an authored box and\n * a default is at least half deliberate. Two defaults on the same slide are\n * nobody's decision — before the style bands that was every pair, and it is\n * still every pair that shares a style.\n *\n * A warning rather than a repair. Moving one of the two would be a layout\n * engine's job (#220), and guessing which one should move is exactly the\n * guess that produces a deck the author did not write.\n */\nfunction warnOverlappingText(slideIndex: number, ctx: CompileContext): void {\n const boxes = ctx.positionlessText;\n for (let i = 0; i < boxes.length; i += 1) {\n for (let j = i + 1; j < boxes.length; j += 1) {\n const a = boxes[i];\n const b = boxes[j];\n const overlaps =\n a.transform.xEmu < b.transform.xEmu + b.transform.widthEmu &&\n b.transform.xEmu < a.transform.xEmu + a.transform.widthEmu &&\n a.transform.yEmu < b.transform.yEmu + b.transform.heightEmu &&\n b.transform.yEmu < a.transform.yEmu + a.transform.heightEmu;\n if (!overlaps) continue;\n warn(\n ctx.warnings,\n W.TEXT_OVERLAP_UNPOSITIONED,\n `Text at ${a.path} and ${b.path} give no x/y and overlap on this slide. ` +\n 'Give at least one of them explicit coordinates, or a named style ' +\n 'whose default band differs.',\n { slide: slideIndex, component: 'text' }\n );\n }\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 * 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 // Recorded before the transform leaves this function: downstream, a band\n // default and an authored coordinate are the same two numbers.\n if (props.x === undefined && props.y === undefined) {\n ctx.positionlessText.push({ path, transform });\n }\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 let 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 // Feature gates read the authored runs: the case lowering below can split one\n // authored run into several, which is a rendering device, not rich text.\n if (runs.length > 1) ctx.features.require('rich-text', path);\n runs = applyTextCase(runs, named.style?.case);\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\n/**\n * PPTX backends lack a shared caps primitive. Lower case to explicit runs.\n *\n * A small-caps run splits per lowercase span, so a run carrying its own\n * hyperlink hands the same link to every piece — the fan-out the office-open\n * backend already performs for an element-level link over rich runs. Splitting\n * is what makes the 80% size possible; a link is at worst repeated, never lost.\n */\nfunction applyTextCase(\n runs: PptxIrTextRun[],\n textCase: 'none' | 'upper' | 'smallCaps' | undefined\n): PptxIrTextRun[] {\n if (!textCase || textCase === 'none') return runs;\n return runs.flatMap((run) => {\n if (textCase === 'upper') return [{ ...run, text: run.text.toUpperCase() }];\n const pieces = run.text.match(/\\p{Ll}+|[^\\p{Ll}]+/gu) ?? [''];\n return pieces.map((text, index) => ({\n ...run,\n text: text.toUpperCase(),\n fontSize: /^\\p{Ll}/u.test(text) ? run.fontSize * 0.8 : run.fontSize,\n ...(index > 0 && { spaceBeforePoints: undefined }),\n ...(index < pieces.length - 1 && {\n breakAfter: undefined,\n spaceAfterPoints: undefined,\n }),\n }));\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 ?? style?.paraSpaceBefore) !== undefined\n ? { spaceBeforePoints: props.paraSpaceBefore ?? style?.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 * Where each named style sits when the author gives no coordinates.\n *\n * Fractions of the slide extent, so a band means the same thing on 16:9, 4:3\n * and any custom size. Without these every positionless text box resolved to\n * (0, 0): a title and a subtitle on one slide stacked on top of each other in\n * the top-left corner, which is the shape the starters had — so the documents\n * meant to be copied were the ones that demonstrated the defect.\n *\n * A style names a role, and a role has a place on the slide. `body` and\n * `caption` still collide with a second box of the same style, which no fixed\n * band can solve; `warnOverlappingText` reports that case rather than letting\n * it render silently.\n */\nconst STYLE_BANDS: Readonly<\n Record<string, { x: number; y: number; w: number }>\n> = {\n // A title slide's title and its subtitle, as two bands in the middle third.\n title: { x: 0.08, y: 0.34, w: 0.84 },\n subtitle: { x: 0.08, y: 0.56, w: 0.84 },\n // Content-slide headings sit in the top margin, all three at the same place:\n // the level changes the type, not where the slide starts.\n heading1: { x: 0.06, y: 0.06, w: 0.88 },\n heading2: { x: 0.06, y: 0.06, w: 0.88 },\n heading3: { x: 0.06, y: 0.06, w: 0.88 },\n // Below a heading, in the content-safe area.\n body: { x: 0.06, y: 0.26, w: 0.88 },\n caption: { x: 0.06, y: 0.88, w: 0.88 },\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 *\n * Each axis is decided on its own: an author who states `x` and not `y` has\n * taken control of one of them, and the band is still the better answer for\n * the other than the origin.\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 // Only a named style carries a band. An unstyled text box keeps the origin\n // it has always had: nothing here knows what role it plays, and inventing\n // one would move every such box in every existing deck.\n const band =\n typeof props.style === 'string' ? STYLE_BANDS[props.style] : undefined;\n\n return {\n xEmu:\n props.x !== undefined\n ? resolveDimensionEmu(props.x, 'X', ctx.extent)\n : Math.round((band?.x ?? 0) * ctx.extent.widthEmu),\n yEmu:\n props.y !== undefined\n ? resolveDimensionEmu(props.y, 'Y', ctx.extent)\n : Math.round((band?.y ?? 0) * ctx.extent.heightEmu),\n widthEmu:\n props.w !== undefined\n ? resolveDimensionEmu(props.w, 'X', ctx.extent)\n : band\n ? Math.round(band.w * ctx.extent.widthEmu)\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 // Gate on the authored runs, before the case lowering can split them.\n if (runs.length > 1) ctx.features.require('rich-text', path);\n runs = applyTextCase(runs, named.style?.case);\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 // A header row is a compile-time treatment of row 0, not a new thing for a\n // backend to understand: both renderers already draw per-cell fill and\n // weight, so nothing about this reaches the IR that was not there before.\n if (props.headerRow && rows.length > 0) {\n rows[0] = {\n cells: rows[0].cells.map((cell) => headerCell(cell, props, ctx)),\n };\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\n/**\n * One cell of the header row, as the theme would have it.\n *\n * Every part of this yields to something the author said. A cell that states\n * its own weight, fill or colour keeps it; so does a table that states a fill\n * or a colour for all of its cells, because \"this table is green\" is a\n * statement about the header too. What is left is the case nobody spoke for,\n * where the header takes `background2` behind `text` — the pair every bundled\n * palette carries for a band that reads as chrome.\n *\n * `fontWeight` counts as speaking for the weight. It aliases the family to a\n * real sub-family rather than setting `bold`, so forcing bold on top of it\n * would both overrule an explicit `400` and ask the renderer to synthesise\n * bold over an already-picked face — a Light header drawn heavier than the\n * body under it, which is not what \"header\" was supposed to mean.\n */\nfunction headerCell(\n cell: PptxIrTableCell,\n tableProps: Record<string, any>,\n ctx: CompileContext\n): PptxIrTableCell {\n const formatting: PptxIrTableCellFormatting = {\n ...(tableProps.fontWeight == null ? { bold: true } : {}),\n ...(tableProps.color\n ? {}\n : { color: irColor(resolveColor('text', ctx.theme, ctx.warnings)) }),\n ...cell.formatting,\n };\n const fill =\n cell.fill ??\n (tableProps.fill\n ? undefined\n : irColor(resolveColor('background2', ctx.theme, ctx.warnings)));\n return {\n ...cell,\n formatting,\n ...(fill ? { fill } : {}),\n };\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","/**\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 {\n DEFAULT_CHART_THEME_COLORS,\n designColors,\n resolveDesignColor,\n} 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 if (theme.palette?.chart) return theme.palette.chart;\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 if (theme.palette) {\n const hex = resolveDesignColor(\n color,\n designColors(theme.colors, theme.palette)\n );\n if (hex) return hex;\n }\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 * 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/** 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 {\n GridConfig,\n GridPosition,\n PptxComponentInput,\n PipelineWarning,\n} 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')\n 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(\n warnings,\n 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(\n gridPos,\n gridConfig,\n slideWidth,\n slideHeight,\n warnings\n );\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 =\n typeof newProps.x === 'string' || typeof newProps.w === 'string';\n const hasPercentY =\n 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)\n newProps.x = hasPercentX ? toPercX(resolved.x) : resolved.x;\n if (newProps.y == null)\n newProps.y = hasPercentY ? toPercY(resolved.y) : resolved.y;\n if (newProps.w == null)\n newProps.w = hasPercentX ? toPercX(resolved.w) : resolved.w;\n if (newProps.h == null)\n 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 a backend is only imported\n * when it is actually selected — choosing `pptxgenjs` never loads\n * `@office-open/pptx`, and a backend that cannot be loaded at all (an\n * `--omit=optional` install, a broken tree) surfaces as an actionable install\n * hint rather than a bare module-resolution failure. `statuses()` asks the\n * same question up front, so a discovery surface never advertises a renderer\n * that would fail on the first render.\n */\n\nimport {\n RendererRegistry,\n type RendererStatus,\n} 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\n/**\n * Every registered renderer with whether its backend can be loaded here.\n *\n * Registration is not availability: the factory only runs on selection, so an\n * id alone says nothing about whether the render behind it will work. Callers\n * that advertise renderers — `jto_info`, `jto_discover` — report this instead\n * of pptxRendererIds() so a renderer that cannot run is never offered as one\n * that can.\n */\nexport function pptxRendererStatuses(): Promise<\n RendererStatus<PptxRendererId>[]\n> {\n return registry.statuses();\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 JsonBlockDefinition,\n} from '@json-to-office/shared';\nimport type {\n GradientFill,\n PptxComponentDefaults,\n PptxRendererId,\n ThemeConfigJson,\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 /** Document-local JSON block definitions, invoked with `name: \"block\"`. */\n blocks?: Record<string, JsonBlockDefinition>;\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 hidden?: boolean;\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 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 hidden?: boolean;\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 type TextStyle = NonNullable<\n NonNullable<ThemeConfigJson['styles']>['body']\n>;\nexport type StyleName = keyof NonNullable<ThemeConfigJson['styles']>;\n\nexport type PptxThemeConfig = ThemeConfigJson;\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 /**\n * Materialize font bytes even when no `onResolved` listener is registered.\n * Set when the deck carries a `highcharts`, whose PNG is drawn by an\n * export server's browser that needs the actual font files to set the chart\n * in a registered face. Matches the DOCX helper.\n */\n forceMaterialize = false\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) runs when a consumer is\n // listening via onResolved — typically the LibreOffice preview stager — or\n // when the caller forces materialization for a chart. Office output never\n // embeds bytes, so skipping fetches when neither applies keeps library\n // callers from paying network cost.\n if (!fonts?.onResolved && !forceMaterialize) 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. On the\n // force-materialize path there may be no listener at all — the resolved\n // fonts still flow back through the return value.\n fonts?.onResolved?.(resolved);\n return resolved;\n}\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';\nimport type { PreparedDocument } from '@json-to-office/quality';\nimport type { PptxQualityFact, PptxQualityModel } from '../quality/facts';\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 /** Canonical prepared model; internal hosts use it to avoid a second prologue. */\n prepared?: PreparedDocument<PptxQualityModel, PptxQualityFact>;\n /**\n * Compiled pointer → authored pointer, from block expansion. Diagnostics\n * raised while processing an expanded tree (a text that cannot fit its\n * declared bounds) are reported at the slot the author can patch.\n */\n sourceMap?: Readonly<Record<string, string>>;\n /**\n * Sink for warnings raised while processing: a grid placement clamped back\n * onto the grid by layout. Hosts that prepare once and render from the\n * prepared model hear each warning once.\n */\n warnings?: PipelineWarning[];\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 * 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 {\n remoteExportNotice,\n REMOTE_EXPORT_WARNING,\n chartFamilyResolver,\n chartPointsPerPixel,\n withChartFontFaceCss,\n withChartTypography,\n type ChartTypography,\n type HighchartsServiceConfig,\n type RasterizeFontFace,\n} 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;\n/** Highcharts' own default canvas width, for a config that states none. */\nconst DEFAULT_CHART_WIDTH_PX = 960;\nconst DEFAULT_EXPORT_SERVER_URL = 'http://localhost:7801';\n\nexport interface HighchartsExpansionResult {\n presentation: ProcessedPresentation;\n}\n\n/**\n * Replace every `highcharts` component with the `image` it renders to.\n *\n * Slide components are expanded in place, groups included. 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 chartFonts?: readonly RasterizeFontFace[]\n): Promise<HighchartsExpansionResult> {\n const scope: ExpansionScope = {\n theme: presentation.theme,\n slideWidth: presentation.slideWidth,\n services,\n warnings,\n chartFonts,\n };\n\n const slides = await Promise.all(\n presentation.slides.map(async (slide, index) => ({\n ...slide,\n components: await expandList(\n slide.components,\n `slides[${index}].elements`,\n scope\n ),\n }))\n );\n\n return { presentation: { ...presentation, slides } };\n}\n\n/** What one expansion needs from the presentation and the caller. */\ninterface ExpansionScope {\n theme: PptxThemeConfig;\n slideWidth: number;\n services: HighchartsServiceConfig | undefined;\n warnings: PipelineWarning[];\n chartFonts: readonly RasterizeFontFace[] | undefined;\n}\n\nasync function expandList(\n components: PptxComponentInput[],\n path: string,\n scope: ExpansionScope\n): Promise<PptxComponentInput[]> {\n const out: PptxComponentInput[] = [];\n for (const [index, component] of components.entries()) {\n if (component.name === 'highcharts') {\n out.push(await expandOne(component, `${path}[${index}]`, scope));\n } else if (component.children && component.children.length > 0) {\n out.push({\n ...component,\n children: await expandList(\n component.children,\n `${path}[${index}].children`,\n scope\n ),\n });\n } else {\n out.push(component);\n }\n }\n return out;\n}\n\nasync function expandOne(\n component: PptxComponentInput,\n path: string,\n scope: ExpansionScope\n): Promise<PptxComponentInput> {\n const props = component.props as unknown as PptxHighchartsProps;\n const chart = await renderChart(\n withChartFontFaces(\n withThemeTypography(\n withThemeColors(props, scope.theme, scope.warnings),\n scope.theme,\n scope.slideWidth,\n scope.warnings\n ),\n scope.theme,\n scope.chartFonts\n ),\n scope.services,\n scope.warnings\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\n/** A public export server is a decision: refused without `allowRemote`, announced with it. */\nfunction assertExportServerAllowed(\n serverUrl: string,\n services: HighchartsServiceConfig | undefined,\n warnings: PipelineWarning[]\n): void {\n const notice = remoteExportNotice(serverUrl, services?.allowRemote);\n if (notice)\n warnings.push({\n code: REMOTE_EXPORT_WARNING,\n component: 'highcharts',\n message: notice,\n });\n}\n\nasync function renderChart(\n config: PptxHighchartsProps,\n services: HighchartsServiceConfig | undefined,\n warnings: PipelineWarning[]\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 assertExportServerAllowed(serverUrl, services, warnings);\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 // The code lets a server route report a missing export server as a\n // dependency outage with this message, not as an internal error.\n throw Object.assign(\n 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 { code: 'SERVICE_UNAVAILABLE' }\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 ?? DEFAULT_CHART_WIDTH_PX,\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/**\n * The width, in points, the chart's image takes on the slide — the rule the\n * `image` it becomes applies: `w` in inches, or a percentage of the slide,\n * else the chart's own pixels at 96 dpi. A grid-placed chart has no width yet\n * and reads as 96 dpi.\n */\nfunction placedWidthPt(\n props: PptxHighchartsProps,\n slideWidth: number\n): number | undefined {\n const { w } = props;\n if (typeof w === 'number') return w * 72;\n if (typeof w === 'string' && w.endsWith('%')) {\n return (parseFloat(w) / 100) * slideWidth * 72;\n }\n if (w === undefined && props.grid === undefined) {\n return (\n ((props.options.chart?.width ?? DEFAULT_CHART_WIDTH_PX) / PX_PER_INCH) *\n 72\n );\n }\n return undefined;\n}\n\n/**\n * The deck's type, read off the resolved theme. `chartLabel` and `source` are\n * the roles a theme declares for exactly this; without them the labels sit two\n * points under the body style and the source at the caption size. The title\n * takes the heading face at the `heading3` size.\n */\nfunction themeChartTypography(\n theme: PptxThemeConfig,\n warnings: PipelineWarning[]\n): ChartTypography {\n const styles = theme.styles ?? {};\n const family = chartFamilyResolver(theme);\n const bodyPt = styles.body?.fontSize ?? theme.defaults.fontSize;\n const label = styles.chartLabel;\n const heading = styles.heading3;\n const labelPt = label?.fontSize ?? Math.max(bodyPt - 2, 6);\n const text = `#${resolveColor('text', theme, warnings)}`;\n return {\n bodyFamily: family(theme.fonts.body),\n headingFamily: family(theme.fonts.heading),\n textColor: text,\n mutedColor: theme.colors.text2\n ? `#${resolveColor('text2', theme, warnings)}`\n : text,\n labelPt,\n labelWeight: label?.fontWeight ?? (label?.bold ? 700 : undefined),\n titlePt: heading?.fontSize ?? bodyPt + 4,\n titleWeight:\n heading?.fontWeight ?? (heading?.bold === false ? undefined : 700),\n sourcePt:\n styles.source?.fontSize ??\n styles.caption?.fontSize ??\n Math.max(labelPt - 2, 6),\n };\n}\n\n/**\n * Set the chart in the deck's type: family, sizes and ink written beneath\n * whatever the author styled, scaled to the width the image is placed at.\n * A theme with no fonts — the empty theme direct callers pass — adds nothing,\n * so their request stays byte-identical.\n */\nfunction withThemeTypography(\n props: PptxHighchartsProps,\n theme: PptxThemeConfig,\n slideWidth: number,\n warnings: PipelineWarning[]\n): PptxHighchartsProps {\n if (!props.options || !theme?.fonts?.body || !theme.fonts.heading) {\n return props;\n }\n return {\n ...props,\n options: withChartTypography(\n props.options,\n themeChartTypography(theme, warnings),\n chartPointsPerPixel(\n props.options.chart?.width ?? DEFAULT_CHART_WIDTH_PX,\n placedWidthPt(props, slideWidth)\n )\n ) as PptxHighchartsProps['options'],\n };\n}\n\n/**\n * Hand the export server the bytes of every staged face of the families the\n * chart is set in, as `@font-face` rules ahead of the author's own CSS.\n * Nothing is added when no face matches.\n */\nfunction withChartFontFaces(\n props: PptxHighchartsProps,\n theme: PptxThemeConfig,\n faces: readonly RasterizeFontFace[] | undefined\n): PptxHighchartsProps {\n if (!faces?.length || !theme?.fonts) return props;\n return withChartFontFaceCss(props, faces, [\n theme.fonts.body,\n theme.fonts.heading,\n ]);\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 * 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 = await Promise.all(\n presentation.slides.map(async (slide) => ({\n ...slide,\n components: await resolve(slide.components),\n }))\n );\n\n return { ...presentation, slides };\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 if (component.name === 'image') {\n out.push(await resolveOne(component, presentation, warnings));\n } else if (component.children && component.children.length > 0) {\n out.push({\n ...component,\n children: await resolveList(component.children, presentation, warnings),\n });\n } else {\n out.push(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","import {\n chartEncodingFor,\n collectColorLiterals,\n collectFontFamilies,\n collectPlaceholders,\n hasUnitMarker,\n normalizeHex,\n normalizeHighchartsChart,\n parseNumericCell,\n type ChartInfoDesign,\n type PlaceholderKind,\n type PreparedDocument,\n type ProvenanceMap,\n type QualityFact,\n type TableAlignment,\n type TableColumnInfoDesign,\n type TableInfoDesign,\n} from '@json-to-office/quality';\nimport type { FontRuntimeOpts, ServicesConfig } from '@json-to-office/shared';\nimport {\n DEFAULT_PPTX_RENDERER_ID,\n SEMANTIC_COLOR_NAMES,\n} from '@json-to-office/shared-pptx';\nimport { designColors } from '@json-to-office/shared';\nimport type {\n GridConfig,\n GridPosition,\n PipelineWarning,\n PptxComponentInput,\n PptxThemeConfig,\n PresentationComponentDefinition,\n ProcessedPresentation,\n TextStyle,\n} from '../types';\nimport { resolveColor } from '../utils/color';\nimport { resolveGridPosition } from '../core/grid';\nimport { resolveThemeContext } from '../core/generationContext';\nimport { processPresentation } from '../core/structure';\nimport {\n blockSlotBudgets,\n blockSlotRoles,\n expandPptxBlocks,\n toAuthoredPointer,\n type BlockSourceMap,\n} from '../blocks';\nimport { defaultLineHeightPt, estimateTextLines } from '../utils/textMetrics';\nimport type { BlockSlotRole } from '@json-to-office/shared';\n\ntype Rec = Record<string, unknown>;\n\nexport interface PptxCanvasFact extends QualityFact {\n kind: 'pptx/canvas';\n widthIn?: number;\n heightIn?: number;\n}\n\nexport interface PptxTextFact extends QualityFact {\n kind: 'pptx/text';\n slidePath: string;\n text: string;\n fontSizePt: number;\n lineSpacingPt: number;\n paraSpaceBeforePt: number;\n paraSpaceAfterPt: number;\n styleName?: string;\n boxXPt?: number;\n boxYPt?: number;\n boxWidthPt?: number;\n boxHeightPt?: number;\n verticalAlign: 'top' | 'middle' | 'bottom';\n /** Horizontal alignment: the prop, else the named style's, else left. */\n align: 'left' | 'center' | 'right' | 'justify';\n rotationDeg: number;\n /**\n * True when neither `h` nor a grid supplies a height. The compiler resolves\n * grid positions before checking `props.h`, so grid height is a hard ceiling.\n */\n autoFit: boolean;\n /** Effective bold, from the run or its named style. */\n bold: boolean;\n /** Resolved run colour, bare hex, when the document states one. */\n colorHex?: string;\n /**\n * Every colour the surface behind this text can paint, bare hex. A gradient\n * contributes each stop: text has to stay legible over all of them, and the\n * worst stop is the one a reader notices.\n */\n backgroundHexes?: readonly string[];\n}\n\nexport interface PptxSlideFact extends QualityFact {\n kind: 'pptx/slide';\n bodyWords: number;\n}\n\n/** A box drawn on a slide, in draw order — the input to the overlap rule. */\nexport interface PptxBoxFact extends QualityFact {\n kind: 'pptx/box';\n slidePath: string;\n componentName: string;\n /** Draw order within the slide; a higher value is painted later, on top. */\n order: number;\n /** Paints its whole rectangle: an image, a chart, a table, a filled shape. */\n opaque: boolean;\n xPt: number;\n yPt: number;\n widthPt: number;\n heightPt: number;\n}\n\n/** The resolved theme, as the brand rules see it. */\nexport interface PptxThemeFact extends QualityFact {\n kind: 'pptx/theme';\n themeName: string;\n /** Token name to `#RRGGBB`, for every palette entry that resolves. */\n paletteHexes: Readonly<Record<string, string>>;\n fontFamilies: readonly string[];\n}\n\n/** A colour written as a literal rather than as a theme token. */\nexport interface PptxColorFact extends QualityFact {\n kind: 'pptx/color';\n raw: string;\n hex: string;\n}\n\n/** A font family the document asks for by name. */\nexport interface PptxFontFact extends QualityFact {\n kind: 'pptx/font-family';\n family: string;\n}\n\n/**\n * A chart on a slide — native or Highcharts — read into the vocabulary the\n * information-design rules speak.\n */\nexport interface PptxChartFact extends QualityFact, ChartInfoDesign {\n kind: 'pptx/chart';\n /** `chart` or `highcharts`; the two answer the same questions differently. */\n componentName: string;\n /** Theme tokens a palette fix can name, in series order. */\n paletteTokens: readonly string[];\n}\n\n/** One authored cell of a slide table, and where a patch would rewrite it. */\nexport interface PptxTableCellRef {\n path: string;\n cell: string | Record<string, unknown>;\n}\n\nexport interface PptxTableColumnFact extends TableColumnInfoDesign {\n /** Every authored cell in this column, header first, in row order. */\n cells: readonly PptxTableCellRef[];\n}\n\nexport interface PptxTableFact extends QualityFact, TableInfoDesign {\n kind: 'pptx/table';\n columns: readonly PptxTableColumnFact[];\n}\n\n/** One authored string that reads as a placeholder rather than as content. */\nexport interface PptxPlaceholderFact extends QualityFact {\n kind: 'pptx/placeholder';\n text: string;\n placeholderKind: PlaceholderKind;\n pattern: string;\n excerpt: string;\n}\n\n/** One text slot of a block, counted against the budget the block declares. */\nexport interface PptxBlockSlotFact extends QualityFact {\n kind: 'pptx/block-slot';\n block: string;\n slot: string;\n words: number;\n maxWords: number;\n}\n\n/**\n * A role-bearing slot of a block invocation, present or not. A profile reads\n * these to require a source under every chart or to measure an action title;\n * the theme that styles them never adds a requirement.\n */\nexport interface PptxChromeSlotFact extends QualityFact {\n kind: 'pptx/chrome-slot';\n block: string;\n /** Authored pointer of the invocation. */\n invocation: string;\n slot: string;\n role: BlockSlotRole;\n present: boolean;\n text?: string;\n /** Lines the slot's text takes in the box the definition gave it. */\n estimatedLines?: number;\n fontSizePt?: number;\n}\n\nexport type PptxQualityFact =\n | PptxCanvasFact\n | PptxBlockSlotFact\n | PptxChromeSlotFact\n | PptxTextFact\n | PptxSlideFact\n | PptxPlaceholderFact\n | PptxBoxFact\n | PptxThemeFact\n | PptxColorFact\n | PptxFontFact\n | PptxChartFact\n | PptxTableFact;\n\nexport interface PptxQualityModel {\n authored: PresentationComponentDefinition;\n /** The document after the export-mode pre-pass and block expansion. */\n document: PresentationComponentDefinition;\n theme: PptxThemeConfig;\n processed: ProcessedPresentation;\n}\n\n/** What `PreparedDocument.metadata.blocks` carries once a block expanded. */\nexport interface PptxBlocksMetadata {\n /** Compiled pointer → authored pointer. */\n sourceMap: BlockSourceMap;\n /** Authored pointers of the expanded blocks. */\n blocks: readonly string[];\n /** The compiled form: the document with every block lowered in place. */\n document: PresentationComponentDefinition;\n}\n\nexport interface PreparePptxQualityOptions {\n customThemes?: Record<string, PptxThemeConfig>;\n fonts?: FontRuntimeOpts;\n services?: ServicesConfig;\n warnings?: PipelineWarning[];\n renderer?: string;\n}\n\ninterface ThemeContext {\n styles: Partial<Record<string, TextStyle>>;\n defaultFontSize: number;\n}\n\ninterface Typography {\n fontSize: number;\n lineSpacing: number;\n paraSpaceBefore: number;\n paraSpaceAfter: number;\n bold: boolean;\n styleName?: string;\n}\n\ninterface TextNode {\n props: Rec;\n path: string;\n text: string;\n /** Draw order on the slide, shared with `Surface`. */\n order: number;\n}\n\ninterface ComponentAtPath {\n component: PptxComponentInput;\n path: string;\n}\n\nfunction asRecord(value: unknown): Rec | undefined {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n ? (value as Rec)\n : undefined;\n}\n\nfunction asNumber(value: unknown): number | undefined {\n return typeof value === 'number' && Number.isFinite(value)\n ? value\n : undefined;\n}\n\n/** An x/y/w/h prop in points: inches as numbers, `\"NN%\"` of the axis. */\nfunction dimToPt(value: unknown, axisIn: number): number | undefined {\n if (typeof value === 'number' && Number.isFinite(value)) return value * 72;\n if (typeof value === 'string') {\n const trimmed = value.trim();\n if (trimmed.endsWith('%')) {\n const pct = Number(trimmed.slice(0, -1));\n return Number.isFinite(pct) ? (pct / 100) * axisIn * 72 : undefined;\n }\n const inches = Number(trimmed);\n return Number.isFinite(inches) ? inches * 72 : undefined;\n }\n return undefined;\n}\n\ninterface Box {\n xPt: number;\n yPt: number;\n widthPt: number;\n heightPt: number;\n}\n\n/** Absolute box in points, falling back to the grid when x/y/w/h are absent. */\nfunction resolveBox(\n props: Rec,\n grid: GridConfig | undefined,\n slideWidthIn: number,\n slideHeightIn: number\n): Partial<Box> {\n let xPt = dimToPt(props.x, slideWidthIn);\n let yPt = dimToPt(props.y, slideHeightIn);\n let widthPt = dimToPt(props.w, slideWidthIn);\n let heightPt = dimToPt(props.h, slideHeightIn);\n const gridPos = asRecord(props.grid);\n if (\n gridPos !== undefined &&\n asNumber(gridPos.column) !== undefined &&\n asNumber(gridPos.row) !== undefined &&\n (xPt === undefined ||\n yPt === undefined ||\n widthPt === undefined ||\n heightPt === undefined)\n ) {\n const resolved = resolveGridPosition(\n gridPos as unknown as GridPosition,\n grid,\n slideWidthIn,\n slideHeightIn\n );\n xPt ??= resolved.x * 72;\n yPt ??= resolved.y * 72;\n widthPt ??= resolved.w * 72;\n heightPt ??= resolved.h * 72;\n }\n return { xPt, yPt, widthPt, heightPt };\n}\n\nfunction isCompleteBox(box: Partial<Box>): box is Box {\n return (\n box.xPt !== undefined &&\n box.yPt !== undefined &&\n box.widthPt !== undefined &&\n box.heightPt !== undefined &&\n box.widthPt > 0 &&\n box.heightPt > 0\n );\n}\n\nfunction containsCentre(surface: Box, text: Box): boolean {\n const cx = text.xPt + text.widthPt / 2;\n const cy = text.yPt + text.heightPt / 2;\n return (\n cx >= surface.xPt &&\n cx <= surface.xPt + surface.widthPt &&\n cy >= surface.yPt &&\n cy <= surface.yPt + surface.heightPt\n );\n}\n\nconst HORIZONTAL_ALIGNMENTS = new Set(['left', 'center', 'right', 'justify']);\n\nfunction horizontalAlign(props: Rec, ctx: ThemeContext): PptxTextFact['align'] {\n const own = typeof props.align === 'string' ? props.align : undefined;\n if (own && HORIZONTAL_ALIGNMENTS.has(own))\n return own as PptxTextFact['align'];\n const styled =\n typeof props.style === 'string'\n ? ctx.styles[props.style]?.align\n : undefined;\n return styled && HORIZONTAL_ALIGNMENTS.has(styled)\n ? (styled as PptxTextFact['align'])\n : 'left';\n}\n\nfunction themeContext(theme: PptxThemeConfig): ThemeContext {\n return {\n styles: theme.styles ?? {},\n defaultFontSize: asNumber(theme.defaults?.fontSize) ?? 18,\n };\n}\n\n/**\n * Every colour a fill can paint, resolved to bare hex.\n *\n * Deliberately structural rather than typed against one fill shape: solid\n * fills, gradients and their stops all nest `color` somewhere, and a background\n * that paints no colour at all (an image) yields nothing, which is the honest\n * answer — the rule then stays quiet instead of guessing at a photograph.\n */\nfunction fillColorHexes(fill: unknown, theme: PptxThemeConfig): string[] {\n const found: string[] = [];\n const visit = (node: unknown): void => {\n if (Array.isArray(node)) {\n node.forEach(visit);\n return;\n }\n const rec = asRecord(node);\n if (!rec) return;\n if (typeof rec.color === 'string') {\n const hex = resolveColor(rec.color, theme);\n if (hex) found.push(hex.toUpperCase());\n }\n for (const value of Object.values(rec)) {\n if (typeof value === 'object' && value !== null) visit(value);\n }\n };\n visit(fill);\n return [...new Set(found)];\n}\n\nconst FOCUS_CORNERS: Readonly<Record<string, readonly [number, number]>> = {\n topLeft: [0, 0],\n topRight: [1, 0],\n bottomLeft: [0, 1],\n bottomRight: [1, 1],\n};\n\nfunction lerpHex(a: string, b: string, t: number): string {\n const pa = parseInt(a, 16);\n const pb = parseInt(b, 16);\n const mix = (shift: number): number =>\n Math.round(\n ((pa >> shift) & 255) +\n (((pb >> shift) & 255) - ((pa >> shift) & 255)) * t\n );\n return [mix(16), mix(8), mix(0)]\n .map((c) => c.toString(16).padStart(2, '0'))\n .join('')\n .toUpperCase();\n}\n\n/**\n * Where along a gradient the point (fx, fy) — both 0..1 across the surface —\n * falls. Radial gradients run outward from the named corner; linear ones run\n * along `angle`, measured clockwise from the x-axis with y pointing down.\n *\n * The radial radius is half the surface's diagonal in real units, which is not\n * an obvious choice — it is the one the renderer makes. Sampling the rendered\n * gradient across a 10 × 5.625in slide put the last stop at exactly half the\n * diagonal from the focus corner, and reproduced every probe: the corner\n * opposite the focus, the two edge midpoints (which a shape-independent model\n * gets wrong, because equal distances in normalized space are unequal on a\n * wide slide), and the centre.\n */\nfunction gradientPosition(\n gradient: Rec,\n fx: number,\n fy: number,\n widthUnits: number,\n heightUnits: number\n): number {\n if (gradient.type === 'radial') {\n const focus =\n FOCUS_CORNERS[\n typeof gradient.focus === 'string' ? gradient.focus : 'topLeft'\n ] ?? FOCUS_CORNERS.topLeft;\n const radius = Math.hypot(widthUnits, heightUnits) / 2;\n if (radius === 0) return 0;\n const distance = Math.hypot(\n (fx - focus[0]) * widthUnits,\n (fy - focus[1]) * heightUnits\n );\n return Math.min(1, distance / radius);\n }\n const angle = ((asNumber(gradient.angle) ?? 0) * Math.PI) / 180;\n const dx = Math.cos(angle);\n const dy = Math.sin(angle);\n const min = Math.min(0, dx) + Math.min(0, dy);\n const max = Math.max(0, dx) + Math.max(0, dy);\n if (max === min) return 0;\n return Math.min(1, Math.max(0, (fx * dx + fy * dy - min) / (max - min)));\n}\n\n/**\n * The colour a fill actually paints at (fx, fy).\n *\n * Sampling matters for gradients: taking the worst stop instead would fail\n * black text against the blue end of a background whose peach end it never\n * touches, and every slide over a two-tone ground would carry a finding for\n * one colour or the other.\n */\nfunction paintedColorHexes(\n fill: unknown,\n theme: PptxThemeConfig,\n fx: number,\n fy: number,\n widthUnits: number,\n heightUnits: number\n): string[] {\n const rec = asRecord(fill);\n const gradient = asRecord(rec?.gradient);\n const stops = Array.isArray(gradient?.stops) ? gradient.stops : undefined;\n if (gradient && stops && stops.length > 0) {\n const parsed = stops\n .flatMap((stop) => {\n const entry = asRecord(stop);\n const color =\n typeof entry?.color === 'string' ? entry.color : undefined;\n if (!color) return [];\n const hex = resolveColor(color, theme);\n if (!hex) return [];\n return [{ pos: asNumber(entry?.pos) ?? 0, hex: hex.toUpperCase() }];\n })\n .sort((a, b) => a.pos - b.pos);\n if (parsed.length === 0) return [];\n const target =\n gradientPosition(gradient, fx, fy, widthUnits, heightUnits) * 100;\n if (target <= parsed[0].pos) return [parsed[0].hex];\n const last = parsed[parsed.length - 1];\n if (target >= last.pos) return [last.hex];\n for (let i = 1; i < parsed.length; i += 1) {\n const previous = parsed[i - 1];\n const next = parsed[i];\n if (target <= next.pos) {\n const span = next.pos - previous.pos;\n const t = span === 0 ? 0 : (target - previous.pos) / span;\n return [lerpHex(previous.hex, next.hex, t)];\n }\n }\n return [last.hex];\n }\n return fillColorHexes(fill, theme);\n}\n\n/** Effective type: explicit prop → named style → theme default. */\nfunction resolveTypography(props: Rec, ctx: ThemeContext): Typography {\n const styleName = typeof props.style === 'string' ? props.style : undefined;\n const style = styleName !== undefined ? ctx.styles[styleName] : undefined;\n const fontSize =\n asNumber(props.fontSize) ?? style?.fontSize ?? ctx.defaultFontSize;\n const multiple = asNumber(props.lineSpacingMultiple);\n const lineSpacing =\n multiple !== undefined\n ? fontSize * multiple\n : asNumber(props.lineSpacing) ??\n style?.lineSpacing ??\n defaultLineHeightPt(fontSize);\n\n // WCAG treats bold text as large from 14pt, so weight has to survive the\n // same explicit-prop -> named-style resolution the size does. `fontWeight`\n // wins over `bold` in the renderer, so it wins here too.\n const weight = asNumber(props.fontWeight) ?? style?.fontWeight;\n const bold =\n weight !== undefined\n ? weight >= 600\n : typeof props.bold === 'boolean'\n ? props.bold\n : style?.bold ?? false;\n\n return {\n fontSize,\n lineSpacing,\n paraSpaceBefore: asNumber(props.paraSpaceBefore) ?? 0,\n paraSpaceAfter:\n asNumber(props.paraSpaceAfter) ?? style?.paraSpaceAfter ?? 0,\n bold,\n ...(styleName && { styleName }),\n };\n}\n\n/**\n * Anything that paints over the slide surface, in the order it is drawn.\n * `colorHexes` is empty for an image — it covers the background without\n * telling us what colour it puts there.\n */\ninterface Surface {\n order: number;\n props: Rec;\n isImage: boolean;\n}\n\n/** Components that paint their whole rectangle, whatever is underneath. */\nconst OPAQUE_COMPONENTS = new Set([\n 'table',\n 'chart',\n 'highcharts',\n 'image',\n 'visual',\n]);\n\n/** Shape types whose ink is the whole bounding box. */\nconst RECTANGULAR_SHAPES = new Set(['rect', 'roundRect']);\n\n/**\n * Whether a fill actually covers what is under it.\n *\n * Any transparency at all disqualifies it: the reference decks stack a\n * primary-coloured disc under the same disc at 90% transparency, and a tinted\n * overlay is a technique rather than a collision. A gradient counts as opaque\n * only when none of its stops is see-through.\n */\nfunction isOpaqueFill(fill: unknown): boolean {\n const rec = asRecord(fill);\n if (!rec) return false;\n if ((asNumber(rec.transparency) ?? 0) > 0) return false;\n const gradient = asRecord(rec.gradient);\n if (gradient) {\n const stops = Array.isArray(gradient.stops) ? gradient.stops : [];\n return stops.every(\n (stop) => (asNumber(asRecord(stop)?.transparency) ?? 0) === 0\n );\n }\n return true;\n}\n\n/**\n * Whether this component hides whatever it is drawn over.\n *\n * A shape qualifies only when it is a rectangle with an opaque fill. An\n * ellipse, a pie wedge or a chevron leaves most of its bounding box empty —\n * the reference decks draw concentric circles and radial segments whose boxes\n * cross by design and whose ink never touches.\n */\nfunction isOpaqueComponent(componentName: string, props: Rec): boolean {\n if (OPAQUE_COMPONENTS.has(componentName)) return true;\n if (props.fill === undefined) return false;\n const type = typeof props.type === 'string' ? props.type : 'rect';\n return RECTANGULAR_SHAPES.has(type) && isOpaqueFill(props.fill);\n}\n\n/**\n * A component with a position, and whether it paints its whole box.\n *\n * Opacity, not \"is this content\", is the property the overlap rule can act\n * on. A text box is routinely declared far larger than the words inside it —\n * an 80pt title in a 5in box, a caption parked in the corner of a wide frame —\n * so two intersecting text rectangles say nothing about whether any ink\n * collides. Two intersecting *opaque* rectangles always hide each other.\n */\ninterface BoxNode {\n props: Rec;\n path: string;\n componentName: string;\n order: number;\n opaque: boolean;\n}\n\n/** A chart or a table: the two components the information-design rules read. */\ninterface ContentNode {\n props: Rec;\n path: string;\n componentName: string;\n}\n\n/**\n * One ordered pass over a slide's components: the text to analyse, the\n * surfaces drawn behind it, and every positioned box. All three need the same\n * z-order, and z-order is just the sequence the renderer walks, so they are\n * collected together rather than in passes that could disagree.\n */\nfunction collectSlideNodes(\n component: unknown,\n path: string,\n text: TextNode[],\n surfaces: Surface[],\n boxes: BoxNode[],\n contentNodes: ContentNode[],\n counter: { next: number }\n): void {\n const rec = asRecord(component);\n if (!rec || rec.enabled === false) return;\n const props = asRecord(rec.props) ?? {};\n const order = counter.next++;\n\n if (rec.name === 'image' || rec.name === 'visual' || rec.name === 'chart') {\n surfaces.push({ order, props, isImage: true });\n } else if (rec.name === 'shape' && props.fill !== undefined) {\n surfaces.push({ order, props, isImage: false });\n }\n\n const content = typeof props.text === 'string' ? props.text : undefined;\n if (\n content !== undefined &&\n content.trim() !== '' &&\n props.runs === undefined\n ) {\n if (rec.name === 'text' || rec.name === 'shape') {\n text.push({ props, path, text: content, order });\n }\n }\n\n const componentName = typeof rec.name === 'string' ? rec.name : '';\n if (\n componentName === 'chart' ||\n componentName === 'highcharts' ||\n componentName === 'table'\n ) {\n contentNodes.push({ props, path, componentName });\n }\n if (componentName !== '') {\n boxes.push({\n props,\n path,\n componentName,\n order,\n opaque: isOpaqueComponent(componentName, props),\n });\n }\n\n const children = Array.isArray(rec.children) ? rec.children : [];\n children.forEach((child, index) =>\n collectSlideNodes(\n child,\n `${path}/children/${index}`,\n text,\n surfaces,\n boxes,\n contentNodes,\n counter\n )\n );\n}\n\n/**\n * Theme slots that can carry a data series, in the order a palette hands them\n * out. `background`, `text` and their variants are excluded: they are the\n * ground and the ink, and a series painted in either disappears into the slide.\n */\nconst SERIES_COLOR_TOKENS: readonly string[] = [\n 'primary',\n 'accent',\n 'secondary',\n 'accent4',\n 'accent5',\n 'accent6',\n];\n\n/** A chart component, native or Highcharts, as the shared rules read it. */\nfunction chartFact(\n node: ContentNode,\n paletteTokens: readonly string[]\n): PptxChartFact | undefined {\n const { props, path } = node;\n const base = {\n id: `pptx:chart:${path}`,\n kind: 'pptx/chart' as const,\n path,\n componentName: node.componentName,\n paletteTokens,\n };\n\n if (node.componentName === 'highcharts') {\n const shape = normalizeHighchartsChart(props.options);\n return {\n ...base,\n chartType: shape.chartType,\n encoding: shape.encoding,\n threeD: shape.threeD,\n seriesCount: shape.seriesCount,\n categoryCount: shape.categoryCount,\n seriesColorsStated: shape.seriesColorsStated,\n seriesColorsPath: `${path}/props/options`,\n ...(shape.valueAxisMin !== undefined && {\n valueAxisMin: shape.valueAxisMin,\n }),\n unitStated: shape.unitStated,\n annotation: {\n stated: shape.annotationStated,\n path,\n slot: 'props.options.caption.text',\n },\n };\n }\n\n const chartType = typeof props.type === 'string' ? props.type : '';\n if (chartType === '') return undefined;\n const series = Array.isArray(props.data) ? props.data : [];\n const categoryCount = Math.max(\n 0,\n ...series.map((entry) => {\n const record = asRecord(entry);\n const labels = Array.isArray(record?.labels) ? record.labels.length : 0;\n const values = Array.isArray(record?.values) ? record.values.length : 0;\n return Math.max(labels, values);\n })\n );\n\n return {\n ...base,\n chartType,\n encoding: chartEncodingFor(chartType),\n threeD: chartType.endsWith('3D'),\n seriesCount: series.length,\n categoryCount,\n seriesColorsStated:\n Array.isArray(props.chartColors) && props.chartColors.length > 0,\n seriesColorsPath: `${path}/props/chartColors`,\n ...(asNumber(props.valAxisMinVal) !== undefined && {\n valueAxisMin: asNumber(props.valAxisMinVal),\n }),\n // A percent-stacked bar and percent data labels both state the unit as\n // surely as an axis title does — the numbers are shares, and the chart\n // says so on its face.\n unitStated:\n (typeof props.valAxisLabelFormatCode === 'string' &&\n props.valAxisLabelFormatCode.trim() !== '') ||\n props.showPercent === true ||\n props.barGrouping === 'percentStacked' ||\n hasUnitMarker(\n typeof props.valAxisTitle === 'string' ? props.valAxisTitle : ''\n ) ||\n hasUnitMarker(typeof props.title === 'string' ? props.title : ''),\n // No `annotation`: a native slide chart has no caption or source property,\n // and a rule that judges a slot the component does not have is a rule\n // nobody can satisfy.\n };\n}\n\n/** The text a slide-table cell shows, whichever of its two shapes it takes. */\nfunction cellText(cell: unknown): string {\n if (typeof cell === 'string') return cell;\n const record = asRecord(cell);\n return typeof record?.text === 'string' ? record.text : '';\n}\n\nconst PPTX_ALIGNMENTS = new Set(['left', 'center', 'right', 'justify']);\n\nfunction cellAlignment(cell: unknown, tableDefault: TableAlignment) {\n const record = asRecord(cell);\n const align = typeof record?.align === 'string' ? record.align : undefined;\n return align !== undefined && PPTX_ALIGNMENTS.has(align)\n ? (align as TableAlignment)\n : tableDefault;\n}\n\n/**\n * A slide table, column by column, out of a row-major model.\n *\n * Row 0 counts as a header when the table says so, and also when it is plainly\n * one: no cell in it parses as a number while the table has body rows to\n * compare. `headerRow` is optional in the schema and routinely left off, and\n * reading a label row as data would hide exactly the columns most likely to\n * have been laid out without thought.\n *\n * A table with merged cells is described without columns: a `colspan` breaks\n * the correspondence between an index and a visual column, and every column\n * finding below is about what sits under what.\n */\nfunction tableFact(\n node: ContentNode,\n slidePath: string,\n authoredProps: Rec | undefined\n): PptxTableFact | undefined {\n const { props, path } = node;\n const rows = Array.isArray(props.rows) ? props.rows : undefined;\n if (!rows || rows.length === 0) return undefined;\n\n // The *authored* border, not the resolved one. Every theme gives tables a\n // rule between cells, so a resolved-border test would report one finding per\n // table for a decision taken once, in the theme, for the whole document.\n // What this rule can say something about is a table that asks for a box of\n // its own.\n const border = asRecord(authoredProps?.border);\n const fullGrid =\n border !== undefined &&\n border.type !== 'none' &&\n (asNumber(border.pt) ?? 1) > 0;\n\n const merged = rows.some(\n (row) =>\n Array.isArray(row) &&\n row.some((cell) => {\n const record = asRecord(cell);\n return record?.colspan !== undefined || record?.rowspan !== undefined;\n })\n );\n\n const base = {\n id: `pptx:table:${path}`,\n kind: 'pptx/table' as const,\n path,\n relatedPaths: [slidePath],\n rowCount: rows.length,\n fullGrid,\n ...(fullGrid && { gridPath: `${path}/props/border` }),\n };\n if (merged) return { ...base, columns: [] };\n\n const cellsOf = (row: unknown): unknown[] => (Array.isArray(row) ? row : []);\n const headerRow =\n props.headerRow === true ||\n (rows.length >= 3 &&\n cellsOf(rows[0]).every(\n (cell) => parseNumericCell(cellText(cell)) === undefined\n ));\n const bodyStart = headerRow ? 1 : 0;\n const tableDefault: TableAlignment =\n typeof props.align === 'string' && PPTX_ALIGNMENTS.has(props.align)\n ? (props.align as TableAlignment)\n : 'left';\n\n const columnCount = Math.max(0, ...rows.map((row) => cellsOf(row).length));\n const columns: PptxTableColumnFact[] = [];\n for (let index = 0; index < columnCount; index += 1) {\n const cells: PptxTableCellRef[] = [];\n const values: string[] = [];\n const alignments = new Set<TableAlignment>();\n rows.forEach((row, rowIndex) => {\n const cell = cellsOf(row)[index];\n if (cell === undefined) return;\n cells.push({\n path: `${path}/props/rows/${rowIndex}/${index}`,\n cell: typeof cell === 'string' ? cell : asRecord(cell) ?? {},\n });\n if (rowIndex < bodyStart) return;\n values.push(cellText(cell));\n alignments.add(cellAlignment(cell, tableDefault));\n });\n const header = headerRow ? cellText(cellsOf(rows[0])[index]) : undefined;\n columns.push({\n index,\n // The top cell of the column. A row-major table has no node standing\n // for a column, and pointing every column of one table at `props/rows`\n // would give two findings the same address — indistinguishable to a\n // reader, and impossible to suppress one at a time.\n path: `${path}/props/rows/0/${index}`,\n ...(header !== undefined && { header }),\n values,\n alignment:\n alignments.size === 1\n ? [...alignments][0]\n : alignments.size === 0\n ? tableDefault\n : 'mixed',\n cells,\n });\n }\n return { ...base, columns };\n}\n\n/**\n * The `props` of the authored node at an RFC 6901 pointer.\n *\n * Facts are otherwise read off the processed tree, which is what the renderer\n * draws. A handful of questions are about what the *document* asked for rather\n * than what it inherited, and those need the authored node at the same pointer\n * the fact reports.\n */\nfunction authoredPropsAtPointer(\n root: unknown,\n pointer: string\n): Rec | undefined {\n let node: unknown = root;\n for (const token of pointer.split('/').slice(1)) {\n const key = token.replace(/~1/g, '/').replace(/~0/g, '~');\n if (Array.isArray(node)) {\n const index = Number(key);\n if (!Number.isInteger(index)) return undefined;\n node = node[index];\n } else {\n const record = asRecord(node);\n if (!record) return undefined;\n node = record[key];\n }\n if (node === undefined) return undefined;\n }\n return asRecord(asRecord(node)?.props);\n}\n\nfunction addSlideFacts(\n roots: ComponentAtPath[],\n slidePath: string,\n renderedIndex: number,\n grid: GridConfig | undefined,\n slideWidthIn: number,\n slideHeightIn: number,\n ctx: ThemeContext,\n theme: PptxThemeConfig,\n slideBackground: (fx: number, fy: number) => readonly string[],\n analyzedTextPaths: Set<string>,\n analyzedContentPaths: Set<string>,\n paletteTokens: readonly string[],\n authoredPropsAt: (path: string) => Rec | undefined,\n addFact: (fact: PptxQualityFact) => void\n): void {\n const nodes: TextNode[] = [];\n const surfaces: Surface[] = [];\n const boxes: BoxNode[] = [];\n const contentNodes: ContentNode[] = [];\n const counter = { next: 0 };\n for (const root of roots) {\n collectSlideNodes(\n root.component,\n root.path,\n nodes,\n surfaces,\n boxes,\n contentNodes,\n counter\n );\n }\n\n // Shared template objects reach every slide that uses the template; their\n // authored path is analysed once, exactly as text is.\n for (const node of contentNodes) {\n if (analyzedContentPaths.has(node.path)) continue;\n analyzedContentPaths.add(node.path);\n const fact =\n node.componentName === 'table'\n ? tableFact(node, slidePath, authoredPropsAt(node.path))\n : chartFact(node, paletteTokens);\n if (fact) addFact(fact);\n }\n boxes.forEach((node, boxIndex) => {\n const box = resolveBox(node.props, grid, slideWidthIn, slideHeightIn);\n if (!isCompleteBox(box)) return;\n addFact({\n id: `pptx:box:${renderedIndex}:${boxIndex}:${node.path}`,\n kind: 'pptx/box',\n path: node.path,\n slidePath,\n componentName: node.componentName,\n order: node.order,\n opaque: node.opaque,\n xPt: box.xPt,\n yPt: box.yPt,\n widthPt: box.widthPt,\n heightPt: box.heightPt,\n });\n });\n const surfaceBoxes = surfaces.flatMap((surface) => {\n const box = resolveBox(surface.props, grid, slideWidthIn, slideHeightIn);\n return isCompleteBox(box) ? [{ ...surface, box }] : [];\n });\n\n let bodyWords = 0;\n nodes.forEach((node, nodeIndex) => {\n const typography = resolveTypography(node.props, ctx);\n if (\n typography.styleName !== 'title' &&\n typography.styleName !== 'subtitle'\n ) {\n bodyWords += node.text.split(/\\s+/).filter(Boolean).length;\n }\n\n // Shared template objects count toward every slide's density, but their\n // authored path should be analyzed only once.\n if (analyzedTextPaths.has(node.path)) return;\n analyzedTextPaths.add(node.path);\n\n const gridPos = asRecord(node.props.grid);\n const nodeBox = resolveBox(node.props, grid, slideWidthIn, slideHeightIn);\n const {\n xPt: boxXPt,\n yPt: boxYPt,\n widthPt: boxWidthPt,\n heightPt: boxHeightPt,\n } = nodeBox;\n\n // What the text actually sits on: its own shape fill, else the topmost\n // earlier-drawn surface covering its centre, else the slide itself.\n // Skipping the occlusion step reads every white-on-blue card as white on\n // the slide's white ground, which is how a contrast rule earns a reputation\n // for crying wolf.\n // Sample the whole box, not just its middle. A text block laid across a\n // gradient has a legibility problem at its worst end, and a centre sample\n // reports the average — which is exactly the point where neither the light\n // nor the dark half of the ground is represented.\n const sampleFractions = (\n box: Partial<Box>,\n originX: number,\n originY: number,\n widthPt: number,\n heightPt: number\n ): Array<readonly [number, number]> => {\n if (!isCompleteBox(box) || widthPt <= 0 || heightPt <= 0) {\n return [[0.5, 0.5]];\n }\n const x0 = (box.xPt - originX) / widthPt;\n const x1 = (box.xPt + box.widthPt - originX) / widthPt;\n const y0 = (box.yPt - originY) / heightPt;\n const y1 = (box.yPt + box.heightPt - originY) / heightPt;\n return [\n [(x0 + x1) / 2, (y0 + y1) / 2],\n [x0, y0],\n [x1, y0],\n [x0, y1],\n [x1, y1],\n ];\n };\n const slideSamples = sampleFractions(\n nodeBox,\n 0,\n 0,\n slideWidthIn * 72,\n slideHeightIn * 72\n );\n // A node's own fill spans the node, not the slide, so it is sampled in the\n // node's own box. Reusing the slide fractions here would read a shape's\n // gradient at the shape's position on the slide — a shape an inch into a\n // 13in canvas would never reach its own later stops.\n const ownFill = [\n ...new Set(\n sampleFractions(\n nodeBox,\n boxXPt ?? 0,\n boxYPt ?? 0,\n boxWidthPt ?? 0,\n boxHeightPt ?? 0\n ).flatMap(([fx, fy]) =>\n paintedColorHexes(\n node.props.fill,\n theme,\n fx,\n fy,\n (boxWidthPt ?? 0) / 72,\n (boxHeightPt ?? 0) / 72\n )\n )\n ),\n ];\n let backgroundHexes: readonly string[] = [\n ...new Set(slideSamples.flatMap(([fx, fy]) => slideBackground(fx, fy))),\n ];\n let backgroundUnknown = false;\n if (ownFill.length > 0) {\n backgroundHexes = ownFill;\n } else if (isCompleteBox(nodeBox)) {\n const covering = surfaceBoxes\n .filter(\n (surface) =>\n surface.order < node.order && containsCentre(surface.box, nodeBox)\n )\n .pop();\n if (covering?.isImage) {\n // An image covers the ground but says nothing about its colour.\n backgroundUnknown = true;\n } else if (covering) {\n // Sample within the covering shape's own box, not the slide's.\n const fill = [\n ...new Set(\n sampleFractions(\n nodeBox,\n covering.box.xPt,\n covering.box.yPt,\n covering.box.widthPt,\n covering.box.heightPt\n ).flatMap(([fx, fy]) =>\n paintedColorHexes(\n covering.props.fill,\n theme,\n fx,\n fy,\n covering.box.widthPt / 72,\n covering.box.heightPt / 72\n )\n )\n ),\n ];\n if (fill.length > 0) backgroundHexes = fill;\n else backgroundUnknown = true;\n }\n }\n const colorHex =\n typeof node.props.color === 'string'\n ? resolveColor(node.props.color, theme)?.toUpperCase()\n : undefined;\n\n addFact({\n id: `pptx:text:${renderedIndex}:${nodeIndex}:${node.path}`,\n kind: 'pptx/text',\n path: node.path,\n slidePath,\n text: node.text,\n fontSizePt: typography.fontSize,\n lineSpacingPt: typography.lineSpacing,\n paraSpaceBeforePt: typography.paraSpaceBefore,\n paraSpaceAfterPt: typography.paraSpaceAfter,\n ...(typography.styleName && { styleName: typography.styleName }),\n ...(boxXPt !== undefined && { boxXPt }),\n ...(boxYPt !== undefined && { boxYPt }),\n ...(boxWidthPt !== undefined && boxWidthPt > 0 && { boxWidthPt }),\n ...(boxHeightPt !== undefined && boxHeightPt > 0 && { boxHeightPt }),\n verticalAlign:\n node.props.valign === 'middle' || node.props.valign === 'bottom'\n ? node.props.valign\n : 'top',\n align: horizontalAlign(node.props, ctx),\n rotationDeg: asNumber(node.props.rotate) ?? 0,\n bold: typography.bold,\n autoFit: node.props.h === undefined && gridPos === undefined,\n ...(colorHex !== undefined && { colorHex }),\n ...(!backgroundUnknown &&\n backgroundHexes.length > 0 && { backgroundHexes }),\n });\n });\n\n addFact({\n id: `pptx:slide:${renderedIndex}:${slidePath}`,\n kind: 'pptx/slide',\n path: slidePath,\n bodyWords,\n });\n}\n\nexport function preparePptxQualityDocument(\n document: PresentationComponentDefinition,\n options: PreparePptxQualityOptions = {}\n): PreparedDocument<PptxQualityModel, PptxQualityFact> {\n const facts: PptxQualityFact[] = [];\n const provenance: Record<string, ProvenanceMap[string]> = {};\n // Blocks lower here, once, for every consumer: the facts below, the\n // compiler and the renderers all read the expanded tree. A fact raised on a\n // compiled child is reported at the authored slot it came from, so a\n // finding inside a block points at what the author wrote, never at a node\n // they never saw.\n let sourceMap: BlockSourceMap = {};\n const authoredPath = (path: string): string =>\n toAuthoredPointer(sourceMap, path);\n const addFact = (raw: PptxQualityFact): void => {\n const fact: PptxQualityFact = {\n ...raw,\n path: authoredPath(raw.path),\n ...(raw.relatedPaths && {\n relatedPaths: raw.relatedPaths.map(authoredPath),\n }),\n };\n facts.push(fact);\n provenance[fact.id] = {\n path: fact.path,\n ...(fact.relatedPaths && { relatedPaths: fact.relatedPaths }),\n };\n };\n\n const props = asRecord(document.props) ?? {};\n addFact({\n id: 'pptx:canvas',\n kind: 'pptx/canvas',\n path: '/props',\n ...(asNumber(props.slideWidth) !== undefined && {\n widthIn: asNumber(props.slideWidth),\n }),\n ...(asNumber(props.slideHeight) !== undefined && {\n heightIn: asNumber(props.slideHeight),\n }),\n });\n\n // Over the authored tree, before any theme or template resolution: a marker\n // has to be reported where the author can patch it out.\n collectPlaceholders(document).forEach((occurrence, index) => {\n addFact({\n id: `pptx:placeholder:${index}:${occurrence.path}`,\n kind: 'pptx/placeholder',\n path: occurrence.path,\n text: occurrence.text,\n placeholderKind: occurrence.match.kind,\n pattern: occurrence.match.pattern,\n excerpt: occurrence.match.excerpt,\n });\n });\n\n collectColorLiterals(document).forEach((literal, index) => {\n addFact({\n id: `pptx:color:${index}:${literal.path}`,\n kind: 'pptx/color',\n path: literal.path,\n raw: literal.raw,\n hex: literal.hex,\n });\n });\n\n collectFontFamilies(document).forEach((use, index) => {\n addFact({\n id: `pptx:font:${index}:${use.path}`,\n kind: 'pptx/font-family',\n path: use.path,\n family: use.family,\n });\n });\n\n const warnings = options.warnings ?? [];\n const context = resolveThemeContext(document, {\n customThemes: options.customThemes,\n fonts: options.fonts,\n warnings,\n });\n const expanded = expandPptxBlocks(context.document, context.theme);\n sourceMap = expanded.sourceMap;\n const processed = processPresentation(expanded.document, {\n theme: context.theme,\n customThemes: options.customThemes,\n services: options.services,\n sourceMap,\n warnings,\n });\n const ctx = themeContext(processed.theme);\n\n const paletteHexes: Record<string, string> = {};\n const visualColors = designColors(\n processed.theme.colors,\n processed.theme.palette\n );\n const entries = {\n ...visualColors,\n ...Object.fromEntries(\n (processed.theme.palette?.chart ?? []).map((value) => [\n `#${resolveColor(value, processed.theme)}`,\n value,\n ])\n ),\n };\n for (const [token, value] of Object.entries(entries)) {\n if (typeof value !== 'string') continue;\n // Through `resolveColor` so a slot naming another slot lands on the colour\n // it actually paints, not on the token name it stores.\n const hex = normalizeHex(resolveColor(value, processed.theme));\n // New palette roles are theme-only, outside the component color enum.\n // Quality fixes must offer a legal literal for those colors.\n if (hex)\n paletteHexes[\n (SEMANTIC_COLOR_NAMES as readonly string[]).includes(token)\n ? token\n : hex\n ] = hex;\n }\n addFact({\n id: 'pptx:theme',\n kind: 'pptx/theme',\n path: '/props',\n themeName: processed.theme.name,\n paletteHexes,\n fontFamilies: [\n ...new Set(\n [processed.theme.fonts?.heading, processed.theme.fonts?.body].filter(\n (family): family is string =>\n typeof family === 'string' && family.trim() !== ''\n )\n ),\n ],\n });\n const authoredChildren = Array.isArray(document.children)\n ? document.children\n : [];\n const slideIndexes = authoredChildren.flatMap((child, index) => {\n const slide = asRecord(child);\n return slide?.name === 'slide' && slide.enabled !== false ? [index] : [];\n });\n const analyzedTextPaths = new Set<string>();\n const analyzedContentPaths = new Set<string>();\n const paletteTokens =\n processed.theme.palette?.chart?.map(\n (value) => `#${resolveColor(value, processed.theme)}`\n ) ??\n SERIES_COLOR_TOKENS.filter((token) => paletteHexes[token] !== undefined);\n // A handful of questions are about what the document asked for rather than\n // what it inherited; for block content the authored node is the slot.\n const authoredPropsAt = (pointer: string): Rec | undefined =>\n authoredPropsAtPointer(document, authoredPath(pointer));\n\n processed.slides.forEach((slide, renderedIndex) => {\n const authoredIndex = slideIndexes[renderedIndex];\n if (authoredIndex === undefined) return;\n const slidePath = `/children/${authoredIndex}`;\n const roots: ComponentAtPath[] = slide.components.map(\n (component, index) => ({\n component,\n path: `${slidePath}/children/${index}`,\n })\n );\n\n addSlideFacts(\n roots,\n slidePath,\n renderedIndex,\n processed.grid,\n processed.slideWidth,\n processed.slideHeight,\n ctx,\n processed.theme,\n (fx, fy) =>\n paintedColorHexes(\n slide.background ?? props.background,\n processed.theme,\n fx,\n fy,\n processed.slideWidth,\n processed.slideHeight\n ),\n analyzedTextPaths,\n analyzedContentPaths,\n paletteTokens,\n authoredPropsAt,\n addFact\n );\n });\n\n for (const budget of blockSlotBudgets(context.document, expanded.blocks)) {\n addFact({\n id: `pptx:block-slot:${budget.path}`,\n kind: 'pptx/block-slot',\n ...budget,\n });\n }\n const slotTextNodes = textNodesBySlot(processed, slideIndexes, sourceMap);\n for (const role of blockSlotRoles(context.document, expanded.blocks)) {\n const present =\n role.value !== undefined &&\n role.value !== null &&\n role.value !== '' &&\n role.value !== false &&\n (!Array.isArray(role.value) || role.value.length > 0);\n const bound = slotTextNodes.get(role.path);\n let measured: { estimatedLines: number; fontSizePt: number } | undefined;\n if (bound && typeof bound.props.text === 'string') {\n const typography = resolveTypography(bound.props, ctx);\n const box = resolveBox(\n bound.props,\n processed.grid,\n processed.slideWidth,\n processed.slideHeight\n );\n if (box.widthPt !== undefined && box.widthPt > 0)\n measured = {\n estimatedLines: estimateTextLines(\n bound.props.text,\n box.widthPt,\n typography.fontSize\n ),\n fontSizePt: typography.fontSize,\n };\n }\n addFact({\n id: `pptx:chrome-slot:${role.path}`,\n kind: 'pptx/chrome-slot',\n path: role.path,\n relatedPaths: [role.invocation],\n block: role.block,\n invocation: role.invocation,\n slot: role.slot,\n role: role.role,\n present,\n ...(typeof role.value === 'string' && { text: role.value }),\n ...measured,\n });\n }\n\n return {\n format: 'pptx',\n model: {\n authored: document,\n document: expanded.document,\n theme: context.theme,\n processed,\n },\n facts,\n provenance,\n renderer: options.renderer ?? DEFAULT_PPTX_RENDERER_ID,\n ...(expanded.blocks.length > 0 && {\n metadata: {\n blocks: {\n sourceMap,\n blocks: expanded.blocks,\n document: expanded.document,\n } satisfies PptxBlocksMetadata,\n },\n }),\n };\n}\n\n/**\n * The processed text node each authored slot became, keyed by slot pointer.\n * Layout has already given every node its absolute box, so a slot's text can\n * be measured in the frame the definition drew for it.\n */\nfunction textNodesBySlot(\n processed: ProcessedPresentation,\n slideIndexes: readonly number[],\n sourceMap: BlockSourceMap\n): Map<string, { props: Rec }> {\n const found = new Map<string, { props: Rec }>();\n const visit = (component: PptxComponentInput, path: string): void => {\n if (component.enabled === false) return;\n if (component.name === 'text') {\n const origin = toAuthoredPointer(sourceMap, `${path}/props/text`);\n if (origin !== `${path}/props/text` && !found.has(origin))\n found.set(origin, { props: asRecord(component.props) ?? {} });\n }\n (component.children ?? []).forEach((child, index) =>\n visit(child, `${path}/children/${index}`)\n );\n };\n processed.slides.forEach((slide, renderedIndex) => {\n const authoredIndex = slideIndexes[renderedIndex];\n if (authoredIndex === undefined) return;\n slide.components.forEach((component, index) =>\n visit(component, `/children/${authoredIndex}/children/${index}`)\n );\n });\n return found;\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';\nimport { resolvePptxDesignSystem } from '../themes/design-system';\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 theme = resolvePptxDesignSystem(\n theme,\n document.props.slideWidth,\n document.props.slideHeight\n );\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 \"name\": \"consulting\",\n \"displayName\": \"Consulting House\",\n \"description\": \"The house style for decision decks — near-black ink, three greys and one deep-blue accent, Calibri body under Arial headings, hairline rules, no fills behind text, safe fonts only\",\n \"whenToUse\": \"Decision decks and client readouts: one message per slide, a chart that carries it, a source under it; the twin of the DOCX house theme, so a deck and its report match.\",\n \"version\": \"1.0.0\",\n \"colors\": {\n \"primary\": \"#1A1F26\",\n \"secondary\": \"#4B5563\",\n \"accent\": \"#1B4F8A\",\n \"background\": \"#FFFFFF\",\n \"text\": \"#1A1F26\",\n \"text2\": \"#4B5563\",\n \"background2\": \"#F2F4F7\",\n \"accent4\": \"#5B8DC9\",\n \"accent5\": \"#A9C4E4\",\n \"accent6\": \"#7B8794\"\n },\n \"palette\": {\n \"rule\": \"#C9CED6\",\n \"textMuted\": \"#7B8794\",\n \"onPrimary\": \"#FFFFFF\",\n \"surfaceInverse\": \"#1A1F26\",\n \"positive\": \"#1E7F4F\",\n \"negative\": \"#B42318\",\n \"chart\": [\"accent\", \"secondary\", \"accent4\", \"textMuted\", \"accent5\", \"rule\"]\n },\n \"fonts\": {\n \"heading\": \"Arial\",\n \"body\": \"Calibri\",\n \"mono\": \"Consolas\"\n },\n \"defaults\": {\n \"fontSize\": 14,\n \"fontColor\": \"#1A1F26\"\n },\n \"styles\": {\n \"title\": {\n \"fontSize\": 32,\n \"bold\": true,\n \"fontColor\": \"text\",\n \"align\": \"left\"\n },\n \"subtitle\": {\n \"fontSize\": 16,\n \"fontColor\": \"text2\",\n \"align\": \"left\"\n },\n \"heading1\": {\n \"fontSize\": 24,\n \"bold\": true,\n \"fontColor\": \"text\"\n },\n \"heading2\": {\n \"fontSize\": 18,\n \"bold\": true,\n \"fontColor\": \"text\"\n },\n \"heading3\": {\n \"fontSize\": 14,\n \"bold\": true,\n \"fontColor\": \"text2\"\n },\n \"body\": {\n \"fontSize\": 14,\n \"fontColor\": \"text\"\n },\n \"caption\": {\n \"fontSize\": 10,\n \"fontColor\": \"text2\"\n }\n },\n \"typography\": {\n \"roles\": {\n \"eyebrow\": {\n \"face\": \"heading\",\n \"size\": 10,\n \"weight\": 700,\n \"case\": \"upper\",\n \"tracking\": 8,\n \"color\": \"accent\"\n },\n \"display\": {\n \"face\": \"heading\",\n \"size\": 28,\n \"weight\": 700,\n \"color\": \"primary\",\n \"lineHeight\": 1.1\n },\n \"stat\": {\n \"face\": \"heading\",\n \"size\": 40,\n \"weight\": 700,\n \"color\": \"accent\",\n \"lineHeight\": 1\n },\n \"quote\": {\n \"face\": \"body\",\n \"size\": 18,\n \"color\": \"text2\",\n \"lineHeight\": 1.3\n },\n \"label\": {\n \"face\": \"body\",\n \"size\": 12,\n \"weight\": 700,\n \"color\": \"text2\"\n },\n \"footer\": {\n \"face\": \"body\",\n \"size\": 9,\n \"color\": \"text2\"\n },\n \"tableHeader\": {\n \"face\": \"body\",\n \"size\": 12,\n \"weight\": 700,\n \"color\": \"primary\"\n },\n \"tableCell\": {\n \"face\": \"body\",\n \"size\": 12,\n \"color\": \"text\"\n },\n \"chartLabel\": {\n \"face\": \"body\",\n \"size\": 11,\n \"weight\": 400,\n \"color\": \"text2\"\n },\n \"tracker\": {\n \"face\": \"body\",\n \"size\": 10,\n \"case\": \"upper\",\n \"tracking\": 6,\n \"color\": \"text2\"\n },\n \"source\": {\n \"face\": \"body\",\n \"size\": 9,\n \"color\": \"text2\"\n }\n },\n \"scale\": {\n \"wide169\": {\n \"base\": 14,\n \"ratio\": 1.2,\n \"baselinePt\": 2\n },\n \"standard43\": {\n \"base\": 14,\n \"ratio\": 1.2,\n \"baselinePt\": 2\n }\n }\n },\n \"spacing\": {\n \"basePt\": 8,\n \"blockGap\": {\n \"tight\": 4,\n \"normal\": 8,\n \"loose\": 16\n },\n \"canvas\": {\n \"wide169\": {\n \"safeAreaIn\": 0.5,\n \"gutterIn\": 0.2,\n \"columns\": 12,\n \"rows\": 8\n },\n \"standard43\": {\n \"safeAreaIn\": 0.5,\n \"gutterIn\": 0.2,\n \"columns\": 12,\n \"rows\": 8\n }\n }\n },\n \"chrome\": {\n \"runningHead\": {\n \"type\": \"tracker\",\n \"color\": \"text2\",\n \"rule\": {\n \"weightPt\": 0.5,\n \"color\": \"rule\"\n },\n \"alignment\": \"right\"\n },\n \"tracker\": {\n \"type\": \"tracker\",\n \"color\": \"text2\",\n \"alignment\": \"right\"\n },\n \"actionTitle\": {\n \"type\": \"display\",\n \"color\": \"primary\"\n },\n \"keyTakeaways\": {\n \"type\": \"label\",\n \"color\": \"primary\",\n \"rule\": {\n \"weightPt\": 2,\n \"color\": \"accent\"\n },\n \"padPt\": 8\n },\n \"sourceLine\": {\n \"type\": \"source\",\n \"color\": \"text2\"\n },\n \"confidentialFooter\": {\n \"type\": \"footer\",\n \"color\": \"text2\",\n \"rule\": {\n \"weightPt\": 0.5,\n \"color\": \"rule\"\n },\n \"alignment\": \"left\"\n },\n \"logoSlot\": {\n \"alignment\": \"right\"\n },\n \"cover\": {\n \"type\": \"display\",\n \"color\": \"primary\",\n \"rule\": {\n \"weightPt\": 3,\n \"color\": \"accent\"\n }\n }\n },\n \"motif\": {\n \"kind\": \"rule\",\n \"color\": \"accent\",\n \"weightPt\": 3,\n \"placement\": \"top\"\n },\n \"componentDefaults\": {\n \"table\": {\n \"border\": {\n \"type\": \"solid\",\n \"pt\": 0.5,\n \"color\": \"#C9CED6\"\n },\n \"headerRow\": true,\n \"fontSize\": 12\n },\n \"chart\": {\n \"showLegend\": true,\n \"legendPos\": \"b\",\n \"legendFontSize\": 11,\n \"catAxisLabelFontSize\": 11,\n \"valAxisLabelFontSize\": 11,\n \"catGridLine\": {\n \"style\": \"none\"\n },\n \"valGridLine\": {\n \"style\": \"solid\",\n \"size\": 0.5,\n \"color\": \"#E4E7EB\"\n },\n \"valAxisLineShow\": false\n }\n }\n}\n","/**\n * The consulting house theme, PPTX twin of `consulting.docx.theme.json`.\n *\n * Shares every visual token with the DOCX theme — ink, three greys, one deep\n * blue, positive/negative, the ordered chart series, Arial over Calibri with\n * Consolas for code — so a deck and its report match without restyling. A\n * guard test pins the agreement.\n *\n * Values only. The theme paints action titles, trackers, sources and footers\n * through its chrome recipes and type roles; whether a slide must carry them\n * is a quality profile's decision (`consulting-deck`), never the theme's.\n *\n * SAFE_FONTS only: nothing here needs a font registry on any Office install.\n *\n * One projection differs from the report: the small roles — footer, tracker,\n * source — and the chrome recipes that paint them take `text2` rather than\n * `textMuted`. On a projected slide a 9pt run in the light grey sits under\n * the 4.5 : 1 the contrast rule asks of small text; the darker grey passes it\n * and reads as the same voice. The agreement test knows this one substitution.\n */\n\nimport type { PptxThemeConfig } from '../types';\nimport consultingThemeJson from './consulting.pptx.theme.json';\n\n/**\n * Data, not code: the theme lives in `consulting.pptx.theme.json` so the\n * playground's theme discovery — a scan for `*.pptx.theme.json`, the way the\n * DOCX built-ins are found — lists it beside the deck. The bundled-themes test\n * validates the file against the theme schema and pins it to the DOCX twin.\n */\nexport const CONSULTING_PPTX_THEME: PptxThemeConfig =\n consultingThemeJson as PptxThemeConfig;\n","{\n \"name\": \"vermilion\",\n \"displayName\": \"Vermilion Editorial\",\n \"description\": \"Poster-red editorial deck — vermilion display titles, ink text, warm creams and hairline rules; the twin of the DOCX vermilion theme\",\n \"whenToUse\": \"Talks and readouts that want a strong red display voice beside a vermilion report: a few large titles, one figure per slide. Not for a dense data deck.\",\n \"version\": \"1.0.0\",\n \"colors\": {\n \"primary\": \"#282829\",\n \"secondary\": \"#58595B\",\n \"accent\": \"#EF4130\",\n \"background\": \"#FFFFFF\",\n \"text\": \"#282829\",\n \"text2\": \"#58595B\",\n \"background2\": \"#FAF7F5\",\n \"accent4\": \"#F4857A\",\n \"accent5\": \"#F9C4BE\",\n \"accent6\": \"#939598\"\n },\n \"palette\": {\n \"rule\": \"#C7C8CA\",\n \"textMuted\": \"#939598\",\n \"onPrimary\": \"#FFFFFF\",\n \"surfaceInverse\": \"#282829\",\n \"positive\": \"#2E7D4F\",\n \"negative\": \"#B42318\",\n \"chart\": [\"accent\", \"primary\", \"textMuted\", \"accent4\", \"rule\", \"accent5\"]\n },\n \"fonts\": {\n \"heading\": \"Arial\",\n \"body\": \"Calibri\",\n \"mono\": \"Courier New\"\n },\n \"defaults\": {\n \"fontSize\": 14,\n \"fontColor\": \"#282829\"\n },\n \"styles\": {\n \"title\": {\n \"fontSize\": 32,\n \"bold\": true,\n \"fontColor\": \"accent\",\n \"align\": \"left\"\n },\n \"subtitle\": {\n \"fontSize\": 16,\n \"fontColor\": \"text2\",\n \"align\": \"left\"\n },\n \"heading1\": {\n \"fontSize\": 24,\n \"bold\": true,\n \"fontColor\": \"accent\"\n },\n \"heading2\": {\n \"fontSize\": 18,\n \"bold\": true,\n \"fontColor\": \"text\"\n },\n \"heading3\": {\n \"fontSize\": 14,\n \"bold\": true,\n \"fontColor\": \"text2\"\n },\n \"body\": {\n \"fontSize\": 14,\n \"fontColor\": \"text\"\n },\n \"caption\": {\n \"fontSize\": 10,\n \"fontColor\": \"text2\"\n }\n },\n \"typography\": {\n \"roles\": {\n \"eyebrow\": {\n \"face\": \"heading\",\n \"size\": 10,\n \"weight\": 700,\n \"case\": \"upper\",\n \"tracking\": 8,\n \"color\": \"accent\"\n },\n \"display\": {\n \"face\": \"heading\",\n \"size\": 28,\n \"weight\": 700,\n \"color\": \"accent\",\n \"lineHeight\": 1.1\n },\n \"stat\": {\n \"face\": \"heading\",\n \"size\": 40,\n \"weight\": 700,\n \"color\": \"accent\",\n \"lineHeight\": 1\n },\n \"quote\": {\n \"face\": \"body\",\n \"size\": 18,\n \"color\": \"text2\",\n \"lineHeight\": 1.3\n },\n \"label\": {\n \"face\": \"body\",\n \"size\": 12,\n \"weight\": 700,\n \"color\": \"text2\"\n },\n \"footer\": {\n \"face\": \"body\",\n \"size\": 9,\n \"color\": \"text2\"\n },\n \"tableHeader\": {\n \"face\": \"body\",\n \"size\": 12,\n \"weight\": 700,\n \"color\": \"accent\"\n },\n \"tableCell\": {\n \"face\": \"body\",\n \"size\": 12,\n \"color\": \"text\"\n },\n \"chartLabel\": {\n \"face\": \"body\",\n \"size\": 11,\n \"weight\": 400,\n \"color\": \"text2\"\n },\n \"tracker\": {\n \"face\": \"body\",\n \"size\": 10,\n \"case\": \"upper\",\n \"tracking\": 6,\n \"color\": \"text2\"\n },\n \"source\": {\n \"face\": \"body\",\n \"size\": 9,\n \"color\": \"text2\"\n }\n },\n \"scale\": {\n \"wide169\": {\n \"base\": 14,\n \"ratio\": 1.2,\n \"baselinePt\": 2\n },\n \"standard43\": {\n \"base\": 14,\n \"ratio\": 1.2,\n \"baselinePt\": 2\n }\n }\n },\n \"spacing\": {\n \"basePt\": 8,\n \"blockGap\": {\n \"tight\": 4,\n \"normal\": 8,\n \"loose\": 16\n },\n \"canvas\": {\n \"wide169\": {\n \"safeAreaIn\": 0.5,\n \"gutterIn\": 0.2,\n \"columns\": 12,\n \"rows\": 8\n },\n \"standard43\": {\n \"safeAreaIn\": 0.5,\n \"gutterIn\": 0.2,\n \"columns\": 12,\n \"rows\": 8\n }\n }\n },\n \"chrome\": {\n \"runningHead\": {\n \"type\": \"tracker\",\n \"color\": \"text2\",\n \"rule\": {\n \"weightPt\": 0.5,\n \"color\": \"rule\"\n },\n \"alignment\": \"right\"\n },\n \"tracker\": {\n \"type\": \"tracker\",\n \"color\": \"text2\",\n \"alignment\": \"right\"\n },\n \"actionTitle\": {\n \"type\": \"display\",\n \"color\": \"primary\"\n },\n \"keyTakeaways\": {\n \"type\": \"label\",\n \"color\": \"primary\",\n \"rule\": {\n \"weightPt\": 1.5,\n \"color\": \"accent\"\n },\n \"padPt\": 8\n },\n \"sourceLine\": {\n \"type\": \"source\",\n \"color\": \"text2\"\n },\n \"confidentialFooter\": {\n \"type\": \"footer\",\n \"color\": \"text2\",\n \"rule\": {\n \"weightPt\": 0.5,\n \"color\": \"rule\"\n },\n \"alignment\": \"left\"\n },\n \"logoSlot\": {\n \"alignment\": \"right\"\n },\n \"cover\": {\n \"type\": \"display\",\n \"color\": \"primary\",\n \"rule\": {\n \"weightPt\": 4,\n \"color\": \"accent\"\n }\n }\n },\n \"motif\": {\n \"kind\": \"rule\",\n \"color\": \"accent\",\n \"weightPt\": 4,\n \"placement\": \"top\"\n },\n \"componentDefaults\": {\n \"table\": {\n \"border\": {\n \"type\": \"solid\",\n \"pt\": 0.5,\n \"color\": \"#C7C8CA\"\n },\n \"headerRow\": true,\n \"fontSize\": 12\n },\n \"chart\": {\n \"showLegend\": true,\n \"legendPos\": \"b\",\n \"legendFontSize\": 11,\n \"catAxisLabelFontSize\": 11,\n \"valAxisLabelFontSize\": 11,\n \"catGridLine\": {\n \"style\": \"none\"\n },\n \"valGridLine\": {\n \"style\": \"solid\",\n \"size\": 0.5,\n \"color\": \"#EFEAE4\"\n },\n \"valAxisLineShow\": false\n }\n }\n}\n","{\n \"name\": \"devportal\",\n \"displayName\": \"Field Editorial\",\n \"description\": \"Compact editorial deck — Helvetica in near-black ink with a burnt-orange accent, tight titles, letterspaced labels, warm tinted fills and hairline rules; the twin of the DOCX devportal theme\",\n \"whenToUse\": \"Product and engineering readouts, API and platform reviews: dense text, code and tables beside a devportal report. Not for a client's decision deck.\",\n \"version\": \"1.0.0\",\n \"colors\": {\n \"primary\": \"#12191F\",\n \"secondary\": \"#172028\",\n \"accent\": \"#E35B3F\",\n \"background\": \"#FFFFFF\",\n \"text\": \"#232323\",\n \"text2\": \"#46494C\",\n \"background2\": \"#F7ECE7\",\n \"accent4\": \"#46494C\",\n \"accent5\": \"#8A9299\",\n \"accent6\": \"#E8A18D\"\n },\n \"palette\": {\n \"rule\": \"#D8D5D1\",\n \"textMuted\": \"#737373\",\n \"onPrimary\": \"#FFFFFF\",\n \"surfaceInverse\": \"#12191F\",\n \"positive\": \"#2E7D4F\",\n \"negative\": \"#B42318\",\n \"chart\": [\"accent\", \"primary\", \"accent4\", \"accent5\", \"accent6\", \"rule\"]\n },\n \"fonts\": {\n \"heading\": \"Helvetica\",\n \"body\": \"Helvetica\",\n \"mono\": \"Courier New\"\n },\n \"defaults\": {\n \"fontSize\": 14,\n \"fontColor\": \"#232323\"\n },\n \"styles\": {\n \"title\": {\n \"fontSize\": 30,\n \"bold\": true,\n \"fontColor\": \"text\",\n \"align\": \"left\"\n },\n \"subtitle\": {\n \"fontSize\": 16,\n \"fontColor\": \"text2\",\n \"align\": \"left\"\n },\n \"heading1\": {\n \"fontSize\": 24,\n \"bold\": true,\n \"fontColor\": \"primary\"\n },\n \"heading2\": {\n \"fontSize\": 18,\n \"bold\": true,\n \"fontColor\": \"secondary\"\n },\n \"heading3\": {\n \"fontSize\": 14,\n \"bold\": true,\n \"fontColor\": \"text2\"\n },\n \"body\": {\n \"fontSize\": 14,\n \"fontColor\": \"text\"\n },\n \"caption\": {\n \"fontSize\": 10,\n \"fontColor\": \"text2\"\n }\n },\n \"typography\": {\n \"roles\": {\n \"eyebrow\": {\n \"face\": \"heading\",\n \"size\": 10,\n \"weight\": 700,\n \"case\": \"upper\",\n \"tracking\": 10,\n \"color\": \"accent\"\n },\n \"display\": {\n \"face\": \"heading\",\n \"size\": 28,\n \"weight\": 700,\n \"color\": \"primary\",\n \"lineHeight\": 1.1,\n \"tracking\": -2\n },\n \"stat\": {\n \"face\": \"heading\",\n \"size\": 40,\n \"weight\": 700,\n \"color\": \"accent\",\n \"lineHeight\": 1\n },\n \"quote\": {\n \"face\": \"body\",\n \"size\": 18,\n \"color\": \"text2\",\n \"lineHeight\": 1.3\n },\n \"label\": {\n \"face\": \"body\",\n \"size\": 12,\n \"weight\": 700,\n \"color\": \"text2\",\n \"case\": \"upper\",\n \"tracking\": 6\n },\n \"footer\": {\n \"face\": \"body\",\n \"size\": 9,\n \"color\": \"text2\"\n },\n \"tableHeader\": {\n \"face\": \"body\",\n \"size\": 12,\n \"weight\": 700,\n \"color\": \"secondary\"\n },\n \"tableCell\": {\n \"face\": \"body\",\n \"size\": 12,\n \"color\": \"text\"\n },\n \"chartLabel\": {\n \"face\": \"body\",\n \"size\": 11,\n \"weight\": 400,\n \"color\": \"text2\"\n },\n \"tracker\": {\n \"face\": \"body\",\n \"size\": 10,\n \"case\": \"upper\",\n \"tracking\": 6,\n \"color\": \"text2\"\n },\n \"source\": {\n \"face\": \"body\",\n \"size\": 9,\n \"color\": \"text2\"\n }\n },\n \"scale\": {\n \"wide169\": {\n \"base\": 14,\n \"ratio\": 1.2,\n \"baselinePt\": 2\n },\n \"standard43\": {\n \"base\": 14,\n \"ratio\": 1.2,\n \"baselinePt\": 2\n }\n }\n },\n \"spacing\": {\n \"basePt\": 8,\n \"blockGap\": {\n \"tight\": 4,\n \"normal\": 8,\n \"loose\": 16\n },\n \"canvas\": {\n \"wide169\": {\n \"safeAreaIn\": 0.5,\n \"gutterIn\": 0.2,\n \"columns\": 12,\n \"rows\": 8\n },\n \"standard43\": {\n \"safeAreaIn\": 0.5,\n \"gutterIn\": 0.2,\n \"columns\": 12,\n \"rows\": 8\n }\n }\n },\n \"chrome\": {\n \"runningHead\": {\n \"type\": \"tracker\",\n \"color\": \"text2\",\n \"rule\": {\n \"weightPt\": 0.5,\n \"color\": \"rule\"\n },\n \"alignment\": \"right\"\n },\n \"tracker\": {\n \"type\": \"tracker\",\n \"color\": \"text2\",\n \"alignment\": \"right\"\n },\n \"actionTitle\": {\n \"type\": \"display\",\n \"color\": \"primary\"\n },\n \"keyTakeaways\": {\n \"type\": \"label\",\n \"color\": \"primary\",\n \"rule\": {\n \"weightPt\": 1,\n \"color\": \"accent\"\n },\n \"padPt\": 8\n },\n \"sourceLine\": {\n \"type\": \"source\",\n \"color\": \"text2\"\n },\n \"confidentialFooter\": {\n \"type\": \"footer\",\n \"color\": \"text2\",\n \"rule\": {\n \"weightPt\": 0.5,\n \"color\": \"rule\"\n },\n \"alignment\": \"left\"\n },\n \"logoSlot\": {\n \"alignment\": \"right\"\n },\n \"cover\": {\n \"type\": \"display\",\n \"color\": \"primary\",\n \"rule\": {\n \"weightPt\": 3,\n \"color\": \"accent\"\n }\n }\n },\n \"motif\": {\n \"kind\": \"rule\",\n \"color\": \"accent\",\n \"weightPt\": 2,\n \"placement\": \"top\"\n },\n \"componentDefaults\": {\n \"table\": {\n \"border\": {\n \"type\": \"solid\",\n \"pt\": 0.5,\n \"color\": \"#D8D5D1\"\n },\n \"headerRow\": true,\n \"fontSize\": 12\n },\n \"chart\": {\n \"showLegend\": true,\n \"legendPos\": \"b\",\n \"legendFontSize\": 11,\n \"catAxisLabelFontSize\": 11,\n \"valAxisLabelFontSize\": 11,\n \"catGridLine\": {\n \"style\": \"none\"\n },\n \"valGridLine\": {\n \"style\": \"solid\",\n \"size\": 0.5,\n \"color\": \"#F2F3F3\"\n },\n \"valAxisLineShow\": false\n }\n }\n}\n","/**\n * The two alternate themes, PPTX twins of `vermilion.docx.theme.json` and\n * `devportal.docx.theme.json`.\n *\n * Each shares its palette roles, chart series, chrome recipes and motif with\n * the report theme of the same name, and names the same font families — all\n * of them in SAFE_FONTS, so neither needs a font registry. The projection\n * substitution the consulting twin makes — small roles and the recipes that\n * paint them take `text2` rather than `textMuted` — holds here for the same\n * contrast reason, and the agreement test knows it.\n *\n * Data, not code, for the same reason as `consulting.pptx.theme.json`: the\n * playground's theme discovery scans for `*.pptx.theme.json`.\n */\n\nimport type { PptxThemeConfig } from '../types';\nimport vermilionThemeJson from './vermilion.pptx.theme.json';\nimport devportalThemeJson from './devportal.pptx.theme.json';\n\nexport const VERMILION_PPTX_THEME: PptxThemeConfig =\n vermilionThemeJson as PptxThemeConfig;\nexport const DEVPORTAL_PPTX_THEME: PptxThemeConfig =\n devportalThemeJson as PptxThemeConfig;\n","/**\n * PPTX Theme Defaults\n */\n\nimport type { PptxComponentDefaults } from '@json-to-office/shared-pptx';\nimport type { PptxThemeConfig, TextStyle, StyleName } from '../types';\nimport { CONSULTING_PPTX_THEME } from './consulting';\nimport { DEVPORTAL_PPTX_THEME, VERMILION_PPTX_THEME } from './alternates';\n\n/**\n * What a table looks like before anyone styles one.\n *\n * With no defaults at all a PPTX table drew as bare text in columns — no rule\n * between cells, nothing marking the first row — so every deck had to restate\n * the same properties to get something presentable. Theme tokens rather than\n * hex, so each palette answers for its own lines.\n *\n * No `margin`: cell insets are a capability the `office-open` renderer does not\n * have, and a theme default that every table inherits would turn a backend that\n * works into one that refuses every table on it. It stays opt-in per table,\n * where the refusal is the author's own choice to make.\n *\n * A document overrides any of this per table, or wholesale through\n * `componentDefaults.table`; `headerRow: false` turns the first-row treatment\n * off for a table that is not a table of anything.\n */\nconst DEFAULT_TABLE: PptxComponentDefaults['table'] = {\n border: { type: 'solid', pt: 1, color: 'background2' },\n headerRow: true,\n};\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 displayName: 'Office Default',\n description:\n 'The stock Office look: blue primary, orange and green accents, Arial throughout, centred titles',\n whenToUse:\n 'A deck that has to match a plain PowerPoint look; pick a designed theme for anything a client will see.',\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 componentDefaults: { table: DEFAULT_TABLE },\n};\n\nconst PPTX_THEMES: Record<string, PptxThemeConfig> = {\n default: DEFAULT_PPTX_THEME,\n consulting: CONSULTING_PPTX_THEME,\n vermilion: VERMILION_PPTX_THEME,\n devportal: DEVPORTAL_PPTX_THEME,\n dark: {\n name: 'dark',\n displayName: 'Dark',\n description:\n 'Light text on a near-black ground with a bright accent, for screens and projectors',\n whenToUse:\n 'Keynote-style talks and product launches shown on a projector or a screen, where light-on-dark reads best.',\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 componentDefaults: { table: DEFAULT_TABLE },\n },\n minimal: {\n name: 'minimal',\n displayName: 'Minimal',\n description:\n 'Ink on white, one accent, no decoration; the content carries the slide',\n whenToUse:\n 'Internal decks and working sessions where the material should speak and decoration would distract.',\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 componentDefaults: { table: DEFAULT_TABLE },\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","import {\n designCanvas,\n resolveTypeRoles,\n validateDesignColors,\n} from '@json-to-office/shared';\nimport type { PptxThemeConfig, GridConfig } from '../types';\nimport { resolveColor } from '../utils/color';\n\nexport function resolvePptxDesignSystem(\n theme: PptxThemeConfig,\n width = 10,\n height = 7.5\n): PptxThemeConfig {\n validateDesignColors(theme, theme.colors);\n if (!theme.typography) return theme;\n const canvas = designCanvas('pptx', { width, height });\n const roles = resolveTypeRoles(theme, canvas, theme.defaults.fontSize);\n const styles = { ...theme.styles };\n for (const [name, role] of Object.entries(roles)) {\n const key = name as keyof typeof styles;\n styles[key] = {\n fontFace:\n theme.fonts[role.face ?? 'body'] ??\n (role.face === 'light' ? theme.fonts.heading : theme.fonts.body),\n fontSize: role.size,\n ...(role.weight !== undefined && { fontWeight: role.weight }),\n ...(role.color !== undefined && {\n fontColor: resolveColor(role.color, theme),\n }),\n ...(role.case !== undefined && { case: role.case }),\n ...(role.lineHeight !== undefined && {\n lineSpacing: role.lineHeight * role.size,\n }),\n ...(role.tracking !== undefined && {\n charSpacing: (role.tracking * role.size) / 100,\n }),\n ...(role.spaceBefore !== undefined && {\n paraSpaceBefore: role.spaceBefore,\n }),\n ...(role.spaceAfter !== undefined && { paraSpaceAfter: role.spaceAfter }),\n ...styles[key],\n };\n }\n return { ...theme, styles };\n}\n\nexport function designGrid(\n theme: PptxThemeConfig,\n width: number,\n height: number\n): GridConfig | undefined {\n const space =\n theme.spacing?.canvas?.[designCanvas('pptx', { width, height })];\n if (!space) return undefined;\n return {\n ...(space.safeAreaIn !== undefined && { margin: space.safeAreaIn }),\n ...(space.gutterIn !== undefined && { gutter: space.gutterIn }),\n ...(space.columns !== undefined && { columns: space.columns }),\n ...(space.rows !== undefined && { rows: space.rows }),\n };\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 * Structure Processing\n * JSON -> internal model\n *\n * The document arrives with every block already expanded (see\n * `blocks/document.ts`); what remains here is theme resolution, component\n * defaults, hyperlink rebasing, and the two engine operations that turn\n * authored composition into the absolute boxes the compiler draws: layout\n * (frames, distribution, grids) and bounded text fit.\n */\n\nimport type {\n PptxComponentInput,\n PptxThemeConfig,\n PresentationComponentDefinition,\n ProcessedPresentation,\n ProcessedSlide,\n SlideComponentDefinition,\n} from '../types';\nimport { isSlideComponent } from '../types';\nimport { mergeGridConfigs } from './grid';\nimport { getPptxTheme } from '../themes';\nimport { resolvePptxDesignSystem, designGrid } from '../themes/design-system';\nimport type { GenerationOptions } from './generator';\nimport { resolveComponentTree } from '../utils/resolveComponentTree';\nimport { remapHyperlinkSlideRefs } from '../utils/hyperlink';\nimport {\n mergeWithDefaults,\n toAuthoredBlockPointer,\n} from '@json-to-office/shared';\nimport { resolveSlideLayout } from './layout';\nimport { applyTextFit } from './fit';\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 let { props } = document;\n const { 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 selectedTheme =\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 // Idempotent, and deliberately repeated: the generation prologue already\n // resolved the theme it hands over, while a direct caller reaches this with a\n // raw theme. Re-resolving projects the same roles onto styles that already\n // carry them, because a style key present in `styles` wins over the role.\n const baseTheme = resolvePptxDesignSystem(\n selectedTheme,\n props.slideWidth,\n props.slideHeight\n );\n const tokenGrid = designGrid(\n baseTheme,\n props.slideWidth ?? 10,\n props.slideHeight ?? 7.5\n );\n if (tokenGrid)\n props = { ...props, grid: mergeGridConfigs(tokenGrid, props.grid) };\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 const sourceMap = options?.sourceMap ?? {};\n const toAuthored = (path: string) => toAuthoredBlockPointer(sourceMap, path);\n\n const slides: ProcessedSlide[] = [];\n\n children.forEach((child, authoredIndex) => {\n if (!isSlideComponent(child)) return;\n // `enabled: false` drops the slide entirely; absent means enabled\n if (!isSlideEnabled(child)) return;\n\n // Resolve componentDefaults on all slide components, then rebase\n // slide-targeted hyperlinks onto the generated slide numbering\n const resolvedComponents = resolveComponentTree(\n child.children ?? [],\n theme\n ).map((component) => remapHyperlinkSlideRefs(component, slideIndexMap));\n\n // Layout, then fit: frames and rows become absolute boxes, and a text\n // that declared bounds is sized within them or refused at its authored\n // pointer.\n const laidOut = resolveSlideLayout(resolvedComponents, {\n grid: props.grid,\n slideWidth,\n slideHeight,\n warnings: options?.warnings,\n });\n const fitted = applyTextFit(laidOut, `/children/${authoredIndex}`, {\n theme,\n slideWidth,\n slideHeight,\n toAuthored,\n });\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 slides.push({\n components: fitted,\n background: slideProps.background,\n transition: slideProps.transition,\n notes: slideProps.notes,\n hidden: slideProps.hidden,\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 services: options?.services,\n };\n}\n","/**\n * One reading of an authored dimension: a number is inches, `\"NN%\"` is a\n * fraction of the axis it sits on. Layout and fit both need it, and both must\n * read the same number for the same prop.\n */\nexport function dimensionInches(\n value: unknown,\n axisIn: number\n): number | undefined {\n if (typeof value === 'number' && Number.isFinite(value)) return value;\n if (typeof value === 'string' && value.trim().endsWith('%')) {\n const pct = Number(value.trim().slice(0, -1));\n return Number.isFinite(pct) ? (pct / 100) * axisIn : undefined;\n }\n return undefined;\n}\n","/**\n * Slide layout resolution: frames, distribution and nested grids.\n *\n * After block expansion a slide holds content components, transparent\n * `group`s, and groups that carry a frame. This pass turns every one of them\n * into what the compiler has always drawn — components at absolute inches —\n * so that a block body written against a frame, a row of two-to-four metric\n * tiles, or a 1.1 : 1 two-column split needs no plugin and no per-block code.\n *\n * Rules, top to bottom:\n *\n * - At the slide level nothing changes for content: a `grid` placement is\n * resolved against the slide grid exactly as before, an authored\n * coordinate stays as authored, and a component with neither keeps its\n * compiler default (the style band for text). A frameless, directionless\n * group is a plain sequence: its children are slide-level children.\n * - A group with a frame (`x`/`y`/`w`/`h`, or `grid`) is a nested coordinate\n * system. Inside it a child's numbers are offsets from the frame origin,\n * percentages are fractions of the frame, and an omitted `x`/`y` or `w`/`h`\n * means \"the frame's\". Its `gridConfig` merges over the enclosing grid; a\n * nested grid spans the frame with no margin unless the config states one.\n * - A group with a `direction` distributes its enabled children into cells\n * along that axis — equal, or by `weights` — separated by `gap`. A child\n * fills its cell unless it states its own offsets. A child that collapsed\n * away (an optional slot) simply is not there, so the rest redistribute.\n *\n * Geometry is decided once, here. The quality facts, the fit pass and the\n * compiler all read the same absolute boxes.\n */\n\nimport type { GridConfig, PipelineWarning, PptxComponentInput } from '../types';\nimport { dimensionInches } from './dimensions';\nimport {\n mergeGridConfigs,\n resolveComponentGridPosition,\n resolveGridPosition,\n} from './grid';\n\nexport interface SlideLayoutOptions {\n grid?: GridConfig;\n slideWidth: number;\n slideHeight: number;\n warnings?: PipelineWarning[];\n}\n\ninterface Extent {\n x: number;\n y: number;\n w: number;\n h: number;\n}\n\ntype Props = Record<string, unknown>;\n\nfunction hasFrame(props: Props): boolean {\n return ['x', 'y', 'w', 'h', 'grid'].some((key) => props[key] !== undefined);\n}\n\n/** Resolve every slide child to absolute inches; groups keep only their children. */\nexport function resolveSlideLayout(\n components: PptxComponentInput[],\n options: SlideLayoutOptions\n): PptxComponentInput[] {\n return components.map((component) => placeAtRoot(component, options));\n}\n\nfunction placeAtRoot(\n component: PptxComponentInput,\n options: SlideLayoutOptions\n): PptxComponentInput {\n if (component.name !== 'group') {\n return resolveComponentGridPosition(\n component,\n options.grid,\n options.slideWidth,\n options.slideHeight,\n options.warnings\n );\n }\n const props = (component.props ?? {}) as Props;\n const config = mergeGridConfigs(\n options.grid,\n props.gridConfig as GridConfig | undefined\n );\n const slide: Extent = {\n x: 0,\n y: 0,\n w: options.slideWidth,\n h: options.slideHeight,\n };\n if (!hasFrame(props) && props.direction === undefined) {\n // A plain sequence: its children are slide-level children.\n return {\n ...component,\n props: {},\n children: (component.children ?? []).map((child) =>\n placeAtRoot(child, { ...options, grid: config })\n ),\n };\n }\n const frame = boxWithin(props, slide, config, options);\n return {\n ...component,\n props: {},\n children: layoutChildren(component, frame, nestedConfig(config, props)),\n };\n}\n\n/**\n * A nested grid spans its frame. The enclosing grid's margin is the slide's\n * safe area, which has no meaning an inch inside a tile, so it is dropped\n * unless the group's own `gridConfig` states one.\n */\nfunction nestedConfig(\n config: GridConfig | undefined,\n props: Props\n): GridConfig {\n const own = props.gridConfig as GridConfig | undefined;\n return {\n ...(config ?? {}),\n margin: own?.margin ?? 0,\n };\n}\n\n/** A component's absolute box inside `extent`, from grid, coordinates or both. */\nfunction boxWithin(\n props: Props,\n extent: Extent,\n config: GridConfig | undefined,\n options: SlideLayoutOptions\n): Extent {\n const grid = props.grid as\n | { column: number; row: number; columnSpan?: number; rowSpan?: number }\n | undefined;\n const base = grid\n ? resolveGridPosition(grid, config, extent.w, extent.h, options.warnings)\n : { x: 0, y: 0, w: extent.w, h: extent.h };\n return {\n x: extent.x + (dimensionInches(props.x, extent.w) ?? base.x),\n y: extent.y + (dimensionInches(props.y, extent.h) ?? base.y),\n w: dimensionInches(props.w, extent.w) ?? base.w,\n h: dimensionInches(props.h, extent.h) ?? base.h,\n };\n}\n\nfunction layoutChildren(\n group: PptxComponentInput,\n frame: Extent,\n config: GridConfig\n): PptxComponentInput[] {\n const children = group.children ?? [];\n const props = (group.props ?? {}) as Props;\n const direction = props.direction as 'row' | 'column' | undefined;\n if (!direction) {\n return children.map((child) => placeInside(child, frame, config));\n }\n const gap = typeof props.gap === 'number' ? props.gap : 0;\n const weights = Array.isArray(props.weights) ? props.weights : [];\n const active = children.filter((child) => child.enabled !== false);\n const total = active.reduce(\n (sum, _child, index) => sum + weightAt(weights, index),\n 0\n );\n const along = direction === 'row' ? frame.w : frame.h;\n const usable = Math.max(0, along - gap * Math.max(0, active.length - 1));\n let cursor = direction === 'row' ? frame.x : frame.y;\n let activeIndex = 0;\n return children.map((child) => {\n if (child.enabled === false) return child;\n const size =\n total > 0 ? (usable * weightAt(weights, activeIndex)) / total : 0;\n const cell: Extent =\n direction === 'row'\n ? { x: cursor, y: frame.y, w: size, h: frame.h }\n : { x: frame.x, y: cursor, w: frame.w, h: size };\n cursor += size + gap;\n activeIndex += 1;\n return placeInside(child, cell, config);\n });\n}\n\nfunction weightAt(weights: unknown[], index: number): number {\n const value = weights[index];\n return typeof value === 'number' && value > 0 ? value : 1;\n}\n\nfunction placeInside(\n component: PptxComponentInput,\n extent: Extent,\n config: GridConfig\n): PptxComponentInput {\n const props = (component.props ?? {}) as Props;\n const box = boxWithin(props, extent, config, {\n slideWidth: extent.w,\n slideHeight: extent.h,\n });\n if (component.name === 'group') {\n return {\n ...component,\n props: {},\n children: layoutChildren(component, box, nestedConfig(config, props)),\n };\n }\n const { grid: _grid, ...rest } = props; // eslint-disable-line @typescript-eslint/no-unused-vars\n return {\n ...component,\n props: { ...rest, x: box.x, y: box.y, w: box.w, h: box.h },\n };\n}\n","/**\n * Bounded text fit.\n *\n * A text component may declare `fit: { maxLines, shrink }`. The engine\n * estimates the lines the text takes at its effective size with the shared\n * width model; when it exceeds `maxLines` — or the box height when no line\n * count is declared — it steps down through the declared readable sizes, in\n * order, and takes the first that fits. Nothing else is tried: no size the\n * author did not declare, no reflow into another box. When nothing fits the\n * text is rejected with `text_fit_overflow` at the pointer the author can\n * patch — the slot for block content, the component otherwise.\n *\n * Runs after layout, so widths are absolute, and before quality analysis and\n * compilation, so both see the size that was actually chosen.\n */\n\nimport { BlockEvaluationError } from '@json-to-office/shared';\nimport type { PptxComponentInput, PptxThemeConfig, StyleName } from '../types';\nimport {\n defaultLineHeightPt,\n estimateTextHeightPt,\n} from '../utils/textMetrics';\nimport { dimensionInches } from './dimensions';\n\nexport interface TextFitOptions {\n theme: PptxThemeConfig;\n slideWidth: number;\n slideHeight: number;\n /** Compiled pointer → the pointer diagnostics should name. */\n toAuthored?: (path: string) => string;\n}\n\ntype Props = Record<string, unknown>;\n\ninterface Fit {\n maxLines?: number;\n shrink?: number[];\n}\n\nfunction textOf(props: Props): string | undefined {\n if (typeof props.text === 'string') return props.text;\n if (Array.isArray(props.runs))\n return props.runs\n .map((run) => {\n const record = run as Props;\n return `${typeof record.text === 'string' ? record.text : ''}${\n record.breakLine ? '\\n' : ''\n }`;\n })\n .join('');\n return undefined;\n}\n\nexport function applyTextFit(\n components: PptxComponentInput[],\n basePath: string,\n options: TextFitOptions\n): PptxComponentInput[] {\n return components.map((component, index) =>\n fitOne(component, `${basePath}/children/${index}`, options)\n );\n}\n\nfunction fitOne(\n component: PptxComponentInput,\n path: string,\n options: TextFitOptions\n): PptxComponentInput {\n if (component.enabled === false) return component;\n if (component.children && component.children.length > 0) {\n return {\n ...component,\n children: applyTextFit(component.children, path, options),\n };\n }\n if (component.name !== 'text') return component;\n const props = (component.props ?? {}) as Props;\n const fit = props.fit as Fit | undefined;\n if (!fit) return component;\n const text = textOf(props);\n if (text === undefined) return component;\n\n const style =\n typeof props.style === 'string'\n ? options.theme.styles?.[props.style as StyleName]\n : undefined;\n const authoredSize =\n typeof props.fontSize === 'number'\n ? props.fontSize\n : style?.fontSize ?? options.theme.defaults.fontSize;\n const x = dimensionInches(props.x, options.slideWidth) ?? 0;\n const widthIn =\n dimensionInches(props.w, options.slideWidth) ??\n Math.max(0.1, options.slideWidth - x);\n const heightIn = dimensionInches(props.h, options.slideHeight);\n const explicitSpacing =\n typeof props.lineSpacing === 'number'\n ? props.lineSpacing\n : style?.lineSpacing;\n const multiple =\n typeof props.lineSpacingMultiple === 'number'\n ? props.lineSpacingMultiple\n : undefined;\n const before =\n typeof props.paraSpaceBefore === 'number' ? props.paraSpaceBefore : 0;\n const after =\n typeof props.paraSpaceAfter === 'number'\n ? props.paraSpaceAfter\n : style?.paraSpaceAfter ?? 0;\n\n const measure = (size: number) =>\n estimateTextHeightPt(\n text,\n widthIn * 72,\n size,\n multiple !== undefined\n ? size * multiple\n : explicitSpacing ?? defaultLineHeightPt(size),\n before,\n after\n );\n const fits = (size: number): boolean => {\n const estimate = measure(size);\n if (fit.maxLines !== undefined && estimate.lines > fit.maxLines)\n return false;\n if (heightIn !== undefined && estimate.heightPt > heightIn * 72)\n return false;\n return true;\n };\n\n if (fits(authoredSize)) return component;\n for (const size of fit.shrink ?? []) {\n if (fits(size)) {\n return { ...component, props: { ...props, fontSize: size } };\n }\n }\n const estimate = measure(authoredSize);\n const bound =\n fit.maxLines !== undefined\n ? `${fit.maxLines} line${fit.maxLines === 1 ? '' : 's'}`\n : `a ${Math.round((heightIn ?? 0) * 72)}pt box`;\n const tried =\n fit.shrink && fit.shrink.length > 0\n ? ` and at ${fit.shrink.join(', ')}pt`\n : '';\n throw new BlockEvaluationError([\n {\n path: (options.toAuthored ?? ((pointer) => pointer))(\n `${path}/props/text`\n ),\n code: 'text_fit_overflow',\n message:\n `Text runs to ${estimate.lines} line${estimate.lines === 1 ? '' : 's'} at ${authoredSize}pt` +\n ` in a ${Math.round(widthIn * 72)}pt-wide box; it must fit ${bound}${tried}.` +\n ' Shorten the text, or declare wider bounds in the definition.',\n },\n ]);\n}\n","/**\n * The width model: how many lines a run of text takes in a box.\n *\n * One estimator, shared by the quality rules (`pptx/text-fit`,\n * `pptx/action-title`) and the engine's bounded `fit` operation, so a title\n * the rules call two lines is the title the engine sizes for two lines.\n * Character-count based, and calibrated against rendered ground truth — see\n * the note on `DEFAULT_CHAR_WIDTH_FACTOR` in `quality/rules.ts`. Real text\n * metrics (#211) replace it in one place when they land.\n */\n\n/** Average glyph advance as a fraction of the font size. */\nexport const DEFAULT_CHAR_WIDTH_FACTOR = 0.46;\n\nexport function defaultLineHeightPt(fontSize: number): number {\n if (fontSize >= 60) return fontSize * 1.05;\n if (fontSize >= 28) return fontSize * 1.15;\n return fontSize * 1.25;\n}\n\n/** Lines the text wraps to in `boxWidthPt` at `fontSizePt`; never below 1. */\nexport function estimateTextLines(\n text: string,\n boxWidthPt: number,\n fontSizePt: number,\n charWidthFactor = DEFAULT_CHAR_WIDTH_FACTOR\n): number {\n const charsPerLine = Math.max(\n 1,\n Math.floor(boxWidthPt / (fontSizePt * charWidthFactor))\n );\n let lines = 0;\n for (const paragraph of text.split('\\n')) {\n const measured = paragraph.trimEnd();\n lines +=\n measured === ''\n ? 1\n : Math.max(1, Math.ceil(measured.length / charsPerLine));\n }\n return lines;\n}\n\nexport interface TextHeightEstimate {\n heightPt: number;\n lines: number;\n}\n\nexport function estimateTextHeightPt(\n text: string,\n boxWidthPt: number,\n fontSizePt: number,\n lineSpacingPt: number,\n paraSpaceBeforePt = 0,\n paraSpaceAfterPt = 0,\n charWidthFactor = DEFAULT_CHAR_WIDTH_FACTOR\n): TextHeightEstimate {\n const lines = estimateTextLines(\n text,\n boxWidthPt,\n fontSizePt,\n charWidthFactor\n );\n const paragraphs = text.split('\\n').length;\n let heightPt = fontSizePt + Math.max(0, lines - 1) * lineSpacingPt;\n if (paragraphs > 1) {\n heightPt += (paragraphs - 1) * (paraSpaceBeforePt + paraSpaceAfterPt);\n }\n return { heightPt, lines };\n}\n","/**\n * Document-local JSON blocks on slides.\n *\n * The PPTX adapter of the shared block contract. A definition in\n * `props.blocks` expands, at its invocation, into a transparent `group` of\n * ordinary slide content — text, shapes, images, charts, tables, nested\n * groups — with a source map from every compiled pointer back to the authored\n * invocation or slot. Geometry is the definition's: component slots take\n * their frame from the `props` merged beneath them, and a group's frame,\n * direction and grid do the distributing. Nothing here knows any block by\n * name.\n *\n * Slide effects are the one thing a block can say about its slide. A\n * definition's `slide.background` and `slide.notes` fill in what the slide\n * did not state; `slide.grid` becomes the expanded group's `gridConfig`, so\n * the body's grid placements resolve against the block's own grid. A slide\n * that states its own background keeps it.\n */\n\nimport {\n BlockEvaluationError,\n JsonBlockEvaluator,\n blockValueAt,\n composeBlocksWithPlugins,\n isBlockRecord,\n readBlockDefinitions,\n toAuthoredBlockPointer,\n type BlockEvaluatorOptions,\n type BlockSlideEffect,\n} from '@json-to-office/shared';\nimport { validatePresentationDocument } from '@json-to-office/shared-pptx';\nimport type { PptxThemeConfig } from '../types';\n\nexport { blockSlotBudgets, blockSlotRoles } from '@json-to-office/shared';\nexport type {\n BlockSlotBudget,\n BlockSlotRoleValue,\n BlockSourceMap,\n ExpandedBlocks,\n} from '@json-to-office/shared';\nimport type { ExpandedBlocks } from '@json-to-office/shared';\n\ntype Rec = Record<string, unknown>;\nexport const toAuthoredPointer = toAuthoredBlockPointer;\n\n/** Deck metadata and the slide's canvas. No slide design is registered here. */\nexport function pptxBlockContext(document: unknown, path = ''): Rec {\n const props =\n isBlockRecord(document) && isBlockRecord(document.props)\n ? document.props\n : {};\n const index = /^\\/children\\/(\\d+)/.exec(path)?.[1];\n const metadata: Rec = {};\n for (const key of ['title', 'author', 'subject', 'company']) {\n if (props[key] !== undefined) metadata[key] = props[key];\n }\n return {\n document: metadata,\n slide: {\n width: typeof props.slideWidth === 'number' ? props.slideWidth : 10,\n height: typeof props.slideHeight === 'number' ? props.slideHeight : 7.5,\n ...(index !== undefined && { index: Number(index) + 1 }),\n },\n };\n}\n\nexport function createPptxBlockEvaluator(\n document: unknown,\n theme: PptxThemeConfig,\n extra: Partial<BlockEvaluatorOptions> = {}\n): JsonBlockEvaluator {\n return new JsonBlockEvaluator(readBlockDefinitions(document), {\n format: 'pptx',\n theme,\n contextAt: (path) => pptxBlockContext(document, path),\n contextSources: { '/document': '/props' },\n // Slide width/height, in inches by default for a format authored in them.\n measure: (axis, unit, context) =>\n Number(blockValueAt(context, `/slide/${axis}`)) *\n (unit === 'in' ? 1 : unit === 'pt' ? 72 : 1440),\n ...extra,\n });\n}\n\nexport function expandPptxBlocks<T>(\n document: T,\n theme: PptxThemeConfig\n): ExpandedBlocks<T> {\n const effects: BlockSlideEffect[] = [];\n const evaluator = createPptxBlockEvaluator(document, theme, {\n onSlide: (effect) => effects.push(effect),\n });\n const expanded = evaluator.expand(document) as T;\n return finishPptxBlocks(expanded, evaluator, effects);\n}\n\nfunction slideIndexOf(path: string): number | undefined {\n const match = /^\\/children\\/(\\d+)\\/children\\/\\d+/.exec(path);\n return match ? Number(match[1]) : undefined;\n}\n\nfunction validateEffects(document: unknown, effects: BlockSlideEffect[]): void {\n for (const effect of effects) {\n const parts = effect.path.split('/').slice(1);\n const slide = blockValueAt(document, '/' + parts.slice(0, 2).join('/'));\n let valid =\n parts.length >= 4 &&\n parts[0] === 'children' &&\n parts[2] === 'children' &&\n isBlockRecord(slide) &&\n slide.name === 'slide';\n for (let i = 4; i < parts.length; i += 2) {\n const parent = blockValueAt(document, '/' + parts.slice(0, i).join('/'));\n valid &&=\n parts[i] === 'children' &&\n isBlockRecord(parent) &&\n parent.name === 'group';\n }\n if (!valid)\n throw new BlockEvaluationError([\n {\n path: effect.environment.source,\n code: 'invalid_placement',\n message:\n 'Slide effects require a block invoked directly on a slide, optionally nested in transparent groups.',\n },\n ]);\n }\n}\n\n/**\n * Background and notes fill in what the slide did not state; among blocks the\n * last declaration on a slide wins, as a section's last tracker does in DOCX.\n * The grid becomes the expanded group's `gridConfig`, scoped to the body.\n */\nfunction applySlideEffects(\n expanded: unknown,\n evaluator: JsonBlockEvaluator,\n effects: BlockSlideEffect[]\n): void {\n if (!isBlockRecord(expanded) || !Array.isArray(expanded.children)) return;\n const supplied = new Set<string>();\n for (const effect of effects) {\n const index = slideIndexOf(effect.path);\n const slide = index === undefined ? undefined : expanded.children[index];\n if (!isBlockRecord(slide) || slide.name !== 'slide') continue;\n const slidePath = `/children/${index}`;\n const props: Rec = isBlockRecord(slide.props) ? { ...slide.props } : {};\n for (const key of ['background', 'notes'] as const) {\n const declared = effect.settings[key];\n if (declared === undefined) continue;\n const claim = `${slidePath}/${key}`;\n if (props[key] !== undefined && !supplied.has(claim)) continue;\n const value = evaluator.evaluate(\n declared,\n effect.environment,\n `${slidePath}/props/${key}`,\n `${effect.environment.definition}/slide/${key}`\n );\n if (value === undefined) continue;\n props[key] = value;\n supplied.add(claim);\n }\n slide.props = props;\n if (effect.settings.grid !== undefined) {\n const group = blockValueAt(expanded, effect.path);\n if (isBlockRecord(group) && group.name === 'group') {\n const grid = evaluator.evaluate(\n effect.settings.grid,\n effect.environment,\n `${effect.path}/props/gridConfig`,\n `${effect.environment.definition}/slide/grid`\n );\n if (grid !== undefined)\n group.props = {\n ...(isBlockRecord(group.props) ? group.props : {}),\n gridConfig: grid,\n };\n }\n }\n }\n}\n\nfunction finishPptxBlocks<T>(\n expanded: T,\n evaluator: JsonBlockEvaluator,\n effects: BlockSlideEffect[]\n): ExpandedBlocks<T> {\n applySlideEffects(expanded, evaluator, effects);\n validateEffects(expanded, effects);\n if (evaluator.blocks.length) {\n const result = validatePresentationDocument(expanded);\n if (!result.valid)\n throw new BlockEvaluationError(\n result.errors.map((issue) => ({\n path: toAuthoredPointer(evaluator.sourceMap, issue.path),\n code: issue.code ?? 'block_invalid_output',\n message: issue.message,\n }))\n );\n }\n return {\n document: expanded,\n sourceMap: evaluator.sourceMap,\n blocks: evaluator.blocks,\n };\n}\n\n/**\n * Registered code and document-local JSON share one bounded expansion: a\n * plugin can emit a block, a block body or component slot can name a plugin,\n * and either can nest. The host supplies the registered code; JSON never\n * loads any. The caller validates the finished tree under its own validation\n * options; block output is validated here regardless, because a definition\n * that emits invalid primitives is a definition error.\n */\nexport async function expandPptxBlocksWithPlugins<T>(\n document: T,\n theme: PptxThemeConfig,\n plugins: ReadonlySet<string>,\n render: (component: Rec, path: string) => Promise<unknown[]>,\n preserve: ReadonlySet<string> = new Set()\n): Promise<ExpandedBlocks<T> & { preserved: T }> {\n const effects: BlockSlideEffect[] = [];\n const evaluator = createPptxBlockEvaluator(document, theme, {\n reservedNames: [...plugins],\n onSlide: (effect) => effects.push(effect),\n });\n const composed = await composeBlocksWithPlugins(evaluator, document, {\n plugins,\n render,\n preserve,\n });\n const finished = finishPptxBlocks(composed.standard as T, evaluator, effects);\n return { ...finished, preserved: composed.preserved as T };\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 {\n isPptxRendererId,\n pptxRendererIds,\n pptxRendererStatuses,\n} 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 {\n CONSULTING_PPTX_THEME,\n DEVPORTAL_PPTX_THEME,\n VERMILION_PPTX_THEME,\n DEFAULT_PPTX_THEME,\n getPptxTheme,\n hasPptxTheme,\n pptxThemes,\n} from './themes';\n\n// Blueprints: deck archetypes as data (#342)\nexport {\n PPTX_BLUEPRINTS,\n pptxBlueprint,\n instantiatePptxBlueprint,\n} from './blueprints';\nexport type {\n BlueprintFillEntry,\n InstantiateBlueprintOptions,\n InstantiatedBlueprint,\n} from './blueprints';\n\n// Design-quality analysis (#216)\nexport { analyzePptxQuality } from './quality/preflight';\nexport type {\n PptxQualityAnalysisOptions,\n PptxQualityOptions,\n} from './quality/preflight';\nexport {\n preparePptxQualityDocument,\n type PptxBlocksMetadata,\n type PptxBlockSlotFact,\n type PptxCanvasFact,\n type PptxChromeSlotFact,\n type PptxQualityFact,\n type PptxQualityModel,\n type PptxSlideFact,\n type PptxTextFact,\n type PreparePptxQualityOptions,\n} from './quality/facts';\nexport {\n PPTX_DEFAULT_QUALITY_PROFILE,\n PPTX_QUALITY_PROFILES,\n PPTX_QUALITY_RULES,\n pptxQualityEngine,\n declaredPptxQualityProfile,\n resolvePptxQualityProfile,\n} from './quality/rules';\n\n// Document-local JSON block composition.\nexport {\n expandPptxBlocks,\n toAuthoredPointer,\n blockSlotBudgets,\n blockSlotRoles,\n} from './blocks';\nexport type { BlockSourceMap, ExpandedBlocks } from './blocks';\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 * PPTX blueprints: deck archetypes as data, and the one operation that turns\n * one into a deck.\n *\n * The registry is the JSON files under `templates/blueprints`: the bundled\n * ones are imported so a stale or missing `dist` cannot lose them, and the\n * directory is scanned for any other `*.pptx.blueprint.json` beside it, so\n * adding a blueprint is a file. What instantiating means is shared with the\n * DOCX core; this module only says what a deck's root looks like: the\n * metadata a deck carries (`title`, `author`, `company`) sits directly under\n * `props`, beside the canvas the blueprint's blocks were drawn for.\n */\nimport { existsSync, readdirSync, readFileSync } from 'node:fs';\nimport { fileURLToPath } from 'node:url';\nimport { dirname, join } from 'node:path';\nimport {\n instantiateBlueprint,\n registerBlueprints,\n type Blueprint,\n type BlueprintFillEntry,\n type InstantiateBlueprintOptions,\n type InstantiatedBlueprint,\n} from '@json-to-office/shared';\nimport { collectPlaceholders } from '@json-to-office/quality';\nimport consultingDeck from '../templates/blueprints/consulting-deck.pptx.blueprint.json';\n\n/**\n * Blueprint files beside this module — `src/templates/blueprints` from source,\n * `dist/templates/blueprints` from the built package — that the static import\n * above does not already carry.\n */\nfunction scanned(known: Readonly<Record<string, unknown>>): unknown[] {\n let here: string;\n try {\n here = dirname(fileURLToPath(import.meta.url));\n } catch {\n return [];\n }\n const directory = [\n join(here, '../templates/blueprints'),\n join(here, 'templates/blueprints'),\n ].find((path) => existsSync(path));\n if (!directory) return [];\n return readdirSync(directory)\n .filter((file) => file.endsWith('.pptx.blueprint.json'))\n .map((file) => JSON.parse(readFileSync(join(directory, file), 'utf8')))\n .filter((candidate) => {\n const id = (candidate as { id?: unknown } | null)?.id;\n return !(typeof id === 'string' && id in known);\n });\n}\n\nconst bundled = registerBlueprints('pptx', [consultingDeck]);\n\n/** Every bundled PPTX blueprint, by id. */\nexport const PPTX_BLUEPRINTS: Readonly<Record<string, Blueprint>> = {\n ...bundled,\n ...registerBlueprints('pptx', scanned(bundled)),\n};\n\nexport function pptxBlueprint(id: string): Blueprint | undefined {\n return PPTX_BLUEPRINTS[id];\n}\n\nexport type {\n BlueprintFillEntry,\n InstantiateBlueprintOptions,\n InstantiatedBlueprint,\n};\n\n/** The wide canvas every bundled deck block is drawn for; any canvas lays out. */\nconst CANVAS = { slideWidth: 13.333, slideHeight: 7.5 } as const;\n\nexport function instantiatePptxBlueprint(\n blueprint: Blueprint,\n options: InstantiateBlueprintOptions\n): InstantiatedBlueprint {\n return instantiateBlueprint(blueprint, options, {\n format: 'pptx',\n props: CANVAS,\n metadataPointer: '/props',\n markers: (document) =>\n collectPlaceholders(document).filter(\n (occurrence) => occurrence.match.kind === 'scaffold-marker'\n ),\n });\n}\n","{\n \"id\": \"consulting-deck\",\n \"format\": \"pptx\",\n \"title\": \"Consulting deck\",\n \"description\": \"A decision deck for a client readout: a cover, the quarter in numbers, one action-chart per finding with its takeaway and source, a two-column slide for the evidence that is a table or a list, a closing statement; every slide invokes one of the five consulting blocks on the house theme.\",\n \"whenToUse\": \"A client readout, a board update or a steering-committee deck: one message per slide, a chart or table that carries it, a source under it. Not for a talk track or a training deck.\",\n \"theme\": \"consulting\",\n \"profile\": \"consulting-deck\",\n \"definitions\": \"consulting-deck-blocks.pptx.json\",\n \"numbering\": \"none\",\n \"toc\": false,\n \"variants\": {\n \"data-heavy\": {\n \"description\": \"Evidence-led: cover, a KPI row, three action-charts, a two-column table slide, a closing statement.\",\n \"whenToUse\": \"The brief comes with numbers the audience will check: performance, finance, operations.\",\n \"pages\": {\n \"min\": 6,\n \"max\": 9\n },\n \"metadata\": {\n \"title\": \"{{Title: as on the cover}}\",\n \"author\": \"{{Author or team}}\",\n \"company\": \"{{Client name}}\"\n },\n \"children\": [\n {\n \"name\": \"slide\",\n \"children\": [\n {\n \"name\": \"block\",\n \"props\": {\n \"ref\": \"cover\",\n \"slots\": {\n \"title\": \"{{Title: the deck's conclusion in one sentence}}\",\n \"subtitle\": \"{{Subtitle: what the deck answers, for whom}}\",\n \"client\": \"{{Client name}}\",\n \"date\": \"{{Month YYYY}}\",\n \"confidentiality\": \"{{Confidentiality: Confidential, or For internal use}}\"\n }\n }\n }\n ]\n },\n {\n \"name\": \"slide\",\n \"children\": [\n {\n \"name\": \"block\",\n \"props\": {\n \"ref\": \"kpi-row\",\n \"slots\": {\n \"title\": \"{{Action title: the claim this slide proves, with its number, two lines at most}}\",\n \"tracker\": \"{{Tracker: the section, one or two words}}\",\n \"items\": [\n {\n \"value\": \"{{0.0}}\",\n \"unit\": \"{{unit}}\",\n \"label\": \"{{What it measures}}\",\n \"delta\": \"{{+0.0}}\"\n },\n {\n \"value\": \"{{0.0}}\",\n \"unit\": \"{{unit}}\",\n \"label\": \"{{What it measures}}\",\n \"delta\": \"{{+0.0}}\"\n },\n {\n \"value\": \"{{0.0}}\",\n \"unit\": \"{{unit}}\",\n \"label\": \"{{What it measures}}\",\n \"delta\": \"{{+0.0}}\"\n }\n ],\n \"source\": \"{{Source: system or document, date}}\"\n }\n }\n }\n ]\n },\n {\n \"name\": \"slide\",\n \"children\": [\n {\n \"name\": \"block\",\n \"props\": {\n \"ref\": \"action-chart\",\n \"slots\": {\n \"title\": \"{{Action title: the claim this slide proves, with its number, two lines at most}}\",\n \"tracker\": \"{{Tracker: the section, one or two words}}\",\n \"chart\": {\n \"name\": \"chart\",\n \"props\": {\n \"type\": \"bar\",\n \"valAxisTitle\": \"{{Measure (unit)}}\",\n \"data\": [\n {\n \"name\": \"{{Series name}}\",\n \"labels\": [\n \"{{Period 1}}\",\n \"{{Period 2}}\",\n \"{{Period 3}}\"\n ],\n \"values\": [0, 0, 0]\n }\n ],\n \"chartColors\": [\n \"accent\",\n \"secondary\",\n \"accent4\",\n \"accent6\",\n \"accent5\"\n ]\n }\n },\n \"takeaway\": \"{{Takeaway: what the reader should conclude, one or two sentences}}\",\n \"source\": \"{{Source: system or document, date}}\"\n }\n }\n }\n ]\n },\n {\n \"name\": \"slide\",\n \"children\": [\n {\n \"name\": \"block\",\n \"props\": {\n \"ref\": \"action-chart\",\n \"slots\": {\n \"title\": \"{{Action title: the claim this slide proves, with its number, two lines at most}}\",\n \"tracker\": \"{{Tracker: the section, one or two words}}\",\n \"chart\": {\n \"name\": \"chart\",\n \"props\": {\n \"type\": \"bar\",\n \"valAxisTitle\": \"{{Measure (unit)}}\",\n \"data\": [\n {\n \"name\": \"{{Series name}}\",\n \"labels\": [\n \"{{Period 1}}\",\n \"{{Period 2}}\",\n \"{{Period 3}}\"\n ],\n \"values\": [0, 0, 0]\n }\n ],\n \"chartColors\": [\n \"accent\",\n \"secondary\",\n \"accent4\",\n \"accent6\",\n \"accent5\"\n ]\n }\n },\n \"takeaway\": \"{{Takeaway: what the reader should conclude, one or two sentences}}\",\n \"source\": \"{{Source: system or document, date}}\"\n }\n }\n }\n ]\n },\n {\n \"name\": \"slide\",\n \"children\": [\n {\n \"name\": \"block\",\n \"props\": {\n \"ref\": \"action-chart\",\n \"slots\": {\n \"title\": \"{{Action title: the claim this slide proves, with its number, two lines at most}}\",\n \"tracker\": \"{{Tracker: the section, one or two words}}\",\n \"chart\": {\n \"name\": \"chart\",\n \"props\": {\n \"type\": \"bar\",\n \"valAxisTitle\": \"{{Measure (unit)}}\",\n \"data\": [\n {\n \"name\": \"{{Series name}}\",\n \"labels\": [\n \"{{Period 1}}\",\n \"{{Period 2}}\",\n \"{{Period 3}}\"\n ],\n \"values\": [0, 0, 0]\n }\n ],\n \"chartColors\": [\n \"accent\",\n \"secondary\",\n \"accent4\",\n \"accent6\",\n \"accent5\"\n ]\n }\n },\n \"takeaway\": \"{{Takeaway: what the reader should conclude, one or two sentences}}\",\n \"source\": \"{{Source: system or document, date}}\"\n }\n }\n }\n ]\n },\n {\n \"name\": \"slide\",\n \"children\": [\n {\n \"name\": \"block\",\n \"props\": {\n \"ref\": \"two-column\",\n \"slots\": {\n \"title\": \"{{Action title: the claim this slide proves, with its number, two lines at most}}\",\n \"tracker\": \"{{Tracker: the section, one or two words}}\",\n \"bullets\": [\n \"{{Bullet 1: one claim, ten words}}\",\n \"{{Bullet 2: one claim, ten words}}\",\n \"{{Bullet 3: one claim, ten words}}\"\n ],\n \"content\": {\n \"name\": \"table\",\n \"props\": {\n \"rows\": [\n [\n \"{{Row label}}\",\n {\n \"text\": \"{{Column (unit)}}\",\n \"align\": \"right\"\n },\n {\n \"text\": \"{{Column (unit)}}\",\n \"align\": \"right\"\n }\n ],\n [\n \"{{Row 1}}\",\n {\n \"text\": \"{{0.0}}\",\n \"align\": \"right\"\n },\n {\n \"text\": \"{{0.0}}\",\n \"align\": \"right\"\n }\n ],\n [\n \"{{Row 2}}\",\n {\n \"text\": \"{{0.0}}\",\n \"align\": \"right\"\n },\n {\n \"text\": \"{{0.0}}\",\n \"align\": \"right\"\n }\n ],\n [\n \"{{Row 3}}\",\n {\n \"text\": \"{{0.0}}\",\n \"align\": \"right\"\n },\n {\n \"text\": \"{{0.0}}\",\n \"align\": \"right\"\n }\n ]\n ]\n }\n },\n \"source\": \"{{Source: system or document, date}}\"\n }\n }\n }\n ]\n },\n {\n \"name\": \"slide\",\n \"children\": [\n {\n \"name\": \"block\",\n \"props\": {\n \"ref\": \"statement\",\n \"slots\": {\n \"tracker\": \"{{Tracker: the section, one or two words}}\",\n \"assertion\": \"{{Assertion: what to do next, in one sentence}}\",\n \"support\": \"{{Support: what backs the assertion, under thirty words}}\"\n }\n }\n }\n ]\n }\n ]\n },\n \"narrative\": {\n \"description\": \"Argument-led: cover, the position as a statement, two two-column slides that argue it beside a chart, one action-chart, a two-column table, a closing statement.\",\n \"whenToUse\": \"The brief is a position or a recommendation with few numbers; the audience follows an argument.\",\n \"pages\": {\n \"min\": 6,\n \"max\": 8\n },\n \"metadata\": {\n \"title\": \"{{Title: as on the cover}}\",\n \"author\": \"{{Author or team}}\",\n \"company\": \"{{Client name}}\"\n },\n \"children\": [\n {\n \"name\": \"slide\",\n \"children\": [\n {\n \"name\": \"block\",\n \"props\": {\n \"ref\": \"cover\",\n \"slots\": {\n \"title\": \"{{Title: the deck's conclusion in one sentence}}\",\n \"subtitle\": \"{{Subtitle: what the deck answers, for whom}}\",\n \"client\": \"{{Client name}}\",\n \"date\": \"{{Month YYYY}}\",\n \"confidentiality\": \"{{Confidentiality: Confidential, or For internal use}}\"\n }\n }\n }\n ]\n },\n {\n \"name\": \"slide\",\n \"children\": [\n {\n \"name\": \"block\",\n \"props\": {\n \"ref\": \"statement\",\n \"slots\": {\n \"tracker\": \"{{Tracker: the section, one or two words}}\",\n \"assertion\": \"{{Assertion: the position, in one sentence}}\",\n \"support\": \"{{Support: what backs the assertion, under thirty words}}\"\n }\n }\n }\n ]\n },\n {\n \"name\": \"slide\",\n \"children\": [\n {\n \"name\": \"block\",\n \"props\": {\n \"ref\": \"two-column\",\n \"slots\": {\n \"title\": \"{{Action title: the claim this slide proves, with its number, two lines at most}}\",\n \"tracker\": \"{{Tracker: the section, one or two words}}\",\n \"text\": \"{{Body: the argument this slide makes, under fifty words}}\",\n \"content\": {\n \"name\": \"chart\",\n \"props\": {\n \"type\": \"bar\",\n \"valAxisTitle\": \"{{Measure (unit)}}\",\n \"data\": [\n {\n \"name\": \"{{Series name}}\",\n \"labels\": [\n \"{{Period 1}}\",\n \"{{Period 2}}\",\n \"{{Period 3}}\"\n ],\n \"values\": [0, 0, 0]\n }\n ],\n \"chartColors\": [\n \"accent\",\n \"secondary\",\n \"accent4\",\n \"accent6\",\n \"accent5\"\n ]\n }\n },\n \"source\": \"{{Source: system or document, date}}\"\n }\n }\n }\n ]\n },\n {\n \"name\": \"slide\",\n \"children\": [\n {\n \"name\": \"block\",\n \"props\": {\n \"ref\": \"two-column\",\n \"slots\": {\n \"title\": \"{{Action title: the claim this slide proves, with its number, two lines at most}}\",\n \"tracker\": \"{{Tracker: the section, one or two words}}\",\n \"text\": \"{{Body: the argument this slide makes, under fifty words}}\",\n \"content\": {\n \"name\": \"chart\",\n \"props\": {\n \"type\": \"bar\",\n \"valAxisTitle\": \"{{Measure (unit)}}\",\n \"data\": [\n {\n \"name\": \"{{Series name}}\",\n \"labels\": [\n \"{{Period 1}}\",\n \"{{Period 2}}\",\n \"{{Period 3}}\"\n ],\n \"values\": [0, 0, 0]\n }\n ],\n \"chartColors\": [\n \"accent\",\n \"secondary\",\n \"accent4\",\n \"accent6\",\n \"accent5\"\n ]\n }\n },\n \"source\": \"{{Source: system or document, date}}\"\n }\n }\n }\n ]\n },\n {\n \"name\": \"slide\",\n \"children\": [\n {\n \"name\": \"block\",\n \"props\": {\n \"ref\": \"action-chart\",\n \"slots\": {\n \"title\": \"{{Action title: the claim this slide proves, with its number, two lines at most}}\",\n \"tracker\": \"{{Tracker: the section, one or two words}}\",\n \"chart\": {\n \"name\": \"chart\",\n \"props\": {\n \"type\": \"bar\",\n \"valAxisTitle\": \"{{Measure (unit)}}\",\n \"data\": [\n {\n \"name\": \"{{Series name}}\",\n \"labels\": [\n \"{{Period 1}}\",\n \"{{Period 2}}\",\n \"{{Period 3}}\"\n ],\n \"values\": [0, 0, 0]\n }\n ],\n \"chartColors\": [\n \"accent\",\n \"secondary\",\n \"accent4\",\n \"accent6\",\n \"accent5\"\n ]\n }\n },\n \"takeaway\": \"{{Takeaway: what the reader should conclude, one or two sentences}}\",\n \"source\": \"{{Source: system or document, date}}\"\n }\n }\n }\n ]\n },\n {\n \"name\": \"slide\",\n \"children\": [\n {\n \"name\": \"block\",\n \"props\": {\n \"ref\": \"two-column\",\n \"slots\": {\n \"title\": \"{{Action title: the claim this slide proves, with its number, two lines at most}}\",\n \"tracker\": \"{{Tracker: the section, one or two words}}\",\n \"bullets\": [\n \"{{Bullet 1: one claim, ten words}}\",\n \"{{Bullet 2: one claim, ten words}}\",\n \"{{Bullet 3: one claim, ten words}}\"\n ],\n \"content\": {\n \"name\": \"table\",\n \"props\": {\n \"rows\": [\n [\n \"{{Row label}}\",\n {\n \"text\": \"{{Column (unit)}}\",\n \"align\": \"right\"\n },\n {\n \"text\": \"{{Column (unit)}}\",\n \"align\": \"right\"\n }\n ],\n [\n \"{{Row 1}}\",\n {\n \"text\": \"{{0.0}}\",\n \"align\": \"right\"\n },\n {\n \"text\": \"{{0.0}}\",\n \"align\": \"right\"\n }\n ],\n [\n \"{{Row 2}}\",\n {\n \"text\": \"{{0.0}}\",\n \"align\": \"right\"\n },\n {\n \"text\": \"{{0.0}}\",\n \"align\": \"right\"\n }\n ],\n [\n \"{{Row 3}}\",\n {\n \"text\": \"{{0.0}}\",\n \"align\": \"right\"\n },\n {\n \"text\": \"{{0.0}}\",\n \"align\": \"right\"\n }\n ]\n ]\n }\n },\n \"source\": \"{{Source: system or document, date}}\"\n }\n }\n }\n ]\n },\n {\n \"name\": \"slide\",\n \"children\": [\n {\n \"name\": \"block\",\n \"props\": {\n \"ref\": \"statement\",\n \"slots\": {\n \"tracker\": \"{{Tracker: the section, one or two words}}\",\n \"assertion\": \"{{Assertion: what to do next, in one sentence}}\",\n \"support\": \"{{Support: what backs the assertion, under thirty words}}\"\n }\n }\n }\n ]\n }\n ]\n }\n }\n}\n","/** PPTX quality analysis over renderer-aligned prepared facts. */\n\nimport {\n assertValidQualityPolicy,\n assertValidQualityProfile,\n type PreparedDocument,\n type QualityAnalysis,\n type QualityPolicy,\n type QualityProfile,\n type QualityRuleError,\n} from '@json-to-office/quality';\nimport type {\n PptxThemeConfig,\n PresentationComponentDefinition,\n} from '../types';\nimport { preparePptxQualityDocument } from './facts';\nimport type { PptxQualityFact, PptxQualityModel } from './facts';\nimport {\n PPTX_DEFAULT_QUALITY_PROFILE,\n pptxQualityEngine,\n declaredPptxQualityProfile,\n resolvePptxQualityProfile,\n} from './rules';\n\n/** Synthetic rule id for a failure raised before any rule could run. */\nconst PREPARE_RULE_ID = 'quality/prepare';\n\nexport interface PptxQualityOptions {\n customThemes?: Record<string, PptxThemeConfig>;\n}\n\nexport interface PptxQualityAnalysisOptions extends PptxQualityOptions {\n renderer?: string;\n profile?: QualityProfile;\n policy?: QualityPolicy;\n prepared?: PreparedDocument<PptxQualityModel, PptxQualityFact>;\n}\n\nfunction emptyAnalysis(\n ruleErrors: readonly QualityRuleError[] = [],\n blocked = false\n): QualityAnalysis {\n return {\n diagnostics: [],\n counts: { error: 0, warning: 0, info: 0 },\n blocked,\n truncated: false,\n suppressedCount: 0,\n evaluatedRuleIds: [],\n ruleErrors,\n };\n}\n\nexport function analyzePptxQuality(\n doc: unknown,\n options: PptxQualityAnalysisOptions = {}\n): QualityAnalysis {\n // Ahead of every early return: a malformed document must not be the reason a\n // caller never hears that its own policy or profile was unusable.\n assertValidQualityPolicy(options.policy);\n assertValidQualityProfile(options.profile);\n\n if (\n typeof doc !== 'object' ||\n doc === null ||\n Array.isArray(doc) ||\n (doc as { name?: unknown }).name !== 'pptx'\n ) {\n return emptyAnalysis();\n }\n\n let prepared = options.prepared;\n try {\n prepared ??= preparePptxQualityDocument(\n doc as PresentationComponentDefinition,\n options\n );\n } catch (error) {\n // Structural validation owns malformed trees; quality remains additive.\n if (options.policy?.onRuleError === 'throw') throw error;\n const gate = options.policy?.gate;\n // A gate that could never be evaluated has not been satisfied: report the\n // failure and fail closed rather than pass a document nothing inspected.\n return emptyAnalysis(\n [\n {\n ruleId: PREPARE_RULE_ID,\n message: error instanceof Error ? error.message : String(error),\n },\n ],\n gate !== undefined && gate !== 'none'\n );\n }\n return pptxQualityEngine.analyzeSync(prepared, {\n profile:\n resolvePptxQualityProfile(options.profile) ??\n declaredPptxQualityProfile(doc) ??\n PPTX_DEFAULT_QUALITY_PROFILE,\n policy: options.policy,\n });\n}\n","import {\n chartInfoDesignFindings,\n DEFAULT_MAXIMUM_CHART_SERIES,\n DEFAULT_MAXIMUM_PIE_SLICES,\n fontCountFinding,\n mergeQualityProfiles,\n nearestPaletteToken,\n offPaletteFinding,\n placeholderFinding,\n QUALITY_CODES,\n QualityEngine,\n resolveRuleConfiguration,\n tableInfoDesignFindings,\n type JsonPatchOperation,\n type QualityProfile,\n type QualityRule,\n type QualityRuleFinding,\n type QualityRulePack,\n} from '@json-to-office/quality';\nimport type {\n PptxBlockSlotFact,\n PptxBoxFact,\n PptxCanvasFact,\n PptxChromeSlotFact,\n PptxChartFact,\n PptxColorFact,\n PptxFontFact,\n PptxPlaceholderFact,\n PptxQualityFact,\n PptxQualityModel,\n PptxSlideFact,\n PptxTableColumnFact,\n PptxTableFact,\n PptxTextFact,\n PptxThemeFact,\n} from './facts';\n\nconst RENDERER_DEFAULT_WIDTH_IN = 10;\nconst RENDERER_DEFAULT_HEIGHT_IN = 7.5;\n// Calibrated against rendered ground truth (jto-ops quality ground-truth\n// harness, 2026-08: 130 comparable mutated-template measurements plus per-box\n// adjudication of every comparable authored flag, all measured from the\n// soffice PDF). 0.46 is the highest value at which the reference stock\n// templates (jto-ops STOCK_REFERENCE_TEMPLATES; management-plan binds) stay\n// warning-clean — the binding constraint, since a rule that flags known-good\n// templates trains every consumer to ignore it. At that operating point the\n// rendered sample catches 52% of >1-line-height spills as OVERFLOW, 91% when\n// TIGHT is included, and 87% of any visible spill, with no OVERFLOW false\n// alarms. Remaining misses require rendered evidence (`rendered` certainty),\n// not a character-count model — see the harness header for the full method.\n// The estimator itself lives in `utils/textMetrics.ts`, shared with the\n// engine's bounded `fit` so both size a title the same way.\nimport {\n DEFAULT_CHAR_WIDTH_FACTOR,\n estimateTextHeightPt as estimateHeight,\n} from '../utils/textMetrics';\nconst DEFAULT_SAFETY_BUFFER_PT = 8;\nconst DEFAULT_MIN_READABLE_FONT_PT = 7;\nconst DEFAULT_MAX_BODY_WORDS_PER_SLIDE = 130;\n\nconst KNOWN_CANVASES: readonly {\n w: number;\n h: number;\n label: string;\n legacy?: boolean;\n}[] = [\n { w: 13.333, h: 7.5, label: '16:9 standard' },\n { w: 10, h: 5.625, label: '16:9 small' },\n { w: 7.5, h: 7.5, label: '1:1 carousel' },\n { w: 7.5, h: 9.375, label: '4:5 vertical' },\n { w: 4.5, h: 8, label: '9:16 story' },\n { w: 10, h: 7.5, label: '4:3 legacy', legacy: true },\n];\n\nfunction numberParameter(\n parameters: Readonly<Record<string, unknown>>,\n name: string,\n fallback: number\n): number {\n const value = parameters[name];\n return typeof value === 'number' && Number.isFinite(value) ? value : fallback;\n}\n\nfunction textFacts(facts: readonly PptxQualityFact[]): PptxTextFact[] {\n return facts.filter(\n (fact): fact is PptxTextFact => fact.kind === 'pptx/text'\n );\n}\n\nfunction estimateTextHeightPt(\n fact: PptxTextFact,\n charWidthFactor: number\n): { heightPt: number; lines: number } | undefined {\n if (fact.boxWidthPt === undefined || fact.boxHeightPt === undefined) {\n return undefined;\n }\n return estimateHeight(\n fact.text,\n fact.boxWidthPt,\n fact.fontSizePt,\n fact.lineSpacingPt,\n fact.paraSpaceBeforePt,\n fact.paraSpaceAfterPt,\n charWidthFactor\n );\n}\n\nexport const pptxCanvasRule: QualityRule<PptxQualityModel, PptxQualityFact> = {\n id: 'pptx/canvas',\n description:\n 'Slide dimensions: partially declared, legacy 4:3, or a size matching no known preset.',\n code: QUALITY_CODES.CANVAS_UNSPECIFIED,\n category: 'composition',\n defaultSeverity: 'info',\n defaultCertainty: 'deterministic',\n formats: ['pptx'],\n evaluate: ({ facts }) => {\n const canvas = facts.find(\n (fact): fact is PptxCanvasFact => fact.kind === 'pptx/canvas'\n );\n if (!canvas) return [];\n const { widthIn: width, heightIn: height } = canvas;\n if (width === undefined || height === undefined) {\n const missing = [\n width === undefined ? 'props.slideWidth' : undefined,\n height === undefined ? 'props.slideHeight' : undefined,\n ].filter((entry): entry is string => entry !== undefined);\n const state =\n missing.length === 2\n ? 'No slide canvas declared'\n : `Incomplete slide canvas (${missing[0]} missing)`;\n return [\n {\n code: QUALITY_CODES.CANVAS_UNSPECIFIED,\n severity: 'warning',\n category: 'integrity',\n message: `${state}: the renderer falls back to 4:3 (${RENDERER_DEFAULT_WIDTH_IN}×${RENDERER_DEFAULT_HEIGHT_IN}\"), and 16:9 content on that canvas leaves a dead strip at the bottom.`,\n path: canvas.path,\n suggestion:\n 'Declare props.slideWidth and props.slideHeight — 13.333 × 7.5 for a standard 16:9 deck.',\n context: {\n missing,\n rendererDefault: {\n slideWidth: RENDERER_DEFAULT_WIDTH_IN,\n slideHeight: RENDERER_DEFAULT_HEIGHT_IN,\n },\n },\n },\n ];\n }\n\n const match = KNOWN_CANVASES.find(\n (known) =>\n Math.abs(known.w - width) < 0.01 && Math.abs(known.h - height) < 0.01\n );\n if (match?.legacy) {\n return [\n {\n code: QUALITY_CODES.CANVAS_LEGACY,\n message: `Canvas is 4:3 legacy (${match.w}×${match.h}\") — modern screens are 16:9.`,\n path: canvas.path,\n suggestion:\n 'If 4:3 is not deliberate, use slideWidth 13.333 and slideHeight 7.5.',\n },\n ];\n }\n if (match) return [];\n return [\n {\n code: QUALITY_CODES.CANVAS_NONSTANDARD,\n message: `Canvas ${width}×${height}\" matches no common preset (16:9, 1:1, 4:5, 9:16).`,\n path: canvas.path,\n suggestion:\n 'Confirm the size is deliberate; a mistyped canvas distorts every slide.',\n context: {\n knownCanvases: KNOWN_CANVASES.map(({ w, h, label }) => ({\n slideWidth: w,\n slideHeight: h,\n label,\n })),\n },\n },\n ];\n },\n};\n\nexport const pptxMinimumFontRule: QualityRule<\n PptxQualityModel,\n PptxQualityFact\n> = {\n id: 'pptx/minimum-font-size',\n description: 'Text below the size a projected slide can carry.',\n code: QUALITY_CODES.FONT_SIZE_MIN,\n category: 'legibility',\n defaultSeverity: 'warning',\n defaultCertainty: 'measured',\n formats: ['pptx'],\n defaultParameters: { minimumFontPt: DEFAULT_MIN_READABLE_FONT_PT },\n evaluate: ({ facts, configuration }) => {\n const minimum = numberParameter(\n configuration.parameters,\n 'minimumFontPt',\n DEFAULT_MIN_READABLE_FONT_PT\n );\n return textFacts(facts)\n .filter((fact) => fact.fontSizePt < minimum)\n .map((fact) => ({\n message: `Effective font size is ${fact.fontSizePt}pt — unreadable on a projected slide.`,\n path: `${fact.path}/props`,\n suggestion: `Use at least ${minimum}pt; captions rarely work below 10pt.`,\n context: { fontSize: fact.fontSizePt, threshold: minimum },\n evidence: { actual: fact.fontSizePt, expected: minimum, unit: 'pt' },\n // `add` replaces an existing member, so this lifts an explicit\n // fontSize and overrides an inherited style value alike.\n fixes: [\n {\n op: 'add' as const,\n path: `${fact.path}/props/fontSize`,\n value: minimum,\n },\n ],\n }));\n },\n};\n\n/**\n * Largest whole font size that fits the box, for a ready-made overflow fix.\n *\n * Conservative on purpose: the authored leading is kept even when it derives\n * from the font size (real leading would shrink too), so a size this returns\n * fits under the same model that produced the finding. Undefined when no\n * readable size fits (the text or the box has to change) or when the box\n * auto-grows (`h` omitted — there is nothing to overflow).\n */\nfunction fittingFontSizePt(\n fact: PptxTextFact,\n charWidthFactor: number,\n minimumFontPt: number\n): number | undefined {\n if (fact.autoFit === true) return undefined;\n const minimumWholeSize = Math.ceil(minimumFontPt);\n for (\n let size = Math.floor(fact.fontSizePt) - 1;\n size >= minimumWholeSize;\n size--\n ) {\n const estimate = estimateTextHeightPt(\n { ...fact, fontSizePt: size },\n charWidthFactor\n );\n if (\n estimate !== undefined &&\n fact.boxHeightPt !== undefined &&\n estimate.heightPt <= fact.boxHeightPt\n ) {\n return size;\n }\n }\n return undefined;\n}\n\nexport const pptxTextFitRule: QualityRule<PptxQualityModel, PptxQualityFact> = {\n id: 'pptx/text-fit',\n description:\n 'Estimated text height against its box. An estimate, not a measurement.',\n code: QUALITY_CODES.TEXT_TIGHT,\n category: 'integrity',\n defaultSeverity: 'info',\n defaultCertainty: 'estimated',\n formats: ['pptx'],\n defaultParameters: {\n characterWidthFactor: DEFAULT_CHAR_WIDTH_FACTOR,\n safetyBufferPt: DEFAULT_SAFETY_BUFFER_PT,\n },\n evaluate: ({ facts, configuration, profile, policy }) => {\n const factor = numberParameter(\n configuration.parameters,\n 'characterWidthFactor',\n DEFAULT_CHAR_WIDTH_FACTOR\n );\n const safetyBufferPt = numberParameter(\n configuration.parameters,\n 'safetyBufferPt',\n DEFAULT_SAFETY_BUFFER_PT\n );\n const minimumFontConfiguration = resolveRuleConfiguration(\n pptxMinimumFontRule,\n profile,\n policy\n );\n const minimumFontPt = minimumFontConfiguration.enabled\n ? numberParameter(\n minimumFontConfiguration.parameters,\n 'minimumFontPt',\n DEFAULT_MIN_READABLE_FONT_PT\n )\n : DEFAULT_MIN_READABLE_FONT_PT;\n const findings: QualityRuleFinding[] = [];\n for (const fact of textFacts(facts)) {\n const estimate = estimateTextHeightPt(fact, factor);\n if (!estimate || fact.boxHeightPt === undefined) continue;\n const marginPt = fact.boxHeightPt - estimate.heightPt;\n const measured = {\n estimatedTextPt: Math.round(estimate.heightPt * 10) / 10,\n availablePt: Math.round(fact.boxHeightPt * 10) / 10,\n marginPt: Math.round(marginPt * 10) / 10,\n estimatedLines: estimate.lines,\n fontSize: fact.fontSizePt,\n boxWidthPt: Math.round((fact.boxWidthPt as number) * 10) / 10,\n };\n\n if (marginPt < -fact.lineSpacingPt) {\n const fittingSize = fittingFontSizePt(fact, factor, minimumFontPt);\n findings.push({\n code: QUALITY_CODES.TEXT_OVERFLOW,\n severity: 'warning',\n message: `Text is estimated at ${measured.estimatedTextPt}pt tall (${estimate.lines} line${estimate.lines === 1 ? '' : 's'} of ${fact.fontSizePt}pt) in a ${measured.availablePt}pt box — it will overflow.`,\n path: fact.path,\n suggestion:\n 'Shorten the text, reduce fontSize, or enlarge the box (h / rowSpan).',\n context: measured,\n evidence: {\n actual: measured.estimatedTextPt,\n expected: measured.availablePt,\n unit: 'pt',\n },\n // A ready-made patch only when a readable size fits; shortening\n // the text or growing the box stays the author's call.\n ...(fittingSize !== undefined && {\n fixes: [\n {\n op: 'add' as const,\n path: `${fact.path}/props/fontSize`,\n value: fittingSize,\n },\n ],\n }),\n });\n continue;\n }\n if (marginPt >= safetyBufferPt) continue;\n findings.push({\n code: QUALITY_CODES.TEXT_TIGHT,\n message:\n marginPt < 0\n ? `Text is estimated to exceed its ${measured.availablePt}pt box by ${-measured.marginPt}pt — within one line-height, so likely a harmless spill into the gap below.`\n : `Text fits its box with only ${measured.marginPt}pt to spare — renderer rounding can push it over.`,\n path: fact.path,\n suggestion: `Leave at least ${safetyBufferPt}pt of vertical margin.`,\n context: measured,\n evidence: {\n actual: measured.marginPt,\n expected: safetyBufferPt,\n unit: 'pt margin',\n },\n });\n }\n return findings;\n },\n};\n\nexport const pptxSlideDensityRule: QualityRule<\n PptxQualityModel,\n PptxQualityFact\n> = {\n id: 'pptx/slide-density',\n description: 'Body word count per slide.',\n code: QUALITY_CODES.SLIDE_DENSITY,\n category: 'information-design',\n defaultSeverity: 'warning',\n defaultCertainty: 'estimated',\n formats: ['pptx'],\n defaultParameters: { maximumBodyWords: DEFAULT_MAX_BODY_WORDS_PER_SLIDE },\n evaluate: ({ facts, configuration }) => {\n const threshold = numberParameter(\n configuration.parameters,\n 'maximumBodyWords',\n DEFAULT_MAX_BODY_WORDS_PER_SLIDE\n );\n return facts\n .filter((fact): fact is PptxSlideFact => fact.kind === 'pptx/slide')\n .filter((fact) => fact.bodyWords > threshold)\n .map((fact) => ({\n message: `${fact.bodyWords} words of body text on one slide — an audience reads a slide, it does not study one.`,\n path: fact.path,\n suggestion: 'One idea per slide: split the content across more slides.',\n context: { bodyWords: fact.bodyWords, threshold },\n evidence: {\n actual: fact.bodyWords,\n expected: threshold,\n unit: 'words',\n },\n }));\n },\n};\n\n/**\n * WCAG 2.1 AA. Large text — 18pt, or 14pt bold — is legible at 3:1; everything\n * else needs 4.5:1. Projection is less forgiving than a screen, not more, so\n * these are floors rather than targets.\n */\nconst AA_NORMAL_RATIO = 4.5;\nconst AA_LARGE_RATIO = 3;\nconst LARGE_TEXT_PT = 18;\n/** AA counts bold text as large from 14pt, two sizes below regular text. */\nconst LARGE_BOLD_TEXT_PT = 14;\n\nfunction channelLuminance(channel: number): number {\n const c = channel / 255;\n return c <= 0.03928 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4);\n}\n\n/** Relative luminance of a bare 6-digit hex, or undefined if unparseable. */\nfunction relativeLuminance(hex: string): number | undefined {\n const match = /^#?([0-9a-f]{6})$/i.exec(hex);\n if (!match) return undefined;\n const value = parseInt(match[1], 16);\n return (\n 0.2126 * channelLuminance((value >> 16) & 255) +\n 0.7152 * channelLuminance((value >> 8) & 255) +\n 0.0722 * channelLuminance(value & 255)\n );\n}\n\nfunction contrastRatio(a: string, b: string): number | undefined {\n const la = relativeLuminance(a);\n const lb = relativeLuminance(b);\n if (la === undefined || lb === undefined) return undefined;\n return (Math.max(la, lb) + 0.05) / (Math.min(la, lb) + 0.05);\n}\n\nexport const pptxTextContrastRule: QualityRule<\n PptxQualityModel,\n PptxQualityFact\n> = {\n id: 'pptx/text-contrast',\n description:\n 'Text against the surface behind it, judged by WCAG AA. Text over an image or a chart is skipped.',\n code: QUALITY_CODES.TEXT_CONTRAST,\n category: 'accessibility',\n defaultSeverity: 'warning',\n defaultCertainty: 'deterministic',\n formats: ['pptx'],\n defaultParameters: {\n normalRatio: AA_NORMAL_RATIO,\n largeRatio: AA_LARGE_RATIO,\n largeTextPt: LARGE_TEXT_PT,\n largeBoldTextPt: LARGE_BOLD_TEXT_PT,\n },\n evaluate: ({ facts, configuration }) => {\n const normalRatio = numberParameter(\n configuration.parameters,\n 'normalRatio',\n AA_NORMAL_RATIO\n );\n const largeRatio = numberParameter(\n configuration.parameters,\n 'largeRatio',\n AA_LARGE_RATIO\n );\n const largeTextPt = numberParameter(\n configuration.parameters,\n 'largeTextPt',\n LARGE_TEXT_PT\n );\n const largeBoldTextPt = numberParameter(\n configuration.parameters,\n 'largeBoldTextPt',\n LARGE_BOLD_TEXT_PT\n );\n\n return textFacts(facts).flatMap((fact) => {\n const { colorHex, backgroundHexes } = fact;\n if (!colorHex || !backgroundHexes?.length) return [];\n\n // A gradient is only as legible as its worst stop: the text crosses all\n // of them, and the reader only remembers where it disappeared.\n let worst: { ratio: number; background: string } | undefined;\n for (const background of backgroundHexes) {\n const ratio = contrastRatio(colorHex, background);\n if (ratio === undefined) continue;\n if (!worst || ratio < worst.ratio) worst = { ratio, background };\n }\n if (!worst) return [];\n\n const isLarge =\n fact.fontSizePt >= largeTextPt ||\n (fact.bold && fact.fontSizePt >= largeBoldTextPt);\n const required = isLarge ? largeRatio : normalRatio;\n if (worst.ratio >= required) return [];\n\n const rounded = Math.round(worst.ratio * 100) / 100;\n return [\n {\n message: `Text at #${colorHex} on #${worst.background} has ${rounded}:1 contrast — below the ${required}:1 needed at ${fact.fontSizePt}pt${fact.bold ? ' bold' : ''}.`,\n path: fact.path,\n suggestion:\n 'Darken the text, lighten it further, or change the surface behind it.',\n context: {\n colorHex,\n backgroundHex: worst.background,\n ratio: rounded,\n required,\n fontSizePt: fact.fontSizePt,\n bold: fact.bold,\n backgroundHexes,\n },\n evidence: {\n actual: rounded,\n expected: required,\n unit: ':1',\n },\n },\n ];\n });\n },\n};\n\n/**\n * Unfilled slots and leftover filler, in one rule over two codes.\n *\n * One rule because it is one question — \"is this text real yet?\" — and two\n * codes because the answers differ in consequence: a scaffold marker blocks\n * generation, filler only advises.\n */\nexport const pptxPlaceholderRule: QualityRule<\n PptxQualityModel,\n PptxQualityFact\n> = {\n id: 'pptx/placeholder-text',\n description: 'An unfilled scaffold slot, or leftover filler copy.',\n code: QUALITY_CODES.PLACEHOLDER_TEXT,\n category: 'integrity',\n defaultSeverity: 'warning',\n defaultCertainty: 'deterministic',\n formats: ['pptx'],\n evaluate: ({ facts }) =>\n facts\n .filter(\n (fact): fact is PptxPlaceholderFact => fact.kind === 'pptx/placeholder'\n )\n .map((fact) =>\n placeholderFinding({\n path: fact.path,\n kind: fact.placeholderKind,\n pattern: fact.pattern,\n excerpt: fact.excerpt,\n })\n ),\n};\n\n/**\n * Two opaque boxes on one slide that land on each other.\n *\n * Opacity is the whole of the geometric claim. An image, a chart, a table or a\n * filled rectangle paints its entire box, so two of them intersecting really\n * do hide each other. A *text* box says nothing of the kind — authors declare\n * one far larger than the words inside it, and the reference decks are full of\n * designs where two text rectangles cross and no ink does: an 80pt title\n * beside a 12pt label, a value centred in the hole of a donut. Word-level\n * overlap belongs to the rendered pass (#344), which can see where ink landed.\n *\n * Intersecting is not the same as wrong, which is why the verdict is split.\n * Reference-quality decks stack opaque rectangles constantly — an accent strip\n * along the top of a card, a badge in the corner of a photograph — so a plain\n * intersection is `info`: visible, not accused. Two cases are warnings because\n * neither is ever a design. A box whose geometry matches another to within a\n * couple of points is a leftover duplicate. And anything covering a chart or a\n * table covers data, which is the one thing a slide cannot afford to lose.\n *\n * A box fully inside a larger one is layering rather than collision. Equal\n * rectangles are not containment — that is the duplicate case, and it is\n * reported.\n */\nconst DEFAULT_OVERLAP_MIN_PT = 4;\nconst DEFAULT_OVERLAP_MIN_AREA_RATIO = 0.15;\n/** Below this share of the outer box, an inner box reads as a deliberate layer. */\nconst CONTAINED_AREA_RATIO = 0.95;\n/** Slack on the containment test: a nested box may sit a rounding step proud. */\nconst CONTAINMENT_SLACK_PT = 0.5;\n/** Two boxes agreeing to within this on every edge are the same box, twice. */\nconst DUPLICATE_TOLERANCE_PT = 2;\n\n/** Components whose whole point is data a reader has to be able to see. */\nconst DATA_COMPONENTS = new Set(['chart', 'highcharts', 'table']);\n\ninterface Rect {\n xPt: number;\n yPt: number;\n widthPt: number;\n heightPt: number;\n}\n\nfunction contains(outer: Rect, inner: Rect): boolean {\n const outerArea = outer.widthPt * outer.heightPt;\n const innerArea = inner.widthPt * inner.heightPt;\n if (outerArea === 0 || innerArea >= outerArea * CONTAINED_AREA_RATIO) {\n return false;\n }\n const slack = CONTAINMENT_SLACK_PT;\n return (\n inner.xPt >= outer.xPt - slack &&\n inner.yPt >= outer.yPt - slack &&\n inner.xPt + inner.widthPt <= outer.xPt + outer.widthPt + slack &&\n inner.yPt + inner.heightPt <= outer.yPt + outer.heightPt + slack\n );\n}\n\nfunction isDuplicate(a: Rect, b: Rect): boolean {\n const near = (x: number, y: number): boolean =>\n Math.abs(x - y) <= DUPLICATE_TOLERANCE_PT;\n return (\n near(a.xPt, b.xPt) &&\n near(a.yPt, b.yPt) &&\n near(a.widthPt, b.widthPt) &&\n near(a.heightPt, b.heightPt)\n );\n}\n\nexport const pptxBoxOverlapRule: QualityRule<\n PptxQualityModel,\n PptxQualityFact\n> = {\n id: 'pptx/box-overlap',\n description:\n 'Two opaque boxes on one slide that land on each other. A duplicate, or anything covering data, is a warning.',\n code: QUALITY_CODES.BOX_OVERLAP,\n category: 'integrity',\n defaultSeverity: 'info',\n defaultCertainty: 'deterministic',\n formats: ['pptx'],\n defaultParameters: {\n minimumOverlapPt: DEFAULT_OVERLAP_MIN_PT,\n minimumAreaRatio: DEFAULT_OVERLAP_MIN_AREA_RATIO,\n },\n evaluate: ({ facts, configuration }) => {\n const minimumOverlapPt = numberParameter(\n configuration.parameters,\n 'minimumOverlapPt',\n DEFAULT_OVERLAP_MIN_PT\n );\n const minimumAreaRatio = numberParameter(\n configuration.parameters,\n 'minimumAreaRatio',\n DEFAULT_OVERLAP_MIN_AREA_RATIO\n );\n const bySlide = new Map<string, PptxBoxFact[]>();\n for (const fact of facts) {\n if (fact.kind !== 'pptx/box' || !fact.opaque) continue;\n const slide = bySlide.get(fact.slidePath);\n if (slide) slide.push(fact);\n else bySlide.set(fact.slidePath, [fact]);\n }\n\n const findings: QualityRuleFinding[] = [];\n for (const slide of bySlide.values()) {\n const ordered = [...slide].sort((a, b) => a.order - b.order);\n for (let i = 0; i < ordered.length; i += 1) {\n for (let j = i + 1; j < ordered.length; j += 1) {\n const under = ordered[i];\n const over = ordered[j];\n // A box nested in another is a group, not a collision.\n if (over.path.startsWith(`${under.path}/`)) continue;\n if (under.path.startsWith(`${over.path}/`)) continue;\n\n const duplicate = isDuplicate(under, over);\n if (!duplicate && (contains(under, over) || contains(over, under))) {\n continue;\n }\n\n const overlapWidth =\n Math.min(under.xPt + under.widthPt, over.xPt + over.widthPt) -\n Math.max(under.xPt, over.xPt);\n const overlapHeight =\n Math.min(under.yPt + under.heightPt, over.yPt + over.heightPt) -\n Math.max(under.yPt, over.yPt);\n if (\n overlapWidth < minimumOverlapPt ||\n overlapHeight < minimumOverlapPt\n ) {\n continue;\n }\n const overlapArea = overlapWidth * overlapHeight;\n const smaller = Math.min(\n under.widthPt * under.heightPt,\n over.widthPt * over.heightPt\n );\n const ratio = smaller === 0 ? 0 : overlapArea / smaller;\n if (ratio < minimumAreaRatio) continue;\n\n const hidesData =\n DATA_COMPONENTS.has(under.componentName) ||\n DATA_COMPONENTS.has(over.componentName);\n const percent = Math.round(ratio * 100);\n findings.push({\n severity: duplicate || hidesData ? 'warning' : 'info',\n message: duplicate\n ? `Two ${over.componentName === under.componentName ? `${over.componentName}s` : 'boxes'} occupy the same rectangle — the later one hides the earlier entirely.`\n : hidesData\n ? `A ${over.componentName} covers ${percent}% of the ${under.componentName} drawn before it, hiding data.`\n : `A ${over.componentName} covers ${percent}% of the ${under.componentName} drawn before it; both paint their whole box.`,\n path: over.path,\n relatedPaths: [under.path],\n suggestion: duplicate\n ? 'Delete whichever of the two is left over.'\n : 'Move or resize one of the two if the overlap is not deliberate.',\n context: {\n covering: over.path,\n covered: under.path,\n overlapPercent: percent,\n duplicate,\n overlapPt: {\n width: Math.round(overlapWidth * 10) / 10,\n height: Math.round(overlapHeight * 10) / 10,\n },\n },\n evidence: {\n actual: percent,\n expected: 0,\n unit: '% of the smaller box',\n },\n });\n }\n }\n }\n return findings;\n },\n};\n\n/**\n * A slide table is a summary, not a report. Twelve rows is what a 16:9 canvas\n * holds at a size an audience can read from the back of a room; past that the\n * table is being stored on the slide rather than shown.\n */\nconst DEFAULT_MAX_TABLE_ROWS_PER_SLIDE = 12;\n\n/** Information design for charts: the comparison, the scale and the palette. */\nexport const pptxChartRule: QualityRule<PptxQualityModel, PptxQualityFact> = {\n id: 'pptx/chart-design',\n description:\n 'What a chart claims about its numbers: the comparison, the scale, the palette and the unit.',\n code: QUALITY_CODES.CHART_3D,\n category: 'information-design',\n defaultSeverity: 'warning',\n defaultCertainty: 'deterministic',\n formats: ['pptx'],\n defaultParameters: {\n maximumSeries: DEFAULT_MAXIMUM_CHART_SERIES,\n maximumSlices: DEFAULT_MAXIMUM_PIE_SLICES,\n },\n evaluate: ({ facts, configuration }) => {\n const maximumSeries = numberParameter(\n configuration.parameters,\n 'maximumSeries',\n DEFAULT_MAXIMUM_CHART_SERIES\n );\n const maximumSlices = numberParameter(\n configuration.parameters,\n 'maximumSlices',\n DEFAULT_MAXIMUM_PIE_SLICES\n );\n return facts\n .filter((fact): fact is PptxChartFact => fact.kind === 'pptx/chart')\n .flatMap((fact) => {\n const fix = seriesColorFix(fact);\n return chartInfoDesignFindings(fact, {\n maximumSeries,\n maximumSlices,\n ...(fix && { seriesColorFix: fix }),\n });\n });\n },\n};\n\n/**\n * The palette patch, when the theme has enough slots to draw every series.\n *\n * Only for a native chart: a Highcharts palette lives inside an options blob\n * the schema keeps opaque and the export server reads verbatim, so writing\n * into it means guessing at a structure this pass never validated.\n */\nfunction seriesColorFix(\n fact: PptxChartFact\n): readonly JsonPatchOperation[] | undefined {\n if (fact.componentName !== 'chart') return undefined;\n if (fact.seriesCount < 1 || fact.paletteTokens.length === 0) return undefined;\n const tokens = Array.from(\n { length: fact.seriesCount },\n (_, index) => fact.paletteTokens[index % fact.paletteTokens.length]\n );\n return [{ op: 'add', path: fact.seriesColorsPath, value: tokens }];\n}\n\n/** Information design for tables: alignment, rounding, rules and length. */\nexport const pptxTableRule: QualityRule<PptxQualityModel, PptxQualityFact> = {\n id: 'pptx/table-design',\n description:\n 'How a table lays its numbers out: alignment, rounding, rules and length.',\n code: QUALITY_CODES.TABLE_NUMERIC_ALIGN,\n category: 'information-design',\n defaultSeverity: 'warning',\n defaultCertainty: 'deterministic',\n formats: ['pptx'],\n defaultParameters: { maximumRows: DEFAULT_MAX_TABLE_ROWS_PER_SLIDE },\n evaluate: ({ facts, configuration }) => {\n const maximumRows = numberParameter(\n configuration.parameters,\n 'maximumRows',\n DEFAULT_MAX_TABLE_ROWS_PER_SLIDE\n );\n return facts\n .filter((fact): fact is PptxTableFact => fact.kind === 'pptx/table')\n .flatMap((fact) =>\n tableInfoDesignFindings(fact, {\n maximumRows,\n rowSurface: 'slide',\n rowSeverity: 'warning',\n alignFix: alignColumnRight,\n })\n );\n },\n};\n\n/**\n * Right-align every cell of one column, header included.\n *\n * A row-major table has no column to patch, so this is one operation per row,\n * and a plain-string cell has to become an object to carry an alignment at\n * all — `replace`, never `add`, because `add` at an array index splices and\n * would push the rest of the row sideways.\n */\nfunction alignColumnRight(\n column: PptxTableColumnFact\n): readonly JsonPatchOperation[] {\n return column.cells\n .filter((entry) => {\n const cell = entry.cell;\n return typeof cell === 'string' || cell.align !== 'right';\n })\n .map((entry) => ({\n op: 'replace' as const,\n path: entry.path,\n value:\n typeof entry.cell === 'string'\n ? { text: entry.cell, align: 'right' }\n : { ...entry.cell, align: 'right' },\n }));\n}\n\nconst DEFAULT_MAX_FONT_FAMILIES = 3;\n\n/** Every family the document can paint: the theme's roles plus authored ones. */\nexport const pptxFontCountRule: QualityRule<PptxQualityModel, PptxQualityFact> =\n {\n id: 'pptx/font-count',\n description: 'Distinct font families the deck can paint.',\n code: QUALITY_CODES.FONT_COUNT,\n category: 'brand',\n defaultSeverity: 'warning',\n defaultCertainty: 'deterministic',\n formats: ['pptx'],\n defaultParameters: { maximumFamilies: DEFAULT_MAX_FONT_FAMILIES },\n evaluate: ({ facts, configuration }) => {\n const maximum = numberParameter(\n configuration.parameters,\n 'maximumFamilies',\n DEFAULT_MAX_FONT_FAMILIES\n );\n const theme = facts.find(\n (fact): fact is PptxThemeFact => fact.kind === 'pptx/theme'\n );\n const authored = facts.filter(\n (fact): fact is PptxFontFact => fact.kind === 'pptx/font-family'\n );\n const families = new Set<string>(theme?.fontFamilies ?? []);\n const extraPaths: string[] = [];\n for (const fact of authored) {\n if (!families.has(fact.family)) extraPaths.push(fact.path);\n families.add(fact.family);\n }\n if (families.size <= maximum) return [];\n return [\n fontCountFinding({\n path: theme?.path ?? '/props',\n families: [...families].sort(),\n maximum,\n relatedPaths: [...new Set(extraPaths)],\n }),\n ];\n },\n };\n\n/** A literal colour the resolved theme does not define. */\nexport const pptxPaletteRule: QualityRule<PptxQualityModel, PptxQualityFact> = {\n id: 'pptx/palette-adherence',\n description: 'A literal colour the resolved theme does not define.',\n code: QUALITY_CODES.OFF_PALETTE,\n category: 'brand',\n defaultSeverity: 'info',\n defaultCertainty: 'deterministic',\n formats: ['pptx'],\n evaluate: ({ facts }) => {\n const theme = facts.find(\n (fact): fact is PptxThemeFact => fact.kind === 'pptx/theme'\n );\n const palette = theme?.paletteHexes ?? {};\n const known = new Set(Object.values(palette));\n return facts\n .filter((fact): fact is PptxColorFact => fact.kind === 'pptx/color')\n .filter((fact) => !known.has(fact.hex))\n .map((fact) => {\n const nearest = nearestPaletteToken(fact.hex, palette);\n return offPaletteFinding({\n path: fact.path,\n raw: fact.raw,\n hex: fact.hex,\n ...(nearest && { nearest }),\n });\n });\n },\n};\n\nconst DEFAULT_OFF_CANVAS_TOLERANCE_PT = 2;\n\n/**\n * Text drawn past the edge of the slide.\n *\n * Only text: a decorative shape or a photograph that bleeds off the canvas is\n * a technique, a word that does is a defect nobody can read. Judged on the\n * ink, not the box — a short left-aligned label in a box that overhangs the\n * edge by a few points loses nothing, while a wrapped title whose box sits an\n * inch off the slide loses a line. The ink is placed inside the box by the\n * text's alignment and estimated with the same width model as `text-fit`, so\n * a block body drawn for a wider canvas is caught on the narrower one it was\n * never designed for.\n */\nexport const pptxOffCanvasRule: QualityRule<PptxQualityModel, PptxQualityFact> =\n {\n id: 'pptx/off-canvas',\n description: 'Text ink drawn past the edge of the slide.',\n code: QUALITY_CODES.OFF_CANVAS,\n category: 'integrity',\n defaultSeverity: 'warning',\n defaultCertainty: 'measured',\n formats: ['pptx'],\n defaultParameters: {\n tolerancePt: DEFAULT_OFF_CANVAS_TOLERANCE_PT,\n characterWidthFactor: DEFAULT_CHAR_WIDTH_FACTOR,\n },\n evaluate: ({ facts, configuration }) => {\n const tolerance = numberParameter(\n configuration.parameters,\n 'tolerancePt',\n DEFAULT_OFF_CANVAS_TOLERANCE_PT\n );\n const canvas = facts.find(\n (fact): fact is PptxCanvasFact => fact.kind === 'pptx/canvas'\n );\n const widthPt = (canvas?.widthIn ?? RENDERER_DEFAULT_WIDTH_IN) * 72;\n const heightPt = (canvas?.heightIn ?? RENDERER_DEFAULT_HEIGHT_IN) * 72;\n const factor = numberParameter(\n configuration.parameters,\n 'characterWidthFactor',\n DEFAULT_CHAR_WIDTH_FACTOR\n );\n const findings: QualityRuleFinding[] = [];\n for (const fact of textFacts(facts)) {\n if (\n fact.boxXPt === undefined ||\n fact.boxYPt === undefined ||\n fact.boxWidthPt === undefined ||\n fact.boxHeightPt === undefined\n )\n continue;\n const longestLinePt =\n Math.max(\n 0,\n ...fact.text.split('\\n').map((line) => line.trimEnd().length)\n ) *\n fact.fontSizePt *\n factor;\n const inkWidthPt = Math.min(fact.boxWidthPt, longestLinePt);\n const inkHeightPt = Math.min(\n fact.boxHeightPt,\n estimateTextHeightPt(fact, factor)?.heightPt ?? fact.boxHeightPt\n );\n const inkLeft =\n fact.align === 'right'\n ? fact.boxXPt + fact.boxWidthPt - inkWidthPt\n : fact.align === 'center'\n ? fact.boxXPt + (fact.boxWidthPt - inkWidthPt) / 2\n : fact.boxXPt;\n const inkTop =\n fact.verticalAlign === 'bottom'\n ? fact.boxYPt + fact.boxHeightPt - inkHeightPt\n : fact.verticalAlign === 'middle'\n ? fact.boxYPt + (fact.boxHeightPt - inkHeightPt) / 2\n : fact.boxYPt;\n const overRight = inkLeft + inkWidthPt - widthPt;\n const overBottom = inkTop + inkHeightPt - heightPt;\n const overLeft = -inkLeft;\n const overTop = -inkTop;\n const worst = Math.max(overRight, overBottom, overLeft, overTop);\n if (worst <= tolerance) continue;\n const edge =\n worst === overRight\n ? 'right'\n : worst === overBottom\n ? 'bottom'\n : worst === overLeft\n ? 'left'\n : 'top';\n findings.push({\n path: fact.path,\n message: `Text runs ${Math.round(worst)}pt past the ${edge} edge of the slide; the reader never sees it.`,\n suggestion:\n 'Move or narrow the box, or size the layout from the slide (percentages, a frame) rather than in fixed inches.',\n context: {\n edge,\n overrunPt: Math.round(worst * 10) / 10,\n slideWidthPt: widthPt,\n slideHeightPt: heightPt,\n },\n evidence: { actual: Math.round(worst), expected: 0, unit: 'pt' },\n });\n }\n return findings;\n },\n };\n\n/** A block slot over the word budget its definition declares. */\nexport const pptxSlotBudgetRule: QualityRule<\n PptxQualityModel,\n PptxQualityFact\n> = {\n id: 'pptx/slot-budget',\n description: 'A block slot over the word budget its definition declares.',\n code: QUALITY_CODES.SLOT_BUDGET,\n category: 'composition',\n defaultSeverity: 'warning',\n defaultCertainty: 'deterministic',\n formats: ['pptx'],\n evaluate: ({ facts }) =>\n facts\n .filter(\n (fact): fact is PptxBlockSlotFact => fact.kind === 'pptx/block-slot'\n )\n .filter((fact) => fact.words > fact.maxWords)\n .map((fact) => ({\n path: fact.path,\n message:\n `${fact.block} ${fact.slot} runs to ${fact.words} words; the slot holds ` +\n `${fact.maxWords} — one claim, one sentence.`,\n suggestion:\n 'Cut it to the conclusion. Move the evidence into the body it summarises.',\n evidence: {\n summary: 'words in the slot against its budget',\n actual: fact.words,\n expected: fact.maxWords,\n unit: 'words',\n },\n context: { block: fact.block, slot: fact.slot },\n })),\n};\n\nfunction stringListParameter(\n parameters: Readonly<Record<string, unknown>>,\n name: string\n): string[] {\n const value = parameters[name];\n return Array.isArray(value)\n ? value.filter((entry): entry is string => typeof entry === 'string')\n : [];\n}\n\n/**\n * Chrome a profile requires, judged where the block declared the slot.\n *\n * The rule reads roles off the document's own definitions and required roles\n * off the profile; with no profile asking for anything it says nothing. That\n * is the theme/profile boundary in one place: selecting the consulting theme\n * styles a source line, selecting the consulting profile requires one.\n */\nexport const pptxRequiredChromeRule: QualityRule<\n PptxQualityModel,\n PptxQualityFact\n> = {\n id: 'pptx/required-chrome',\n description:\n 'A block slot with a role a profile or policy requires — a takeaway, a source — left empty. Off until one names roles.',\n code: QUALITY_CODES.CHROME_MISSING,\n category: 'consistency',\n defaultSeverity: 'warning',\n defaultCertainty: 'deterministic',\n formats: ['pptx'],\n defaultParameters: { required: [] },\n evaluate: ({ facts, configuration, profile }) => {\n const required = stringListParameter(configuration.parameters, 'required');\n if (required.length === 0) return [];\n return facts\n .filter(\n (fact): fact is PptxChromeSlotFact => fact.kind === 'pptx/chrome-slot'\n )\n .filter((fact) => required.includes(fact.role) && !fact.present)\n .map((fact) => ({\n path: fact.path,\n relatedPaths: [fact.invocation],\n message:\n `${fact.block} states no ${fact.role} in its \"${fact.slot}\" slot; ` +\n `the ${profile?.id ?? 'selected'} profile expects one on every ${fact.block}.`,\n suggestion: `Fill the \"${fact.slot}\" slot. The theme already styles it.`,\n context: { block: fact.block, slot: fact.slot, role: fact.role },\n }));\n },\n};\n\n/**\n * An action title that wraps past the lines a profile allows, measured in\n * the box its definition drew and with the width model the fit pass uses.\n * Off by default (`maxLines: 0`): a label title is a content convention,\n * and only a consulting profile asks every slide to lead with a claim.\n */\nexport const pptxActionTitleRule: QualityRule<\n PptxQualityModel,\n PptxQualityFact\n> = {\n id: 'pptx/action-title',\n description:\n 'An action-title slot that wraps past the lines a profile or policy allows. Off at 0.',\n code: QUALITY_CODES.ACTION_TITLE_LENGTH,\n category: 'hierarchy',\n defaultSeverity: 'warning',\n defaultCertainty: 'estimated',\n formats: ['pptx'],\n defaultParameters: { maxLines: 0 },\n evaluate: ({ facts, configuration }) => {\n const maxLines = numberParameter(configuration.parameters, 'maxLines', 0);\n if (maxLines <= 0) return [];\n return facts\n .filter(\n (fact): fact is PptxChromeSlotFact =>\n fact.kind === 'pptx/chrome-slot' &&\n fact.role === 'actionTitle' &&\n fact.estimatedLines !== undefined\n )\n .filter((fact) => (fact.estimatedLines ?? 0) > maxLines)\n .map((fact) => ({\n path: fact.path,\n relatedPaths: [fact.invocation],\n message:\n `The action title runs to ${fact.estimatedLines} lines at ${fact.fontSizePt}pt; ` +\n `an action title states its claim in at most ${maxLines}.`,\n suggestion:\n 'Cut the title to one claim with a number or a verb. Move the rest into the takeaway.',\n evidence: {\n summary: 'estimated lines against the profile limit',\n actual: fact.estimatedLines,\n expected: maxLines,\n unit: 'lines',\n },\n context: { block: fact.block, slot: fact.slot },\n }));\n },\n};\n\nexport const PPTX_QUALITY_RULES: QualityRulePack<\n PptxQualityModel,\n PptxQualityFact\n> = {\n id: 'pptx/default',\n rules: [\n pptxCanvasRule,\n pptxMinimumFontRule,\n pptxTextFitRule,\n pptxSlideDensityRule,\n pptxTextContrastRule,\n pptxPlaceholderRule,\n pptxBoxOverlapRule,\n pptxChartRule,\n pptxTableRule,\n pptxFontCountRule,\n pptxPaletteRule,\n pptxOffCanvasRule,\n pptxSlotBudgetRule,\n pptxRequiredChromeRule,\n pptxActionTitleRule,\n ],\n};\n\nexport const PPTX_QUALITY_PROFILES = {\n 'executive-presentation': {\n id: 'executive-presentation',\n formats: ['pptx'],\n description: 'Decision deck optimized for scan speed and projection.',\n rules: {\n 'pptx/minimum-font-size': { parameters: { minimumFontPt: 14 } },\n 'pptx/slide-density': { parameters: { maximumBodyWords: 70 } },\n },\n },\n 'technical-presentation': {\n id: 'technical-presentation',\n formats: ['pptx'],\n description: 'Portable professional presentation defaults.',\n },\n 'consulting-deck': {\n id: 'consulting-deck',\n formats: ['pptx'],\n description:\n 'Consulting readout: every content slide leads with a two-line action title, every chart carries a takeaway and a source.',\n rules: {\n 'pptx/required-chrome': {\n parameters: { required: ['takeaway', 'source'] },\n },\n 'pptx/action-title': { parameters: { maxLines: 2 } },\n 'pptx/slide-density': { parameters: { maximumBodyWords: 90 } },\n },\n },\n} as const satisfies Record<string, QualityProfile>;\n\nexport const PPTX_DEFAULT_QUALITY_PROFILE: QualityProfile =\n PPTX_QUALITY_PROFILES['technical-presentation'];\n\nconst PPTX_PROFILES_BY_ID: Readonly<Record<string, QualityProfile>> =\n PPTX_QUALITY_PROFILES;\n\n/**\n * The shipped profile a deck names in `props.qualityProfile`, so that\n * validation without arguments judges a blueprint scaffold by its archetype.\n * An unknown name is nobody's profile: the format default applies.\n */\nexport function declaredPptxQualityProfile(\n document: unknown\n): QualityProfile | undefined {\n const props = (document as { props?: { qualityProfile?: unknown } })?.props;\n const id = props?.qualityProfile;\n return typeof id === 'string' &&\n Object.prototype.hasOwnProperty.call(PPTX_PROFILES_BY_ID, id)\n ? PPTX_PROFILES_BY_ID[id]\n : undefined;\n}\n\n/**\n * Callers name a shipped profile by id — `{ id: 'executive-presentation', formats: ['pptx'] }`.\n * Without this lookup that request reaches the engine carrying nothing but its id,\n * so the analysis runs on defaults while stamping the requested profileId.\n */\nexport function resolvePptxQualityProfile(\n requested: QualityProfile | undefined\n): QualityProfile | undefined {\n if (!requested) return undefined;\n const registered = PPTX_PROFILES_BY_ID[requested.id];\n if (!registered) return requested;\n return mergeQualityProfiles(registered, requested);\n}\n\nexport const pptxQualityEngine = new QualityEngine(PPTX_QUALITY_RULES.rules);\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 { expandPptxBlocksWithPlugins } from '../blocks/document';\nimport { generatePluginPresentationSchema, exportPluginSchema } from './schema';\nimport { processPresentation } from '../core/structure';\nimport type { PresentationPackagingOptions } from '../core/finalizePackage';\nimport {\n containsHighcharts,\n renderProcessedViaIr,\n} from '../core/generateFromIr';\nimport { toChartFontFaces } from '@json-to-office/shared/fonts/node';\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 * Expand one registered component at its authored path.\n *\n * The shared block/plugin composition walks the tree; this is the code it\n * calls when it meets a registered name. Children have already been\n * expanded by the time it runs, so a container plugin receives standard\n * components exactly as before.\n */\n function pluginRenderer(\n warningsCollector: PipelineWarning[],\n theme: PptxThemeConfig,\n validateEmitted: ValidateEmitted | undefined\n ): (component: Record<string, unknown>, path: string) => Promise<unknown[]> {\n return async (component, path) => {\n const customComponent = componentMap.get(String(component.name))!;\n if (!component.props) {\n throw new Error(\n `Custom component '${customComponent.name}' must have a 'props' property. ` +\n `Use format: { name: '${customComponent.name}', props: {...} }`\n );\n }\n const version = component.version as string | undefined;\n const versionEntry = resolveComponentVersion(\n customComponent.name,\n customComponent.versions,\n version\n );\n const cleanedProps = cleanComponentProps(\n versionEntry,\n component.props as Record<string, unknown>\n );\n const versionLabel = version\n ? `${customComponent.name}@${version}`\n : customComponent.name;\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 let result: unknown;\n try {\n result = await versionEntry.render({\n props: cleanedProps,\n theme,\n addWarning,\n children: component.children as unknown[] | undefined,\n });\n } catch (error) {\n if (error instanceof ComponentValidationError) throw error;\n throw new Error(\n `Error processing custom component '${customComponent.name}': ${\n error instanceof Error ? error.message : String(error)\n }`\n );\n }\n const emitted = (\n Array.isArray(result) ? result : [result]\n ) as PptxComponentInput[];\n // The authored parent decides what emitted output may be: a slide for\n // slide-level plugins, the deck for slide-emitting ones.\n const depth = path.split('/children/').length - 1;\n validateEmitted?.(\n emitted,\n versionLabel,\n depth === 1 ? 'pptx' : depth === 2 ? 'slide' : undefined\n );\n return emitted;\n };\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 // Document-local JSON blocks and registered code share one bounded\n // expansion, in both directions: a plugin can emit a block, a block can\n // name a plugin. Nothing here loads code by name; a missing\n // registration is a validation error.\n const expanded = await expandPptxBlocksWithPlugins(\n modedRoot,\n resolvedTheme,\n new Set(componentMap.keys()),\n pluginRenderer(warnings, resolvedTheme, validateEmitted)\n );\n const processedDocument = expanded.document;\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; a chart-bearing deck materialises them\n // for the export server's browser, exactly as the core pipeline does.\n const processed = processPresentation(processedDocument, {\n theme: resolvedTheme,\n services: state.services,\n sourceMap: expanded.sourceMap,\n warnings,\n });\n const hasHighcharts = containsHighcharts(processed);\n const resolvedFonts = await resolveDocumentFonts(\n processedDocument,\n resolvedTheme,\n warnings,\n state.fonts,\n hasHighcharts\n );\n const chartFonts = hasHighcharts ? toChartFontFaces(resolvedFonts) : [];\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(processed, warnings, {\n renderer,\n services: state.services,\n deterministic:\n options?.deterministic ?? state.packaging.deterministic,\n generatedAt: options?.generatedAt ?? state.packaging.generatedAt,\n ...(chartFonts.length > 0 ? { chartFonts } : {}),\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 * 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":";;;;;;;;;;;AA2BO,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;AAtCA,IAEa;AAFb;AAAA;AAAA;AAEO,IAAM,IAAI;AAAA,MACf,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A,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;;;ADrdA,SAAS,2BAAAI,gCAA+B;;;AL5EjC,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","path","background","hyperlink","fill","color","createPptxGenJsRenderer","createOfficeOpenPptxRenderer","registry","path","path","resolve","result","path","DEFAULT_PPTX_RENDERER_ID","SEMANTIC_COLOR_NAMES","designColors","mergeWithDefaults","frame","path","estimate","mergeWithDefaults","path","BlockEvaluationError","toAuthoredBlockPointer","validatePresentationDocument","path","effects","fill","color","path","designColors","SEMANTIC_COLOR_NAMES","DEFAULT_PPTX_RENDERER_ID","readFileSync","collectPlaceholders","path","collectPlaceholders","estimateTextHeightPt","background","resolveComponentVersion","DuplicateComponentError","ComponentValidationError","validatePresentationDocument","ComponentValidationError","toChartFontFaces","path","resolveComponentVersion","ComponentValidationError","DuplicateComponentError","validationDocument","toChartFontFaces","resolveComponentVersion"]}
|
|
1
|
+
{"version":3,"sources":["../src/utils/warn.ts","../src/ir/types.ts","../src/ir/units.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/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/generationOptions.ts","../src/core/expandHighcharts.ts","../src/utils/environment.ts","../src/core/resolveImageLayout.ts","../src/quality/facts.ts","../src/core/generationContext.ts","../src/themes/consulting.pptx.theme.json","../src/themes/consulting.ts","../src/themes/vermilion.pptx.theme.json","../src/themes/devportal.pptx.theme.json","../src/themes/alternates.ts","../src/themes/defaults.ts","../src/themes/design-system.ts","../src/utils/componentDefaults.ts","../src/utils/resolveComponentTree.ts","../src/core/structure.ts","../src/core/dimensions.ts","../src/core/layout.ts","../src/core/fit.ts","../src/utils/textMetrics.ts","../src/blocks/document.ts","../src/index.ts","../src/blueprints/index.ts","../src/templates/blueprints/consulting-deck.pptx.blueprint.json","../src/quality/preflight.ts","../src/quality/rules.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 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 TEXT_OVERLAP_UNPOSITIONED: 'TEXT_OVERLAP_UNPOSITIONED',\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 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\n * ------------------------------------------------------------------ */\n\nexport interface PptxIrSlide {\n /** Deterministic: `slide${n}`, 1-based in generated order. */\n id: string;\n path: 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","/**\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 * 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 type { PptxFeature } from '../../ir/features';\nimport type {\n PptxIR,\n PptxIrBackground,\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 * Explicit allowlist with four verified gaps. A new `PptxFeature` stays\n * unsupported until this adapter deliberately adds and tests it.\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 'rich-text',\n 'text',\n 'shapes',\n 'images',\n 'svg',\n 'image-crop',\n 'image-rounding',\n 'tables',\n 'table-merged-cells',\n 'table-insets',\n 'table-rounded-corners',\n 'table-auto-page',\n 'charts',\n 'chart-bar-style',\n 'chart-pie-style',\n 'chart-line-style',\n 'chart-radar-style',\n 'chart-data-labels',\n 'chart-data-border',\n 'chart-axis-scale',\n 'chart-axis-visibility',\n 'chart-axis-style',\n 'chart-text-style',\n 'solid-fills',\n 'gradient-fills',\n 'pattern-fills',\n 'lines',\n 'shadows',\n 'backgrounds',\n 'speaker-notes',\n 'hidden-slides',\n 'external-links',\n 'internal-links',\n 'text-hyperlinks',\n 'element-hyperlinks',\n 'rotation',\n 'image-transform',\n 'flip-horizontal',\n 'flip-vertical',\n 'proofing-language',\n 'rtl',\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 slide of ir.slides) {\n emitSlide(pptx, slide, ctx);\n }\n\n return pptx;\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 = 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 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 * This adapter uses an explicit allowlist: a new `PptxFeature` stays\n * unsupported until the adapter deliberately adds and tests it. What it does\n * not declare, and why — each is a verified gap or an explicit mapping\n * boundary:\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 * - `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 OFFICE_OPEN_CAPABILITIES: ReadonlySet<PptxFeature> = new Set([\n 'rich-text',\n 'complex-bullet-glyphs',\n 'text',\n 'shapes',\n 'images',\n 'tables',\n 'charts',\n 'chart-bar-style',\n 'chart-pie-style',\n 'chart-line-style',\n 'chart-radar-style',\n 'chart-data-labels',\n 'chart-data-border',\n 'chart-axis-scale',\n 'chart-axis-visibility',\n 'chart-axis-style',\n 'chart-text-style',\n 'solid-fills',\n 'gradient-fills',\n 'pattern-fills',\n 'image-fills',\n 'lines',\n 'shadows',\n 'backgrounds',\n 'speaker-notes',\n 'hidden-slides',\n 'transitions',\n 'external-links',\n 'internal-links',\n 'text-hyperlinks',\n 'rotation',\n 'flip-horizontal',\n 'groups',\n 'proofing-language',\n 'rtl',\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 { toChartFontFaces } from '@json-to-office/shared/fonts/node';\nimport type { RasterizeFontFace } from '@json-to-office/shared';\nimport {\n assertNoContentConflicts,\n assertValidPresentationForGeneration,\n type GenerationOptions,\n} from './generationOptions';\nimport { expandHighchartsComponents } from './expandHighcharts';\nimport { resolveImageLayout } from './resolveImageLayout';\nimport { preparePptxQualityDocument } from '../quality/facts';\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 assertNoContentConflicts(component);\n const warnings: PipelineWarning[] = [];\n\n const prepared =\n options?.prepared ??\n preparePptxQualityDocument(component, {\n customThemes: options?.customThemes,\n fonts: options?.fonts,\n warnings,\n services: options?.services,\n renderer: selectedRenderer,\n });\n\n const result = await runWithBaseDir(options?.baseDir, async () => {\n const expansion = await expandHighchartsComponents(\n prepared.model.processed,\n options?.services?.highcharts,\n warnings\n );\n const laidOut = await resolveImageLayout(expansion.presentation, warnings);\n return compilePresentation(laidOut, warnings);\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 assertNoContentConflicts(component);\n const warnings: PipelineWarning[] = [];\n\n const prepared =\n options?.prepared ??\n preparePptxQualityDocument(component, {\n customThemes: options?.customThemes,\n fonts: options?.fonts,\n warnings,\n services: options?.services,\n renderer: selectedRenderer,\n });\n\n // Fires `fonts.onResolved` for the preview stager, exactly as the legacy\n // path does. The PPTX itself never embeds font bytes; a `highcharts` is\n // drawn by an export server's browser, though, which needs the bytes of any\n // registered face to set the chart in the deck's type, so a chart-bearing\n // deck materialises them for that.\n const hasHighcharts = containsHighcharts(prepared.model.processed);\n const resolvedFonts = await resolveDocumentFonts(\n prepared.model.document,\n prepared.model.theme,\n warnings,\n options?.fonts,\n hasHighcharts\n );\n const chartFonts = hasHighcharts ? toChartFontFaces(resolvedFonts) : [];\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(prepared.model.processed, warnings, {\n ...effectiveOptions,\n ...(chartFonts.length > 0 ? { chartFonts } : {}),\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 options?.chartFonts\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 if (compiled.unsupported.length > 0) {\n throw new UncompiledComponentError(compiled.unsupported);\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 /** Staged faces a chart's export server is handed as inline `@font-face`. */\n chartFonts?: readonly RasterizeFontFace[];\n};\n\n/** Whether any slide carries an enabled `highcharts`, groups included. */\nexport function containsHighcharts(\n presentation: ProcessedPresentation\n): boolean {\n const named = (\n components:\n | readonly {\n name: string;\n enabled?: boolean;\n children?: readonly unknown[];\n }[]\n | undefined\n ): boolean =>\n components?.some(\n (component) =>\n component.enabled !== false &&\n (component.name === 'highcharts' ||\n named(component.children as typeof components))\n ) ?? false;\n return presentation.slides.some((slide) => named(slide.components));\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, block and custom-component expansion, theme resolution,\n * component defaults, layout and fit. What remains, and what this module\n * does, is the last mile of resolution: inches become EMU transforms, groups\n * flatten into slide elements, theme colour tokens become hex, the font\n * cascade is flattened onto every run, and page-number placeholders are\n * 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 PipelineWarning,\n PptxComponentInput,\n PptxThemeConfig,\n ProcessedPresentation,\n ProcessedSlide,\n SlideContext,\n StyleName,\n} from '../types';\nimport { definedChartColorTokens, resolveColor } from '../utils/color';\nimport { applyFontWeight } from '../utils/fontAliasContext';\nimport { resolveImageSource, safeLocalPath } from '../utils/imageSource';\nimport {\n HYPERLINK_SLIDE_UNRESOLVED,\n type HyperlinkProps,\n} from '../utils/hyperlink';\nimport { resolveComponentGridPosition } from '../core/grid';\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 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 * Text boxes on the slide being compiled that stated no coordinates at all.\n *\n * Reset per slide by `compileSlide`. A named style now lands each role in a\n * band of its own, but two boxes sharing a style still share a band, and the\n * IR alone cannot tell a deliberate overlay from two elements nobody\n * positioned — so authored-ness is recorded here while it is still known.\n */\n positionlessText: Array<{ path: string; transform: PptxIrTransform }>;\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 positionlessText: [],\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 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 * 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\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 // Per slide: two boxes only collide with each other if they share one.\n ctx.positionlessText = [];\n\n // A gradient background renders as a full-bleed rectangle added first, so it\n // sits behind everything else.\n const gradientSource = slide.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 // A `group` is transparent: layout already resolved its children to\n // absolute boxes, so the compiler draws them in order as slide elements.\n // Grid placement was resolved by layout too; resolving it again is a no-op\n // that keeps the compiler correct on a tree that skipped that pass.\n const visit = (components: readonly PptxComponentInput[]): void => {\n for (const component of components) {\n if (component.name === 'group') {\n if (component.enabled !== false) visit(component.children ?? []);\n continue;\n }\n const resolved = resolveComponentGridPosition(\n component,\n processed.grid,\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 visit(slide.components);\n\n warnOverlappingText(slideIndex, ctx);\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 ...(background ? { background } : {}),\n elements,\n ...(slide.notes ? { notes: slide.notes } : {}),\n hidden: slide.hidden === true,\n ...(transition ? { transition } : {}),\n };\n}\n\n/**\n * Report text boxes nobody positioned that landed on top of each other.\n *\n * Only boxes that stated neither `x` nor `y` are compared: an overlap between\n * two authored positions is a composition, and one between an authored box and\n * a default is at least half deliberate. Two defaults on the same slide are\n * nobody's decision — before the style bands that was every pair, and it is\n * still every pair that shares a style.\n *\n * A warning rather than a repair. Moving one of the two would be a layout\n * engine's job (#220), and guessing which one should move is exactly the\n * guess that produces a deck the author did not write.\n */\nfunction warnOverlappingText(slideIndex: number, ctx: CompileContext): void {\n const boxes = ctx.positionlessText;\n for (let i = 0; i < boxes.length; i += 1) {\n for (let j = i + 1; j < boxes.length; j += 1) {\n const a = boxes[i];\n const b = boxes[j];\n const overlaps =\n a.transform.xEmu < b.transform.xEmu + b.transform.widthEmu &&\n b.transform.xEmu < a.transform.xEmu + a.transform.widthEmu &&\n a.transform.yEmu < b.transform.yEmu + b.transform.heightEmu &&\n b.transform.yEmu < a.transform.yEmu + a.transform.heightEmu;\n if (!overlaps) continue;\n warn(\n ctx.warnings,\n W.TEXT_OVERLAP_UNPOSITIONED,\n `Text at ${a.path} and ${b.path} give no x/y and overlap on this slide. ` +\n 'Give at least one of them explicit coordinates, or a named style ' +\n 'whose default band differs.',\n { slide: slideIndex, component: 'text' }\n );\n }\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 * 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 // Recorded before the transform leaves this function: downstream, a band\n // default and an authored coordinate are the same two numbers.\n if (props.x === undefined && props.y === undefined) {\n ctx.positionlessText.push({ path, transform });\n }\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 let 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 // Feature gates read the authored runs: the case lowering below can split one\n // authored run into several, which is a rendering device, not rich text.\n if (runs.length > 1) ctx.features.require('rich-text', path);\n runs = applyTextCase(runs, named.style?.case);\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\n/**\n * PPTX backends lack a shared caps primitive. Lower case to explicit runs.\n *\n * A small-caps run splits per lowercase span, so a run carrying its own\n * hyperlink hands the same link to every piece — the fan-out the office-open\n * backend already performs for an element-level link over rich runs. Splitting\n * is what makes the 80% size possible; a link is at worst repeated, never lost.\n */\nfunction applyTextCase(\n runs: PptxIrTextRun[],\n textCase: 'none' | 'upper' | 'smallCaps' | undefined\n): PptxIrTextRun[] {\n if (!textCase || textCase === 'none') return runs;\n return runs.flatMap((run) => {\n if (textCase === 'upper') return [{ ...run, text: run.text.toUpperCase() }];\n const pieces = run.text.match(/\\p{Ll}+|[^\\p{Ll}]+/gu) ?? [''];\n return pieces.map((text, index) => ({\n ...run,\n text: text.toUpperCase(),\n fontSize: /^\\p{Ll}/u.test(text) ? run.fontSize * 0.8 : run.fontSize,\n ...(index > 0 && { spaceBeforePoints: undefined }),\n ...(index < pieces.length - 1 && {\n breakAfter: undefined,\n spaceAfterPoints: undefined,\n }),\n }));\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 ?? style?.paraSpaceBefore) !== undefined\n ? { spaceBeforePoints: props.paraSpaceBefore ?? style?.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 * Where each named style sits when the author gives no coordinates.\n *\n * Fractions of the slide extent, so a band means the same thing on 16:9, 4:3\n * and any custom size. Without these every positionless text box resolved to\n * (0, 0): a title and a subtitle on one slide stacked on top of each other in\n * the top-left corner, which is the shape the starters had — so the documents\n * meant to be copied were the ones that demonstrated the defect.\n *\n * A style names a role, and a role has a place on the slide. `body` and\n * `caption` still collide with a second box of the same style, which no fixed\n * band can solve; `warnOverlappingText` reports that case rather than letting\n * it render silently.\n */\nconst STYLE_BANDS: Readonly<\n Record<string, { x: number; y: number; w: number }>\n> = {\n // A title slide's title and its subtitle, as two bands in the middle third.\n title: { x: 0.08, y: 0.34, w: 0.84 },\n subtitle: { x: 0.08, y: 0.56, w: 0.84 },\n // Content-slide headings sit in the top margin, all three at the same place:\n // the level changes the type, not where the slide starts.\n heading1: { x: 0.06, y: 0.06, w: 0.88 },\n heading2: { x: 0.06, y: 0.06, w: 0.88 },\n heading3: { x: 0.06, y: 0.06, w: 0.88 },\n // Below a heading, in the content-safe area.\n body: { x: 0.06, y: 0.26, w: 0.88 },\n caption: { x: 0.06, y: 0.88, w: 0.88 },\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 *\n * Each axis is decided on its own: an author who states `x` and not `y` has\n * taken control of one of them, and the band is still the better answer for\n * the other than the origin.\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 // Only a named style carries a band. An unstyled text box keeps the origin\n // it has always had: nothing here knows what role it plays, and inventing\n // one would move every such box in every existing deck.\n const band =\n typeof props.style === 'string' ? STYLE_BANDS[props.style] : undefined;\n\n return {\n xEmu:\n props.x !== undefined\n ? resolveDimensionEmu(props.x, 'X', ctx.extent)\n : Math.round((band?.x ?? 0) * ctx.extent.widthEmu),\n yEmu:\n props.y !== undefined\n ? resolveDimensionEmu(props.y, 'Y', ctx.extent)\n : Math.round((band?.y ?? 0) * ctx.extent.heightEmu),\n widthEmu:\n props.w !== undefined\n ? resolveDimensionEmu(props.w, 'X', ctx.extent)\n : band\n ? Math.round(band.w * ctx.extent.widthEmu)\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 // Gate on the authored runs, before the case lowering can split them.\n if (runs.length > 1) ctx.features.require('rich-text', path);\n runs = applyTextCase(runs, named.style?.case);\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 // A header row is a compile-time treatment of row 0, not a new thing for a\n // backend to understand: both renderers already draw per-cell fill and\n // weight, so nothing about this reaches the IR that was not there before.\n if (props.headerRow && rows.length > 0) {\n rows[0] = {\n cells: rows[0].cells.map((cell) => headerCell(cell, props, ctx)),\n };\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\n/**\n * One cell of the header row, as the theme would have it.\n *\n * Every part of this yields to something the author said. A cell that states\n * its own weight, fill or colour keeps it; so does a table that states a fill\n * or a colour for all of its cells, because \"this table is green\" is a\n * statement about the header too. What is left is the case nobody spoke for,\n * where the header takes `background2` behind `text` — the pair every bundled\n * palette carries for a band that reads as chrome.\n *\n * `fontWeight` counts as speaking for the weight. It aliases the family to a\n * real sub-family rather than setting `bold`, so forcing bold on top of it\n * would both overrule an explicit `400` and ask the renderer to synthesise\n * bold over an already-picked face — a Light header drawn heavier than the\n * body under it, which is not what \"header\" was supposed to mean.\n */\nfunction headerCell(\n cell: PptxIrTableCell,\n tableProps: Record<string, any>,\n ctx: CompileContext\n): PptxIrTableCell {\n const formatting: PptxIrTableCellFormatting = {\n ...(tableProps.fontWeight == null ? { bold: true } : {}),\n ...(tableProps.color\n ? {}\n : { color: irColor(resolveColor('text', ctx.theme, ctx.warnings)) }),\n ...cell.formatting,\n };\n const fill =\n cell.fill ??\n (tableProps.fill\n ? undefined\n : irColor(resolveColor('background2', ctx.theme, ctx.warnings)));\n return {\n ...cell,\n formatting,\n ...(fill ? { fill } : {}),\n };\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","/**\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 {\n DEFAULT_CHART_THEME_COLORS,\n designColors,\n resolveDesignColor,\n} 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 if (theme.palette?.chart) return theme.palette.chart;\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 if (theme.palette) {\n const hex = resolveDesignColor(\n color,\n designColors(theme.colors, theme.palette)\n );\n if (hex) return hex;\n }\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 * 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/** 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 {\n GridConfig,\n GridPosition,\n PptxComponentInput,\n PipelineWarning,\n} 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')\n 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(\n warnings,\n 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(\n gridPos,\n gridConfig,\n slideWidth,\n slideHeight,\n warnings\n );\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 =\n typeof newProps.x === 'string' || typeof newProps.w === 'string';\n const hasPercentY =\n 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)\n newProps.x = hasPercentX ? toPercX(resolved.x) : resolved.x;\n if (newProps.y == null)\n newProps.y = hasPercentY ? toPercY(resolved.y) : resolved.y;\n if (newProps.w == null)\n newProps.w = hasPercentX ? toPercX(resolved.w) : resolved.w;\n if (newProps.h == null)\n 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 a backend is only imported\n * when it is actually selected — choosing `pptxgenjs` never loads\n * `@office-open/pptx`, and a backend that cannot be loaded at all (an\n * `--omit=optional` install, a broken tree) surfaces as an actionable install\n * hint rather than a bare module-resolution failure. `statuses()` asks the\n * same question up front, so a discovery surface never advertises a renderer\n * that would fail on the first render.\n */\n\nimport {\n RendererRegistry,\n type RendererStatus,\n} 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\n/**\n * Every registered renderer with whether its backend can be loaded here.\n *\n * Registration is not availability: the factory only runs on selection, so an\n * id alone says nothing about whether the render behind it will work. Callers\n * that advertise renderers — `jto_info`, `jto_discover` — report this instead\n * of pptxRendererIds() so a renderer that cannot run is never offered as one\n * that can.\n */\nexport function pptxRendererStatuses(): Promise<\n RendererStatus<PptxRendererId>[]\n> {\n return registry.statuses();\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 JsonBlockDefinition,\n} from '@json-to-office/shared';\nimport type {\n GradientFill,\n PptxComponentDefaults,\n PptxRendererId,\n ThemeConfigJson,\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 /** Document-local JSON block definitions, invoked with `name: \"block\"`. */\n blocks?: Record<string, JsonBlockDefinition>;\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 hidden?: boolean;\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 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 hidden?: boolean;\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 type TextStyle = NonNullable<\n NonNullable<ThemeConfigJson['styles']>['body']\n>;\nexport type StyleName = keyof NonNullable<ThemeConfigJson['styles']>;\n\nexport type PptxThemeConfig = ThemeConfigJson;\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 /**\n * Materialize font bytes even when no `onResolved` listener is registered.\n * Set when the deck carries a `highcharts`, whose PNG is drawn by an\n * export server's browser that needs the actual font files to set the chart\n * in a registered face. Matches the DOCX helper.\n */\n forceMaterialize = false\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) runs when a consumer is\n // listening via onResolved — typically the LibreOffice preview stager — or\n // when the caller forces materialization for a chart. Office output never\n // embeds bytes, so skipping fetches when neither applies keeps library\n // callers from paying network cost.\n if (!fonts?.onResolved && !forceMaterialize) 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. On the\n // force-materialize path there may be no listener at all — the resolved\n // fonts still flow back through the return value.\n fonts?.onResolved?.(resolved);\n return resolved;\n}\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';\nimport type { PreparedDocument } from '@json-to-office/quality';\nimport type { PptxQualityFact, PptxQualityModel } from '../quality/facts';\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 /** Canonical prepared model; internal hosts use it to avoid a second prologue. */\n prepared?: PreparedDocument<PptxQualityModel, PptxQualityFact>;\n /**\n * Compiled pointer → authored pointer, from block expansion. Diagnostics\n * raised while processing an expanded tree (a text that cannot fit its\n * declared bounds) are reported at the slot the author can patch.\n */\n sourceMap?: Readonly<Record<string, string>>;\n /**\n * Sink for warnings raised while processing: a grid placement clamped back\n * onto the grid by layout. Hosts that prepare once and render from the\n * prepared model hear each warning once.\n */\n warnings?: PipelineWarning[];\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 * 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 {\n remoteExportNotice,\n REMOTE_EXPORT_WARNING,\n chartFamilyResolver,\n chartPointsPerPixel,\n chartRequestKey,\n dedupeChartRequest,\n limitChartRequest,\n postJsonToService,\n recordChartRetry,\n resolveServiceUrl,\n type ChartRenderCache,\n withChartFontFaceCss,\n withChartTypography,\n type ChartTypography,\n type HighchartsServiceConfig,\n type RasterizeFontFace,\n} 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;\n/** Highcharts' own default canvas width, for a config that states none. */\nconst DEFAULT_CHART_WIDTH_PX = 960;\nconst DEFAULT_EXPORT_SERVER_URL = 'http://localhost:7801';\n\nexport interface HighchartsExpansionResult {\n presentation: ProcessedPresentation;\n}\n\n/**\n * Replace every `highcharts` component with the `image` it renders to.\n *\n * Slide components are expanded in place, groups included. 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 chartFonts?: readonly RasterizeFontFace[]\n): Promise<HighchartsExpansionResult> {\n const scope: ExpansionScope = {\n theme: presentation.theme,\n slideWidth: presentation.slideWidth,\n services,\n warnings,\n chartFonts,\n // Per deck: a chart repeated on an agenda slide and again in its section\n // is one render.\n chartCache: new Map(),\n };\n\n const slides = await Promise.all(\n presentation.slides.map(async (slide, index) => ({\n ...slide,\n components: await expandList(\n slide.components,\n `slides[${index}].elements`,\n scope\n ),\n }))\n );\n\n return { presentation: { ...presentation, slides } };\n}\n\n/** What one expansion needs from the presentation and the caller. */\ninterface ExpansionScope {\n theme: PptxThemeConfig;\n slideWidth: number;\n services: HighchartsServiceConfig | undefined;\n warnings: PipelineWarning[];\n chartFonts: readonly RasterizeFontFace[] | undefined;\n chartCache: ChartRenderCache<RenderedChart>;\n}\n\nasync function expandList(\n components: PptxComponentInput[],\n path: string,\n scope: ExpansionScope\n): Promise<PptxComponentInput[]> {\n const out: PptxComponentInput[] = [];\n for (const [index, component] of components.entries()) {\n if (component.name === 'highcharts') {\n out.push(await expandOne(component, `${path}[${index}]`, scope));\n } else if (component.children && component.children.length > 0) {\n out.push({\n ...component,\n children: await expandList(\n component.children,\n `${path}[${index}].children`,\n scope\n ),\n });\n } else {\n out.push(component);\n }\n }\n return out;\n}\n\nasync function expandOne(\n component: PptxComponentInput,\n path: string,\n scope: ExpansionScope\n): Promise<PptxComponentInput> {\n const props = component.props as unknown as PptxHighchartsProps;\n // Slides expand with `Promise.all`, so without the gate a deck's charts\n // are all posted at once — the same burst the docx walk used to produce.\n // The gate is the shared one, keyed by server URL, so a process rendering\n // a deck and a document together still respects one cap per server.\n const chart = await limitChartRequest(\n exportServerUrl(props.serverUrl, scope.services?.serverUrl),\n scope.services?.concurrency,\n () =>\n renderChart(\n withChartFontFaces(\n withThemeTypography(\n withThemeColors(props, scope.theme, scope.warnings),\n scope.theme,\n scope.slideWidth,\n scope.warnings\n ),\n scope.theme,\n scope.chartFonts\n ),\n scope.services,\n scope.warnings,\n scope.chartCache\n )\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\n/** A public export server is a decision: refused without `allowRemote`, announced with it. */\nfunction assertExportServerAllowed(\n serverUrl: string,\n services: HighchartsServiceConfig | undefined,\n warnings: PipelineWarning[]\n): void {\n const notice = remoteExportNotice(serverUrl, services?.allowRemote);\n if (!notice) return;\n // Once per deck per destination: the notice is about where the data went,\n // and a chart-heavy deck repeating it drowns out every other warning. The\n // message names the URL, so matching on it is matching on the destination.\n const alreadySaid = warnings.some(\n (warning) =>\n warning.code === REMOTE_EXPORT_WARNING && warning.message === notice\n );\n if (alreadySaid) return;\n warnings.push({\n code: REMOTE_EXPORT_WARNING,\n component: 'highcharts',\n message: notice,\n });\n}\n\nasync function renderChart(\n config: PptxHighchartsProps,\n services: HighchartsServiceConfig | undefined,\n warnings: PipelineWarning[],\n cache?: ChartRenderCache<RenderedChart>\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 assertExportServerAllowed(serverUrl, services, warnings);\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 return dedupeChartRequest(\n cache,\n chartRequestKey(serverUrl, requestBody),\n () => postChart(serverUrl, requestBody, config, services)\n );\n}\n\nasync function postChart(\n serverUrl: string,\n requestBody: Record<string, unknown>,\n config: PptxHighchartsProps,\n services: HighchartsServiceConfig | undefined\n): Promise<RenderedChart> {\n const response = await postJsonToService({\n url: serverUrl,\n path: '/export',\n body: requestBody,\n headers: services?.headers,\n timeoutMs: services?.timeoutMs,\n retries: services?.retries,\n onRetry: recordChartRetry,\n serviceLabel: 'Highcharts export server',\n // The code lets a server route report a missing export server as a\n // dependency outage with this message, not as an internal error.\n onUnreachable: (url, cause) =>\n `Highcharts Export Server is not running at ${url}. ` +\n 'Start it with: npx highcharts-export-server --enableServer true\\n' +\n `Cause: ${cause}`,\n });\n\n return {\n dataUri: `data:image/png;base64,${await response.text()}`,\n widthPx: config.options.chart?.width ?? DEFAULT_CHART_WIDTH_PX,\n heightPx: config.options.chart?.height ?? 720,\n };\n}\n\n/**\n * The export server this chart will actually be posted to. Also what keys the\n * concurrency gate, so resolving it in two places is what would let a deck\n * open a second pool against the same server.\n */\nfunction exportServerUrl(propsUrl?: string, servicesUrl?: string): string {\n return resolveServiceUrl(propsUrl, servicesUrl, DEFAULT_EXPORT_SERVER_URL);\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/**\n * The width, in points, the chart's image takes on the slide — the rule the\n * `image` it becomes applies: `w` in inches, or a percentage of the slide,\n * else the chart's own pixels at 96 dpi. A grid-placed chart has no width yet\n * and reads as 96 dpi.\n */\nfunction placedWidthPt(\n props: PptxHighchartsProps,\n slideWidth: number\n): number | undefined {\n const { w } = props;\n if (typeof w === 'number') return w * 72;\n if (typeof w === 'string' && w.endsWith('%')) {\n return (parseFloat(w) / 100) * slideWidth * 72;\n }\n if (w === undefined && props.grid === undefined) {\n return (\n ((props.options.chart?.width ?? DEFAULT_CHART_WIDTH_PX) / PX_PER_INCH) *\n 72\n );\n }\n return undefined;\n}\n\n/**\n * The deck's type, read off the resolved theme. `chartLabel` and `source` are\n * the roles a theme declares for exactly this; without them the labels sit two\n * points under the body style and the source at the caption size. The title\n * takes the heading face at the `heading3` size.\n */\nfunction themeChartTypography(\n theme: PptxThemeConfig,\n warnings: PipelineWarning[]\n): ChartTypography {\n const styles = theme.styles ?? {};\n const family = chartFamilyResolver(theme);\n const bodyPt = styles.body?.fontSize ?? theme.defaults.fontSize;\n const label = styles.chartLabel;\n const heading = styles.heading3;\n const labelPt = label?.fontSize ?? Math.max(bodyPt - 2, 6);\n const text = `#${resolveColor('text', theme, warnings)}`;\n return {\n bodyFamily: family(theme.fonts.body),\n headingFamily: family(theme.fonts.heading),\n textColor: text,\n mutedColor: theme.colors.text2\n ? `#${resolveColor('text2', theme, warnings)}`\n : text,\n labelPt,\n labelWeight: label?.fontWeight ?? (label?.bold ? 700 : undefined),\n titlePt: heading?.fontSize ?? bodyPt + 4,\n titleWeight:\n heading?.fontWeight ?? (heading?.bold === false ? undefined : 700),\n sourcePt:\n styles.source?.fontSize ??\n styles.caption?.fontSize ??\n Math.max(labelPt - 2, 6),\n };\n}\n\n/**\n * Set the chart in the deck's type: family, sizes and ink written beneath\n * whatever the author styled, scaled to the width the image is placed at.\n * A theme with no fonts — the empty theme direct callers pass — adds nothing,\n * so their request stays byte-identical.\n */\nfunction withThemeTypography(\n props: PptxHighchartsProps,\n theme: PptxThemeConfig,\n slideWidth: number,\n warnings: PipelineWarning[]\n): PptxHighchartsProps {\n if (!props.options || !theme?.fonts?.body || !theme.fonts.heading) {\n return props;\n }\n return {\n ...props,\n options: withChartTypography(\n props.options,\n themeChartTypography(theme, warnings),\n chartPointsPerPixel(\n props.options.chart?.width ?? DEFAULT_CHART_WIDTH_PX,\n placedWidthPt(props, slideWidth)\n )\n ) as PptxHighchartsProps['options'],\n };\n}\n\n/**\n * Hand the export server the bytes of every staged face of the families the\n * chart is set in, as `@font-face` rules ahead of the author's own CSS.\n * Nothing is added when no face matches.\n */\nfunction withChartFontFaces(\n props: PptxHighchartsProps,\n theme: PptxThemeConfig,\n faces: readonly RasterizeFontFace[] | undefined\n): PptxHighchartsProps {\n if (!faces?.length || !theme?.fonts) return props;\n return withChartFontFaceCss(props, faces, [\n theme.fonts.body,\n theme.fonts.heading,\n ]);\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 * 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 = await Promise.all(\n presentation.slides.map(async (slide) => ({\n ...slide,\n components: await resolve(slide.components),\n }))\n );\n\n return { ...presentation, slides };\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 if (component.name === 'image') {\n out.push(await resolveOne(component, presentation, warnings));\n } else if (component.children && component.children.length > 0) {\n out.push({\n ...component,\n children: await resolveList(component.children, presentation, warnings),\n });\n } else {\n out.push(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","import {\n chartEncodingFor,\n collectColorLiterals,\n collectFontFamilies,\n collectPlaceholders,\n hasUnitMarker,\n normalizeHex,\n normalizeHighchartsChart,\n parseNumericCell,\n type ChartInfoDesign,\n type PlaceholderKind,\n type PreparedDocument,\n type ProvenanceMap,\n type QualityFact,\n type TableAlignment,\n type TableColumnInfoDesign,\n type TableInfoDesign,\n} from '@json-to-office/quality';\nimport type { FontRuntimeOpts, ServicesConfig } from '@json-to-office/shared';\nimport {\n DEFAULT_PPTX_RENDERER_ID,\n SEMANTIC_COLOR_NAMES,\n} from '@json-to-office/shared-pptx';\nimport { designColors } from '@json-to-office/shared';\nimport type {\n GridConfig,\n GridPosition,\n PipelineWarning,\n PptxComponentInput,\n PptxThemeConfig,\n PresentationComponentDefinition,\n ProcessedPresentation,\n TextStyle,\n} from '../types';\nimport { resolveColor } from '../utils/color';\nimport { resolveGridPosition } from '../core/grid';\nimport { resolveThemeContext } from '../core/generationContext';\nimport { processPresentation } from '../core/structure';\nimport {\n blockSlotBudgets,\n blockSlotRoles,\n expandPptxBlocks,\n toAuthoredPointer,\n type BlockSourceMap,\n} from '../blocks';\nimport { defaultLineHeightPt, estimateTextLines } from '../utils/textMetrics';\nimport type { BlockSlotRole } from '@json-to-office/shared';\n\ntype Rec = Record<string, unknown>;\n\nexport interface PptxCanvasFact extends QualityFact {\n kind: 'pptx/canvas';\n widthIn?: number;\n heightIn?: number;\n}\n\nexport interface PptxTextFact extends QualityFact {\n kind: 'pptx/text';\n slidePath: string;\n text: string;\n fontSizePt: number;\n lineSpacingPt: number;\n paraSpaceBeforePt: number;\n paraSpaceAfterPt: number;\n styleName?: string;\n boxXPt?: number;\n boxYPt?: number;\n boxWidthPt?: number;\n boxHeightPt?: number;\n verticalAlign: 'top' | 'middle' | 'bottom';\n /** Horizontal alignment: the prop, else the named style's, else left. */\n align: 'left' | 'center' | 'right' | 'justify';\n rotationDeg: number;\n /**\n * True when neither `h` nor a grid supplies a height. The compiler resolves\n * grid positions before checking `props.h`, so grid height is a hard ceiling.\n */\n autoFit: boolean;\n /** Effective bold, from the run or its named style. */\n bold: boolean;\n /** Resolved run colour, bare hex, when the document states one. */\n colorHex?: string;\n /**\n * Every colour the surface behind this text can paint, bare hex. A gradient\n * contributes each stop: text has to stay legible over all of them, and the\n * worst stop is the one a reader notices.\n */\n backgroundHexes?: readonly string[];\n}\n\nexport interface PptxSlideFact extends QualityFact {\n kind: 'pptx/slide';\n bodyWords: number;\n}\n\n/** A box drawn on a slide, in draw order — the input to the overlap rule. */\nexport interface PptxBoxFact extends QualityFact {\n kind: 'pptx/box';\n slidePath: string;\n componentName: string;\n /** Draw order within the slide; a higher value is painted later, on top. */\n order: number;\n /** Paints its whole rectangle: an image, a chart, a table, a filled shape. */\n opaque: boolean;\n xPt: number;\n yPt: number;\n widthPt: number;\n heightPt: number;\n}\n\n/** The resolved theme, as the brand rules see it. */\nexport interface PptxThemeFact extends QualityFact {\n kind: 'pptx/theme';\n themeName: string;\n /** Token name to `#RRGGBB`, for every palette entry that resolves. */\n paletteHexes: Readonly<Record<string, string>>;\n fontFamilies: readonly string[];\n}\n\n/** A colour written as a literal rather than as a theme token. */\nexport interface PptxColorFact extends QualityFact {\n kind: 'pptx/color';\n raw: string;\n hex: string;\n}\n\n/** A font family the document asks for by name. */\nexport interface PptxFontFact extends QualityFact {\n kind: 'pptx/font-family';\n family: string;\n}\n\n/**\n * A chart on a slide — native or Highcharts — read into the vocabulary the\n * information-design rules speak.\n */\nexport interface PptxChartFact extends QualityFact, ChartInfoDesign {\n kind: 'pptx/chart';\n /** `chart` or `highcharts`; the two answer the same questions differently. */\n componentName: string;\n /** Theme tokens a palette fix can name, in series order. */\n paletteTokens: readonly string[];\n}\n\n/** One authored cell of a slide table, and where a patch would rewrite it. */\nexport interface PptxTableCellRef {\n path: string;\n cell: string | Record<string, unknown>;\n}\n\nexport interface PptxTableColumnFact extends TableColumnInfoDesign {\n /** Every authored cell in this column, header first, in row order. */\n cells: readonly PptxTableCellRef[];\n}\n\nexport interface PptxTableFact extends QualityFact, TableInfoDesign {\n kind: 'pptx/table';\n columns: readonly PptxTableColumnFact[];\n}\n\n/** One authored string that reads as a placeholder rather than as content. */\nexport interface PptxPlaceholderFact extends QualityFact {\n kind: 'pptx/placeholder';\n text: string;\n placeholderKind: PlaceholderKind;\n pattern: string;\n excerpt: string;\n}\n\n/** One text slot of a block, counted against the budget the block declares. */\nexport interface PptxBlockSlotFact extends QualityFact {\n kind: 'pptx/block-slot';\n block: string;\n slot: string;\n words: number;\n maxWords: number;\n}\n\n/**\n * A role-bearing slot of a block invocation, present or not. A profile reads\n * these to require a source under every chart or to measure an action title;\n * the theme that styles them never adds a requirement.\n */\nexport interface PptxChromeSlotFact extends QualityFact {\n kind: 'pptx/chrome-slot';\n block: string;\n /** Authored pointer of the invocation. */\n invocation: string;\n slot: string;\n role: BlockSlotRole;\n present: boolean;\n text?: string;\n /** Lines the slot's text takes in the box the definition gave it. */\n estimatedLines?: number;\n fontSizePt?: number;\n}\n\nexport type PptxQualityFact =\n | PptxCanvasFact\n | PptxBlockSlotFact\n | PptxChromeSlotFact\n | PptxTextFact\n | PptxSlideFact\n | PptxPlaceholderFact\n | PptxBoxFact\n | PptxThemeFact\n | PptxColorFact\n | PptxFontFact\n | PptxChartFact\n | PptxTableFact;\n\nexport interface PptxQualityModel {\n authored: PresentationComponentDefinition;\n /** The document after the export-mode pre-pass and block expansion. */\n document: PresentationComponentDefinition;\n theme: PptxThemeConfig;\n processed: ProcessedPresentation;\n}\n\n/** What `PreparedDocument.metadata.blocks` carries once a block expanded. */\nexport interface PptxBlocksMetadata {\n /** Compiled pointer → authored pointer. */\n sourceMap: BlockSourceMap;\n /** Authored pointers of the expanded blocks. */\n blocks: readonly string[];\n /** The compiled form: the document with every block lowered in place. */\n document: PresentationComponentDefinition;\n}\n\nexport interface PreparePptxQualityOptions {\n customThemes?: Record<string, PptxThemeConfig>;\n fonts?: FontRuntimeOpts;\n services?: ServicesConfig;\n warnings?: PipelineWarning[];\n renderer?: string;\n}\n\ninterface ThemeContext {\n styles: Partial<Record<string, TextStyle>>;\n defaultFontSize: number;\n}\n\ninterface Typography {\n fontSize: number;\n lineSpacing: number;\n paraSpaceBefore: number;\n paraSpaceAfter: number;\n bold: boolean;\n styleName?: string;\n}\n\ninterface TextNode {\n props: Rec;\n path: string;\n text: string;\n /** Draw order on the slide, shared with `Surface`. */\n order: number;\n}\n\ninterface ComponentAtPath {\n component: PptxComponentInput;\n path: string;\n}\n\nfunction asRecord(value: unknown): Rec | undefined {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n ? (value as Rec)\n : undefined;\n}\n\nfunction asNumber(value: unknown): number | undefined {\n return typeof value === 'number' && Number.isFinite(value)\n ? value\n : undefined;\n}\n\n/** An x/y/w/h prop in points: inches as numbers, `\"NN%\"` of the axis. */\nfunction dimToPt(value: unknown, axisIn: number): number | undefined {\n if (typeof value === 'number' && Number.isFinite(value)) return value * 72;\n if (typeof value === 'string') {\n const trimmed = value.trim();\n if (trimmed.endsWith('%')) {\n const pct = Number(trimmed.slice(0, -1));\n return Number.isFinite(pct) ? (pct / 100) * axisIn * 72 : undefined;\n }\n const inches = Number(trimmed);\n return Number.isFinite(inches) ? inches * 72 : undefined;\n }\n return undefined;\n}\n\ninterface Box {\n xPt: number;\n yPt: number;\n widthPt: number;\n heightPt: number;\n}\n\n/** Absolute box in points, falling back to the grid when x/y/w/h are absent. */\nfunction resolveBox(\n props: Rec,\n grid: GridConfig | undefined,\n slideWidthIn: number,\n slideHeightIn: number\n): Partial<Box> {\n let xPt = dimToPt(props.x, slideWidthIn);\n let yPt = dimToPt(props.y, slideHeightIn);\n let widthPt = dimToPt(props.w, slideWidthIn);\n let heightPt = dimToPt(props.h, slideHeightIn);\n const gridPos = asRecord(props.grid);\n if (\n gridPos !== undefined &&\n asNumber(gridPos.column) !== undefined &&\n asNumber(gridPos.row) !== undefined &&\n (xPt === undefined ||\n yPt === undefined ||\n widthPt === undefined ||\n heightPt === undefined)\n ) {\n const resolved = resolveGridPosition(\n gridPos as unknown as GridPosition,\n grid,\n slideWidthIn,\n slideHeightIn\n );\n xPt ??= resolved.x * 72;\n yPt ??= resolved.y * 72;\n widthPt ??= resolved.w * 72;\n heightPt ??= resolved.h * 72;\n }\n return { xPt, yPt, widthPt, heightPt };\n}\n\nfunction isCompleteBox(box: Partial<Box>): box is Box {\n return (\n box.xPt !== undefined &&\n box.yPt !== undefined &&\n box.widthPt !== undefined &&\n box.heightPt !== undefined &&\n box.widthPt > 0 &&\n box.heightPt > 0\n );\n}\n\nfunction containsCentre(surface: Box, text: Box): boolean {\n const cx = text.xPt + text.widthPt / 2;\n const cy = text.yPt + text.heightPt / 2;\n return (\n cx >= surface.xPt &&\n cx <= surface.xPt + surface.widthPt &&\n cy >= surface.yPt &&\n cy <= surface.yPt + surface.heightPt\n );\n}\n\nconst HORIZONTAL_ALIGNMENTS = new Set(['left', 'center', 'right', 'justify']);\n\nfunction horizontalAlign(props: Rec, ctx: ThemeContext): PptxTextFact['align'] {\n const own = typeof props.align === 'string' ? props.align : undefined;\n if (own && HORIZONTAL_ALIGNMENTS.has(own))\n return own as PptxTextFact['align'];\n const styled =\n typeof props.style === 'string'\n ? ctx.styles[props.style]?.align\n : undefined;\n return styled && HORIZONTAL_ALIGNMENTS.has(styled)\n ? (styled as PptxTextFact['align'])\n : 'left';\n}\n\nfunction themeContext(theme: PptxThemeConfig): ThemeContext {\n return {\n styles: theme.styles ?? {},\n defaultFontSize: asNumber(theme.defaults?.fontSize) ?? 18,\n };\n}\n\n/**\n * Every colour a fill can paint, resolved to bare hex.\n *\n * Deliberately structural rather than typed against one fill shape: solid\n * fills, gradients and their stops all nest `color` somewhere, and a background\n * that paints no colour at all (an image) yields nothing, which is the honest\n * answer — the rule then stays quiet instead of guessing at a photograph.\n */\nfunction fillColorHexes(fill: unknown, theme: PptxThemeConfig): string[] {\n const found: string[] = [];\n const visit = (node: unknown): void => {\n if (Array.isArray(node)) {\n node.forEach(visit);\n return;\n }\n const rec = asRecord(node);\n if (!rec) return;\n if (typeof rec.color === 'string') {\n const hex = resolveColor(rec.color, theme);\n if (hex) found.push(hex.toUpperCase());\n }\n for (const value of Object.values(rec)) {\n if (typeof value === 'object' && value !== null) visit(value);\n }\n };\n visit(fill);\n return [...new Set(found)];\n}\n\nconst FOCUS_CORNERS: Readonly<Record<string, readonly [number, number]>> = {\n topLeft: [0, 0],\n topRight: [1, 0],\n bottomLeft: [0, 1],\n bottomRight: [1, 1],\n};\n\nfunction lerpHex(a: string, b: string, t: number): string {\n const pa = parseInt(a, 16);\n const pb = parseInt(b, 16);\n const mix = (shift: number): number =>\n Math.round(\n ((pa >> shift) & 255) +\n (((pb >> shift) & 255) - ((pa >> shift) & 255)) * t\n );\n return [mix(16), mix(8), mix(0)]\n .map((c) => c.toString(16).padStart(2, '0'))\n .join('')\n .toUpperCase();\n}\n\n/**\n * Where along a gradient the point (fx, fy) — both 0..1 across the surface —\n * falls. Radial gradients run outward from the named corner; linear ones run\n * along `angle`, measured clockwise from the x-axis with y pointing down.\n *\n * The radial radius is half the surface's diagonal in real units, which is not\n * an obvious choice — it is the one the renderer makes. Sampling the rendered\n * gradient across a 10 × 5.625in slide put the last stop at exactly half the\n * diagonal from the focus corner, and reproduced every probe: the corner\n * opposite the focus, the two edge midpoints (which a shape-independent model\n * gets wrong, because equal distances in normalized space are unequal on a\n * wide slide), and the centre.\n */\nfunction gradientPosition(\n gradient: Rec,\n fx: number,\n fy: number,\n widthUnits: number,\n heightUnits: number\n): number {\n if (gradient.type === 'radial') {\n const focus =\n FOCUS_CORNERS[\n typeof gradient.focus === 'string' ? gradient.focus : 'topLeft'\n ] ?? FOCUS_CORNERS.topLeft;\n const radius = Math.hypot(widthUnits, heightUnits) / 2;\n if (radius === 0) return 0;\n const distance = Math.hypot(\n (fx - focus[0]) * widthUnits,\n (fy - focus[1]) * heightUnits\n );\n return Math.min(1, distance / radius);\n }\n const angle = ((asNumber(gradient.angle) ?? 0) * Math.PI) / 180;\n const dx = Math.cos(angle);\n const dy = Math.sin(angle);\n const min = Math.min(0, dx) + Math.min(0, dy);\n const max = Math.max(0, dx) + Math.max(0, dy);\n if (max === min) return 0;\n return Math.min(1, Math.max(0, (fx * dx + fy * dy - min) / (max - min)));\n}\n\n/**\n * The colour a fill actually paints at (fx, fy).\n *\n * Sampling matters for gradients: taking the worst stop instead would fail\n * black text against the blue end of a background whose peach end it never\n * touches, and every slide over a two-tone ground would carry a finding for\n * one colour or the other.\n */\nfunction paintedColorHexes(\n fill: unknown,\n theme: PptxThemeConfig,\n fx: number,\n fy: number,\n widthUnits: number,\n heightUnits: number\n): string[] {\n const rec = asRecord(fill);\n const gradient = asRecord(rec?.gradient);\n const stops = Array.isArray(gradient?.stops) ? gradient.stops : undefined;\n if (gradient && stops && stops.length > 0) {\n const parsed = stops\n .flatMap((stop) => {\n const entry = asRecord(stop);\n const color =\n typeof entry?.color === 'string' ? entry.color : undefined;\n if (!color) return [];\n const hex = resolveColor(color, theme);\n if (!hex) return [];\n return [{ pos: asNumber(entry?.pos) ?? 0, hex: hex.toUpperCase() }];\n })\n .sort((a, b) => a.pos - b.pos);\n if (parsed.length === 0) return [];\n const target =\n gradientPosition(gradient, fx, fy, widthUnits, heightUnits) * 100;\n if (target <= parsed[0].pos) return [parsed[0].hex];\n const last = parsed[parsed.length - 1];\n if (target >= last.pos) return [last.hex];\n for (let i = 1; i < parsed.length; i += 1) {\n const previous = parsed[i - 1];\n const next = parsed[i];\n if (target <= next.pos) {\n const span = next.pos - previous.pos;\n const t = span === 0 ? 0 : (target - previous.pos) / span;\n return [lerpHex(previous.hex, next.hex, t)];\n }\n }\n return [last.hex];\n }\n return fillColorHexes(fill, theme);\n}\n\n/** Effective type: explicit prop → named style → theme default. */\nfunction resolveTypography(props: Rec, ctx: ThemeContext): Typography {\n const styleName = typeof props.style === 'string' ? props.style : undefined;\n const style = styleName !== undefined ? ctx.styles[styleName] : undefined;\n const fontSize =\n asNumber(props.fontSize) ?? style?.fontSize ?? ctx.defaultFontSize;\n const multiple = asNumber(props.lineSpacingMultiple);\n const lineSpacing =\n multiple !== undefined\n ? fontSize * multiple\n : asNumber(props.lineSpacing) ??\n style?.lineSpacing ??\n defaultLineHeightPt(fontSize);\n\n // WCAG treats bold text as large from 14pt, so weight has to survive the\n // same explicit-prop -> named-style resolution the size does. `fontWeight`\n // wins over `bold` in the renderer, so it wins here too.\n const weight = asNumber(props.fontWeight) ?? style?.fontWeight;\n const bold =\n weight !== undefined\n ? weight >= 600\n : typeof props.bold === 'boolean'\n ? props.bold\n : style?.bold ?? false;\n\n return {\n fontSize,\n lineSpacing,\n paraSpaceBefore: asNumber(props.paraSpaceBefore) ?? 0,\n paraSpaceAfter:\n asNumber(props.paraSpaceAfter) ?? style?.paraSpaceAfter ?? 0,\n bold,\n ...(styleName && { styleName }),\n };\n}\n\n/**\n * Anything that paints over the slide surface, in the order it is drawn.\n * `colorHexes` is empty for an image — it covers the background without\n * telling us what colour it puts there.\n */\ninterface Surface {\n order: number;\n props: Rec;\n isImage: boolean;\n}\n\n/** Components that paint their whole rectangle, whatever is underneath. */\nconst OPAQUE_COMPONENTS = new Set([\n 'table',\n 'chart',\n 'highcharts',\n 'image',\n 'visual',\n]);\n\n/** Shape types whose ink is the whole bounding box. */\nconst RECTANGULAR_SHAPES = new Set(['rect', 'roundRect']);\n\n/**\n * Whether a fill actually covers what is under it.\n *\n * Any transparency at all disqualifies it: the reference decks stack a\n * primary-coloured disc under the same disc at 90% transparency, and a tinted\n * overlay is a technique rather than a collision. A gradient counts as opaque\n * only when none of its stops is see-through.\n */\nfunction isOpaqueFill(fill: unknown): boolean {\n const rec = asRecord(fill);\n if (!rec) return false;\n if ((asNumber(rec.transparency) ?? 0) > 0) return false;\n const gradient = asRecord(rec.gradient);\n if (gradient) {\n const stops = Array.isArray(gradient.stops) ? gradient.stops : [];\n return stops.every(\n (stop) => (asNumber(asRecord(stop)?.transparency) ?? 0) === 0\n );\n }\n return true;\n}\n\n/**\n * Whether this component hides whatever it is drawn over.\n *\n * A shape qualifies only when it is a rectangle with an opaque fill. An\n * ellipse, a pie wedge or a chevron leaves most of its bounding box empty —\n * the reference decks draw concentric circles and radial segments whose boxes\n * cross by design and whose ink never touches.\n */\nfunction isOpaqueComponent(componentName: string, props: Rec): boolean {\n if (OPAQUE_COMPONENTS.has(componentName)) return true;\n if (props.fill === undefined) return false;\n const type = typeof props.type === 'string' ? props.type : 'rect';\n return RECTANGULAR_SHAPES.has(type) && isOpaqueFill(props.fill);\n}\n\n/**\n * A component with a position, and whether it paints its whole box.\n *\n * Opacity, not \"is this content\", is the property the overlap rule can act\n * on. A text box is routinely declared far larger than the words inside it —\n * an 80pt title in a 5in box, a caption parked in the corner of a wide frame —\n * so two intersecting text rectangles say nothing about whether any ink\n * collides. Two intersecting *opaque* rectangles always hide each other.\n */\ninterface BoxNode {\n props: Rec;\n path: string;\n componentName: string;\n order: number;\n opaque: boolean;\n}\n\n/** A chart or a table: the two components the information-design rules read. */\ninterface ContentNode {\n props: Rec;\n path: string;\n componentName: string;\n}\n\n/**\n * One ordered pass over a slide's components: the text to analyse, the\n * surfaces drawn behind it, and every positioned box. All three need the same\n * z-order, and z-order is just the sequence the renderer walks, so they are\n * collected together rather than in passes that could disagree.\n */\nfunction collectSlideNodes(\n component: unknown,\n path: string,\n text: TextNode[],\n surfaces: Surface[],\n boxes: BoxNode[],\n contentNodes: ContentNode[],\n counter: { next: number }\n): void {\n const rec = asRecord(component);\n if (!rec || rec.enabled === false) return;\n const props = asRecord(rec.props) ?? {};\n const order = counter.next++;\n\n if (rec.name === 'image' || rec.name === 'visual' || rec.name === 'chart') {\n surfaces.push({ order, props, isImage: true });\n } else if (rec.name === 'shape' && props.fill !== undefined) {\n surfaces.push({ order, props, isImage: false });\n }\n\n const content = typeof props.text === 'string' ? props.text : undefined;\n if (\n content !== undefined &&\n content.trim() !== '' &&\n props.runs === undefined\n ) {\n if (rec.name === 'text' || rec.name === 'shape') {\n text.push({ props, path, text: content, order });\n }\n }\n\n const componentName = typeof rec.name === 'string' ? rec.name : '';\n if (\n componentName === 'chart' ||\n componentName === 'highcharts' ||\n componentName === 'table'\n ) {\n contentNodes.push({ props, path, componentName });\n }\n if (componentName !== '') {\n boxes.push({\n props,\n path,\n componentName,\n order,\n opaque: isOpaqueComponent(componentName, props),\n });\n }\n\n const children = Array.isArray(rec.children) ? rec.children : [];\n children.forEach((child, index) =>\n collectSlideNodes(\n child,\n `${path}/children/${index}`,\n text,\n surfaces,\n boxes,\n contentNodes,\n counter\n )\n );\n}\n\n/**\n * Theme slots that can carry a data series, in the order a palette hands them\n * out. `background`, `text` and their variants are excluded: they are the\n * ground and the ink, and a series painted in either disappears into the slide.\n */\nconst SERIES_COLOR_TOKENS: readonly string[] = [\n 'primary',\n 'accent',\n 'secondary',\n 'accent4',\n 'accent5',\n 'accent6',\n];\n\n/** A chart component, native or Highcharts, as the shared rules read it. */\nfunction chartFact(\n node: ContentNode,\n paletteTokens: readonly string[]\n): PptxChartFact | undefined {\n const { props, path } = node;\n const base = {\n id: `pptx:chart:${path}`,\n kind: 'pptx/chart' as const,\n path,\n componentName: node.componentName,\n paletteTokens,\n };\n\n if (node.componentName === 'highcharts') {\n const shape = normalizeHighchartsChart(props.options);\n return {\n ...base,\n chartType: shape.chartType,\n encoding: shape.encoding,\n threeD: shape.threeD,\n seriesCount: shape.seriesCount,\n categoryCount: shape.categoryCount,\n seriesColorsStated: shape.seriesColorsStated,\n seriesColorsPath: `${path}/props/options`,\n ...(shape.valueAxisMin !== undefined && {\n valueAxisMin: shape.valueAxisMin,\n }),\n unitStated: shape.unitStated,\n annotation: {\n stated: shape.annotationStated,\n path,\n slot: 'props.options.caption.text',\n },\n };\n }\n\n const chartType = typeof props.type === 'string' ? props.type : '';\n if (chartType === '') return undefined;\n const series = Array.isArray(props.data) ? props.data : [];\n const categoryCount = Math.max(\n 0,\n ...series.map((entry) => {\n const record = asRecord(entry);\n const labels = Array.isArray(record?.labels) ? record.labels.length : 0;\n const values = Array.isArray(record?.values) ? record.values.length : 0;\n return Math.max(labels, values);\n })\n );\n\n return {\n ...base,\n chartType,\n encoding: chartEncodingFor(chartType),\n threeD: chartType.endsWith('3D'),\n seriesCount: series.length,\n categoryCount,\n seriesColorsStated:\n Array.isArray(props.chartColors) && props.chartColors.length > 0,\n seriesColorsPath: `${path}/props/chartColors`,\n ...(asNumber(props.valAxisMinVal) !== undefined && {\n valueAxisMin: asNumber(props.valAxisMinVal),\n }),\n // A percent-stacked bar and percent data labels both state the unit as\n // surely as an axis title does — the numbers are shares, and the chart\n // says so on its face.\n unitStated:\n (typeof props.valAxisLabelFormatCode === 'string' &&\n props.valAxisLabelFormatCode.trim() !== '') ||\n props.showPercent === true ||\n props.barGrouping === 'percentStacked' ||\n hasUnitMarker(\n typeof props.valAxisTitle === 'string' ? props.valAxisTitle : ''\n ) ||\n hasUnitMarker(typeof props.title === 'string' ? props.title : ''),\n // No `annotation`: a native slide chart has no caption or source property,\n // and a rule that judges a slot the component does not have is a rule\n // nobody can satisfy.\n };\n}\n\n/** The text a slide-table cell shows, whichever of its two shapes it takes. */\nfunction cellText(cell: unknown): string {\n if (typeof cell === 'string') return cell;\n const record = asRecord(cell);\n return typeof record?.text === 'string' ? record.text : '';\n}\n\nconst PPTX_ALIGNMENTS = new Set(['left', 'center', 'right', 'justify']);\n\nfunction cellAlignment(cell: unknown, tableDefault: TableAlignment) {\n const record = asRecord(cell);\n const align = typeof record?.align === 'string' ? record.align : undefined;\n return align !== undefined && PPTX_ALIGNMENTS.has(align)\n ? (align as TableAlignment)\n : tableDefault;\n}\n\n/**\n * A slide table, column by column, out of a row-major model.\n *\n * Row 0 counts as a header when the table says so, and also when it is plainly\n * one: no cell in it parses as a number while the table has body rows to\n * compare. `headerRow` is optional in the schema and routinely left off, and\n * reading a label row as data would hide exactly the columns most likely to\n * have been laid out without thought.\n *\n * A table with merged cells is described without columns: a `colspan` breaks\n * the correspondence between an index and a visual column, and every column\n * finding below is about what sits under what.\n */\nfunction tableFact(\n node: ContentNode,\n slidePath: string,\n authoredProps: Rec | undefined\n): PptxTableFact | undefined {\n const { props, path } = node;\n const rows = Array.isArray(props.rows) ? props.rows : undefined;\n if (!rows || rows.length === 0) return undefined;\n\n // The *authored* border, not the resolved one. Every theme gives tables a\n // rule between cells, so a resolved-border test would report one finding per\n // table for a decision taken once, in the theme, for the whole document.\n // What this rule can say something about is a table that asks for a box of\n // its own.\n const border = asRecord(authoredProps?.border);\n const fullGrid =\n border !== undefined &&\n border.type !== 'none' &&\n (asNumber(border.pt) ?? 1) > 0;\n\n const merged = rows.some(\n (row) =>\n Array.isArray(row) &&\n row.some((cell) => {\n const record = asRecord(cell);\n return record?.colspan !== undefined || record?.rowspan !== undefined;\n })\n );\n\n const base = {\n id: `pptx:table:${path}`,\n kind: 'pptx/table' as const,\n path,\n relatedPaths: [slidePath],\n rowCount: rows.length,\n fullGrid,\n ...(fullGrid && { gridPath: `${path}/props/border` }),\n };\n if (merged) return { ...base, columns: [] };\n\n const cellsOf = (row: unknown): unknown[] => (Array.isArray(row) ? row : []);\n const headerRow =\n props.headerRow === true ||\n (rows.length >= 3 &&\n cellsOf(rows[0]).every(\n (cell) => parseNumericCell(cellText(cell)) === undefined\n ));\n const bodyStart = headerRow ? 1 : 0;\n const tableDefault: TableAlignment =\n typeof props.align === 'string' && PPTX_ALIGNMENTS.has(props.align)\n ? (props.align as TableAlignment)\n : 'left';\n\n const columnCount = Math.max(0, ...rows.map((row) => cellsOf(row).length));\n const columns: PptxTableColumnFact[] = [];\n for (let index = 0; index < columnCount; index += 1) {\n const cells: PptxTableCellRef[] = [];\n const values: string[] = [];\n const alignments = new Set<TableAlignment>();\n rows.forEach((row, rowIndex) => {\n const cell = cellsOf(row)[index];\n if (cell === undefined) return;\n cells.push({\n path: `${path}/props/rows/${rowIndex}/${index}`,\n cell: typeof cell === 'string' ? cell : asRecord(cell) ?? {},\n });\n if (rowIndex < bodyStart) return;\n values.push(cellText(cell));\n alignments.add(cellAlignment(cell, tableDefault));\n });\n const header = headerRow ? cellText(cellsOf(rows[0])[index]) : undefined;\n columns.push({\n index,\n // The top cell of the column. A row-major table has no node standing\n // for a column, and pointing every column of one table at `props/rows`\n // would give two findings the same address — indistinguishable to a\n // reader, and impossible to suppress one at a time.\n path: `${path}/props/rows/0/${index}`,\n ...(header !== undefined && { header }),\n values,\n alignment:\n alignments.size === 1\n ? [...alignments][0]\n : alignments.size === 0\n ? tableDefault\n : 'mixed',\n cells,\n });\n }\n return { ...base, columns };\n}\n\n/**\n * The `props` of the authored node at an RFC 6901 pointer.\n *\n * Facts are otherwise read off the processed tree, which is what the renderer\n * draws. A handful of questions are about what the *document* asked for rather\n * than what it inherited, and those need the authored node at the same pointer\n * the fact reports.\n */\nfunction authoredPropsAtPointer(\n root: unknown,\n pointer: string\n): Rec | undefined {\n let node: unknown = root;\n for (const token of pointer.split('/').slice(1)) {\n const key = token.replace(/~1/g, '/').replace(/~0/g, '~');\n if (Array.isArray(node)) {\n const index = Number(key);\n if (!Number.isInteger(index)) return undefined;\n node = node[index];\n } else {\n const record = asRecord(node);\n if (!record) return undefined;\n node = record[key];\n }\n if (node === undefined) return undefined;\n }\n return asRecord(asRecord(node)?.props);\n}\n\nfunction addSlideFacts(\n roots: ComponentAtPath[],\n slidePath: string,\n renderedIndex: number,\n grid: GridConfig | undefined,\n slideWidthIn: number,\n slideHeightIn: number,\n ctx: ThemeContext,\n theme: PptxThemeConfig,\n slideBackground: (fx: number, fy: number) => readonly string[],\n analyzedTextPaths: Set<string>,\n analyzedContentPaths: Set<string>,\n paletteTokens: readonly string[],\n authoredPropsAt: (path: string) => Rec | undefined,\n addFact: (fact: PptxQualityFact) => void\n): void {\n const nodes: TextNode[] = [];\n const surfaces: Surface[] = [];\n const boxes: BoxNode[] = [];\n const contentNodes: ContentNode[] = [];\n const counter = { next: 0 };\n for (const root of roots) {\n collectSlideNodes(\n root.component,\n root.path,\n nodes,\n surfaces,\n boxes,\n contentNodes,\n counter\n );\n }\n\n // Shared template objects reach every slide that uses the template; their\n // authored path is analysed once, exactly as text is.\n for (const node of contentNodes) {\n if (analyzedContentPaths.has(node.path)) continue;\n analyzedContentPaths.add(node.path);\n const fact =\n node.componentName === 'table'\n ? tableFact(node, slidePath, authoredPropsAt(node.path))\n : chartFact(node, paletteTokens);\n if (fact) addFact(fact);\n }\n boxes.forEach((node, boxIndex) => {\n const box = resolveBox(node.props, grid, slideWidthIn, slideHeightIn);\n if (!isCompleteBox(box)) return;\n addFact({\n id: `pptx:box:${renderedIndex}:${boxIndex}:${node.path}`,\n kind: 'pptx/box',\n path: node.path,\n slidePath,\n componentName: node.componentName,\n order: node.order,\n opaque: node.opaque,\n xPt: box.xPt,\n yPt: box.yPt,\n widthPt: box.widthPt,\n heightPt: box.heightPt,\n });\n });\n const surfaceBoxes = surfaces.flatMap((surface) => {\n const box = resolveBox(surface.props, grid, slideWidthIn, slideHeightIn);\n return isCompleteBox(box) ? [{ ...surface, box }] : [];\n });\n\n let bodyWords = 0;\n nodes.forEach((node, nodeIndex) => {\n const typography = resolveTypography(node.props, ctx);\n if (\n typography.styleName !== 'title' &&\n typography.styleName !== 'subtitle'\n ) {\n bodyWords += node.text.split(/\\s+/).filter(Boolean).length;\n }\n\n // Shared template objects count toward every slide's density, but their\n // authored path should be analyzed only once.\n if (analyzedTextPaths.has(node.path)) return;\n analyzedTextPaths.add(node.path);\n\n const gridPos = asRecord(node.props.grid);\n const nodeBox = resolveBox(node.props, grid, slideWidthIn, slideHeightIn);\n const {\n xPt: boxXPt,\n yPt: boxYPt,\n widthPt: boxWidthPt,\n heightPt: boxHeightPt,\n } = nodeBox;\n\n // What the text actually sits on: its own shape fill, else the topmost\n // earlier-drawn surface covering its centre, else the slide itself.\n // Skipping the occlusion step reads every white-on-blue card as white on\n // the slide's white ground, which is how a contrast rule earns a reputation\n // for crying wolf.\n // Sample the whole box, not just its middle. A text block laid across a\n // gradient has a legibility problem at its worst end, and a centre sample\n // reports the average — which is exactly the point where neither the light\n // nor the dark half of the ground is represented.\n const sampleFractions = (\n box: Partial<Box>,\n originX: number,\n originY: number,\n widthPt: number,\n heightPt: number\n ): Array<readonly [number, number]> => {\n if (!isCompleteBox(box) || widthPt <= 0 || heightPt <= 0) {\n return [[0.5, 0.5]];\n }\n const x0 = (box.xPt - originX) / widthPt;\n const x1 = (box.xPt + box.widthPt - originX) / widthPt;\n const y0 = (box.yPt - originY) / heightPt;\n const y1 = (box.yPt + box.heightPt - originY) / heightPt;\n return [\n [(x0 + x1) / 2, (y0 + y1) / 2],\n [x0, y0],\n [x1, y0],\n [x0, y1],\n [x1, y1],\n ];\n };\n const slideSamples = sampleFractions(\n nodeBox,\n 0,\n 0,\n slideWidthIn * 72,\n slideHeightIn * 72\n );\n // A node's own fill spans the node, not the slide, so it is sampled in the\n // node's own box. Reusing the slide fractions here would read a shape's\n // gradient at the shape's position on the slide — a shape an inch into a\n // 13in canvas would never reach its own later stops.\n const ownFill = [\n ...new Set(\n sampleFractions(\n nodeBox,\n boxXPt ?? 0,\n boxYPt ?? 0,\n boxWidthPt ?? 0,\n boxHeightPt ?? 0\n ).flatMap(([fx, fy]) =>\n paintedColorHexes(\n node.props.fill,\n theme,\n fx,\n fy,\n (boxWidthPt ?? 0) / 72,\n (boxHeightPt ?? 0) / 72\n )\n )\n ),\n ];\n let backgroundHexes: readonly string[] = [\n ...new Set(slideSamples.flatMap(([fx, fy]) => slideBackground(fx, fy))),\n ];\n let backgroundUnknown = false;\n if (ownFill.length > 0) {\n backgroundHexes = ownFill;\n } else if (isCompleteBox(nodeBox)) {\n const covering = surfaceBoxes\n .filter(\n (surface) =>\n surface.order < node.order && containsCentre(surface.box, nodeBox)\n )\n .pop();\n if (covering?.isImage) {\n // An image covers the ground but says nothing about its colour.\n backgroundUnknown = true;\n } else if (covering) {\n // Sample within the covering shape's own box, not the slide's.\n const fill = [\n ...new Set(\n sampleFractions(\n nodeBox,\n covering.box.xPt,\n covering.box.yPt,\n covering.box.widthPt,\n covering.box.heightPt\n ).flatMap(([fx, fy]) =>\n paintedColorHexes(\n covering.props.fill,\n theme,\n fx,\n fy,\n covering.box.widthPt / 72,\n covering.box.heightPt / 72\n )\n )\n ),\n ];\n if (fill.length > 0) backgroundHexes = fill;\n else backgroundUnknown = true;\n }\n }\n const colorHex =\n typeof node.props.color === 'string'\n ? resolveColor(node.props.color, theme)?.toUpperCase()\n : undefined;\n\n addFact({\n id: `pptx:text:${renderedIndex}:${nodeIndex}:${node.path}`,\n kind: 'pptx/text',\n path: node.path,\n slidePath,\n text: node.text,\n fontSizePt: typography.fontSize,\n lineSpacingPt: typography.lineSpacing,\n paraSpaceBeforePt: typography.paraSpaceBefore,\n paraSpaceAfterPt: typography.paraSpaceAfter,\n ...(typography.styleName && { styleName: typography.styleName }),\n ...(boxXPt !== undefined && { boxXPt }),\n ...(boxYPt !== undefined && { boxYPt }),\n ...(boxWidthPt !== undefined && boxWidthPt > 0 && { boxWidthPt }),\n ...(boxHeightPt !== undefined && boxHeightPt > 0 && { boxHeightPt }),\n verticalAlign:\n node.props.valign === 'middle' || node.props.valign === 'bottom'\n ? node.props.valign\n : 'top',\n align: horizontalAlign(node.props, ctx),\n rotationDeg: asNumber(node.props.rotate) ?? 0,\n bold: typography.bold,\n autoFit: node.props.h === undefined && gridPos === undefined,\n ...(colorHex !== undefined && { colorHex }),\n ...(!backgroundUnknown &&\n backgroundHexes.length > 0 && { backgroundHexes }),\n });\n });\n\n addFact({\n id: `pptx:slide:${renderedIndex}:${slidePath}`,\n kind: 'pptx/slide',\n path: slidePath,\n bodyWords,\n });\n}\n\nexport function preparePptxQualityDocument(\n document: PresentationComponentDefinition,\n options: PreparePptxQualityOptions = {}\n): PreparedDocument<PptxQualityModel, PptxQualityFact> {\n const facts: PptxQualityFact[] = [];\n const provenance: Record<string, ProvenanceMap[string]> = {};\n // Blocks lower here, once, for every consumer: the facts below, the\n // compiler and the renderers all read the expanded tree. A fact raised on a\n // compiled child is reported at the authored slot it came from, so a\n // finding inside a block points at what the author wrote, never at a node\n // they never saw.\n let sourceMap: BlockSourceMap = {};\n const authoredPath = (path: string): string =>\n toAuthoredPointer(sourceMap, path);\n const addFact = (raw: PptxQualityFact): void => {\n const fact: PptxQualityFact = {\n ...raw,\n path: authoredPath(raw.path),\n ...(raw.relatedPaths && {\n relatedPaths: raw.relatedPaths.map(authoredPath),\n }),\n };\n facts.push(fact);\n provenance[fact.id] = {\n path: fact.path,\n ...(fact.relatedPaths && { relatedPaths: fact.relatedPaths }),\n };\n };\n\n const props = asRecord(document.props) ?? {};\n addFact({\n id: 'pptx:canvas',\n kind: 'pptx/canvas',\n path: '/props',\n ...(asNumber(props.slideWidth) !== undefined && {\n widthIn: asNumber(props.slideWidth),\n }),\n ...(asNumber(props.slideHeight) !== undefined && {\n heightIn: asNumber(props.slideHeight),\n }),\n });\n\n // Over the authored tree, before any theme or template resolution: a marker\n // has to be reported where the author can patch it out.\n collectPlaceholders(document).forEach((occurrence, index) => {\n addFact({\n id: `pptx:placeholder:${index}:${occurrence.path}`,\n kind: 'pptx/placeholder',\n path: occurrence.path,\n text: occurrence.text,\n placeholderKind: occurrence.match.kind,\n pattern: occurrence.match.pattern,\n excerpt: occurrence.match.excerpt,\n });\n });\n\n collectColorLiterals(document).forEach((literal, index) => {\n addFact({\n id: `pptx:color:${index}:${literal.path}`,\n kind: 'pptx/color',\n path: literal.path,\n raw: literal.raw,\n hex: literal.hex,\n });\n });\n\n collectFontFamilies(document).forEach((use, index) => {\n addFact({\n id: `pptx:font:${index}:${use.path}`,\n kind: 'pptx/font-family',\n path: use.path,\n family: use.family,\n });\n });\n\n const warnings = options.warnings ?? [];\n const context = resolveThemeContext(document, {\n customThemes: options.customThemes,\n fonts: options.fonts,\n warnings,\n });\n const expanded = expandPptxBlocks(context.document, context.theme);\n sourceMap = expanded.sourceMap;\n const processed = processPresentation(expanded.document, {\n theme: context.theme,\n customThemes: options.customThemes,\n services: options.services,\n sourceMap,\n warnings,\n });\n const ctx = themeContext(processed.theme);\n\n const paletteHexes: Record<string, string> = {};\n const visualColors = designColors(\n processed.theme.colors,\n processed.theme.palette\n );\n const entries = {\n ...visualColors,\n ...Object.fromEntries(\n (processed.theme.palette?.chart ?? []).map((value) => [\n `#${resolveColor(value, processed.theme)}`,\n value,\n ])\n ),\n };\n for (const [token, value] of Object.entries(entries)) {\n if (typeof value !== 'string') continue;\n // Through `resolveColor` so a slot naming another slot lands on the colour\n // it actually paints, not on the token name it stores.\n const hex = normalizeHex(resolveColor(value, processed.theme));\n // New palette roles are theme-only, outside the component color enum.\n // Quality fixes must offer a legal literal for those colors.\n if (hex)\n paletteHexes[\n (SEMANTIC_COLOR_NAMES as readonly string[]).includes(token)\n ? token\n : hex\n ] = hex;\n }\n addFact({\n id: 'pptx:theme',\n kind: 'pptx/theme',\n path: '/props',\n themeName: processed.theme.name,\n paletteHexes,\n fontFamilies: [\n ...new Set(\n [processed.theme.fonts?.heading, processed.theme.fonts?.body].filter(\n (family): family is string =>\n typeof family === 'string' && family.trim() !== ''\n )\n ),\n ],\n });\n const authoredChildren = Array.isArray(document.children)\n ? document.children\n : [];\n const slideIndexes = authoredChildren.flatMap((child, index) => {\n const slide = asRecord(child);\n return slide?.name === 'slide' && slide.enabled !== false ? [index] : [];\n });\n const analyzedTextPaths = new Set<string>();\n const analyzedContentPaths = new Set<string>();\n const paletteTokens =\n processed.theme.palette?.chart?.map(\n (value) => `#${resolveColor(value, processed.theme)}`\n ) ??\n SERIES_COLOR_TOKENS.filter((token) => paletteHexes[token] !== undefined);\n // A handful of questions are about what the document asked for rather than\n // what it inherited; for block content the authored node is the slot.\n const authoredPropsAt = (pointer: string): Rec | undefined =>\n authoredPropsAtPointer(document, authoredPath(pointer));\n\n processed.slides.forEach((slide, renderedIndex) => {\n const authoredIndex = slideIndexes[renderedIndex];\n if (authoredIndex === undefined) return;\n const slidePath = `/children/${authoredIndex}`;\n const roots: ComponentAtPath[] = slide.components.map(\n (component, index) => ({\n component,\n path: `${slidePath}/children/${index}`,\n })\n );\n\n addSlideFacts(\n roots,\n slidePath,\n renderedIndex,\n processed.grid,\n processed.slideWidth,\n processed.slideHeight,\n ctx,\n processed.theme,\n (fx, fy) =>\n paintedColorHexes(\n slide.background ?? props.background,\n processed.theme,\n fx,\n fy,\n processed.slideWidth,\n processed.slideHeight\n ),\n analyzedTextPaths,\n analyzedContentPaths,\n paletteTokens,\n authoredPropsAt,\n addFact\n );\n });\n\n for (const budget of blockSlotBudgets(context.document, expanded.blocks)) {\n addFact({\n id: `pptx:block-slot:${budget.path}`,\n kind: 'pptx/block-slot',\n ...budget,\n });\n }\n const slotTextNodes = textNodesBySlot(processed, slideIndexes, sourceMap);\n for (const role of blockSlotRoles(context.document, expanded.blocks)) {\n const present =\n role.value !== undefined &&\n role.value !== null &&\n role.value !== '' &&\n role.value !== false &&\n (!Array.isArray(role.value) || role.value.length > 0);\n const bound = slotTextNodes.get(role.path);\n let measured: { estimatedLines: number; fontSizePt: number } | undefined;\n if (bound && typeof bound.props.text === 'string') {\n const typography = resolveTypography(bound.props, ctx);\n const box = resolveBox(\n bound.props,\n processed.grid,\n processed.slideWidth,\n processed.slideHeight\n );\n if (box.widthPt !== undefined && box.widthPt > 0)\n measured = {\n estimatedLines: estimateTextLines(\n bound.props.text,\n box.widthPt,\n typography.fontSize\n ),\n fontSizePt: typography.fontSize,\n };\n }\n addFact({\n id: `pptx:chrome-slot:${role.path}`,\n kind: 'pptx/chrome-slot',\n path: role.path,\n relatedPaths: [role.invocation],\n block: role.block,\n invocation: role.invocation,\n slot: role.slot,\n role: role.role,\n present,\n ...(typeof role.value === 'string' && { text: role.value }),\n ...measured,\n });\n }\n\n return {\n format: 'pptx',\n model: {\n authored: document,\n document: expanded.document,\n theme: context.theme,\n processed,\n },\n facts,\n provenance,\n renderer: options.renderer ?? DEFAULT_PPTX_RENDERER_ID,\n ...(expanded.blocks.length > 0 && {\n metadata: {\n blocks: {\n sourceMap,\n blocks: expanded.blocks,\n document: expanded.document,\n } satisfies PptxBlocksMetadata,\n },\n }),\n };\n}\n\n/**\n * The processed text node each authored slot became, keyed by slot pointer.\n * Layout has already given every node its absolute box, so a slot's text can\n * be measured in the frame the definition drew for it.\n */\nfunction textNodesBySlot(\n processed: ProcessedPresentation,\n slideIndexes: readonly number[],\n sourceMap: BlockSourceMap\n): Map<string, { props: Rec }> {\n const found = new Map<string, { props: Rec }>();\n const visit = (component: PptxComponentInput, path: string): void => {\n if (component.enabled === false) return;\n if (component.name === 'text') {\n const origin = toAuthoredPointer(sourceMap, `${path}/props/text`);\n if (origin !== `${path}/props/text` && !found.has(origin))\n found.set(origin, { props: asRecord(component.props) ?? {} });\n }\n (component.children ?? []).forEach((child, index) =>\n visit(child, `${path}/children/${index}`)\n );\n };\n processed.slides.forEach((slide, renderedIndex) => {\n const authoredIndex = slideIndexes[renderedIndex];\n if (authoredIndex === undefined) return;\n slide.components.forEach((component, index) =>\n visit(component, `/children/${authoredIndex}/children/${index}`)\n );\n });\n return found;\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';\nimport { resolvePptxDesignSystem } from '../themes/design-system';\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 theme = resolvePptxDesignSystem(\n theme,\n document.props.slideWidth,\n document.props.slideHeight\n );\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 \"name\": \"consulting\",\n \"displayName\": \"Consulting House\",\n \"description\": \"The house style for decision decks — near-black ink, three greys and one deep-blue accent, Calibri body under Arial headings, hairline rules, no fills behind text, safe fonts only\",\n \"whenToUse\": \"Decision decks and client readouts: one message per slide, a chart that carries it, a source under it; the twin of the DOCX house theme, so a deck and its report match.\",\n \"version\": \"1.0.0\",\n \"colors\": {\n \"primary\": \"#1A1F26\",\n \"secondary\": \"#4B5563\",\n \"accent\": \"#1B4F8A\",\n \"background\": \"#FFFFFF\",\n \"text\": \"#1A1F26\",\n \"text2\": \"#4B5563\",\n \"background2\": \"#F2F4F7\",\n \"accent4\": \"#5B8DC9\",\n \"accent5\": \"#A9C4E4\",\n \"accent6\": \"#7B8794\"\n },\n \"palette\": {\n \"rule\": \"#C9CED6\",\n \"textMuted\": \"#7B8794\",\n \"onPrimary\": \"#FFFFFF\",\n \"surfaceInverse\": \"#1A1F26\",\n \"positive\": \"#1E7F4F\",\n \"negative\": \"#B42318\",\n \"chart\": [\"accent\", \"secondary\", \"accent4\", \"textMuted\", \"accent5\", \"rule\"]\n },\n \"fonts\": {\n \"heading\": \"Arial\",\n \"body\": \"Calibri\",\n \"mono\": \"Consolas\"\n },\n \"defaults\": {\n \"fontSize\": 14,\n \"fontColor\": \"#1A1F26\"\n },\n \"styles\": {\n \"title\": {\n \"fontSize\": 32,\n \"bold\": true,\n \"fontColor\": \"text\",\n \"align\": \"left\"\n },\n \"subtitle\": {\n \"fontSize\": 16,\n \"fontColor\": \"text2\",\n \"align\": \"left\"\n },\n \"heading1\": {\n \"fontSize\": 24,\n \"bold\": true,\n \"fontColor\": \"text\"\n },\n \"heading2\": {\n \"fontSize\": 18,\n \"bold\": true,\n \"fontColor\": \"text\"\n },\n \"heading3\": {\n \"fontSize\": 14,\n \"bold\": true,\n \"fontColor\": \"text2\"\n },\n \"body\": {\n \"fontSize\": 14,\n \"fontColor\": \"text\"\n },\n \"caption\": {\n \"fontSize\": 10,\n \"fontColor\": \"text2\"\n }\n },\n \"typography\": {\n \"roles\": {\n \"eyebrow\": {\n \"face\": \"heading\",\n \"size\": 10,\n \"weight\": 700,\n \"case\": \"upper\",\n \"tracking\": 8,\n \"color\": \"accent\"\n },\n \"display\": {\n \"face\": \"heading\",\n \"size\": 28,\n \"weight\": 700,\n \"color\": \"primary\",\n \"lineHeight\": 1.1\n },\n \"stat\": {\n \"face\": \"heading\",\n \"size\": 40,\n \"weight\": 700,\n \"color\": \"accent\",\n \"lineHeight\": 1\n },\n \"quote\": {\n \"face\": \"body\",\n \"size\": 18,\n \"color\": \"text2\",\n \"lineHeight\": 1.3\n },\n \"label\": {\n \"face\": \"body\",\n \"size\": 12,\n \"weight\": 700,\n \"color\": \"text2\"\n },\n \"footer\": {\n \"face\": \"body\",\n \"size\": 9,\n \"color\": \"text2\"\n },\n \"tableHeader\": {\n \"face\": \"body\",\n \"size\": 12,\n \"weight\": 700,\n \"color\": \"primary\"\n },\n \"tableCell\": {\n \"face\": \"body\",\n \"size\": 12,\n \"color\": \"text\"\n },\n \"chartLabel\": {\n \"face\": \"body\",\n \"size\": 11,\n \"weight\": 400,\n \"color\": \"text2\"\n },\n \"tracker\": {\n \"face\": \"body\",\n \"size\": 10,\n \"case\": \"upper\",\n \"tracking\": 6,\n \"color\": \"text2\"\n },\n \"source\": {\n \"face\": \"body\",\n \"size\": 9,\n \"color\": \"text2\"\n }\n },\n \"scale\": {\n \"wide169\": {\n \"base\": 14,\n \"ratio\": 1.2,\n \"baselinePt\": 2\n },\n \"standard43\": {\n \"base\": 14,\n \"ratio\": 1.2,\n \"baselinePt\": 2\n }\n }\n },\n \"spacing\": {\n \"basePt\": 8,\n \"blockGap\": {\n \"tight\": 4,\n \"normal\": 8,\n \"loose\": 16\n },\n \"canvas\": {\n \"wide169\": {\n \"safeAreaIn\": 0.5,\n \"gutterIn\": 0.2,\n \"columns\": 12,\n \"rows\": 8\n },\n \"standard43\": {\n \"safeAreaIn\": 0.5,\n \"gutterIn\": 0.2,\n \"columns\": 12,\n \"rows\": 8\n }\n }\n },\n \"chrome\": {\n \"runningHead\": {\n \"type\": \"tracker\",\n \"color\": \"text2\",\n \"rule\": {\n \"weightPt\": 0.5,\n \"color\": \"rule\"\n },\n \"alignment\": \"right\"\n },\n \"tracker\": {\n \"type\": \"tracker\",\n \"color\": \"text2\",\n \"alignment\": \"right\"\n },\n \"actionTitle\": {\n \"type\": \"display\",\n \"color\": \"primary\"\n },\n \"keyTakeaways\": {\n \"type\": \"label\",\n \"color\": \"primary\",\n \"rule\": {\n \"weightPt\": 2,\n \"color\": \"accent\"\n },\n \"padPt\": 8\n },\n \"sourceLine\": {\n \"type\": \"source\",\n \"color\": \"text2\"\n },\n \"confidentialFooter\": {\n \"type\": \"footer\",\n \"color\": \"text2\",\n \"rule\": {\n \"weightPt\": 0.5,\n \"color\": \"rule\"\n },\n \"alignment\": \"left\"\n },\n \"logoSlot\": {\n \"alignment\": \"right\"\n },\n \"cover\": {\n \"type\": \"display\",\n \"color\": \"primary\",\n \"rule\": {\n \"weightPt\": 3,\n \"color\": \"accent\"\n }\n }\n },\n \"motif\": {\n \"kind\": \"rule\",\n \"color\": \"accent\",\n \"weightPt\": 3,\n \"placement\": \"top\"\n },\n \"componentDefaults\": {\n \"table\": {\n \"border\": {\n \"type\": \"solid\",\n \"pt\": 0.5,\n \"color\": \"#C9CED6\"\n },\n \"headerRow\": true,\n \"fontSize\": 12\n },\n \"chart\": {\n \"showLegend\": true,\n \"legendPos\": \"b\",\n \"legendFontSize\": 11,\n \"catAxisLabelFontSize\": 11,\n \"valAxisLabelFontSize\": 11,\n \"catGridLine\": {\n \"style\": \"none\"\n },\n \"valGridLine\": {\n \"style\": \"solid\",\n \"size\": 0.5,\n \"color\": \"#E4E7EB\"\n },\n \"valAxisLineShow\": false\n }\n }\n}\n","/**\n * The consulting house theme, PPTX twin of `consulting.docx.theme.json`.\n *\n * Shares every visual token with the DOCX theme — ink, three greys, one deep\n * blue, positive/negative, the ordered chart series, Arial over Calibri with\n * Consolas for code — so a deck and its report match without restyling. A\n * guard test pins the agreement.\n *\n * Values only. The theme paints action titles, trackers, sources and footers\n * through its chrome recipes and type roles; whether a slide must carry them\n * is a quality profile's decision (`consulting-deck`), never the theme's.\n *\n * SAFE_FONTS only: nothing here needs a font registry on any Office install.\n *\n * One projection differs from the report: the small roles — footer, tracker,\n * source — and the chrome recipes that paint them take `text2` rather than\n * `textMuted`. On a projected slide a 9pt run in the light grey sits under\n * the 4.5 : 1 the contrast rule asks of small text; the darker grey passes it\n * and reads as the same voice. The agreement test knows this one substitution.\n */\n\nimport type { PptxThemeConfig } from '../types';\nimport consultingThemeJson from './consulting.pptx.theme.json';\n\n/**\n * Data, not code: the theme lives in `consulting.pptx.theme.json` so the\n * playground's theme discovery — a scan for `*.pptx.theme.json`, the way the\n * DOCX built-ins are found — lists it beside the deck. The bundled-themes test\n * validates the file against the theme schema and pins it to the DOCX twin.\n */\nexport const CONSULTING_PPTX_THEME: PptxThemeConfig =\n consultingThemeJson as PptxThemeConfig;\n","{\n \"name\": \"vermilion\",\n \"displayName\": \"Vermilion Editorial\",\n \"description\": \"Poster-red editorial deck — vermilion display titles, ink text, warm creams and hairline rules; the twin of the DOCX vermilion theme\",\n \"whenToUse\": \"Talks and readouts that want a strong red display voice beside a vermilion report: a few large titles, one figure per slide. Not for a dense data deck.\",\n \"version\": \"1.0.0\",\n \"colors\": {\n \"primary\": \"#282829\",\n \"secondary\": \"#58595B\",\n \"accent\": \"#EF4130\",\n \"background\": \"#FFFFFF\",\n \"text\": \"#282829\",\n \"text2\": \"#58595B\",\n \"background2\": \"#FAF7F5\",\n \"accent4\": \"#F4857A\",\n \"accent5\": \"#F9C4BE\",\n \"accent6\": \"#939598\"\n },\n \"palette\": {\n \"rule\": \"#C7C8CA\",\n \"textMuted\": \"#939598\",\n \"onPrimary\": \"#FFFFFF\",\n \"surfaceInverse\": \"#282829\",\n \"positive\": \"#2E7D4F\",\n \"negative\": \"#B42318\",\n \"chart\": [\"accent\", \"primary\", \"textMuted\", \"accent4\", \"rule\", \"accent5\"]\n },\n \"fonts\": {\n \"heading\": \"Arial\",\n \"body\": \"Calibri\",\n \"mono\": \"Courier New\"\n },\n \"defaults\": {\n \"fontSize\": 14,\n \"fontColor\": \"#282829\"\n },\n \"styles\": {\n \"title\": {\n \"fontSize\": 32,\n \"bold\": true,\n \"fontColor\": \"accent\",\n \"align\": \"left\"\n },\n \"subtitle\": {\n \"fontSize\": 16,\n \"fontColor\": \"text2\",\n \"align\": \"left\"\n },\n \"heading1\": {\n \"fontSize\": 24,\n \"bold\": true,\n \"fontColor\": \"accent\"\n },\n \"heading2\": {\n \"fontSize\": 18,\n \"bold\": true,\n \"fontColor\": \"text\"\n },\n \"heading3\": {\n \"fontSize\": 14,\n \"bold\": true,\n \"fontColor\": \"text2\"\n },\n \"body\": {\n \"fontSize\": 14,\n \"fontColor\": \"text\"\n },\n \"caption\": {\n \"fontSize\": 10,\n \"fontColor\": \"text2\"\n }\n },\n \"typography\": {\n \"roles\": {\n \"eyebrow\": {\n \"face\": \"heading\",\n \"size\": 10,\n \"weight\": 700,\n \"case\": \"upper\",\n \"tracking\": 8,\n \"color\": \"accent\"\n },\n \"display\": {\n \"face\": \"heading\",\n \"size\": 28,\n \"weight\": 700,\n \"color\": \"accent\",\n \"lineHeight\": 1.1\n },\n \"stat\": {\n \"face\": \"heading\",\n \"size\": 40,\n \"weight\": 700,\n \"color\": \"accent\",\n \"lineHeight\": 1\n },\n \"quote\": {\n \"face\": \"body\",\n \"size\": 18,\n \"color\": \"text2\",\n \"lineHeight\": 1.3\n },\n \"label\": {\n \"face\": \"body\",\n \"size\": 12,\n \"weight\": 700,\n \"color\": \"text2\"\n },\n \"footer\": {\n \"face\": \"body\",\n \"size\": 9,\n \"color\": \"text2\"\n },\n \"tableHeader\": {\n \"face\": \"body\",\n \"size\": 12,\n \"weight\": 700,\n \"color\": \"accent\"\n },\n \"tableCell\": {\n \"face\": \"body\",\n \"size\": 12,\n \"color\": \"text\"\n },\n \"chartLabel\": {\n \"face\": \"body\",\n \"size\": 11,\n \"weight\": 400,\n \"color\": \"text2\"\n },\n \"tracker\": {\n \"face\": \"body\",\n \"size\": 10,\n \"case\": \"upper\",\n \"tracking\": 6,\n \"color\": \"text2\"\n },\n \"source\": {\n \"face\": \"body\",\n \"size\": 9,\n \"color\": \"text2\"\n }\n },\n \"scale\": {\n \"wide169\": {\n \"base\": 14,\n \"ratio\": 1.2,\n \"baselinePt\": 2\n },\n \"standard43\": {\n \"base\": 14,\n \"ratio\": 1.2,\n \"baselinePt\": 2\n }\n }\n },\n \"spacing\": {\n \"basePt\": 8,\n \"blockGap\": {\n \"tight\": 4,\n \"normal\": 8,\n \"loose\": 16\n },\n \"canvas\": {\n \"wide169\": {\n \"safeAreaIn\": 0.5,\n \"gutterIn\": 0.2,\n \"columns\": 12,\n \"rows\": 8\n },\n \"standard43\": {\n \"safeAreaIn\": 0.5,\n \"gutterIn\": 0.2,\n \"columns\": 12,\n \"rows\": 8\n }\n }\n },\n \"chrome\": {\n \"runningHead\": {\n \"type\": \"tracker\",\n \"color\": \"text2\",\n \"rule\": {\n \"weightPt\": 0.5,\n \"color\": \"rule\"\n },\n \"alignment\": \"right\"\n },\n \"tracker\": {\n \"type\": \"tracker\",\n \"color\": \"text2\",\n \"alignment\": \"right\"\n },\n \"actionTitle\": {\n \"type\": \"display\",\n \"color\": \"accent\"\n },\n \"keyTakeaways\": {\n \"type\": \"label\",\n \"color\": \"primary\",\n \"rule\": {\n \"weightPt\": 1.5,\n \"color\": \"accent\"\n },\n \"padPt\": 8\n },\n \"sourceLine\": {\n \"type\": \"source\",\n \"color\": \"text2\"\n },\n \"confidentialFooter\": {\n \"type\": \"footer\",\n \"color\": \"text2\",\n \"rule\": {\n \"weightPt\": 0.5,\n \"color\": \"rule\"\n },\n \"alignment\": \"left\"\n },\n \"logoSlot\": {\n \"alignment\": \"right\"\n },\n \"cover\": {\n \"type\": \"display\",\n \"color\": \"accent\",\n \"rule\": {\n \"weightPt\": 4,\n \"color\": \"accent\"\n }\n }\n },\n \"motif\": {\n \"kind\": \"rule\",\n \"color\": \"accent\",\n \"weightPt\": 4,\n \"placement\": \"top\"\n },\n \"componentDefaults\": {\n \"table\": {\n \"border\": {\n \"type\": \"solid\",\n \"pt\": 0.5,\n \"color\": \"#C7C8CA\"\n },\n \"headerRow\": true,\n \"fontSize\": 12\n },\n \"chart\": {\n \"showLegend\": true,\n \"legendPos\": \"b\",\n \"legendFontSize\": 11,\n \"catAxisLabelFontSize\": 11,\n \"valAxisLabelFontSize\": 11,\n \"catGridLine\": {\n \"style\": \"none\"\n },\n \"valGridLine\": {\n \"style\": \"solid\",\n \"size\": 0.5,\n \"color\": \"#EFEAE4\"\n },\n \"valAxisLineShow\": false\n }\n }\n}\n","{\n \"name\": \"devportal\",\n \"displayName\": \"Field Editorial\",\n \"description\": \"Compact editorial deck — Helvetica in near-black ink with a burnt-orange accent, tight titles, letterspaced labels, warm tinted fills and hairline rules; the twin of the DOCX devportal theme\",\n \"whenToUse\": \"Product and engineering readouts, API and platform reviews: dense text, code and tables beside a devportal report. Not for a client's decision deck.\",\n \"version\": \"1.0.0\",\n \"colors\": {\n \"primary\": \"#12191F\",\n \"secondary\": \"#172028\",\n \"accent\": \"#E35B3F\",\n \"background\": \"#FFFFFF\",\n \"text\": \"#232323\",\n \"text2\": \"#46494C\",\n \"background2\": \"#F7ECE7\",\n \"accent4\": \"#46494C\",\n \"accent5\": \"#8A9299\",\n \"accent6\": \"#E8A18D\"\n },\n \"palette\": {\n \"rule\": \"#D8D5D1\",\n \"textMuted\": \"#737373\",\n \"onPrimary\": \"#FFFFFF\",\n \"surfaceInverse\": \"#12191F\",\n \"positive\": \"#2E7D4F\",\n \"negative\": \"#B42318\",\n \"chart\": [\"accent\", \"primary\", \"accent4\", \"accent5\", \"accent6\", \"rule\"]\n },\n \"fonts\": {\n \"heading\": \"Helvetica\",\n \"body\": \"Helvetica\",\n \"mono\": \"Courier New\"\n },\n \"defaults\": {\n \"fontSize\": 14,\n \"fontColor\": \"#232323\"\n },\n \"styles\": {\n \"title\": {\n \"fontSize\": 30,\n \"bold\": true,\n \"fontColor\": \"text\",\n \"align\": \"left\"\n },\n \"subtitle\": {\n \"fontSize\": 16,\n \"fontColor\": \"text2\",\n \"align\": \"left\"\n },\n \"heading1\": {\n \"fontSize\": 24,\n \"bold\": true,\n \"fontColor\": \"primary\"\n },\n \"heading2\": {\n \"fontSize\": 18,\n \"bold\": true,\n \"fontColor\": \"secondary\"\n },\n \"heading3\": {\n \"fontSize\": 14,\n \"bold\": true,\n \"fontColor\": \"text2\"\n },\n \"body\": {\n \"fontSize\": 14,\n \"fontColor\": \"text\"\n },\n \"caption\": {\n \"fontSize\": 10,\n \"fontColor\": \"text2\"\n }\n },\n \"typography\": {\n \"roles\": {\n \"eyebrow\": {\n \"face\": \"heading\",\n \"size\": 10,\n \"weight\": 700,\n \"case\": \"upper\",\n \"tracking\": 10,\n \"color\": \"accent\"\n },\n \"display\": {\n \"face\": \"heading\",\n \"size\": 28,\n \"weight\": 700,\n \"color\": \"primary\",\n \"lineHeight\": 1.1,\n \"tracking\": -2\n },\n \"stat\": {\n \"face\": \"heading\",\n \"size\": 40,\n \"weight\": 700,\n \"color\": \"accent\",\n \"lineHeight\": 1\n },\n \"quote\": {\n \"face\": \"body\",\n \"size\": 18,\n \"color\": \"text2\",\n \"lineHeight\": 1.3\n },\n \"label\": {\n \"face\": \"body\",\n \"size\": 12,\n \"weight\": 700,\n \"color\": \"text2\",\n \"case\": \"upper\",\n \"tracking\": 6\n },\n \"footer\": {\n \"face\": \"body\",\n \"size\": 9,\n \"color\": \"text2\"\n },\n \"tableHeader\": {\n \"face\": \"body\",\n \"size\": 12,\n \"weight\": 700,\n \"color\": \"secondary\"\n },\n \"tableCell\": {\n \"face\": \"body\",\n \"size\": 12,\n \"color\": \"text\"\n },\n \"chartLabel\": {\n \"face\": \"body\",\n \"size\": 11,\n \"weight\": 400,\n \"color\": \"text2\"\n },\n \"tracker\": {\n \"face\": \"body\",\n \"size\": 10,\n \"case\": \"upper\",\n \"tracking\": 6,\n \"color\": \"text2\"\n },\n \"source\": {\n \"face\": \"body\",\n \"size\": 9,\n \"color\": \"text2\"\n }\n },\n \"scale\": {\n \"wide169\": {\n \"base\": 14,\n \"ratio\": 1.2,\n \"baselinePt\": 2\n },\n \"standard43\": {\n \"base\": 14,\n \"ratio\": 1.2,\n \"baselinePt\": 2\n }\n }\n },\n \"spacing\": {\n \"basePt\": 8,\n \"blockGap\": {\n \"tight\": 4,\n \"normal\": 8,\n \"loose\": 16\n },\n \"canvas\": {\n \"wide169\": {\n \"safeAreaIn\": 0.5,\n \"gutterIn\": 0.2,\n \"columns\": 12,\n \"rows\": 8\n },\n \"standard43\": {\n \"safeAreaIn\": 0.5,\n \"gutterIn\": 0.2,\n \"columns\": 12,\n \"rows\": 8\n }\n }\n },\n \"chrome\": {\n \"runningHead\": {\n \"type\": \"tracker\",\n \"color\": \"text2\",\n \"rule\": {\n \"weightPt\": 0.5,\n \"color\": \"rule\"\n },\n \"alignment\": \"right\"\n },\n \"tracker\": {\n \"type\": \"tracker\",\n \"color\": \"text2\",\n \"alignment\": \"right\"\n },\n \"actionTitle\": {\n \"type\": \"display\",\n \"color\": \"primary\"\n },\n \"keyTakeaways\": {\n \"type\": \"label\",\n \"color\": \"primary\",\n \"rule\": {\n \"weightPt\": 1,\n \"color\": \"accent\"\n },\n \"padPt\": 8\n },\n \"sourceLine\": {\n \"type\": \"source\",\n \"color\": \"text2\"\n },\n \"confidentialFooter\": {\n \"type\": \"footer\",\n \"color\": \"text2\",\n \"rule\": {\n \"weightPt\": 0.5,\n \"color\": \"rule\"\n },\n \"alignment\": \"left\"\n },\n \"logoSlot\": {\n \"alignment\": \"right\"\n },\n \"cover\": {\n \"type\": \"display\",\n \"color\": \"primary\",\n \"rule\": {\n \"weightPt\": 3,\n \"color\": \"accent\"\n }\n }\n },\n \"motif\": {\n \"kind\": \"rule\",\n \"color\": \"accent\",\n \"weightPt\": 2,\n \"placement\": \"top\"\n },\n \"componentDefaults\": {\n \"table\": {\n \"border\": {\n \"type\": \"solid\",\n \"pt\": 0.5,\n \"color\": \"#D8D5D1\"\n },\n \"headerRow\": true,\n \"fontSize\": 12\n },\n \"chart\": {\n \"showLegend\": true,\n \"legendPos\": \"b\",\n \"legendFontSize\": 11,\n \"catAxisLabelFontSize\": 11,\n \"valAxisLabelFontSize\": 11,\n \"catGridLine\": {\n \"style\": \"none\"\n },\n \"valGridLine\": {\n \"style\": \"solid\",\n \"size\": 0.5,\n \"color\": \"#F2F3F3\"\n },\n \"valAxisLineShow\": false\n }\n }\n}\n","/**\n * The two alternate themes, PPTX twins of `vermilion.docx.theme.json` and\n * `devportal.docx.theme.json`.\n *\n * Each shares its palette roles, chart series, chrome recipes and motif with\n * the report theme of the same name, and names the same font families — all\n * of them in SAFE_FONTS, so neither needs a font registry. The projection\n * substitution the consulting twin makes — small roles and the recipes that\n * paint them take `text2` rather than `textMuted` — holds here for the same\n * contrast reason, and the agreement test knows it.\n *\n * Data, not code, for the same reason as `consulting.pptx.theme.json`: the\n * playground's theme discovery scans for `*.pptx.theme.json`.\n */\n\nimport type { PptxThemeConfig } from '../types';\nimport vermilionThemeJson from './vermilion.pptx.theme.json';\nimport devportalThemeJson from './devportal.pptx.theme.json';\n\nexport const VERMILION_PPTX_THEME: PptxThemeConfig =\n vermilionThemeJson as PptxThemeConfig;\nexport const DEVPORTAL_PPTX_THEME: PptxThemeConfig =\n devportalThemeJson as PptxThemeConfig;\n","/**\n * PPTX Theme Defaults\n */\n\nimport type { PptxComponentDefaults } from '@json-to-office/shared-pptx';\nimport type { PptxThemeConfig, TextStyle, StyleName } from '../types';\nimport { CONSULTING_PPTX_THEME } from './consulting';\nimport { DEVPORTAL_PPTX_THEME, VERMILION_PPTX_THEME } from './alternates';\n\n/**\n * What a table looks like before anyone styles one.\n *\n * With no defaults at all a PPTX table drew as bare text in columns — no rule\n * between cells, nothing marking the first row — so every deck had to restate\n * the same properties to get something presentable. Theme tokens rather than\n * hex, so each palette answers for its own lines.\n *\n * No `margin`: cell insets are a capability the `office-open` renderer does not\n * have, and a theme default that every table inherits would turn a backend that\n * works into one that refuses every table on it. It stays opt-in per table,\n * where the refusal is the author's own choice to make.\n *\n * A document overrides any of this per table, or wholesale through\n * `componentDefaults.table`; `headerRow: false` turns the first-row treatment\n * off for a table that is not a table of anything.\n */\nconst DEFAULT_TABLE: PptxComponentDefaults['table'] = {\n border: { type: 'solid', pt: 1, color: 'background2' },\n headerRow: true,\n};\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 displayName: 'Office Default',\n description:\n 'The stock Office look: blue primary, orange and green accents, Arial throughout, centred titles',\n whenToUse:\n 'A deck that has to match a plain PowerPoint look; pick a designed theme for anything a client will see.',\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 componentDefaults: { table: DEFAULT_TABLE },\n};\n\nconst PPTX_THEMES: Record<string, PptxThemeConfig> = {\n default: DEFAULT_PPTX_THEME,\n consulting: CONSULTING_PPTX_THEME,\n vermilion: VERMILION_PPTX_THEME,\n devportal: DEVPORTAL_PPTX_THEME,\n dark: {\n name: 'dark',\n displayName: 'Dark',\n description:\n 'Light text on a near-black ground with a bright accent, for screens and projectors',\n whenToUse:\n 'Keynote-style talks and product launches shown on a projector or a screen, where light-on-dark reads best.',\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 componentDefaults: { table: DEFAULT_TABLE },\n },\n minimal: {\n name: 'minimal',\n displayName: 'Minimal',\n description:\n 'Ink on white, one accent, no decoration; the content carries the slide',\n whenToUse:\n 'Internal decks and working sessions where the material should speak and decoration would distract.',\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 componentDefaults: { table: DEFAULT_TABLE },\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","import {\n designCanvas,\n resolveMotif,\n resolveTypeRoles,\n validateDesignColors,\n} from '@json-to-office/shared';\nimport type { PptxThemeConfig, GridConfig } from '../types';\nimport { resolveColor } from '../utils/color';\n\nexport function resolvePptxDesignSystem(\n theme: PptxThemeConfig,\n width = 10,\n height = 7.5\n): PptxThemeConfig {\n validateDesignColors(theme, theme.colors);\n const motif = resolveMotif(theme.motif);\n if (!theme.typography)\n return motif === theme.motif ? theme : withMotif(theme, motif);\n const canvas = designCanvas('pptx', { width, height });\n const roles = resolveTypeRoles(theme, canvas, theme.defaults.fontSize);\n const styles = { ...theme.styles };\n for (const [name, role] of Object.entries(roles)) {\n const key = name as keyof typeof styles;\n styles[key] = {\n fontFace:\n theme.fonts[role.face ?? 'body'] ??\n (role.face === 'light' ? theme.fonts.heading : theme.fonts.body),\n fontSize: role.size,\n ...(role.weight !== undefined && { fontWeight: role.weight }),\n ...(role.color !== undefined && {\n fontColor: resolveColor(role.color, theme),\n }),\n ...(role.case !== undefined && { case: role.case }),\n ...(role.lineHeight !== undefined && {\n lineSpacing: role.lineHeight * role.size,\n }),\n ...(role.tracking !== undefined && {\n charSpacing: (role.tracking * role.size) / 100,\n }),\n ...(role.spaceBefore !== undefined && {\n paraSpaceBefore: role.spaceBefore,\n }),\n ...(role.spaceAfter !== undefined && { paraSpaceAfter: role.spaceAfter }),\n ...styles[key],\n };\n }\n return { ...withMotif(theme, motif), styles };\n}\n\n/** `motif` present only when the theme declares one other than `none`. */\nfunction withMotif(\n theme: PptxThemeConfig,\n motif: PptxThemeConfig['motif']\n): PptxThemeConfig {\n if (motif !== undefined) return { ...theme, motif };\n const rest = { ...theme };\n delete rest.motif;\n return rest;\n}\n\nexport function designGrid(\n theme: PptxThemeConfig,\n width: number,\n height: number\n): GridConfig | undefined {\n const space =\n theme.spacing?.canvas?.[designCanvas('pptx', { width, height })];\n if (!space) return undefined;\n return {\n ...(space.safeAreaIn !== undefined && { margin: space.safeAreaIn }),\n ...(space.gutterIn !== undefined && { gutter: space.gutterIn }),\n ...(space.columns !== undefined && { columns: space.columns }),\n ...(space.rows !== undefined && { rows: space.rows }),\n };\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 * Structure Processing\n * JSON -> internal model\n *\n * The document arrives with every block already expanded (see\n * `blocks/document.ts`); what remains here is theme resolution, component\n * defaults, hyperlink rebasing, and the two engine operations that turn\n * authored composition into the absolute boxes the compiler draws: layout\n * (frames, distribution, grids) and bounded text fit.\n */\n\nimport type {\n PptxComponentInput,\n PptxThemeConfig,\n PresentationComponentDefinition,\n ProcessedPresentation,\n ProcessedSlide,\n SlideComponentDefinition,\n} from '../types';\nimport { isSlideComponent } from '../types';\nimport { mergeGridConfigs } from './grid';\nimport { getPptxTheme } from '../themes';\nimport { resolvePptxDesignSystem, designGrid } from '../themes/design-system';\nimport type { GenerationOptions } from './generator';\nimport { resolveComponentTree } from '../utils/resolveComponentTree';\nimport { remapHyperlinkSlideRefs } from '../utils/hyperlink';\nimport {\n mergeWithDefaults,\n toAuthoredBlockPointer,\n} from '@json-to-office/shared';\nimport { resolveSlideLayout } from './layout';\nimport { applyTextFit } from './fit';\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 let { props } = document;\n const { 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 selectedTheme =\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 // Idempotent, and deliberately repeated: the generation prologue already\n // resolved the theme it hands over, while a direct caller reaches this with a\n // raw theme. Re-resolving projects the same roles onto styles that already\n // carry them, because a style key present in `styles` wins over the role.\n const baseTheme = resolvePptxDesignSystem(\n selectedTheme,\n props.slideWidth,\n props.slideHeight\n );\n const tokenGrid = designGrid(\n baseTheme,\n props.slideWidth ?? 10,\n props.slideHeight ?? 7.5\n );\n if (tokenGrid)\n props = { ...props, grid: mergeGridConfigs(tokenGrid, props.grid) };\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 const sourceMap = options?.sourceMap ?? {};\n const toAuthored = (path: string) => toAuthoredBlockPointer(sourceMap, path);\n\n const slides: ProcessedSlide[] = [];\n\n children.forEach((child, authoredIndex) => {\n if (!isSlideComponent(child)) return;\n // `enabled: false` drops the slide entirely; absent means enabled\n if (!isSlideEnabled(child)) return;\n\n // Resolve componentDefaults on all slide components, then rebase\n // slide-targeted hyperlinks onto the generated slide numbering\n const resolvedComponents = resolveComponentTree(\n child.children ?? [],\n theme\n ).map((component) => remapHyperlinkSlideRefs(component, slideIndexMap));\n\n // Layout, then fit: frames and rows become absolute boxes, and a text\n // that declared bounds is sized within them or refused at its authored\n // pointer.\n const laidOut = resolveSlideLayout(resolvedComponents, {\n grid: props.grid,\n slideWidth,\n slideHeight,\n warnings: options?.warnings,\n });\n const fitted = applyTextFit(laidOut, `/children/${authoredIndex}`, {\n theme,\n slideWidth,\n slideHeight,\n toAuthored,\n });\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 slides.push({\n components: fitted,\n background: slideProps.background,\n transition: slideProps.transition,\n notes: slideProps.notes,\n hidden: slideProps.hidden,\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 services: options?.services,\n };\n}\n","/**\n * One reading of an authored dimension: a number is inches, `\"NN%\"` is a\n * fraction of the axis it sits on. Layout and fit both need it, and both must\n * read the same number for the same prop.\n */\nexport function dimensionInches(\n value: unknown,\n axisIn: number\n): number | undefined {\n if (typeof value === 'number' && Number.isFinite(value)) return value;\n if (typeof value === 'string' && value.trim().endsWith('%')) {\n const pct = Number(value.trim().slice(0, -1));\n return Number.isFinite(pct) ? (pct / 100) * axisIn : undefined;\n }\n return undefined;\n}\n","/**\n * Slide layout resolution: frames, distribution and nested grids.\n *\n * After block expansion a slide holds content components, transparent\n * `group`s, and groups that carry a frame. This pass turns every one of them\n * into what the compiler has always drawn — components at absolute inches —\n * so that a block body written against a frame, a row of two-to-four metric\n * tiles, or a 1.1 : 1 two-column split needs no plugin and no per-block code.\n *\n * Rules, top to bottom:\n *\n * - At the slide level nothing changes for content: a `grid` placement is\n * resolved against the slide grid exactly as before, an authored\n * coordinate stays as authored, and a component with neither keeps its\n * compiler default (the style band for text). A frameless, directionless\n * group is a plain sequence: its children are slide-level children.\n * - A group with a frame (`x`/`y`/`w`/`h`, or `grid`) is a nested coordinate\n * system. Inside it a child's numbers are offsets from the frame origin,\n * percentages are fractions of the frame, and an omitted `x`/`y` or `w`/`h`\n * means \"the frame's\". Its `gridConfig` merges over the enclosing grid; a\n * nested grid spans the frame with no margin unless the config states one.\n * - A group with a `direction` distributes its enabled children into cells\n * along that axis — equal, or by `weights` — separated by `gap`. A child\n * fills its cell unless it states its own offsets. A child that collapsed\n * away (an optional slot) simply is not there, so the rest redistribute.\n *\n * Geometry is decided once, here. The quality facts, the fit pass and the\n * compiler all read the same absolute boxes.\n */\n\nimport type { GridConfig, PipelineWarning, PptxComponentInput } from '../types';\nimport { dimensionInches } from './dimensions';\nimport {\n mergeGridConfigs,\n resolveComponentGridPosition,\n resolveGridPosition,\n} from './grid';\n\nexport interface SlideLayoutOptions {\n grid?: GridConfig;\n slideWidth: number;\n slideHeight: number;\n warnings?: PipelineWarning[];\n}\n\ninterface Extent {\n x: number;\n y: number;\n w: number;\n h: number;\n}\n\ntype Props = Record<string, unknown>;\n\nfunction hasFrame(props: Props): boolean {\n return ['x', 'y', 'w', 'h', 'grid'].some((key) => props[key] !== undefined);\n}\n\n/** Resolve every slide child to absolute inches; groups keep only their children. */\nexport function resolveSlideLayout(\n components: PptxComponentInput[],\n options: SlideLayoutOptions\n): PptxComponentInput[] {\n return components.map((component) => placeAtRoot(component, options));\n}\n\nfunction placeAtRoot(\n component: PptxComponentInput,\n options: SlideLayoutOptions\n): PptxComponentInput {\n if (component.name !== 'group') {\n return resolveComponentGridPosition(\n component,\n options.grid,\n options.slideWidth,\n options.slideHeight,\n options.warnings\n );\n }\n const props = (component.props ?? {}) as Props;\n const config = mergeGridConfigs(\n options.grid,\n props.gridConfig as GridConfig | undefined\n );\n const slide: Extent = {\n x: 0,\n y: 0,\n w: options.slideWidth,\n h: options.slideHeight,\n };\n if (!hasFrame(props) && props.direction === undefined) {\n // A plain sequence: its children are slide-level children.\n return {\n ...component,\n props: {},\n children: (component.children ?? []).map((child) =>\n placeAtRoot(child, { ...options, grid: config })\n ),\n };\n }\n const frame = boxWithin(props, slide, config, options);\n return {\n ...component,\n props: {},\n children: layoutChildren(component, frame, nestedConfig(config, props)),\n };\n}\n\n/**\n * A nested grid spans its frame. The enclosing grid's margin is the slide's\n * safe area, which has no meaning an inch inside a tile, so it is dropped\n * unless the group's own `gridConfig` states one.\n */\nfunction nestedConfig(\n config: GridConfig | undefined,\n props: Props\n): GridConfig {\n const own = props.gridConfig as GridConfig | undefined;\n return {\n ...(config ?? {}),\n margin: own?.margin ?? 0,\n };\n}\n\n/** A component's absolute box inside `extent`, from grid, coordinates or both. */\nfunction boxWithin(\n props: Props,\n extent: Extent,\n config: GridConfig | undefined,\n options: SlideLayoutOptions\n): Extent {\n const grid = props.grid as\n | { column: number; row: number; columnSpan?: number; rowSpan?: number }\n | undefined;\n const base = grid\n ? resolveGridPosition(grid, config, extent.w, extent.h, options.warnings)\n : { x: 0, y: 0, w: extent.w, h: extent.h };\n return {\n x: extent.x + (dimensionInches(props.x, extent.w) ?? base.x),\n y: extent.y + (dimensionInches(props.y, extent.h) ?? base.y),\n w: dimensionInches(props.w, extent.w) ?? base.w,\n h: dimensionInches(props.h, extent.h) ?? base.h,\n };\n}\n\nfunction layoutChildren(\n group: PptxComponentInput,\n frame: Extent,\n config: GridConfig\n): PptxComponentInput[] {\n const children = group.children ?? [];\n const props = (group.props ?? {}) as Props;\n const direction = props.direction as 'row' | 'column' | undefined;\n if (!direction) {\n return children.map((child) => placeInside(child, frame, config));\n }\n const gap = typeof props.gap === 'number' ? props.gap : 0;\n const weights = Array.isArray(props.weights) ? props.weights : [];\n const active = children.filter((child) => child.enabled !== false);\n const total = active.reduce(\n (sum, _child, index) => sum + weightAt(weights, index),\n 0\n );\n const along = direction === 'row' ? frame.w : frame.h;\n const usable = Math.max(0, along - gap * Math.max(0, active.length - 1));\n let cursor = direction === 'row' ? frame.x : frame.y;\n let activeIndex = 0;\n return children.map((child) => {\n if (child.enabled === false) return child;\n const size =\n total > 0 ? (usable * weightAt(weights, activeIndex)) / total : 0;\n const cell: Extent =\n direction === 'row'\n ? { x: cursor, y: frame.y, w: size, h: frame.h }\n : { x: frame.x, y: cursor, w: frame.w, h: size };\n cursor += size + gap;\n activeIndex += 1;\n return placeInside(child, cell, config);\n });\n}\n\nfunction weightAt(weights: unknown[], index: number): number {\n const value = weights[index];\n return typeof value === 'number' && value > 0 ? value : 1;\n}\n\nfunction placeInside(\n component: PptxComponentInput,\n extent: Extent,\n config: GridConfig\n): PptxComponentInput {\n const props = (component.props ?? {}) as Props;\n const box = boxWithin(props, extent, config, {\n slideWidth: extent.w,\n slideHeight: extent.h,\n });\n if (component.name === 'group') {\n return {\n ...component,\n props: {},\n children: layoutChildren(component, box, nestedConfig(config, props)),\n };\n }\n const { grid: _grid, ...rest } = props; // eslint-disable-line @typescript-eslint/no-unused-vars\n return {\n ...component,\n props: { ...rest, x: box.x, y: box.y, w: box.w, h: box.h },\n };\n}\n","/**\n * Bounded text fit.\n *\n * A text component may declare `fit: { maxLines, shrink }`. The engine\n * estimates the lines the text takes at its effective size with the shared\n * width model; when it exceeds `maxLines` — or the box height when no line\n * count is declared — it steps down through the declared readable sizes, in\n * order, and takes the first that fits. Nothing else is tried: no size the\n * author did not declare, no reflow into another box. When nothing fits the\n * text is rejected with `text_fit_overflow` at the pointer the author can\n * patch — the slot for block content, the component otherwise.\n *\n * Runs after layout, so widths are absolute, and before quality analysis and\n * compilation, so both see the size that was actually chosen.\n */\n\nimport { BlockEvaluationError } from '@json-to-office/shared';\nimport type { PptxComponentInput, PptxThemeConfig, StyleName } from '../types';\nimport {\n defaultLineHeightPt,\n estimateTextHeightPt,\n} from '../utils/textMetrics';\nimport { dimensionInches } from './dimensions';\n\nexport interface TextFitOptions {\n theme: PptxThemeConfig;\n slideWidth: number;\n slideHeight: number;\n /** Compiled pointer → the pointer diagnostics should name. */\n toAuthored?: (path: string) => string;\n}\n\ntype Props = Record<string, unknown>;\n\ninterface Fit {\n maxLines?: number;\n shrink?: number[];\n}\n\nfunction textOf(props: Props): string | undefined {\n if (typeof props.text === 'string') return props.text;\n if (Array.isArray(props.runs))\n return props.runs\n .map((run) => {\n const record = run as Props;\n return `${typeof record.text === 'string' ? record.text : ''}${\n record.breakLine ? '\\n' : ''\n }`;\n })\n .join('');\n return undefined;\n}\n\nexport function applyTextFit(\n components: PptxComponentInput[],\n basePath: string,\n options: TextFitOptions\n): PptxComponentInput[] {\n return components.map((component, index) =>\n fitOne(component, `${basePath}/children/${index}`, options)\n );\n}\n\nfunction fitOne(\n component: PptxComponentInput,\n path: string,\n options: TextFitOptions\n): PptxComponentInput {\n if (component.enabled === false) return component;\n if (component.children && component.children.length > 0) {\n return {\n ...component,\n children: applyTextFit(component.children, path, options),\n };\n }\n if (component.name !== 'text') return component;\n const props = (component.props ?? {}) as Props;\n const fit = props.fit as Fit | undefined;\n if (!fit) return component;\n const text = textOf(props);\n if (text === undefined) return component;\n\n const style =\n typeof props.style === 'string'\n ? options.theme.styles?.[props.style as StyleName]\n : undefined;\n const authoredSize =\n typeof props.fontSize === 'number'\n ? props.fontSize\n : style?.fontSize ?? options.theme.defaults.fontSize;\n const x = dimensionInches(props.x, options.slideWidth) ?? 0;\n const widthIn =\n dimensionInches(props.w, options.slideWidth) ??\n Math.max(0.1, options.slideWidth - x);\n const heightIn = dimensionInches(props.h, options.slideHeight);\n const explicitSpacing =\n typeof props.lineSpacing === 'number'\n ? props.lineSpacing\n : style?.lineSpacing;\n const multiple =\n typeof props.lineSpacingMultiple === 'number'\n ? props.lineSpacingMultiple\n : undefined;\n const before =\n typeof props.paraSpaceBefore === 'number' ? props.paraSpaceBefore : 0;\n const after =\n typeof props.paraSpaceAfter === 'number'\n ? props.paraSpaceAfter\n : style?.paraSpaceAfter ?? 0;\n\n const measure = (size: number) =>\n estimateTextHeightPt(\n text,\n widthIn * 72,\n size,\n multiple !== undefined\n ? size * multiple\n : explicitSpacing ?? defaultLineHeightPt(size),\n before,\n after\n );\n const fits = (size: number): boolean => {\n const estimate = measure(size);\n if (fit.maxLines !== undefined && estimate.lines > fit.maxLines)\n return false;\n if (heightIn !== undefined && estimate.heightPt > heightIn * 72)\n return false;\n return true;\n };\n\n if (fits(authoredSize)) return component;\n for (const size of fit.shrink ?? []) {\n if (fits(size)) {\n return { ...component, props: { ...props, fontSize: size } };\n }\n }\n const estimate = measure(authoredSize);\n const bound =\n fit.maxLines !== undefined\n ? `${fit.maxLines} line${fit.maxLines === 1 ? '' : 's'}`\n : `a ${Math.round((heightIn ?? 0) * 72)}pt box`;\n const tried =\n fit.shrink && fit.shrink.length > 0\n ? ` and at ${fit.shrink.join(', ')}pt`\n : '';\n throw new BlockEvaluationError([\n {\n path: (options.toAuthored ?? ((pointer) => pointer))(\n `${path}/props/text`\n ),\n code: 'text_fit_overflow',\n message:\n `Text runs to ${estimate.lines} line${estimate.lines === 1 ? '' : 's'} at ${authoredSize}pt` +\n ` in a ${Math.round(widthIn * 72)}pt-wide box; it must fit ${bound}${tried}.` +\n ' Shorten the text, or declare wider bounds in the definition.',\n },\n ]);\n}\n","/**\n * The width model: how many lines a run of text takes in a box.\n *\n * One estimator, shared by the quality rules (`pptx/text-fit`,\n * `pptx/action-title`) and the engine's bounded `fit` operation, so a title\n * the rules call two lines is the title the engine sizes for two lines.\n * Character-count based, and calibrated against rendered ground truth — see\n * the note on `DEFAULT_CHAR_WIDTH_FACTOR` in `quality/rules.ts`. Real text\n * metrics (#211) replace it in one place when they land.\n */\n\n/** Average glyph advance as a fraction of the font size. */\nexport const DEFAULT_CHAR_WIDTH_FACTOR = 0.46;\n\nexport function defaultLineHeightPt(fontSize: number): number {\n if (fontSize >= 60) return fontSize * 1.05;\n if (fontSize >= 28) return fontSize * 1.15;\n return fontSize * 1.25;\n}\n\n/** Lines the text wraps to in `boxWidthPt` at `fontSizePt`; never below 1. */\nexport function estimateTextLines(\n text: string,\n boxWidthPt: number,\n fontSizePt: number,\n charWidthFactor = DEFAULT_CHAR_WIDTH_FACTOR\n): number {\n const charsPerLine = Math.max(\n 1,\n Math.floor(boxWidthPt / (fontSizePt * charWidthFactor))\n );\n let lines = 0;\n for (const paragraph of text.split('\\n')) {\n const measured = paragraph.trimEnd();\n lines +=\n measured === ''\n ? 1\n : Math.max(1, Math.ceil(measured.length / charsPerLine));\n }\n return lines;\n}\n\nexport interface TextHeightEstimate {\n heightPt: number;\n lines: number;\n}\n\nexport function estimateTextHeightPt(\n text: string,\n boxWidthPt: number,\n fontSizePt: number,\n lineSpacingPt: number,\n paraSpaceBeforePt = 0,\n paraSpaceAfterPt = 0,\n charWidthFactor = DEFAULT_CHAR_WIDTH_FACTOR\n): TextHeightEstimate {\n const lines = estimateTextLines(\n text,\n boxWidthPt,\n fontSizePt,\n charWidthFactor\n );\n const paragraphs = text.split('\\n').length;\n let heightPt = fontSizePt + Math.max(0, lines - 1) * lineSpacingPt;\n if (paragraphs > 1) {\n heightPt += (paragraphs - 1) * (paraSpaceBeforePt + paraSpaceAfterPt);\n }\n return { heightPt, lines };\n}\n","/**\n * Document-local JSON blocks on slides.\n *\n * The PPTX adapter of the shared block contract. A definition in\n * `props.blocks` expands, at its invocation, into a transparent `group` of\n * ordinary slide content — text, shapes, images, charts, tables, nested\n * groups — with a source map from every compiled pointer back to the authored\n * invocation or slot. Geometry is the definition's: component slots take\n * their frame from the `props` merged beneath them, and a group's frame,\n * direction and grid do the distributing. Nothing here knows any block by\n * name.\n *\n * Slide effects are the one thing a block can say about its slide. A\n * definition's `slide.background` and `slide.notes` fill in what the slide\n * did not state; `slide.grid` becomes the expanded group's `gridConfig`, so\n * the body's grid placements resolve against the block's own grid. A slide\n * that states its own background keeps it.\n */\n\nimport {\n BlockEvaluationError,\n JsonBlockEvaluator,\n blockValueAt,\n composeBlocksWithPlugins,\n isBlockRecord,\n readBlockDefinitions,\n toAuthoredBlockPointer,\n type BlockEvaluatorOptions,\n type BlockSlideEffect,\n} from '@json-to-office/shared';\nimport { validatePresentationDocument } from '@json-to-office/shared-pptx';\nimport type { PptxThemeConfig } from '../types';\n\nexport { blockSlotBudgets, blockSlotRoles } from '@json-to-office/shared';\nexport type {\n BlockSlotBudget,\n BlockSlotRoleValue,\n BlockSourceMap,\n ExpandedBlocks,\n} from '@json-to-office/shared';\nimport type { ExpandedBlocks } from '@json-to-office/shared';\n\ntype Rec = Record<string, unknown>;\nexport const toAuthoredPointer = toAuthoredBlockPointer;\n\n/** Deck metadata and the slide's canvas. No slide design is registered here. */\nexport function pptxBlockContext(document: unknown, path = ''): Rec {\n const props =\n isBlockRecord(document) && isBlockRecord(document.props)\n ? document.props\n : {};\n const index = /^\\/children\\/(\\d+)/.exec(path)?.[1];\n const metadata: Rec = {};\n for (const key of ['title', 'author', 'subject', 'company']) {\n if (props[key] !== undefined) metadata[key] = props[key];\n }\n return {\n document: metadata,\n slide: {\n width: typeof props.slideWidth === 'number' ? props.slideWidth : 10,\n height: typeof props.slideHeight === 'number' ? props.slideHeight : 7.5,\n ...(index !== undefined && { index: Number(index) + 1 }),\n },\n };\n}\n\nexport function createPptxBlockEvaluator(\n document: unknown,\n theme: PptxThemeConfig,\n extra: Partial<BlockEvaluatorOptions> = {}\n): JsonBlockEvaluator {\n return new JsonBlockEvaluator(readBlockDefinitions(document), {\n format: 'pptx',\n theme,\n contextAt: (path) => pptxBlockContext(document, path),\n contextSources: { '/document': '/props' },\n // Slide width/height, in inches by default for a format authored in them.\n measure: (axis, unit, context) =>\n Number(blockValueAt(context, `/slide/${axis}`)) *\n (unit === 'in' ? 1 : unit === 'pt' ? 72 : 1440),\n ...extra,\n });\n}\n\nexport function expandPptxBlocks<T>(\n document: T,\n theme: PptxThemeConfig\n): ExpandedBlocks<T> {\n const effects: BlockSlideEffect[] = [];\n const evaluator = createPptxBlockEvaluator(document, theme, {\n onSlide: (effect) => effects.push(effect),\n });\n const expanded = evaluator.expand(document) as T;\n return finishPptxBlocks(expanded, evaluator, effects);\n}\n\nfunction slideIndexOf(path: string): number | undefined {\n const match = /^\\/children\\/(\\d+)\\/children\\/\\d+/.exec(path);\n return match ? Number(match[1]) : undefined;\n}\n\nfunction validateEffects(document: unknown, effects: BlockSlideEffect[]): void {\n for (const effect of effects) {\n const parts = effect.path.split('/').slice(1);\n const slide = blockValueAt(document, '/' + parts.slice(0, 2).join('/'));\n let valid =\n parts.length >= 4 &&\n parts[0] === 'children' &&\n parts[2] === 'children' &&\n isBlockRecord(slide) &&\n slide.name === 'slide';\n for (let i = 4; i < parts.length; i += 2) {\n const parent = blockValueAt(document, '/' + parts.slice(0, i).join('/'));\n valid &&=\n parts[i] === 'children' &&\n isBlockRecord(parent) &&\n parent.name === 'group';\n }\n if (!valid)\n throw new BlockEvaluationError([\n {\n path: effect.environment.source,\n code: 'invalid_placement',\n message:\n 'Slide effects require a block invoked directly on a slide, optionally nested in transparent groups.',\n },\n ]);\n }\n}\n\n/**\n * Background and notes fill in what the slide did not state; among blocks the\n * last declaration on a slide wins, as a section's last tracker does in DOCX.\n * The grid becomes the expanded group's `gridConfig`, scoped to the body.\n */\nfunction applySlideEffects(\n expanded: unknown,\n evaluator: JsonBlockEvaluator,\n effects: BlockSlideEffect[]\n): void {\n if (!isBlockRecord(expanded) || !Array.isArray(expanded.children)) return;\n const supplied = new Set<string>();\n for (const effect of effects) {\n const index = slideIndexOf(effect.path);\n const slide = index === undefined ? undefined : expanded.children[index];\n if (!isBlockRecord(slide) || slide.name !== 'slide') continue;\n const slidePath = `/children/${index}`;\n const props: Rec = isBlockRecord(slide.props) ? { ...slide.props } : {};\n for (const key of ['background', 'notes'] as const) {\n const declared = effect.settings[key];\n if (declared === undefined) continue;\n const claim = `${slidePath}/${key}`;\n if (props[key] !== undefined && !supplied.has(claim)) continue;\n const value = evaluator.evaluate(\n declared,\n effect.environment,\n `${slidePath}/props/${key}`,\n `${effect.environment.definition}/slide/${key}`\n );\n if (value === undefined) continue;\n props[key] = value;\n supplied.add(claim);\n }\n slide.props = props;\n if (effect.settings.grid !== undefined) {\n const group = blockValueAt(expanded, effect.path);\n if (isBlockRecord(group) && group.name === 'group') {\n const grid = evaluator.evaluate(\n effect.settings.grid,\n effect.environment,\n `${effect.path}/props/gridConfig`,\n `${effect.environment.definition}/slide/grid`\n );\n if (grid !== undefined)\n group.props = {\n ...(isBlockRecord(group.props) ? group.props : {}),\n gridConfig: grid,\n };\n }\n }\n }\n}\n\nfunction finishPptxBlocks<T>(\n expanded: T,\n evaluator: JsonBlockEvaluator,\n effects: BlockSlideEffect[]\n): ExpandedBlocks<T> {\n applySlideEffects(expanded, evaluator, effects);\n validateEffects(expanded, effects);\n if (evaluator.blocks.length) {\n const result = validatePresentationDocument(expanded);\n if (!result.valid)\n throw new BlockEvaluationError(\n result.errors.map((issue) => ({\n path: toAuthoredPointer(evaluator.sourceMap, issue.path),\n code: issue.code ?? 'block_invalid_output',\n message: issue.message,\n }))\n );\n }\n return {\n document: expanded,\n sourceMap: evaluator.sourceMap,\n blocks: evaluator.blocks,\n };\n}\n\n/**\n * Registered code and document-local JSON share one bounded expansion: a\n * plugin can emit a block, a block body or component slot can name a plugin,\n * and either can nest. The host supplies the registered code; JSON never\n * loads any. The caller validates the finished tree under its own validation\n * options; block output is validated here regardless, because a definition\n * that emits invalid primitives is a definition error.\n */\nexport async function expandPptxBlocksWithPlugins<T>(\n document: T,\n theme: PptxThemeConfig,\n plugins: ReadonlySet<string>,\n render: (component: Rec, path: string) => Promise<unknown[]>,\n preserve: ReadonlySet<string> = new Set()\n): Promise<ExpandedBlocks<T> & { preserved: T }> {\n const effects: BlockSlideEffect[] = [];\n const evaluator = createPptxBlockEvaluator(document, theme, {\n reservedNames: [...plugins],\n onSlide: (effect) => effects.push(effect),\n });\n const composed = await composeBlocksWithPlugins(evaluator, document, {\n plugins,\n render,\n preserve,\n });\n const finished = finishPptxBlocks(composed.standard as T, evaluator, effects);\n return { ...finished, preserved: composed.preserved as T };\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 {\n isPptxRendererId,\n pptxRendererIds,\n pptxRendererStatuses,\n} from './renderers/registry';\nexport { UncompiledComponentError } from './core/generateFromIr';\n\n// Chart export-server counters (bounded concurrency, dedupe, retries)\nexport {\n getChartRequestStats,\n resetChartRequestStats,\n type ChartRequestStats,\n} from '@json-to-office/shared';\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 {\n CONSULTING_PPTX_THEME,\n DEVPORTAL_PPTX_THEME,\n VERMILION_PPTX_THEME,\n DEFAULT_PPTX_THEME,\n getPptxTheme,\n hasPptxTheme,\n pptxThemes,\n} from './themes';\n\n// Blueprints: deck archetypes as data (#342)\nexport {\n PPTX_BLUEPRINTS,\n pptxBlueprint,\n instantiatePptxBlueprint,\n} from './blueprints';\nexport type {\n BlueprintFillEntry,\n InstantiateBlueprintOptions,\n InstantiatedBlueprint,\n} from './blueprints';\n\n// Design-quality analysis (#216)\nexport { analyzePptxQuality } from './quality/preflight';\nexport type {\n PptxQualityAnalysisOptions,\n PptxQualityOptions,\n} from './quality/preflight';\nexport {\n preparePptxQualityDocument,\n type PptxBlocksMetadata,\n type PptxBlockSlotFact,\n type PptxCanvasFact,\n type PptxChromeSlotFact,\n type PptxQualityFact,\n type PptxQualityModel,\n type PptxSlideFact,\n type PptxTextFact,\n type PreparePptxQualityOptions,\n} from './quality/facts';\nexport {\n PPTX_DEFAULT_QUALITY_PROFILE,\n PPTX_QUALITY_PROFILES,\n PPTX_QUALITY_RULES,\n pptxQualityEngine,\n declaredPptxQualityProfile,\n resolvePptxQualityProfile,\n} from './quality/rules';\n\n// Document-local JSON block composition.\nexport {\n expandPptxBlocks,\n toAuthoredPointer,\n blockSlotBudgets,\n blockSlotRoles,\n} from './blocks';\nexport type { BlockSourceMap, ExpandedBlocks } from './blocks';\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 * PPTX blueprints: deck archetypes as data, and the one operation that turns\n * one into a deck.\n *\n * The registry is the JSON files under `templates/blueprints`: the bundled\n * ones are imported so a stale or missing `dist` cannot lose them, and the\n * directory is scanned for any other `*.pptx.blueprint.json` beside it, so\n * adding a blueprint is a file. What instantiating means is shared with the\n * DOCX core; this module only says what a deck's root looks like: the\n * metadata a deck carries (`title`, `author`, `company`) sits directly under\n * `props`, beside the canvas the blueprint's blocks were drawn for.\n */\nimport { existsSync, readdirSync, readFileSync } from 'node:fs';\nimport { fileURLToPath } from 'node:url';\nimport { dirname, join } from 'node:path';\nimport {\n instantiateBlueprint,\n registerBlueprints,\n type Blueprint,\n type BlueprintFillEntry,\n type InstantiateBlueprintOptions,\n type InstantiatedBlueprint,\n} from '@json-to-office/shared';\nimport { collectPlaceholders } from '@json-to-office/quality';\nimport consultingDeck from '../templates/blueprints/consulting-deck.pptx.blueprint.json';\n\n/**\n * Blueprint files beside this module — `src/templates/blueprints` from source,\n * `dist/templates/blueprints` from the built package — that the static import\n * above does not already carry.\n */\nfunction scanned(known: Readonly<Record<string, unknown>>): unknown[] {\n let here: string;\n try {\n here = dirname(fileURLToPath(import.meta.url));\n } catch {\n return [];\n }\n const directory = [\n join(here, '../templates/blueprints'),\n join(here, 'templates/blueprints'),\n ].find((path) => existsSync(path));\n if (!directory) return [];\n return readdirSync(directory)\n .filter((file) => file.endsWith('.pptx.blueprint.json'))\n .map((file) => JSON.parse(readFileSync(join(directory, file), 'utf8')))\n .filter((candidate) => {\n const id = (candidate as { id?: unknown } | null)?.id;\n return !(typeof id === 'string' && id in known);\n });\n}\n\nconst bundled = registerBlueprints('pptx', [consultingDeck]);\n\n/** Every bundled PPTX blueprint, by id. */\nexport const PPTX_BLUEPRINTS: Readonly<Record<string, Blueprint>> = {\n ...bundled,\n ...registerBlueprints('pptx', scanned(bundled)),\n};\n\nexport function pptxBlueprint(id: string): Blueprint | undefined {\n return PPTX_BLUEPRINTS[id];\n}\n\nexport type {\n BlueprintFillEntry,\n InstantiateBlueprintOptions,\n InstantiatedBlueprint,\n};\n\n/** The wide canvas every bundled deck block is drawn for; any canvas lays out. */\nconst CANVAS = { slideWidth: 13.333, slideHeight: 7.5 } as const;\n\nexport function instantiatePptxBlueprint(\n blueprint: Blueprint,\n options: InstantiateBlueprintOptions\n): InstantiatedBlueprint {\n return instantiateBlueprint(blueprint, options, {\n format: 'pptx',\n props: CANVAS,\n metadataPointer: '/props',\n markers: (document) =>\n collectPlaceholders(document).filter(\n (occurrence) => occurrence.match.kind === 'scaffold-marker'\n ),\n });\n}\n","{\n \"id\": \"consulting-deck\",\n \"format\": \"pptx\",\n \"title\": \"Consulting deck\",\n \"description\": \"A decision deck for a client readout: a cover, the quarter in numbers, one action-chart per finding with its takeaway and source, a two-column slide for the evidence that is a table or a list, a closing statement; every slide invokes one of the five consulting blocks on the house theme.\",\n \"whenToUse\": \"A client readout, a board update or a steering-committee deck: one message per slide, a chart or table that carries it, a source under it. Not for a talk track or a training deck.\",\n \"theme\": \"consulting\",\n \"profile\": \"consulting-deck\",\n \"definitions\": \"consulting-deck-blocks.pptx.json\",\n \"numbering\": \"none\",\n \"toc\": false,\n \"variants\": {\n \"data-heavy\": {\n \"description\": \"Evidence-led: cover, a KPI row, three action-charts, a two-column table slide, a closing statement.\",\n \"whenToUse\": \"The brief comes with numbers the audience will check: performance, finance, operations.\",\n \"pages\": {\n \"min\": 6,\n \"max\": 9\n },\n \"metadata\": {\n \"title\": \"{{Title: as on the cover}}\",\n \"author\": \"{{Author or team}}\",\n \"company\": \"{{Client name}}\"\n },\n \"children\": [\n {\n \"name\": \"slide\",\n \"children\": [\n {\n \"name\": \"block\",\n \"props\": {\n \"ref\": \"cover\",\n \"slots\": {\n \"title\": \"{{Title: the deck's conclusion in one sentence}}\",\n \"subtitle\": \"{{Subtitle: what the deck answers, for whom}}\",\n \"client\": \"{{Client name}}\",\n \"date\": \"{{Month YYYY}}\",\n \"confidentiality\": \"{{Confidentiality: Confidential, or For internal use}}\"\n }\n }\n }\n ]\n },\n {\n \"name\": \"slide\",\n \"children\": [\n {\n \"name\": \"block\",\n \"props\": {\n \"ref\": \"kpi-row\",\n \"slots\": {\n \"title\": \"{{Action title: the claim this slide proves, with its number, two lines at most}}\",\n \"tracker\": \"{{Tracker: the section, one or two words}}\",\n \"items\": [\n {\n \"value\": \"{{0.0}}\",\n \"unit\": \"{{unit}}\",\n \"label\": \"{{What it measures}}\",\n \"delta\": \"{{+0.0}}\"\n },\n {\n \"value\": \"{{0.0}}\",\n \"unit\": \"{{unit}}\",\n \"label\": \"{{What it measures}}\",\n \"delta\": \"{{+0.0}}\"\n },\n {\n \"value\": \"{{0.0}}\",\n \"unit\": \"{{unit}}\",\n \"label\": \"{{What it measures}}\",\n \"delta\": \"{{+0.0}}\"\n }\n ],\n \"source\": \"{{Source: system or document, date}}\"\n }\n }\n }\n ]\n },\n {\n \"name\": \"slide\",\n \"children\": [\n {\n \"name\": \"block\",\n \"props\": {\n \"ref\": \"action-chart\",\n \"slots\": {\n \"title\": \"{{Action title: the claim this slide proves, with its number, two lines at most}}\",\n \"tracker\": \"{{Tracker: the section, one or two words}}\",\n \"chart\": {\n \"name\": \"chart\",\n \"props\": {\n \"type\": \"bar\",\n \"valAxisTitle\": \"{{Measure (unit)}}\",\n \"data\": [\n {\n \"name\": \"{{Series name}}\",\n \"labels\": [\n \"{{Period 1}}\",\n \"{{Period 2}}\",\n \"{{Period 3}}\"\n ],\n \"values\": [0, 0, 0]\n }\n ],\n \"chartColors\": [\n \"accent\",\n \"secondary\",\n \"accent4\",\n \"accent6\",\n \"accent5\"\n ]\n }\n },\n \"takeaway\": \"{{Takeaway: what the reader should conclude, one or two sentences}}\",\n \"source\": \"{{Source: system or document, date}}\"\n }\n }\n }\n ]\n },\n {\n \"name\": \"slide\",\n \"children\": [\n {\n \"name\": \"block\",\n \"props\": {\n \"ref\": \"action-chart\",\n \"slots\": {\n \"title\": \"{{Action title: the claim this slide proves, with its number, two lines at most}}\",\n \"tracker\": \"{{Tracker: the section, one or two words}}\",\n \"chart\": {\n \"name\": \"chart\",\n \"props\": {\n \"type\": \"bar\",\n \"valAxisTitle\": \"{{Measure (unit)}}\",\n \"data\": [\n {\n \"name\": \"{{Series name}}\",\n \"labels\": [\n \"{{Period 1}}\",\n \"{{Period 2}}\",\n \"{{Period 3}}\"\n ],\n \"values\": [0, 0, 0]\n }\n ],\n \"chartColors\": [\n \"accent\",\n \"secondary\",\n \"accent4\",\n \"accent6\",\n \"accent5\"\n ]\n }\n },\n \"takeaway\": \"{{Takeaway: what the reader should conclude, one or two sentences}}\",\n \"source\": \"{{Source: system or document, date}}\"\n }\n }\n }\n ]\n },\n {\n \"name\": \"slide\",\n \"children\": [\n {\n \"name\": \"block\",\n \"props\": {\n \"ref\": \"action-chart\",\n \"slots\": {\n \"title\": \"{{Action title: the claim this slide proves, with its number, two lines at most}}\",\n \"tracker\": \"{{Tracker: the section, one or two words}}\",\n \"chart\": {\n \"name\": \"chart\",\n \"props\": {\n \"type\": \"bar\",\n \"valAxisTitle\": \"{{Measure (unit)}}\",\n \"data\": [\n {\n \"name\": \"{{Series name}}\",\n \"labels\": [\n \"{{Period 1}}\",\n \"{{Period 2}}\",\n \"{{Period 3}}\"\n ],\n \"values\": [0, 0, 0]\n }\n ],\n \"chartColors\": [\n \"accent\",\n \"secondary\",\n \"accent4\",\n \"accent6\",\n \"accent5\"\n ]\n }\n },\n \"takeaway\": \"{{Takeaway: what the reader should conclude, one or two sentences}}\",\n \"source\": \"{{Source: system or document, date}}\"\n }\n }\n }\n ]\n },\n {\n \"name\": \"slide\",\n \"children\": [\n {\n \"name\": \"block\",\n \"props\": {\n \"ref\": \"two-column\",\n \"slots\": {\n \"title\": \"{{Action title: the claim this slide proves, with its number, two lines at most}}\",\n \"tracker\": \"{{Tracker: the section, one or two words}}\",\n \"bullets\": [\n \"{{Bullet 1: one claim, ten words}}\",\n \"{{Bullet 2: one claim, ten words}}\",\n \"{{Bullet 3: one claim, ten words}}\"\n ],\n \"content\": {\n \"name\": \"table\",\n \"props\": {\n \"rows\": [\n [\n \"{{Row label}}\",\n {\n \"text\": \"{{Column (unit)}}\",\n \"align\": \"right\"\n },\n {\n \"text\": \"{{Column (unit)}}\",\n \"align\": \"right\"\n }\n ],\n [\n \"{{Row 1}}\",\n {\n \"text\": \"{{0.0}}\",\n \"align\": \"right\"\n },\n {\n \"text\": \"{{0.0}}\",\n \"align\": \"right\"\n }\n ],\n [\n \"{{Row 2}}\",\n {\n \"text\": \"{{0.0}}\",\n \"align\": \"right\"\n },\n {\n \"text\": \"{{0.0}}\",\n \"align\": \"right\"\n }\n ],\n [\n \"{{Row 3}}\",\n {\n \"text\": \"{{0.0}}\",\n \"align\": \"right\"\n },\n {\n \"text\": \"{{0.0}}\",\n \"align\": \"right\"\n }\n ]\n ]\n }\n },\n \"source\": \"{{Source: system or document, date}}\"\n }\n }\n }\n ]\n },\n {\n \"name\": \"slide\",\n \"children\": [\n {\n \"name\": \"block\",\n \"props\": {\n \"ref\": \"statement\",\n \"slots\": {\n \"tracker\": \"{{Tracker: the section, one or two words}}\",\n \"assertion\": \"{{Assertion: what to do next, in one sentence}}\",\n \"support\": \"{{Support: what backs the assertion, under thirty words}}\"\n }\n }\n }\n ]\n }\n ]\n },\n \"narrative\": {\n \"description\": \"Argument-led: cover, the position as a statement, two two-column slides that argue it beside a chart, one action-chart, a two-column table, a closing statement.\",\n \"whenToUse\": \"The brief is a position or a recommendation with few numbers; the audience follows an argument.\",\n \"pages\": {\n \"min\": 6,\n \"max\": 8\n },\n \"metadata\": {\n \"title\": \"{{Title: as on the cover}}\",\n \"author\": \"{{Author or team}}\",\n \"company\": \"{{Client name}}\"\n },\n \"children\": [\n {\n \"name\": \"slide\",\n \"children\": [\n {\n \"name\": \"block\",\n \"props\": {\n \"ref\": \"cover\",\n \"slots\": {\n \"title\": \"{{Title: the deck's conclusion in one sentence}}\",\n \"subtitle\": \"{{Subtitle: what the deck answers, for whom}}\",\n \"client\": \"{{Client name}}\",\n \"date\": \"{{Month YYYY}}\",\n \"confidentiality\": \"{{Confidentiality: Confidential, or For internal use}}\"\n }\n }\n }\n ]\n },\n {\n \"name\": \"slide\",\n \"children\": [\n {\n \"name\": \"block\",\n \"props\": {\n \"ref\": \"statement\",\n \"slots\": {\n \"tracker\": \"{{Tracker: the section, one or two words}}\",\n \"assertion\": \"{{Assertion: the position, in one sentence}}\",\n \"support\": \"{{Support: what backs the assertion, under thirty words}}\"\n }\n }\n }\n ]\n },\n {\n \"name\": \"slide\",\n \"children\": [\n {\n \"name\": \"block\",\n \"props\": {\n \"ref\": \"two-column\",\n \"slots\": {\n \"title\": \"{{Action title: the claim this slide proves, with its number, two lines at most}}\",\n \"tracker\": \"{{Tracker: the section, one or two words}}\",\n \"text\": \"{{Body: the argument this slide makes, under fifty words}}\",\n \"content\": {\n \"name\": \"chart\",\n \"props\": {\n \"type\": \"bar\",\n \"valAxisTitle\": \"{{Measure (unit)}}\",\n \"data\": [\n {\n \"name\": \"{{Series name}}\",\n \"labels\": [\n \"{{Period 1}}\",\n \"{{Period 2}}\",\n \"{{Period 3}}\"\n ],\n \"values\": [0, 0, 0]\n }\n ],\n \"chartColors\": [\n \"accent\",\n \"secondary\",\n \"accent4\",\n \"accent6\",\n \"accent5\"\n ]\n }\n },\n \"source\": \"{{Source: system or document, date}}\"\n }\n }\n }\n ]\n },\n {\n \"name\": \"slide\",\n \"children\": [\n {\n \"name\": \"block\",\n \"props\": {\n \"ref\": \"two-column\",\n \"slots\": {\n \"title\": \"{{Action title: the claim this slide proves, with its number, two lines at most}}\",\n \"tracker\": \"{{Tracker: the section, one or two words}}\",\n \"text\": \"{{Body: the argument this slide makes, under fifty words}}\",\n \"content\": {\n \"name\": \"chart\",\n \"props\": {\n \"type\": \"bar\",\n \"valAxisTitle\": \"{{Measure (unit)}}\",\n \"data\": [\n {\n \"name\": \"{{Series name}}\",\n \"labels\": [\n \"{{Period 1}}\",\n \"{{Period 2}}\",\n \"{{Period 3}}\"\n ],\n \"values\": [0, 0, 0]\n }\n ],\n \"chartColors\": [\n \"accent\",\n \"secondary\",\n \"accent4\",\n \"accent6\",\n \"accent5\"\n ]\n }\n },\n \"source\": \"{{Source: system or document, date}}\"\n }\n }\n }\n ]\n },\n {\n \"name\": \"slide\",\n \"children\": [\n {\n \"name\": \"block\",\n \"props\": {\n \"ref\": \"action-chart\",\n \"slots\": {\n \"title\": \"{{Action title: the claim this slide proves, with its number, two lines at most}}\",\n \"tracker\": \"{{Tracker: the section, one or two words}}\",\n \"chart\": {\n \"name\": \"chart\",\n \"props\": {\n \"type\": \"bar\",\n \"valAxisTitle\": \"{{Measure (unit)}}\",\n \"data\": [\n {\n \"name\": \"{{Series name}}\",\n \"labels\": [\n \"{{Period 1}}\",\n \"{{Period 2}}\",\n \"{{Period 3}}\"\n ],\n \"values\": [0, 0, 0]\n }\n ],\n \"chartColors\": [\n \"accent\",\n \"secondary\",\n \"accent4\",\n \"accent6\",\n \"accent5\"\n ]\n }\n },\n \"takeaway\": \"{{Takeaway: what the reader should conclude, one or two sentences}}\",\n \"source\": \"{{Source: system or document, date}}\"\n }\n }\n }\n ]\n },\n {\n \"name\": \"slide\",\n \"children\": [\n {\n \"name\": \"block\",\n \"props\": {\n \"ref\": \"two-column\",\n \"slots\": {\n \"title\": \"{{Action title: the claim this slide proves, with its number, two lines at most}}\",\n \"tracker\": \"{{Tracker: the section, one or two words}}\",\n \"bullets\": [\n \"{{Bullet 1: one claim, ten words}}\",\n \"{{Bullet 2: one claim, ten words}}\",\n \"{{Bullet 3: one claim, ten words}}\"\n ],\n \"content\": {\n \"name\": \"table\",\n \"props\": {\n \"rows\": [\n [\n \"{{Row label}}\",\n {\n \"text\": \"{{Column (unit)}}\",\n \"align\": \"right\"\n },\n {\n \"text\": \"{{Column (unit)}}\",\n \"align\": \"right\"\n }\n ],\n [\n \"{{Row 1}}\",\n {\n \"text\": \"{{0.0}}\",\n \"align\": \"right\"\n },\n {\n \"text\": \"{{0.0}}\",\n \"align\": \"right\"\n }\n ],\n [\n \"{{Row 2}}\",\n {\n \"text\": \"{{0.0}}\",\n \"align\": \"right\"\n },\n {\n \"text\": \"{{0.0}}\",\n \"align\": \"right\"\n }\n ],\n [\n \"{{Row 3}}\",\n {\n \"text\": \"{{0.0}}\",\n \"align\": \"right\"\n },\n {\n \"text\": \"{{0.0}}\",\n \"align\": \"right\"\n }\n ]\n ]\n }\n },\n \"source\": \"{{Source: system or document, date}}\"\n }\n }\n }\n ]\n },\n {\n \"name\": \"slide\",\n \"children\": [\n {\n \"name\": \"block\",\n \"props\": {\n \"ref\": \"statement\",\n \"slots\": {\n \"tracker\": \"{{Tracker: the section, one or two words}}\",\n \"assertion\": \"{{Assertion: what to do next, in one sentence}}\",\n \"support\": \"{{Support: what backs the assertion, under thirty words}}\"\n }\n }\n }\n ]\n }\n ]\n }\n }\n}\n","/** PPTX quality analysis over renderer-aligned prepared facts. */\n\nimport {\n assertValidQualityPolicy,\n assertValidQualityProfile,\n type PreparedDocument,\n type QualityAnalysis,\n type QualityPolicy,\n type QualityProfile,\n type QualityRuleError,\n} from '@json-to-office/quality';\nimport type {\n PptxThemeConfig,\n PresentationComponentDefinition,\n} from '../types';\nimport { preparePptxQualityDocument } from './facts';\nimport type { PptxQualityFact, PptxQualityModel } from './facts';\nimport {\n PPTX_DEFAULT_QUALITY_PROFILE,\n pptxQualityEngine,\n declaredPptxQualityProfile,\n resolvePptxQualityProfile,\n} from './rules';\n\n/** Synthetic rule id for a failure raised before any rule could run. */\nconst PREPARE_RULE_ID = 'quality/prepare';\n\nexport interface PptxQualityOptions {\n customThemes?: Record<string, PptxThemeConfig>;\n}\n\nexport interface PptxQualityAnalysisOptions extends PptxQualityOptions {\n renderer?: string;\n profile?: QualityProfile;\n policy?: QualityPolicy;\n prepared?: PreparedDocument<PptxQualityModel, PptxQualityFact>;\n}\n\nfunction emptyAnalysis(\n ruleErrors: readonly QualityRuleError[] = [],\n blocked = false\n): QualityAnalysis {\n return {\n diagnostics: [],\n counts: { error: 0, warning: 0, info: 0 },\n blocked,\n truncated: false,\n suppressedCount: 0,\n evaluatedRuleIds: [],\n ruleErrors,\n };\n}\n\nexport function analyzePptxQuality(\n doc: unknown,\n options: PptxQualityAnalysisOptions = {}\n): QualityAnalysis {\n // Ahead of every early return: a malformed document must not be the reason a\n // caller never hears that its own policy or profile was unusable.\n assertValidQualityPolicy(options.policy);\n assertValidQualityProfile(options.profile);\n\n if (\n typeof doc !== 'object' ||\n doc === null ||\n Array.isArray(doc) ||\n (doc as { name?: unknown }).name !== 'pptx'\n ) {\n return emptyAnalysis();\n }\n\n let prepared = options.prepared;\n try {\n prepared ??= preparePptxQualityDocument(\n doc as PresentationComponentDefinition,\n options\n );\n } catch (error) {\n // Structural validation owns malformed trees; quality remains additive.\n if (options.policy?.onRuleError === 'throw') throw error;\n const gate = options.policy?.gate;\n // A gate that could never be evaluated has not been satisfied: report the\n // failure and fail closed rather than pass a document nothing inspected.\n return emptyAnalysis(\n [\n {\n ruleId: PREPARE_RULE_ID,\n message: error instanceof Error ? error.message : String(error),\n },\n ],\n gate !== undefined && gate !== 'none'\n );\n }\n return pptxQualityEngine.analyzeSync(prepared, {\n profile:\n resolvePptxQualityProfile(options.profile) ??\n declaredPptxQualityProfile(doc) ??\n PPTX_DEFAULT_QUALITY_PROFILE,\n policy: options.policy,\n });\n}\n","import {\n chartInfoDesignFindings,\n DEFAULT_MAXIMUM_CHART_SERIES,\n DEFAULT_MAXIMUM_PIE_SLICES,\n fontCountFinding,\n mergeQualityProfiles,\n nearestPaletteToken,\n offPaletteFinding,\n placeholderFinding,\n QUALITY_CODES,\n QualityEngine,\n resolveRuleConfiguration,\n tableInfoDesignFindings,\n type JsonPatchOperation,\n type QualityProfile,\n type QualityRule,\n type QualityRuleFinding,\n type QualityRulePack,\n} from '@json-to-office/quality';\nimport type {\n PptxBlockSlotFact,\n PptxBoxFact,\n PptxCanvasFact,\n PptxChromeSlotFact,\n PptxChartFact,\n PptxColorFact,\n PptxFontFact,\n PptxPlaceholderFact,\n PptxQualityFact,\n PptxQualityModel,\n PptxSlideFact,\n PptxTableColumnFact,\n PptxTableFact,\n PptxTextFact,\n PptxThemeFact,\n} from './facts';\n\nconst RENDERER_DEFAULT_WIDTH_IN = 10;\nconst RENDERER_DEFAULT_HEIGHT_IN = 7.5;\n// Calibrated against rendered ground truth (jto-ops quality ground-truth\n// harness, 2026-08: 130 comparable mutated-template measurements plus per-box\n// adjudication of every comparable authored flag, all measured from the\n// soffice PDF). 0.46 is the highest value at which the reference stock\n// templates (jto-ops STOCK_REFERENCE_TEMPLATES; management-plan binds) stay\n// warning-clean — the binding constraint, since a rule that flags known-good\n// templates trains every consumer to ignore it. At that operating point the\n// rendered sample catches 52% of >1-line-height spills as OVERFLOW, 91% when\n// TIGHT is included, and 87% of any visible spill, with no OVERFLOW false\n// alarms. Remaining misses require rendered evidence (`rendered` certainty),\n// not a character-count model — see the harness header for the full method.\n// The estimator itself lives in `utils/textMetrics.ts`, shared with the\n// engine's bounded `fit` so both size a title the same way.\nimport {\n DEFAULT_CHAR_WIDTH_FACTOR,\n estimateTextHeightPt as estimateHeight,\n} from '../utils/textMetrics';\nconst DEFAULT_SAFETY_BUFFER_PT = 8;\nconst DEFAULT_MIN_READABLE_FONT_PT = 7;\nconst DEFAULT_MAX_BODY_WORDS_PER_SLIDE = 130;\n\nconst KNOWN_CANVASES: readonly {\n w: number;\n h: number;\n label: string;\n legacy?: boolean;\n}[] = [\n { w: 13.333, h: 7.5, label: '16:9 standard' },\n { w: 10, h: 5.625, label: '16:9 small' },\n { w: 7.5, h: 7.5, label: '1:1 carousel' },\n { w: 7.5, h: 9.375, label: '4:5 vertical' },\n { w: 4.5, h: 8, label: '9:16 story' },\n { w: 10, h: 7.5, label: '4:3 legacy', legacy: true },\n];\n\nfunction numberParameter(\n parameters: Readonly<Record<string, unknown>>,\n name: string,\n fallback: number\n): number {\n const value = parameters[name];\n return typeof value === 'number' && Number.isFinite(value) ? value : fallback;\n}\n\nfunction textFacts(facts: readonly PptxQualityFact[]): PptxTextFact[] {\n return facts.filter(\n (fact): fact is PptxTextFact => fact.kind === 'pptx/text'\n );\n}\n\nfunction estimateTextHeightPt(\n fact: PptxTextFact,\n charWidthFactor: number\n): { heightPt: number; lines: number } | undefined {\n if (fact.boxWidthPt === undefined || fact.boxHeightPt === undefined) {\n return undefined;\n }\n return estimateHeight(\n fact.text,\n fact.boxWidthPt,\n fact.fontSizePt,\n fact.lineSpacingPt,\n fact.paraSpaceBeforePt,\n fact.paraSpaceAfterPt,\n charWidthFactor\n );\n}\n\nexport const pptxCanvasRule: QualityRule<PptxQualityModel, PptxQualityFact> = {\n id: 'pptx/canvas',\n description:\n 'Slide dimensions: partially declared, legacy 4:3, or a size matching no known preset.',\n code: QUALITY_CODES.CANVAS_UNSPECIFIED,\n category: 'composition',\n defaultSeverity: 'info',\n defaultCertainty: 'deterministic',\n formats: ['pptx'],\n evaluate: ({ facts }) => {\n const canvas = facts.find(\n (fact): fact is PptxCanvasFact => fact.kind === 'pptx/canvas'\n );\n if (!canvas) return [];\n const { widthIn: width, heightIn: height } = canvas;\n if (width === undefined || height === undefined) {\n const missing = [\n width === undefined ? 'props.slideWidth' : undefined,\n height === undefined ? 'props.slideHeight' : undefined,\n ].filter((entry): entry is string => entry !== undefined);\n const state =\n missing.length === 2\n ? 'No slide canvas declared'\n : `Incomplete slide canvas (${missing[0]} missing)`;\n return [\n {\n code: QUALITY_CODES.CANVAS_UNSPECIFIED,\n severity: 'warning',\n category: 'integrity',\n message: `${state}: the renderer falls back to 4:3 (${RENDERER_DEFAULT_WIDTH_IN}×${RENDERER_DEFAULT_HEIGHT_IN}\"), and 16:9 content on that canvas leaves a dead strip at the bottom.`,\n path: canvas.path,\n suggestion:\n 'Declare props.slideWidth and props.slideHeight — 13.333 × 7.5 for a standard 16:9 deck.',\n context: {\n missing,\n rendererDefault: {\n slideWidth: RENDERER_DEFAULT_WIDTH_IN,\n slideHeight: RENDERER_DEFAULT_HEIGHT_IN,\n },\n },\n },\n ];\n }\n\n const match = KNOWN_CANVASES.find(\n (known) =>\n Math.abs(known.w - width) < 0.01 && Math.abs(known.h - height) < 0.01\n );\n if (match?.legacy) {\n return [\n {\n code: QUALITY_CODES.CANVAS_LEGACY,\n message: `Canvas is 4:3 legacy (${match.w}×${match.h}\") — modern screens are 16:9.`,\n path: canvas.path,\n suggestion:\n 'If 4:3 is not deliberate, use slideWidth 13.333 and slideHeight 7.5.',\n },\n ];\n }\n if (match) return [];\n return [\n {\n code: QUALITY_CODES.CANVAS_NONSTANDARD,\n message: `Canvas ${width}×${height}\" matches no common preset (16:9, 1:1, 4:5, 9:16).`,\n path: canvas.path,\n suggestion:\n 'Confirm the size is deliberate; a mistyped canvas distorts every slide.',\n context: {\n knownCanvases: KNOWN_CANVASES.map(({ w, h, label }) => ({\n slideWidth: w,\n slideHeight: h,\n label,\n })),\n },\n },\n ];\n },\n};\n\nexport const pptxMinimumFontRule: QualityRule<\n PptxQualityModel,\n PptxQualityFact\n> = {\n id: 'pptx/minimum-font-size',\n description: 'Text below the size a projected slide can carry.',\n code: QUALITY_CODES.FONT_SIZE_MIN,\n category: 'legibility',\n defaultSeverity: 'warning',\n defaultCertainty: 'measured',\n formats: ['pptx'],\n defaultParameters: { minimumFontPt: DEFAULT_MIN_READABLE_FONT_PT },\n evaluate: ({ facts, configuration }) => {\n const minimum = numberParameter(\n configuration.parameters,\n 'minimumFontPt',\n DEFAULT_MIN_READABLE_FONT_PT\n );\n return textFacts(facts)\n .filter((fact) => fact.fontSizePt < minimum)\n .map((fact) => ({\n message: `Effective font size is ${fact.fontSizePt}pt — unreadable on a projected slide.`,\n path: `${fact.path}/props`,\n suggestion: `Use at least ${minimum}pt; captions rarely work below 10pt.`,\n context: { fontSize: fact.fontSizePt, threshold: minimum },\n evidence: { actual: fact.fontSizePt, expected: minimum, unit: 'pt' },\n // `add` replaces an existing member, so this lifts an explicit\n // fontSize and overrides an inherited style value alike.\n fixes: [\n {\n op: 'add' as const,\n path: `${fact.path}/props/fontSize`,\n value: minimum,\n },\n ],\n }));\n },\n};\n\n/**\n * Largest whole font size that fits the box, for a ready-made overflow fix.\n *\n * Conservative on purpose: the authored leading is kept even when it derives\n * from the font size (real leading would shrink too), so a size this returns\n * fits under the same model that produced the finding. Undefined when no\n * readable size fits (the text or the box has to change) or when the box\n * auto-grows (`h` omitted — there is nothing to overflow).\n */\nfunction fittingFontSizePt(\n fact: PptxTextFact,\n charWidthFactor: number,\n minimumFontPt: number\n): number | undefined {\n if (fact.autoFit === true) return undefined;\n const minimumWholeSize = Math.ceil(minimumFontPt);\n for (\n let size = Math.floor(fact.fontSizePt) - 1;\n size >= minimumWholeSize;\n size--\n ) {\n const estimate = estimateTextHeightPt(\n { ...fact, fontSizePt: size },\n charWidthFactor\n );\n if (\n estimate !== undefined &&\n fact.boxHeightPt !== undefined &&\n estimate.heightPt <= fact.boxHeightPt\n ) {\n return size;\n }\n }\n return undefined;\n}\n\nexport const pptxTextFitRule: QualityRule<PptxQualityModel, PptxQualityFact> = {\n id: 'pptx/text-fit',\n description:\n 'Estimated text height against its box. An estimate, not a measurement.',\n code: QUALITY_CODES.TEXT_TIGHT,\n category: 'integrity',\n defaultSeverity: 'info',\n defaultCertainty: 'estimated',\n formats: ['pptx'],\n defaultParameters: {\n characterWidthFactor: DEFAULT_CHAR_WIDTH_FACTOR,\n safetyBufferPt: DEFAULT_SAFETY_BUFFER_PT,\n },\n evaluate: ({ facts, configuration, profile, policy }) => {\n const factor = numberParameter(\n configuration.parameters,\n 'characterWidthFactor',\n DEFAULT_CHAR_WIDTH_FACTOR\n );\n const safetyBufferPt = numberParameter(\n configuration.parameters,\n 'safetyBufferPt',\n DEFAULT_SAFETY_BUFFER_PT\n );\n const minimumFontConfiguration = resolveRuleConfiguration(\n pptxMinimumFontRule,\n profile,\n policy\n );\n const minimumFontPt = minimumFontConfiguration.enabled\n ? numberParameter(\n minimumFontConfiguration.parameters,\n 'minimumFontPt',\n DEFAULT_MIN_READABLE_FONT_PT\n )\n : DEFAULT_MIN_READABLE_FONT_PT;\n const findings: QualityRuleFinding[] = [];\n for (const fact of textFacts(facts)) {\n const estimate = estimateTextHeightPt(fact, factor);\n if (!estimate || fact.boxHeightPt === undefined) continue;\n const marginPt = fact.boxHeightPt - estimate.heightPt;\n const measured = {\n estimatedTextPt: Math.round(estimate.heightPt * 10) / 10,\n availablePt: Math.round(fact.boxHeightPt * 10) / 10,\n marginPt: Math.round(marginPt * 10) / 10,\n estimatedLines: estimate.lines,\n fontSize: fact.fontSizePt,\n boxWidthPt: Math.round((fact.boxWidthPt as number) * 10) / 10,\n };\n\n if (marginPt < -fact.lineSpacingPt) {\n const fittingSize = fittingFontSizePt(fact, factor, minimumFontPt);\n findings.push({\n code: QUALITY_CODES.TEXT_OVERFLOW,\n severity: 'warning',\n message: `Text is estimated at ${measured.estimatedTextPt}pt tall (${estimate.lines} line${estimate.lines === 1 ? '' : 's'} of ${fact.fontSizePt}pt) in a ${measured.availablePt}pt box — it will overflow.`,\n path: fact.path,\n suggestion:\n 'Shorten the text, reduce fontSize, or enlarge the box (h / rowSpan).',\n context: measured,\n evidence: {\n actual: measured.estimatedTextPt,\n expected: measured.availablePt,\n unit: 'pt',\n },\n // A ready-made patch only when a readable size fits; shortening\n // the text or growing the box stays the author's call.\n ...(fittingSize !== undefined && {\n fixes: [\n {\n op: 'add' as const,\n path: `${fact.path}/props/fontSize`,\n value: fittingSize,\n },\n ],\n }),\n });\n continue;\n }\n if (marginPt >= safetyBufferPt) continue;\n findings.push({\n code: QUALITY_CODES.TEXT_TIGHT,\n message:\n marginPt < 0\n ? `Text is estimated to exceed its ${measured.availablePt}pt box by ${-measured.marginPt}pt — within one line-height, so likely a harmless spill into the gap below.`\n : `Text fits its box with only ${measured.marginPt}pt to spare — renderer rounding can push it over.`,\n path: fact.path,\n suggestion: `Leave at least ${safetyBufferPt}pt of vertical margin.`,\n context: measured,\n evidence: {\n actual: measured.marginPt,\n expected: safetyBufferPt,\n unit: 'pt margin',\n },\n });\n }\n return findings;\n },\n};\n\nexport const pptxSlideDensityRule: QualityRule<\n PptxQualityModel,\n PptxQualityFact\n> = {\n id: 'pptx/slide-density',\n description: 'Body word count per slide.',\n code: QUALITY_CODES.SLIDE_DENSITY,\n category: 'information-design',\n defaultSeverity: 'warning',\n defaultCertainty: 'estimated',\n formats: ['pptx'],\n defaultParameters: { maximumBodyWords: DEFAULT_MAX_BODY_WORDS_PER_SLIDE },\n evaluate: ({ facts, configuration }) => {\n const threshold = numberParameter(\n configuration.parameters,\n 'maximumBodyWords',\n DEFAULT_MAX_BODY_WORDS_PER_SLIDE\n );\n return facts\n .filter((fact): fact is PptxSlideFact => fact.kind === 'pptx/slide')\n .filter((fact) => fact.bodyWords > threshold)\n .map((fact) => ({\n message: `${fact.bodyWords} words of body text on one slide — an audience reads a slide, it does not study one.`,\n path: fact.path,\n suggestion: 'One idea per slide: split the content across more slides.',\n context: { bodyWords: fact.bodyWords, threshold },\n evidence: {\n actual: fact.bodyWords,\n expected: threshold,\n unit: 'words',\n },\n }));\n },\n};\n\n/**\n * WCAG 2.1 AA. Large text — 18pt, or 14pt bold — is legible at 3:1; everything\n * else needs 4.5:1. Projection is less forgiving than a screen, not more, so\n * these are floors rather than targets.\n */\nconst AA_NORMAL_RATIO = 4.5;\nconst AA_LARGE_RATIO = 3;\nconst LARGE_TEXT_PT = 18;\n/** AA counts bold text as large from 14pt, two sizes below regular text. */\nconst LARGE_BOLD_TEXT_PT = 14;\n\nfunction channelLuminance(channel: number): number {\n const c = channel / 255;\n return c <= 0.03928 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4);\n}\n\n/** Relative luminance of a bare 6-digit hex, or undefined if unparseable. */\nfunction relativeLuminance(hex: string): number | undefined {\n const match = /^#?([0-9a-f]{6})$/i.exec(hex);\n if (!match) return undefined;\n const value = parseInt(match[1], 16);\n return (\n 0.2126 * channelLuminance((value >> 16) & 255) +\n 0.7152 * channelLuminance((value >> 8) & 255) +\n 0.0722 * channelLuminance(value & 255)\n );\n}\n\nfunction contrastRatio(a: string, b: string): number | undefined {\n const la = relativeLuminance(a);\n const lb = relativeLuminance(b);\n if (la === undefined || lb === undefined) return undefined;\n return (Math.max(la, lb) + 0.05) / (Math.min(la, lb) + 0.05);\n}\n\nexport const pptxTextContrastRule: QualityRule<\n PptxQualityModel,\n PptxQualityFact\n> = {\n id: 'pptx/text-contrast',\n description:\n 'Text against the surface behind it, judged by WCAG AA. Text over an image or a chart is skipped.',\n code: QUALITY_CODES.TEXT_CONTRAST,\n category: 'accessibility',\n defaultSeverity: 'warning',\n defaultCertainty: 'deterministic',\n formats: ['pptx'],\n defaultParameters: {\n normalRatio: AA_NORMAL_RATIO,\n largeRatio: AA_LARGE_RATIO,\n largeTextPt: LARGE_TEXT_PT,\n largeBoldTextPt: LARGE_BOLD_TEXT_PT,\n },\n evaluate: ({ facts, configuration }) => {\n const normalRatio = numberParameter(\n configuration.parameters,\n 'normalRatio',\n AA_NORMAL_RATIO\n );\n const largeRatio = numberParameter(\n configuration.parameters,\n 'largeRatio',\n AA_LARGE_RATIO\n );\n const largeTextPt = numberParameter(\n configuration.parameters,\n 'largeTextPt',\n LARGE_TEXT_PT\n );\n const largeBoldTextPt = numberParameter(\n configuration.parameters,\n 'largeBoldTextPt',\n LARGE_BOLD_TEXT_PT\n );\n\n return textFacts(facts).flatMap((fact) => {\n const { colorHex, backgroundHexes } = fact;\n if (!colorHex || !backgroundHexes?.length) return [];\n\n // A gradient is only as legible as its worst stop: the text crosses all\n // of them, and the reader only remembers where it disappeared.\n let worst: { ratio: number; background: string } | undefined;\n for (const background of backgroundHexes) {\n const ratio = contrastRatio(colorHex, background);\n if (ratio === undefined) continue;\n if (!worst || ratio < worst.ratio) worst = { ratio, background };\n }\n if (!worst) return [];\n\n const isLarge =\n fact.fontSizePt >= largeTextPt ||\n (fact.bold && fact.fontSizePt >= largeBoldTextPt);\n const required = isLarge ? largeRatio : normalRatio;\n if (worst.ratio >= required) return [];\n\n const rounded = Math.round(worst.ratio * 100) / 100;\n return [\n {\n message: `Text at #${colorHex} on #${worst.background} has ${rounded}:1 contrast — below the ${required}:1 needed at ${fact.fontSizePt}pt${fact.bold ? ' bold' : ''}.`,\n path: fact.path,\n suggestion:\n 'Darken the text, lighten it further, or change the surface behind it.',\n context: {\n colorHex,\n backgroundHex: worst.background,\n ratio: rounded,\n required,\n fontSizePt: fact.fontSizePt,\n bold: fact.bold,\n backgroundHexes,\n },\n evidence: {\n actual: rounded,\n expected: required,\n unit: ':1',\n },\n },\n ];\n });\n },\n};\n\n/**\n * Unfilled slots and leftover filler, in one rule over two codes.\n *\n * One rule because it is one question — \"is this text real yet?\" — and two\n * codes because the answers differ in consequence: a scaffold marker blocks\n * generation, filler only advises.\n */\nexport const pptxPlaceholderRule: QualityRule<\n PptxQualityModel,\n PptxQualityFact\n> = {\n id: 'pptx/placeholder-text',\n description: 'An unfilled scaffold slot, or leftover filler copy.',\n code: QUALITY_CODES.PLACEHOLDER_TEXT,\n category: 'integrity',\n defaultSeverity: 'warning',\n defaultCertainty: 'deterministic',\n formats: ['pptx'],\n evaluate: ({ facts }) =>\n facts\n .filter(\n (fact): fact is PptxPlaceholderFact => fact.kind === 'pptx/placeholder'\n )\n .map((fact) =>\n placeholderFinding({\n path: fact.path,\n kind: fact.placeholderKind,\n pattern: fact.pattern,\n excerpt: fact.excerpt,\n })\n ),\n};\n\n/**\n * Two opaque boxes on one slide that land on each other.\n *\n * Opacity is the whole of the geometric claim. An image, a chart, a table or a\n * filled rectangle paints its entire box, so two of them intersecting really\n * do hide each other. A *text* box says nothing of the kind — authors declare\n * one far larger than the words inside it, and the reference decks are full of\n * designs where two text rectangles cross and no ink does: an 80pt title\n * beside a 12pt label, a value centred in the hole of a donut. Word-level\n * overlap belongs to the rendered pass (#344), which can see where ink landed.\n *\n * Intersecting is not the same as wrong, which is why the verdict is split.\n * Reference-quality decks stack opaque rectangles constantly — an accent strip\n * along the top of a card, a badge in the corner of a photograph — so a plain\n * intersection is `info`: visible, not accused. Two cases are warnings because\n * neither is ever a design. A box whose geometry matches another to within a\n * couple of points is a leftover duplicate. And anything covering a chart or a\n * table covers data, which is the one thing a slide cannot afford to lose.\n *\n * A box fully inside a larger one is layering rather than collision. Equal\n * rectangles are not containment — that is the duplicate case, and it is\n * reported.\n */\nconst DEFAULT_OVERLAP_MIN_PT = 4;\nconst DEFAULT_OVERLAP_MIN_AREA_RATIO = 0.15;\n/** Below this share of the outer box, an inner box reads as a deliberate layer. */\nconst CONTAINED_AREA_RATIO = 0.95;\n/** Slack on the containment test: a nested box may sit a rounding step proud. */\nconst CONTAINMENT_SLACK_PT = 0.5;\n/** Two boxes agreeing to within this on every edge are the same box, twice. */\nconst DUPLICATE_TOLERANCE_PT = 2;\n\n/** Components whose whole point is data a reader has to be able to see. */\nconst DATA_COMPONENTS = new Set(['chart', 'highcharts', 'table']);\n\ninterface Rect {\n xPt: number;\n yPt: number;\n widthPt: number;\n heightPt: number;\n}\n\nfunction contains(outer: Rect, inner: Rect): boolean {\n const outerArea = outer.widthPt * outer.heightPt;\n const innerArea = inner.widthPt * inner.heightPt;\n if (outerArea === 0 || innerArea >= outerArea * CONTAINED_AREA_RATIO) {\n return false;\n }\n const slack = CONTAINMENT_SLACK_PT;\n return (\n inner.xPt >= outer.xPt - slack &&\n inner.yPt >= outer.yPt - slack &&\n inner.xPt + inner.widthPt <= outer.xPt + outer.widthPt + slack &&\n inner.yPt + inner.heightPt <= outer.yPt + outer.heightPt + slack\n );\n}\n\nfunction isDuplicate(a: Rect, b: Rect): boolean {\n const near = (x: number, y: number): boolean =>\n Math.abs(x - y) <= DUPLICATE_TOLERANCE_PT;\n return (\n near(a.xPt, b.xPt) &&\n near(a.yPt, b.yPt) &&\n near(a.widthPt, b.widthPt) &&\n near(a.heightPt, b.heightPt)\n );\n}\n\nexport const pptxBoxOverlapRule: QualityRule<\n PptxQualityModel,\n PptxQualityFact\n> = {\n id: 'pptx/box-overlap',\n description:\n 'Two opaque boxes on one slide that land on each other. A duplicate, or anything covering data, is a warning.',\n code: QUALITY_CODES.BOX_OVERLAP,\n category: 'integrity',\n defaultSeverity: 'info',\n defaultCertainty: 'deterministic',\n formats: ['pptx'],\n defaultParameters: {\n minimumOverlapPt: DEFAULT_OVERLAP_MIN_PT,\n minimumAreaRatio: DEFAULT_OVERLAP_MIN_AREA_RATIO,\n },\n evaluate: ({ facts, configuration }) => {\n const minimumOverlapPt = numberParameter(\n configuration.parameters,\n 'minimumOverlapPt',\n DEFAULT_OVERLAP_MIN_PT\n );\n const minimumAreaRatio = numberParameter(\n configuration.parameters,\n 'minimumAreaRatio',\n DEFAULT_OVERLAP_MIN_AREA_RATIO\n );\n const bySlide = new Map<string, PptxBoxFact[]>();\n for (const fact of facts) {\n if (fact.kind !== 'pptx/box' || !fact.opaque) continue;\n const slide = bySlide.get(fact.slidePath);\n if (slide) slide.push(fact);\n else bySlide.set(fact.slidePath, [fact]);\n }\n\n const findings: QualityRuleFinding[] = [];\n for (const slide of bySlide.values()) {\n const ordered = [...slide].sort((a, b) => a.order - b.order);\n for (let i = 0; i < ordered.length; i += 1) {\n for (let j = i + 1; j < ordered.length; j += 1) {\n const under = ordered[i];\n const over = ordered[j];\n // A box nested in another is a group, not a collision.\n if (over.path.startsWith(`${under.path}/`)) continue;\n if (under.path.startsWith(`${over.path}/`)) continue;\n\n const duplicate = isDuplicate(under, over);\n if (!duplicate && (contains(under, over) || contains(over, under))) {\n continue;\n }\n\n const overlapWidth =\n Math.min(under.xPt + under.widthPt, over.xPt + over.widthPt) -\n Math.max(under.xPt, over.xPt);\n const overlapHeight =\n Math.min(under.yPt + under.heightPt, over.yPt + over.heightPt) -\n Math.max(under.yPt, over.yPt);\n if (\n overlapWidth < minimumOverlapPt ||\n overlapHeight < minimumOverlapPt\n ) {\n continue;\n }\n const overlapArea = overlapWidth * overlapHeight;\n const smaller = Math.min(\n under.widthPt * under.heightPt,\n over.widthPt * over.heightPt\n );\n const ratio = smaller === 0 ? 0 : overlapArea / smaller;\n if (ratio < minimumAreaRatio) continue;\n\n const hidesData =\n DATA_COMPONENTS.has(under.componentName) ||\n DATA_COMPONENTS.has(over.componentName);\n const percent = Math.round(ratio * 100);\n findings.push({\n severity: duplicate || hidesData ? 'warning' : 'info',\n message: duplicate\n ? `Two ${over.componentName === under.componentName ? `${over.componentName}s` : 'boxes'} occupy the same rectangle — the later one hides the earlier entirely.`\n : hidesData\n ? `A ${over.componentName} covers ${percent}% of the ${under.componentName} drawn before it, hiding data.`\n : `A ${over.componentName} covers ${percent}% of the ${under.componentName} drawn before it; both paint their whole box.`,\n path: over.path,\n relatedPaths: [under.path],\n suggestion: duplicate\n ? 'Delete whichever of the two is left over.'\n : 'Move or resize one of the two if the overlap is not deliberate.',\n context: {\n covering: over.path,\n covered: under.path,\n overlapPercent: percent,\n duplicate,\n overlapPt: {\n width: Math.round(overlapWidth * 10) / 10,\n height: Math.round(overlapHeight * 10) / 10,\n },\n },\n evidence: {\n actual: percent,\n expected: 0,\n unit: '% of the smaller box',\n },\n });\n }\n }\n }\n return findings;\n },\n};\n\n/**\n * A slide table is a summary, not a report. Twelve rows is what a 16:9 canvas\n * holds at a size an audience can read from the back of a room; past that the\n * table is being stored on the slide rather than shown.\n */\nconst DEFAULT_MAX_TABLE_ROWS_PER_SLIDE = 12;\n\n/** Information design for charts: the comparison, the scale and the palette. */\nexport const pptxChartRule: QualityRule<PptxQualityModel, PptxQualityFact> = {\n id: 'pptx/chart-design',\n description:\n 'What a chart claims about its numbers: the comparison, the scale, the palette and the unit.',\n code: QUALITY_CODES.CHART_3D,\n category: 'information-design',\n defaultSeverity: 'warning',\n defaultCertainty: 'deterministic',\n formats: ['pptx'],\n defaultParameters: {\n maximumSeries: DEFAULT_MAXIMUM_CHART_SERIES,\n maximumSlices: DEFAULT_MAXIMUM_PIE_SLICES,\n },\n evaluate: ({ facts, configuration }) => {\n const maximumSeries = numberParameter(\n configuration.parameters,\n 'maximumSeries',\n DEFAULT_MAXIMUM_CHART_SERIES\n );\n const maximumSlices = numberParameter(\n configuration.parameters,\n 'maximumSlices',\n DEFAULT_MAXIMUM_PIE_SLICES\n );\n return facts\n .filter((fact): fact is PptxChartFact => fact.kind === 'pptx/chart')\n .flatMap((fact) => {\n const fix = seriesColorFix(fact);\n return chartInfoDesignFindings(fact, {\n maximumSeries,\n maximumSlices,\n ...(fix && { seriesColorFix: fix }),\n });\n });\n },\n};\n\n/**\n * The palette patch, when the theme has enough slots to draw every series.\n *\n * Only for a native chart: a Highcharts palette lives inside an options blob\n * the schema keeps opaque and the export server reads verbatim, so writing\n * into it means guessing at a structure this pass never validated.\n */\nfunction seriesColorFix(\n fact: PptxChartFact\n): readonly JsonPatchOperation[] | undefined {\n if (fact.componentName !== 'chart') return undefined;\n if (fact.seriesCount < 1 || fact.paletteTokens.length === 0) return undefined;\n const tokens = Array.from(\n { length: fact.seriesCount },\n (_, index) => fact.paletteTokens[index % fact.paletteTokens.length]\n );\n return [{ op: 'add', path: fact.seriesColorsPath, value: tokens }];\n}\n\n/** Information design for tables: alignment, rounding, rules and length. */\nexport const pptxTableRule: QualityRule<PptxQualityModel, PptxQualityFact> = {\n id: 'pptx/table-design',\n description:\n 'How a table lays its numbers out: alignment, rounding, rules and length.',\n code: QUALITY_CODES.TABLE_NUMERIC_ALIGN,\n category: 'information-design',\n defaultSeverity: 'warning',\n defaultCertainty: 'deterministic',\n formats: ['pptx'],\n defaultParameters: { maximumRows: DEFAULT_MAX_TABLE_ROWS_PER_SLIDE },\n evaluate: ({ facts, configuration }) => {\n const maximumRows = numberParameter(\n configuration.parameters,\n 'maximumRows',\n DEFAULT_MAX_TABLE_ROWS_PER_SLIDE\n );\n return facts\n .filter((fact): fact is PptxTableFact => fact.kind === 'pptx/table')\n .flatMap((fact) =>\n tableInfoDesignFindings(fact, {\n maximumRows,\n rowSurface: 'slide',\n rowSeverity: 'warning',\n alignFix: alignColumnRight,\n })\n );\n },\n};\n\n/**\n * Right-align every cell of one column, header included.\n *\n * A row-major table has no column to patch, so this is one operation per row,\n * and a plain-string cell has to become an object to carry an alignment at\n * all — `replace`, never `add`, because `add` at an array index splices and\n * would push the rest of the row sideways.\n */\nfunction alignColumnRight(\n column: PptxTableColumnFact\n): readonly JsonPatchOperation[] {\n return column.cells\n .filter((entry) => {\n const cell = entry.cell;\n return typeof cell === 'string' || cell.align !== 'right';\n })\n .map((entry) => ({\n op: 'replace' as const,\n path: entry.path,\n value:\n typeof entry.cell === 'string'\n ? { text: entry.cell, align: 'right' }\n : { ...entry.cell, align: 'right' },\n }));\n}\n\nconst DEFAULT_MAX_FONT_FAMILIES = 3;\n\n/** Every family the document can paint: the theme's roles plus authored ones. */\nexport const pptxFontCountRule: QualityRule<PptxQualityModel, PptxQualityFact> =\n {\n id: 'pptx/font-count',\n description: 'Distinct font families the deck can paint.',\n code: QUALITY_CODES.FONT_COUNT,\n category: 'brand',\n defaultSeverity: 'warning',\n defaultCertainty: 'deterministic',\n formats: ['pptx'],\n defaultParameters: { maximumFamilies: DEFAULT_MAX_FONT_FAMILIES },\n evaluate: ({ facts, configuration }) => {\n const maximum = numberParameter(\n configuration.parameters,\n 'maximumFamilies',\n DEFAULT_MAX_FONT_FAMILIES\n );\n const theme = facts.find(\n (fact): fact is PptxThemeFact => fact.kind === 'pptx/theme'\n );\n const authored = facts.filter(\n (fact): fact is PptxFontFact => fact.kind === 'pptx/font-family'\n );\n const families = new Set<string>(theme?.fontFamilies ?? []);\n const extraPaths: string[] = [];\n for (const fact of authored) {\n if (!families.has(fact.family)) extraPaths.push(fact.path);\n families.add(fact.family);\n }\n if (families.size <= maximum) return [];\n return [\n fontCountFinding({\n path: theme?.path ?? '/props',\n families: [...families].sort(),\n maximum,\n relatedPaths: [...new Set(extraPaths)],\n }),\n ];\n },\n };\n\n/** A literal colour the resolved theme does not define. */\nexport const pptxPaletteRule: QualityRule<PptxQualityModel, PptxQualityFact> = {\n id: 'pptx/palette-adherence',\n description: 'A literal colour the resolved theme does not define.',\n code: QUALITY_CODES.OFF_PALETTE,\n category: 'brand',\n defaultSeverity: 'info',\n defaultCertainty: 'deterministic',\n formats: ['pptx'],\n evaluate: ({ facts }) => {\n const theme = facts.find(\n (fact): fact is PptxThemeFact => fact.kind === 'pptx/theme'\n );\n const palette = theme?.paletteHexes ?? {};\n const known = new Set(Object.values(palette));\n return facts\n .filter((fact): fact is PptxColorFact => fact.kind === 'pptx/color')\n .filter((fact) => !known.has(fact.hex))\n .map((fact) => {\n const nearest = nearestPaletteToken(fact.hex, palette);\n return offPaletteFinding({\n path: fact.path,\n raw: fact.raw,\n hex: fact.hex,\n ...(nearest && { nearest }),\n });\n });\n },\n};\n\nconst DEFAULT_OFF_CANVAS_TOLERANCE_PT = 2;\n\n/**\n * Text drawn past the edge of the slide.\n *\n * Only text: a decorative shape or a photograph that bleeds off the canvas is\n * a technique, a word that does is a defect nobody can read. Judged on the\n * ink, not the box — a short left-aligned label in a box that overhangs the\n * edge by a few points loses nothing, while a wrapped title whose box sits an\n * inch off the slide loses a line. The ink is placed inside the box by the\n * text's alignment and estimated with the same width model as `text-fit`, so\n * a block body drawn for a wider canvas is caught on the narrower one it was\n * never designed for.\n */\nexport const pptxOffCanvasRule: QualityRule<PptxQualityModel, PptxQualityFact> =\n {\n id: 'pptx/off-canvas',\n description: 'Text ink drawn past the edge of the slide.',\n code: QUALITY_CODES.OFF_CANVAS,\n category: 'integrity',\n defaultSeverity: 'warning',\n defaultCertainty: 'measured',\n formats: ['pptx'],\n defaultParameters: {\n tolerancePt: DEFAULT_OFF_CANVAS_TOLERANCE_PT,\n characterWidthFactor: DEFAULT_CHAR_WIDTH_FACTOR,\n },\n evaluate: ({ facts, configuration }) => {\n const tolerance = numberParameter(\n configuration.parameters,\n 'tolerancePt',\n DEFAULT_OFF_CANVAS_TOLERANCE_PT\n );\n const canvas = facts.find(\n (fact): fact is PptxCanvasFact => fact.kind === 'pptx/canvas'\n );\n const widthPt = (canvas?.widthIn ?? RENDERER_DEFAULT_WIDTH_IN) * 72;\n const heightPt = (canvas?.heightIn ?? RENDERER_DEFAULT_HEIGHT_IN) * 72;\n const factor = numberParameter(\n configuration.parameters,\n 'characterWidthFactor',\n DEFAULT_CHAR_WIDTH_FACTOR\n );\n const findings: QualityRuleFinding[] = [];\n for (const fact of textFacts(facts)) {\n if (\n fact.boxXPt === undefined ||\n fact.boxYPt === undefined ||\n fact.boxWidthPt === undefined ||\n fact.boxHeightPt === undefined\n )\n continue;\n const longestLinePt =\n Math.max(\n 0,\n ...fact.text.split('\\n').map((line) => line.trimEnd().length)\n ) *\n fact.fontSizePt *\n factor;\n const inkWidthPt = Math.min(fact.boxWidthPt, longestLinePt);\n const inkHeightPt = Math.min(\n fact.boxHeightPt,\n estimateTextHeightPt(fact, factor)?.heightPt ?? fact.boxHeightPt\n );\n const inkLeft =\n fact.align === 'right'\n ? fact.boxXPt + fact.boxWidthPt - inkWidthPt\n : fact.align === 'center'\n ? fact.boxXPt + (fact.boxWidthPt - inkWidthPt) / 2\n : fact.boxXPt;\n const inkTop =\n fact.verticalAlign === 'bottom'\n ? fact.boxYPt + fact.boxHeightPt - inkHeightPt\n : fact.verticalAlign === 'middle'\n ? fact.boxYPt + (fact.boxHeightPt - inkHeightPt) / 2\n : fact.boxYPt;\n const overRight = inkLeft + inkWidthPt - widthPt;\n const overBottom = inkTop + inkHeightPt - heightPt;\n const overLeft = -inkLeft;\n const overTop = -inkTop;\n const worst = Math.max(overRight, overBottom, overLeft, overTop);\n if (worst <= tolerance) continue;\n const edge =\n worst === overRight\n ? 'right'\n : worst === overBottom\n ? 'bottom'\n : worst === overLeft\n ? 'left'\n : 'top';\n findings.push({\n path: fact.path,\n message: `Text runs ${Math.round(worst)}pt past the ${edge} edge of the slide; the reader never sees it.`,\n suggestion:\n 'Move or narrow the box, or size the layout from the slide (percentages, a frame) rather than in fixed inches.',\n context: {\n edge,\n overrunPt: Math.round(worst * 10) / 10,\n slideWidthPt: widthPt,\n slideHeightPt: heightPt,\n },\n evidence: { actual: Math.round(worst), expected: 0, unit: 'pt' },\n });\n }\n return findings;\n },\n };\n\n/** A block slot over the word budget its definition declares. */\nexport const pptxSlotBudgetRule: QualityRule<\n PptxQualityModel,\n PptxQualityFact\n> = {\n id: 'pptx/slot-budget',\n description: 'A block slot over the word budget its definition declares.',\n code: QUALITY_CODES.SLOT_BUDGET,\n category: 'composition',\n defaultSeverity: 'warning',\n defaultCertainty: 'deterministic',\n formats: ['pptx'],\n evaluate: ({ facts }) =>\n facts\n .filter(\n (fact): fact is PptxBlockSlotFact => fact.kind === 'pptx/block-slot'\n )\n .filter((fact) => fact.words > fact.maxWords)\n .map((fact) => ({\n path: fact.path,\n message:\n `${fact.block} ${fact.slot} runs to ${fact.words} words; the slot holds ` +\n `${fact.maxWords} — one claim, one sentence.`,\n suggestion:\n 'Cut it to the conclusion. Move the evidence into the body it summarises.',\n evidence: {\n summary: 'words in the slot against its budget',\n actual: fact.words,\n expected: fact.maxWords,\n unit: 'words',\n },\n context: { block: fact.block, slot: fact.slot },\n })),\n};\n\nfunction stringListParameter(\n parameters: Readonly<Record<string, unknown>>,\n name: string\n): string[] {\n const value = parameters[name];\n return Array.isArray(value)\n ? value.filter((entry): entry is string => typeof entry === 'string')\n : [];\n}\n\n/**\n * Chrome a profile requires, judged where the block declared the slot.\n *\n * The rule reads roles off the document's own definitions and required roles\n * off the profile; with no profile asking for anything it says nothing. That\n * is the theme/profile boundary in one place: selecting the consulting theme\n * styles a source line, selecting the consulting profile requires one.\n */\nexport const pptxRequiredChromeRule: QualityRule<\n PptxQualityModel,\n PptxQualityFact\n> = {\n id: 'pptx/required-chrome',\n description:\n 'A block slot with a role a profile or policy requires — a takeaway, a source — left empty. Off until one names roles.',\n code: QUALITY_CODES.CHROME_MISSING,\n category: 'consistency',\n defaultSeverity: 'warning',\n defaultCertainty: 'deterministic',\n formats: ['pptx'],\n defaultParameters: { required: [] },\n evaluate: ({ facts, configuration, profile }) => {\n const required = stringListParameter(configuration.parameters, 'required');\n if (required.length === 0) return [];\n return facts\n .filter(\n (fact): fact is PptxChromeSlotFact => fact.kind === 'pptx/chrome-slot'\n )\n .filter((fact) => required.includes(fact.role) && !fact.present)\n .map((fact) => ({\n path: fact.path,\n relatedPaths: [fact.invocation],\n message:\n `${fact.block} states no ${fact.role} in its \"${fact.slot}\" slot; ` +\n `the ${profile?.id ?? 'selected'} profile expects one on every ${fact.block}.`,\n suggestion: `Fill the \"${fact.slot}\" slot. The theme already styles it.`,\n context: { block: fact.block, slot: fact.slot, role: fact.role },\n }));\n },\n};\n\n/**\n * An action title that wraps past the lines a profile allows, measured in\n * the box its definition drew and with the width model the fit pass uses.\n * Off by default (`maxLines: 0`): a label title is a content convention,\n * and only a consulting profile asks every slide to lead with a claim.\n */\nexport const pptxActionTitleRule: QualityRule<\n PptxQualityModel,\n PptxQualityFact\n> = {\n id: 'pptx/action-title',\n description:\n 'An action-title slot that wraps past the lines a profile or policy allows. Off at 0.',\n code: QUALITY_CODES.ACTION_TITLE_LENGTH,\n category: 'hierarchy',\n defaultSeverity: 'warning',\n defaultCertainty: 'estimated',\n formats: ['pptx'],\n defaultParameters: { maxLines: 0 },\n evaluate: ({ facts, configuration }) => {\n const maxLines = numberParameter(configuration.parameters, 'maxLines', 0);\n if (maxLines <= 0) return [];\n return facts\n .filter(\n (fact): fact is PptxChromeSlotFact =>\n fact.kind === 'pptx/chrome-slot' &&\n fact.role === 'actionTitle' &&\n fact.estimatedLines !== undefined\n )\n .filter((fact) => (fact.estimatedLines ?? 0) > maxLines)\n .map((fact) => ({\n path: fact.path,\n relatedPaths: [fact.invocation],\n message:\n `The action title runs to ${fact.estimatedLines} lines at ${fact.fontSizePt}pt; ` +\n `an action title states its claim in at most ${maxLines}.`,\n suggestion:\n 'Cut the title to one claim with a number or a verb. Move the rest into the takeaway.',\n evidence: {\n summary: 'estimated lines against the profile limit',\n actual: fact.estimatedLines,\n expected: maxLines,\n unit: 'lines',\n },\n context: { block: fact.block, slot: fact.slot },\n }));\n },\n};\n\nexport const PPTX_QUALITY_RULES: QualityRulePack<\n PptxQualityModel,\n PptxQualityFact\n> = {\n id: 'pptx/default',\n rules: [\n pptxCanvasRule,\n pptxMinimumFontRule,\n pptxTextFitRule,\n pptxSlideDensityRule,\n pptxTextContrastRule,\n pptxPlaceholderRule,\n pptxBoxOverlapRule,\n pptxChartRule,\n pptxTableRule,\n pptxFontCountRule,\n pptxPaletteRule,\n pptxOffCanvasRule,\n pptxSlotBudgetRule,\n pptxRequiredChromeRule,\n pptxActionTitleRule,\n ],\n};\n\nexport const PPTX_QUALITY_PROFILES = {\n 'executive-presentation': {\n id: 'executive-presentation',\n formats: ['pptx'],\n description: 'Decision deck optimized for scan speed and projection.',\n rules: {\n 'pptx/minimum-font-size': { parameters: { minimumFontPt: 14 } },\n 'pptx/slide-density': { parameters: { maximumBodyWords: 70 } },\n },\n },\n 'technical-presentation': {\n id: 'technical-presentation',\n formats: ['pptx'],\n description: 'Portable professional presentation defaults.',\n },\n 'consulting-deck': {\n id: 'consulting-deck',\n formats: ['pptx'],\n description:\n 'Consulting readout: every content slide leads with a two-line action title, every chart carries a takeaway and a source.',\n rules: {\n 'pptx/required-chrome': {\n parameters: { required: ['takeaway', 'source'] },\n },\n 'pptx/action-title': { parameters: { maxLines: 2 } },\n 'pptx/slide-density': { parameters: { maximumBodyWords: 90 } },\n },\n },\n} as const satisfies Record<string, QualityProfile>;\n\nexport const PPTX_DEFAULT_QUALITY_PROFILE: QualityProfile =\n PPTX_QUALITY_PROFILES['technical-presentation'];\n\nconst PPTX_PROFILES_BY_ID: Readonly<Record<string, QualityProfile>> =\n PPTX_QUALITY_PROFILES;\n\n/**\n * The shipped profile a deck names in `props.qualityProfile`, so that\n * validation without arguments judges a blueprint scaffold by its archetype.\n * An unknown name is nobody's profile: the format default applies.\n */\nexport function declaredPptxQualityProfile(\n document: unknown\n): QualityProfile | undefined {\n const props = (document as { props?: { qualityProfile?: unknown } })?.props;\n const id = props?.qualityProfile;\n return typeof id === 'string' &&\n Object.prototype.hasOwnProperty.call(PPTX_PROFILES_BY_ID, id)\n ? PPTX_PROFILES_BY_ID[id]\n : undefined;\n}\n\n/**\n * Callers name a shipped profile by id — `{ id: 'executive-presentation', formats: ['pptx'] }`.\n * Without this lookup that request reaches the engine carrying nothing but its id,\n * so the analysis runs on defaults while stamping the requested profileId.\n */\nexport function resolvePptxQualityProfile(\n requested: QualityProfile | undefined\n): QualityProfile | undefined {\n if (!requested) return undefined;\n const registered = PPTX_PROFILES_BY_ID[requested.id];\n if (!registered) return requested;\n return mergeQualityProfiles(registered, requested);\n}\n\nexport const pptxQualityEngine = new QualityEngine(PPTX_QUALITY_RULES.rules);\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 { expandPptxBlocksWithPlugins } from '../blocks/document';\nimport { generatePluginPresentationSchema, exportPluginSchema } from './schema';\nimport { processPresentation } from '../core/structure';\nimport type { PresentationPackagingOptions } from '../core/finalizePackage';\nimport {\n containsHighcharts,\n renderProcessedViaIr,\n} from '../core/generateFromIr';\nimport { toChartFontFaces } from '@json-to-office/shared/fonts/node';\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 * Expand one registered component at its authored path.\n *\n * The shared block/plugin composition walks the tree; this is the code it\n * calls when it meets a registered name. Children have already been\n * expanded by the time it runs, so a container plugin receives standard\n * components exactly as before.\n */\n function pluginRenderer(\n warningsCollector: PipelineWarning[],\n theme: PptxThemeConfig,\n validateEmitted: ValidateEmitted | undefined\n ): (component: Record<string, unknown>, path: string) => Promise<unknown[]> {\n return async (component, path) => {\n const customComponent = componentMap.get(String(component.name))!;\n if (!component.props) {\n throw new Error(\n `Custom component '${customComponent.name}' must have a 'props' property. ` +\n `Use format: { name: '${customComponent.name}', props: {...} }`\n );\n }\n const version = component.version as string | undefined;\n const versionEntry = resolveComponentVersion(\n customComponent.name,\n customComponent.versions,\n version\n );\n const cleanedProps = cleanComponentProps(\n versionEntry,\n component.props as Record<string, unknown>\n );\n const versionLabel = version\n ? `${customComponent.name}@${version}`\n : customComponent.name;\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 let result: unknown;\n try {\n result = await versionEntry.render({\n props: cleanedProps,\n theme,\n addWarning,\n children: component.children as unknown[] | undefined,\n });\n } catch (error) {\n if (error instanceof ComponentValidationError) throw error;\n throw new Error(\n `Error processing custom component '${customComponent.name}': ${\n error instanceof Error ? error.message : String(error)\n }`\n );\n }\n const emitted = (\n Array.isArray(result) ? result : [result]\n ) as PptxComponentInput[];\n // The authored parent decides what emitted output may be: a slide for\n // slide-level plugins, the deck for slide-emitting ones.\n const depth = path.split('/children/').length - 1;\n validateEmitted?.(\n emitted,\n versionLabel,\n depth === 1 ? 'pptx' : depth === 2 ? 'slide' : undefined\n );\n return emitted;\n };\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 // Document-local JSON blocks and registered code share one bounded\n // expansion, in both directions: a plugin can emit a block, a block can\n // name a plugin. Nothing here loads code by name; a missing\n // registration is a validation error.\n const expanded = await expandPptxBlocksWithPlugins(\n modedRoot,\n resolvedTheme,\n new Set(componentMap.keys()),\n pluginRenderer(warnings, resolvedTheme, validateEmitted)\n );\n const processedDocument = expanded.document;\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; a chart-bearing deck materialises them\n // for the export server's browser, exactly as the core pipeline does.\n const processed = processPresentation(processedDocument, {\n theme: resolvedTheme,\n services: state.services,\n sourceMap: expanded.sourceMap,\n warnings,\n });\n const hasHighcharts = containsHighcharts(processed);\n const resolvedFonts = await resolveDocumentFonts(\n processedDocument,\n resolvedTheme,\n warnings,\n state.fonts,\n hasHighcharts\n );\n const chartFonts = hasHighcharts ? toChartFontFaces(resolvedFonts) : [];\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(processed, warnings, {\n renderer,\n services: state.services,\n deterministic:\n options?.deterministic ?? state.packaging.deterministic,\n generatedAt: options?.generatedAt ?? state.packaging.generatedAt,\n ...(chartFonts.length > 0 ? { chartFonts } : {}),\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 * 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":";;;;;;;;;;;AA2BO,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;AAtCA,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,sBAAsB;AAAA,MACtB,eAAe;AAAA,MACf,uBAAuB;AAAA,MACvB,iBAAiB;AAAA,MACjB,2BAA2B;AAAA,MAC3B,wBAAwB;AAAA,MACxB,wBAAwB;AAAA,MACxB,gBAAgB;AAAA,MAChB,iBAAiB;AAAA,IACnB;AAAA;AAAA;;;ACvBA,IAuBa,cAEA,eAEA,wBAwa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AO,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;;;ADrdA,SAAS,2BAAAI,gCAA+B;;;AL5EjC,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","path","background","hyperlink","fill","color","createPptxGenJsRenderer","createOfficeOpenPptxRenderer","registry","path","path","resolve","result","path","DEFAULT_PPTX_RENDERER_ID","SEMANTIC_COLOR_NAMES","designColors","mergeWithDefaults","frame","path","estimate","mergeWithDefaults","path","BlockEvaluationError","toAuthoredBlockPointer","validatePresentationDocument","path","effects","fill","color","path","designColors","SEMANTIC_COLOR_NAMES","DEFAULT_PPTX_RENDERER_ID","readFileSync","collectPlaceholders","path","collectPlaceholders","estimateTextHeightPt","background","resolveComponentVersion","DuplicateComponentError","ComponentValidationError","validatePresentationDocument","ComponentValidationError","toChartFontFaces","path","resolveComponentVersion","ComponentValidationError","DuplicateComponentError","validationDocument","toChartFontFaces","resolveComponentVersion"]}
|