@json-to-office/core-pptx 0.26.0 → 0.28.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/components/image.d.ts.map +1 -1
- package/dist/core/generationContext.d.ts +7 -3
- package/dist/core/generationContext.d.ts.map +1 -1
- package/dist/core/generator.d.ts +6 -0
- package/dist/core/generator.d.ts.map +1 -1
- package/dist/core/render.d.ts.map +1 -1
- package/dist/core/template.d.ts.map +1 -1
- package/dist/index.js +110 -38
- package/dist/index.js.map +1 -1
- package/dist/plugin/createPresentationGenerator.d.ts +6 -0
- package/dist/plugin/createPresentationGenerator.d.ts.map +1 -1
- package/dist/plugin/types.d.ts +7 -0
- package/dist/plugin/types.d.ts.map +1 -1
- package/dist/themes/defaults.d.ts +6 -0
- package/dist/themes/defaults.d.ts.map +1 -1
- package/dist/themes/index.d.ts +1 -1
- package/dist/themes/index.d.ts.map +1 -1
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/dist/utils/baseDirContext.d.ts +19 -0
- package/dist/utils/baseDirContext.d.ts.map +1 -0
- package/dist/utils/imageSource.d.ts +14 -0
- package/dist/utils/imageSource.d.ts.map +1 -1
- package/dist/utils/warn.d.ts +1 -0
- package/dist/utils/warn.d.ts.map +1 -1
- package/package.json +3 -3
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/core/generator.ts","../src/types.ts","../src/utils/warn.ts","../src/core/grid.ts","../src/themes/defaults.ts","../src/utils/componentDefaults.ts","../src/utils/resolveComponentTree.ts","../src/utils/hyperlink.ts","../src/core/structure.ts","../src/core/render.ts","../src/utils/color.ts","../src/utils/fontAliasContext.ts","../src/components/text.ts","../src/components/image.ts","../src/utils/imageSource.ts","../src/components/shape.ts","../src/utils/fillXml.ts","../src/components/table.ts","../src/utils/environment.ts","../src/components/highcharts.ts","../src/components/chart.ts","../src/components/index.ts","../src/core/template.ts","../src/core/fontResolution.ts","../src/core/generationContext.ts","../src/core/packagePresentation.ts","../src/plugin/index.ts","../src/plugin/createPresentationGenerator.ts","../src/plugin/validation.ts","../src/plugin/schema.ts","../src/index.ts"],"sourcesContent":["/**\n * Presentation Generator\n * Main orchestration functions for the PPTX generation pipeline\n */\n\nimport PptxGenJS from 'pptxgenjs';\nimport { writeFileSync } from 'fs';\nimport type {\n PresentationComponentDefinition,\n PptxThemeConfig,\n PipelineWarning,\n PendingXmlFill,\n} from '../types';\nimport { isPresentationComponent } from '../types';\nimport type { ServicesConfig, FontRuntimeOpts } from '@json-to-office/shared';\nimport { processPresentation } from './structure';\nimport { renderPresentation } from './render';\nimport { resolveDocumentFonts } from './fontResolution';\nimport { resolveThemeContext } from './generationContext';\nimport {\n collectImageSourceConflicts,\n collectTextContentConflicts,\n validateJsonPresentationDocument,\n validatePresentationDocument,\n type ValidationError,\n} from '@json-to-office/shared-pptx';\nimport {\n packagePresentationBuffer,\n type PresentationPackagingOptions,\n} from './packagePresentation';\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\n/**\n * Options for the generation pipeline\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\n// Font resolution shared with the plugin path — see ./fontResolution.ts\n\n/**\n * Result from generateBufferWithWarnings\n */\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\nfunction assertValidPresentation(\n input: string | unknown,\n validation?: GenerationValidationOptions\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 if (!result.valid) {\n throw new PresentationValidationError(result.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/**\n * Type guard for presentation component\n */\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/**\n * Generate a PptxGenJS instance from a presentation component definition\n */\nexport async function generatePresentation(\n document: PresentationComponentDefinition,\n options?: GenerationOptions,\n warnings?: PipelineWarning[],\n pendingFills?: PendingXmlFill[]\n): Promise<PptxGenJS> {\n assertValidPresentation(document, options?.validation);\n\n if (!document || document.name !== 'pptx') {\n throw new Error('Top-level component must be a pptx component');\n }\n\n assertNoContentConflicts(document);\n\n const processed = processPresentation(document, options);\n return await renderPresentation(processed, warnings, pendingFills);\n}\n\n/**\n * Generate a buffer from JSON 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 buffer from JSON definition, returning warnings alongside the buffer\n */\nexport async function generateBufferWithWarnings(\n jsonConfig: string | PresentationComponentDefinition,\n options?: GenerationOptions\n): Promise<GenerationResult> {\n assertValidPresentation(jsonConfig, options?.validation);\n\n let component: PresentationComponentDefinition;\n\n if (typeof jsonConfig === 'string') {\n const parsed = JSON.parse(jsonConfig);\n if (!isPresentationComponent(parsed)) {\n throw new Error('Parsed JSON must be a presentation component');\n }\n component = parsed;\n } else {\n component = jsonConfig;\n }\n\n const warnings: PipelineWarning[] = [];\n\n // Props defaulting, inline-theme normalization, theme resolution,\n // export-mode pre-pass and cache-key scoping — shared with the plugin\n // pipeline so the two cannot drift (see core/generationContext.ts).\n const context = resolveThemeContext(component, {\n customThemes: options?.customThemes,\n fonts: options?.fonts,\n warnings,\n });\n component = context.document;\n // resolveDocumentFonts fires `fonts.onResolved` internally when a\n // listener is registered (LibreOffice preview stager). The PPTX itself\n // never embeds bytes.\n await resolveDocumentFonts(\n component,\n context.theme,\n warnings,\n options?.fonts\n );\n // processPresentation takes the resolved theme by value — the document's\n // `props.theme` stays as authored and is not consulted again.\n const effectiveOptions: GenerationOptions = {\n ...options,\n theme: context.theme,\n };\n // Gradient/pattern fills render as sentinel solid fills during generation;\n // packagePresentationBuffer splices the real fill XML in afterwards.\n const pendingFills: PendingXmlFill[] = [];\n const pptx = await generatePresentation(\n component,\n effectiveOptions,\n warnings,\n pendingFills\n );\n const data = await pptx.write({ outputType: 'nodebuffer' });\n const buffer = await packagePresentationBuffer(data as Buffer, {\n ...options,\n pendingFills,\n });\n return { buffer, warnings };\n}\n\n/**\n * Generate and save a .pptx file from JSON 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\n/**\n * Save a PptxGenJS instance to file\n */\nexport async function savePresentation(\n pptx: PptxGenJS,\n outputPath: string,\n options?: PresentationPackagingOptions\n): Promise<void> {\n const data = await pptx.write({ outputType: 'nodebuffer' });\n const buffer = await packagePresentationBuffer(data as Buffer, options);\n writeFileSync(outputPath, buffer);\n}\n\n/**\n * Export the main API\n */\nexport const PresentationGenerator = {\n generate: generatePresentation,\n generateBufferFromJson,\n generateBufferWithWarnings,\n generateAndSaveFromJson,\n generateFromFile,\n save: savePresentation,\n isPresentationComponentDefinition,\n};\n","/**\n * PPTX Core Types\n */\n\nimport type { ServicesConfig } from '@json-to-office/shared';\nimport type {\n GradientFill,\n PptxComponentDefaults,\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 id?: string;\n props: {\n title?: string;\n author?: string;\n subject?: string;\n company?: string;\n theme?: string;\n slideWidth?: number;\n slideHeight?: number;\n rtlMode?: boolean;\n language?: string;\n pageNumberFormat?: '9' | '09';\n componentDefaults?: PptxComponentDefaults;\n grid?: GridConfig;\n templates?: TemplateSlideDefinition[];\n };\n children?: PptxComponentInput[];\n}\n\nexport interface SlideComponentDefinition {\n name: 'slide';\n id?: string;\n props: {\n background?: {\n color?: string;\n gradient?: GradientFill;\n image?: { path?: string; base64?: string };\n };\n transition?: {\n type?: string;\n speed?: string;\n };\n notes?: string;\n layout?: string;\n hidden?: boolean;\n template?: string;\n placeholders?: Record<string, PptxComponentInput>;\n };\n children?: PptxComponentInput[];\n}\n\nexport interface ProcessedPresentation {\n metadata: {\n title?: string;\n author?: string;\n subject?: string;\n company?: string;\n };\n theme: PptxThemeConfig;\n grid?: GridConfig;\n slideWidth: number;\n slideHeight: number;\n rtlMode: boolean;\n /** Default presentation language (BCP-47) for spell-checking */\n language?: string;\n pageNumberFormat: '9' | '09';\n slides: ProcessedSlide[];\n templates?: TemplateSlideDefinition[];\n services?: ServicesConfig;\n}\n\nexport interface ProcessedSlide {\n components: PptxComponentInput[];\n background?: {\n color?: string;\n gradient?: GradientFill;\n image?: { path?: string; base64?: string };\n };\n notes?: string;\n layout?: string;\n hidden?: boolean;\n template?: string;\n placeholders?: Record<string, PptxComponentInput>;\n}\n\nexport interface GridConfig {\n columns?: number;\n rows?: number;\n margin?:\n | number\n | { top: number; right: number; bottom: number; left: number };\n gutter?: number | { column: number; row: number };\n}\n\nexport interface GridPosition {\n column: number;\n row: number;\n columnSpan?: number;\n rowSpan?: number;\n}\n\nexport interface TextStyle {\n fontSize?: number;\n fontFace?: string;\n fontColor?: string;\n bold?: boolean;\n /**\n * Per-style weight (100–900). Overrides `bold` when set — renderer picks\n * the closest embedded variant via CSS font-matching and emits the run\n * under a synthetic family alias (e.g. \"Inter Light\" for weight 300).\n */\n fontWeight?: number;\n italic?: boolean;\n align?: string;\n lineSpacing?: number;\n charSpacing?: number;\n paraSpaceAfter?: number;\n}\n\nexport type StyleName =\n | 'title'\n | 'subtitle'\n | 'heading1'\n | 'heading2'\n | 'heading3'\n | 'body'\n | 'caption';\n\nexport interface PptxThemeConfig {\n name: string;\n colors: {\n primary: string;\n secondary: string;\n accent: string;\n background: string;\n text: string;\n text2?: string;\n background2?: string;\n accent4?: string;\n accent5?: string;\n accent6?: string;\n };\n fonts: {\n heading: string;\n body: string;\n };\n defaults: {\n fontSize: number;\n fontColor: string;\n };\n styles?: Partial<Record<StyleName, TextStyle>>;\n componentDefaults?: PptxComponentDefaults;\n}\n\nexport interface PlaceholderDefinition {\n name: string;\n x?: number;\n y?: number;\n w?: number;\n h?: number;\n grid?: GridPosition;\n defaults?: PptxComponentInput;\n}\n\nexport interface TemplateSlideDefinition {\n name: string;\n background?: {\n color?: string;\n gradient?: GradientFill;\n image?: { path?: string; base64?: string };\n };\n margin?: number | [number, number, number, number];\n slideNumber?: {\n x: number;\n y: number;\n w?: number;\n h?: number;\n color?: string;\n fontSize?: number;\n };\n objects?: PptxComponentInput[];\n placeholders?: PlaceholderDefinition[];\n grid?: GridConfig;\n}\n\nexport interface SlideContext {\n slideNumber: number;\n totalSlides: number;\n pageNumberFormat: '9' | '09';\n /** Default presentation language (BCP-47); text runs inherit it unless overridden */\n language?: string;\n}\n\nexport interface SlideRenderContext {\n slideCtx?: SlideContext;\n services?: ServicesConfig;\n slideWidth: number;\n slideHeight: number;\n /**\n * Per-generation registry of fills (gradient/pattern) that pptxgenjs cannot\n * express. Components render a sentinel solid fill tagged with a unique\n * objectName; packagePresentationBuffer 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","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 IMAGE_NO_SOURCE: 'IMAGE_NO_SOURCE',\n IMAGE_PROBE_FAILED: 'IMAGE_PROBE_FAILED',\n MISSING_TEMPLATE: 'MISSING_TEMPLATE',\n UNKNOWN_PLACEHOLDER: 'UNKNOWN_PLACEHOLDER',\n PLACEHOLDER_NO_POSITION: 'PLACEHOLDER_NO_POSITION',\n THEME_COLOR_FALLBACK: 'THEME_COLOR_FALLBACK',\n UNKNOWN_COLOR: 'UNKNOWN_COLOR',\n GRID_POSITION_CLAMPED: 'GRID_POSITION_CLAMPED',\n TEXT_NO_CONTENT: 'TEXT_NO_CONTENT',\n UNKNOWN_PATTERN_PRESET: 'UNKNOWN_PATTERN_PRESET',\n ADVANCED_FILL_FALLBACK: 'ADVANCED_FILL_FALLBACK',\n IMAGE_ZERO_BOX: 'IMAGE_ZERO_BOX',\n FONT_UNRESOLVED: 'FONT_UNRESOLVED',\n} as const;\n\nexport type WarningCode = (typeof W)[keyof typeof W];\n\nexport function warn(\n warnings: PipelineWarning[] | undefined,\n code: WarningCode,\n message: string,\n extra?: Partial<PipelineWarning>\n): void {\n if (warnings) {\n warnings.push({ code, message, ...extra });\n } else {\n console.warn(message);\n }\n}\n","/**\n * Grid Layout Resolution\n * Converts grid coordinates to absolute x/y/w/h positions\n */\n\nimport type { GridConfig, GridPosition, PptxComponentInput, PipelineWarning } from '../types';\nimport { warn, W } from '../utils/warn';\n\nexport const DEFAULT_GRID_CONFIG: Required<{\n columns: number;\n rows: number;\n margin: { top: number; right: number; bottom: number; left: number };\n gutter: { column: number; row: number };\n}> = {\n columns: 12,\n rows: 6,\n margin: { top: 0.5, right: 0.5, bottom: 0.5, left: 0.5 },\n gutter: { column: 0.2, row: 0.2 },\n};\n\nfunction resolveMargin(margin: GridConfig['margin']) {\n if (margin == null) return DEFAULT_GRID_CONFIG.margin;\n if (typeof margin === 'number') return { top: margin, right: margin, bottom: margin, left: margin };\n return margin;\n}\n\nfunction resolveGutter(gutter: GridConfig['gutter']) {\n if (gutter == null) return DEFAULT_GRID_CONFIG.gutter;\n if (typeof gutter === 'number') return { column: gutter, row: gutter };\n return gutter;\n}\n\n/**\n * Merge a template-level grid override on top of the presentation grid.\n * Template fields take precedence; nested margin/gutter objects are shallow-merged.\n * Both sides are normalized to object form before merging so that a shorthand\n * base (e.g. margin: 0.5) combined with a partial override (e.g. { top: 1.1 })\n * doesn't lose the other sides.\n */\nexport function mergeGridConfigs(\n base: GridConfig | undefined,\n override: GridConfig | undefined\n): GridConfig | undefined {\n if (!override) return base;\n if (!base) return override;\n\n const merged: GridConfig = {\n columns: override.columns ?? base.columns,\n rows: override.rows ?? base.rows,\n };\n\n // Merge margin — normalize both to object form first\n if (override.margin !== undefined) {\n if (typeof override.margin === 'number') {\n merged.margin = override.margin;\n } else {\n merged.margin = { ...resolveMargin(base.margin), ...override.margin };\n }\n } else {\n merged.margin = base.margin;\n }\n\n // Merge gutter — same normalization\n if (override.gutter !== undefined) {\n if (typeof override.gutter === 'number') {\n merged.gutter = override.gutter;\n } else {\n merged.gutter = { ...resolveGutter(base.gutter), ...override.gutter };\n }\n } else {\n merged.gutter = base.gutter;\n }\n\n return merged;\n}\n\nexport function resolveGridPosition(\n gridPos: GridPosition,\n gridConfig: GridConfig | undefined,\n slideWidth: number,\n slideHeight: number,\n warnings?: PipelineWarning[]\n): { x: number; y: number; w: number; h: number } {\n const cols = Math.max(1, gridConfig?.columns ?? DEFAULT_GRID_CONFIG.columns);\n const rows = Math.max(1, gridConfig?.rows ?? DEFAULT_GRID_CONFIG.rows);\n const margin = resolveMargin(gridConfig?.margin);\n const gutter = resolveGutter(gridConfig?.gutter);\n\n const col = Math.max(0, Math.min(gridPos.column, cols - 1));\n const row = Math.max(0, Math.min(gridPos.row, rows - 1));\n const colSpan = Math.max(1, Math.min(gridPos.columnSpan ?? 1, cols - col));\n const rowSpan = Math.max(1, Math.min(gridPos.rowSpan ?? 1, rows - row));\n\n if (gridPos.column !== col || gridPos.row !== row) {\n warn(warnings, W.GRID_POSITION_CLAMPED,\n `Grid position clamped: column ${gridPos.column}→${col}, row ${gridPos.row}→${row} (grid: ${cols}×${rows})`\n );\n }\n\n const availableW = slideWidth - margin.left - margin.right;\n const availableH = slideHeight - margin.top - margin.bottom;\n const trackW = (availableW - (cols - 1) * gutter.column) / cols;\n const trackH = (availableH - (rows - 1) * gutter.row) / rows;\n\n const x = margin.left + col * (trackW + gutter.column);\n const y = margin.top + row * (trackH + gutter.row);\n const w = colSpan * trackW + (colSpan - 1) * gutter.column;\n const h = rowSpan * trackH + (rowSpan - 1) * gutter.row;\n\n return { x, y, w, h };\n}\n\nexport function resolveComponentGridPosition(\n component: PptxComponentInput,\n gridConfig: GridConfig | undefined,\n slideWidth: number,\n slideHeight: number,\n warnings?: PipelineWarning[]\n): PptxComponentInput {\n const gridPos = component.props.grid as GridPosition | undefined;\n if (!gridPos) return component;\n\n const resolved = resolveGridPosition(gridPos, gridConfig, slideWidth, slideHeight, warnings);\n\n const { grid: _grid, ...restProps } = component.props; // eslint-disable-line no-unused-vars, @typescript-eslint/no-unused-vars\n const newProps = { ...restProps };\n\n // When explicit values use percentage strings, convert grid-resolved inches\n // to percentages too so pptxgenjs receives consistent units per element.\n const hasPercentX = typeof newProps.x === 'string' || typeof newProps.w === 'string';\n const hasPercentY = typeof newProps.y === 'string' || typeof newProps.h === 'string';\n\n const toPercX = (v: number) => `${+((v / slideWidth) * 100).toFixed(2)}%`;\n const toPercY = (v: number) => `${+((v / slideHeight) * 100).toFixed(2)}%`;\n\n // Grid sets x/y/w/h, but explicit values on the element override individually\n if (newProps.x == null) newProps.x = hasPercentX ? toPercX(resolved.x) : resolved.x;\n if (newProps.y == null) newProps.y = hasPercentY ? toPercY(resolved.y) : resolved.y;\n if (newProps.w == null) newProps.w = hasPercentX ? toPercX(resolved.w) : resolved.w;\n if (newProps.h == null) newProps.h = hasPercentY ? toPercY(resolved.h) : resolved.h;\n\n return { ...component, props: newProps };\n}\n","/**\n * PPTX Theme Defaults\n */\n\nimport type { PptxThemeConfig, TextStyle, StyleName } from '../types';\n\nconst DEFAULT_STYLES: Partial<Record<StyleName, TextStyle>> = {\n title: { fontSize: 36, bold: true, fontColor: 'text', align: 'center' },\n subtitle: { fontSize: 20, italic: true, fontColor: 'text2', align: 'center' },\n heading1: { fontSize: 28, bold: true, fontColor: 'primary' },\n heading2: { fontSize: 22, bold: true, fontColor: 'primary' },\n heading3: { fontSize: 18, bold: true, fontColor: 'text' },\n body: { fontSize: 14 },\n caption: { fontSize: 10, italic: true, fontColor: 'text2' },\n};\n\nexport const DEFAULT_PPTX_THEME: PptxThemeConfig = {\n name: 'default',\n colors: {\n primary: '#4472C4',\n secondary: '#ED7D31',\n accent: '#70AD47',\n background: '#FFFFFF',\n text: '#333333',\n text2: '#44546A',\n background2: '#E7E6E6',\n accent4: '#FFC000',\n accent5: '#5B9BD5',\n accent6: '#70AD47',\n },\n fonts: {\n heading: 'Arial',\n body: 'Arial',\n },\n defaults: {\n fontSize: 18,\n fontColor: '#333333',\n },\n styles: DEFAULT_STYLES,\n};\n\nconst PPTX_THEMES: Record<string, PptxThemeConfig> = {\n default: DEFAULT_PPTX_THEME,\n dark: {\n name: 'dark',\n colors: {\n primary: '#5B9BD5',\n secondary: '#FF6F61',\n accent: '#6BCB77',\n background: '#2D2D2D',\n text: '#FFFFFF',\n text2: '#CCCCCC',\n background2: '#3D3D3D',\n accent4: '#FFB347',\n accent5: '#77DD77',\n accent6: '#AEC6CF',\n },\n fonts: {\n heading: 'Arial',\n body: 'Arial',\n },\n defaults: {\n fontSize: 18,\n fontColor: '#FFFFFF',\n },\n styles: DEFAULT_STYLES,\n },\n minimal: {\n name: 'minimal',\n colors: {\n primary: '#000000',\n secondary: '#666666',\n accent: '#999999',\n background: '#FFFFFF',\n text: '#000000',\n text2: '#444444',\n background2: '#F5F5F5',\n accent4: '#BBBBBB',\n accent5: '#DDDDDD',\n accent6: '#888888',\n },\n fonts: {\n heading: 'Helvetica',\n body: 'Helvetica',\n },\n defaults: {\n fontSize: 18,\n fontColor: '#000000',\n },\n styles: DEFAULT_STYLES,\n },\n};\n\nexport function getPptxTheme(name: string): PptxThemeConfig {\n return PPTX_THEMES[name] || DEFAULT_PPTX_THEME;\n}\n\nexport const pptxThemes = PPTX_THEMES;\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 * Slide-targeted hyperlinks\n *\n * `hyperlink.slide` is 1-based over the slides *as authored* in the JSON —\n * slides carrying `enabled: false` still count. Structure processing remaps\n * every ref to the position its target ends up at in the generated deck, so\n * toggling one slide off never silently retargets the links after it.\n *\n * A ref that cannot be resolved — target dropped, or index outside the\n * authored range — is marked unresolved here and dropped by the writer with a\n * warning. It must never reach pptxgenjs: it would emit a relationship to a\n * `slideN.xml` part that is not in the archive, which PowerPoint reports as a\n * damaged file.\n */\n\nimport type { PipelineWarning, PptxComponentInput } from '../types';\n\nexport const HYPERLINK_SLIDE_UNRESOLVED = 'HYPERLINK_SLIDE_UNRESOLVED';\n\nexport interface HyperlinkProps {\n url?: string;\n slide?: number;\n tooltip?: string;\n /** Internal: authored `slide` ref that resolves to no rendered slide. */\n unresolvedSlideRef?: number;\n}\n\n/** Authored 1-based slide number -> rendered 1-based slide number. */\nexport type SlideIndexMap = ReadonlyMap<number, number>;\n\nfunction remapHyperlink(\n hyperlink: HyperlinkProps,\n map: SlideIndexMap\n): HyperlinkProps {\n // `url` wins over `slide` at write time, so leave those refs alone.\n if (hyperlink.url || hyperlink.slide == null) return hyperlink;\n\n const rendered = map.get(hyperlink.slide);\n if (rendered === undefined) {\n const { slide, ...rest } = hyperlink;\n return { ...rest, unresolvedSlideRef: slide };\n }\n return rendered === hyperlink.slide\n ? hyperlink\n : { ...hyperlink, slide: rendered };\n}\n\n/**\n * Rewrite `hyperlink.slide` in a bare props bag. Template placeholder\n * `defaults` are merged into a component at render time without ever being a\n * component themselves, so they need rebasing on their own — otherwise a\n * `defaults.props.hyperlink.slide` reaches the writer as a raw authored index.\n */\nexport function remapHyperlinkProps<T extends Record<string, unknown>>(\n props: T,\n map: SlideIndexMap\n): T {\n const hyperlink = props.hyperlink as HyperlinkProps | undefined;\n if (!hyperlink || typeof hyperlink !== 'object') return props;\n\n const remapped = remapHyperlink(hyperlink, map);\n return remapped === hyperlink ? props : { ...props, hyperlink: remapped };\n}\n\n/** Rewrite every `hyperlink.slide` in a component subtree. Returns a new tree. */\nexport function remapHyperlinkSlideRefs(\n component: PptxComponentInput,\n map: SlideIndexMap\n): PptxComponentInput {\n const hyperlink = component.props?.hyperlink as HyperlinkProps | undefined;\n let next = component;\n\n if (hyperlink && typeof hyperlink === 'object') {\n const remapped = remapHyperlink(hyperlink, map);\n if (remapped !== hyperlink) {\n next = { ...next, props: { ...next.props, hyperlink: remapped } };\n }\n }\n\n if (next.children && next.children.length > 0) {\n next = {\n ...next,\n children: next.children.map((child) =>\n remapHyperlinkSlideRefs(child, map)\n ),\n };\n }\n\n return next;\n}\n\n/**\n * Write the pptxgenjs `hyperlink` option, dropping unresolvable slide refs.\n * Shared by every component that accepts a hyperlink.\n */\nexport function applyHyperlink(\n opts: Record<string, unknown>,\n hyperlink: HyperlinkProps | undefined,\n componentName: string,\n warnings?: PipelineWarning[]\n): void {\n if (!hyperlink) return;\n\n if (hyperlink.url) {\n opts.hyperlink = { url: hyperlink.url, tooltip: hyperlink.tooltip };\n return;\n }\n\n if (hyperlink.unresolvedSlideRef != null) {\n const message =\n `hyperlink.slide ${hyperlink.unresolvedSlideRef} matches no slide in the generated ` +\n `presentation (slide disabled, or index out of range) — hyperlink dropped`;\n if (warnings) {\n warnings.push({\n code: HYPERLINK_SLIDE_UNRESOLVED,\n message,\n component: componentName,\n });\n } else {\n console.warn(message);\n }\n return;\n }\n\n if (hyperlink.slide) {\n opts.hyperlink = { slide: hyperlink.slide, tooltip: hyperlink.tooltip };\n }\n}\n","/**\n * Structure Processing\n * JSON -> internal model\n */\n\nimport type {\n PptxComponentInput,\n PptxThemeConfig,\n PresentationComponentDefinition,\n ProcessedPresentation,\n ProcessedSlide,\n TemplateSlideDefinition,\n} from '../types';\nimport { isSlideComponent } from '../types';\nimport {\n resolveGridPosition,\n resolveComponentGridPosition,\n mergeGridConfigs,\n} from './grid';\nimport { getPptxTheme } from '../themes';\nimport type { GenerationOptions } from './generator';\nimport { resolveComponentTree } from '../utils/resolveComponentTree';\nimport {\n remapHyperlinkProps,\n remapHyperlinkSlideRefs,\n} from '../utils/hyperlink';\nimport { mergeWithDefaults } from '@json-to-office/shared';\n\n/** A slide child is rendered unless it carries `enabled: false`. */\nfunction isSlideEnabled(child: object): boolean {\n return !(\n 'enabled' in child && (child as { enabled?: boolean }).enabled === false\n );\n}\n\n/**\n * Map authored 1-based slide numbers (disabled slides included) to their\n * position in the generated deck. Dropped slides are absent from the map, so\n * hyperlinks pointing at them resolve to nothing instead of to whichever slide\n * happened to shift into that number.\n */\nfunction buildSlideIndexMap(\n children: PptxComponentInput[]\n): Map<number, number> {\n const map = new Map<number, number>();\n let authored = 0;\n let rendered = 0;\n for (const child of children) {\n if (!isSlideComponent(child)) continue;\n authored++;\n if (isSlideEnabled(child)) map.set(authored, ++rendered);\n }\n return map;\n}\n\nexport function processPresentation(\n document: PresentationComponentDefinition,\n options?: GenerationOptions\n): ProcessedPresentation {\n const { props, children = [] } = document;\n\n // The generation prologue hands the resolved theme over directly — after\n // the export-mode pre-pass, so a name lookup here would resurrect\n // pre-substitute font families. The `props.theme` resolution below (a name,\n // or an inline theme config object embedded in the document itself —\n // self-contained documents-as-data) is the fallback for direct callers.\n const baseTheme =\n options?.theme ??\n (typeof props.theme === 'object' && props.theme !== null\n ? (props.theme as PptxThemeConfig)\n : options?.customThemes?.[props.theme ?? 'default'] ??\n getPptxTheme(props.theme ?? 'default'));\n\n // Merge presentation-level componentDefaults on top of theme-level ones\n const presDefaults = props.componentDefaults;\n const theme = presDefaults\n ? {\n ...baseTheme,\n componentDefaults: mergeWithDefaults(\n presDefaults,\n baseTheme.componentDefaults || {}\n ),\n }\n : baseTheme;\n\n const slideWidth = props.slideWidth ?? 10;\n const slideHeight = props.slideHeight ?? 7.5;\n\n const slideIndexMap = buildSlideIndexMap(children);\n\n // Process template slide definitions\n let templates: TemplateSlideDefinition[] | undefined;\n if (props.templates && props.templates.length > 0) {\n templates = props.templates.map((m: TemplateSlideDefinition) => {\n const effectiveGrid = mergeGridConfigs(props.grid, m.grid);\n\n // Rebase slide refs in placeholder `defaults`, then resolve grid\n // positions. `defaults.props` is merged into the rendered component by\n // core/render.ts, so it reaches the writer just like a component's own\n // props and needs the same remapping.\n const resolvedPhs = m.placeholders?.map((ph) => {\n const phDefaults = ph.defaults;\n const defaultProps = phDefaults?.props\n ? remapHyperlinkProps(phDefaults.props, slideIndexMap)\n : undefined;\n const base =\n phDefaults && defaultProps && defaultProps !== phDefaults.props\n ? { ...ph, defaults: { ...phDefaults, props: defaultProps } }\n : ph;\n\n if (!base.grid) return base;\n const abs = resolveGridPosition(\n base.grid,\n effectiveGrid,\n slideWidth,\n slideHeight\n );\n return {\n ...base,\n x: base.x ?? abs.x,\n y: base.y ?? abs.y,\n w: base.w ?? abs.w,\n h: base.h ?? abs.h,\n grid: undefined,\n };\n });\n\n // Resolve componentDefaults then grid positions on fixed objects\n const defaultedObjects = m.objects\n ? resolveComponentTree(m.objects, theme)\n : undefined;\n const resolvedObjects = defaultedObjects?.map((obj) =>\n remapHyperlinkSlideRefs(\n resolveComponentGridPosition(\n obj,\n effectiveGrid,\n slideWidth,\n slideHeight\n ),\n slideIndexMap\n )\n );\n\n return { ...m, placeholders: resolvedPhs, objects: resolvedObjects };\n });\n }\n\n const slides: ProcessedSlide[] = [];\n\n for (const child of children) {\n if (isSlideComponent(child)) {\n // `enabled: false` drops the slide entirely; absent means enabled\n if (!isSlideEnabled(child)) continue;\n\n const slideComponents: PptxComponentInput[] = [];\n if (child.children) {\n for (const slideChild of child.children) {\n slideComponents.push(slideChild);\n }\n }\n\n // Resolve componentDefaults on all slide components, then rebase\n // slide-targeted hyperlinks onto the generated slide numbering\n const resolvedComponents = resolveComponentTree(\n slideComponents,\n theme\n ).map((component) => remapHyperlinkSlideRefs(component, slideIndexMap));\n\n const placeholders = child.props.placeholders as\n | Record<string, PptxComponentInput>\n | undefined;\n\n slides.push({\n components: resolvedComponents,\n background: child.props.background,\n notes: child.props.notes,\n layout: child.props.layout,\n hidden: child.props.hidden,\n template: child.props.template,\n placeholders: placeholders\n ? Object.fromEntries(\n Object.entries(placeholders).map(([name, component]) => [\n name,\n remapHyperlinkSlideRefs(component, slideIndexMap),\n ])\n )\n : undefined,\n });\n }\n }\n\n return {\n metadata: {\n title: props.title,\n author: props.author,\n subject: props.subject,\n company: props.company,\n },\n theme,\n grid: props.grid,\n slideWidth,\n slideHeight,\n rtlMode: props.rtlMode ?? false,\n language: props.language,\n pageNumberFormat: props.pageNumberFormat ?? '9',\n slides,\n templates,\n services: options?.services,\n };\n}\n","/**\n * Render Pipeline\n * Internal model -> pptxgenjs calls\n */\n\nimport PptxGenJS from 'pptxgenjs';\nimport type {\n ProcessedPresentation,\n PipelineWarning,\n PendingXmlFill,\n SlideContext,\n SlideRenderContext,\n} from '../types';\nimport { renderComponent, renderShapeComponent } from '../components';\nimport { resolveComponentGridPosition, mergeGridConfigs } from './grid';\nimport { resolveColor } from '../utils/color';\nimport { warn, W } from '../utils/warn';\nimport { buildSlideTemplateProps } from './template';\nimport { getDefaultsForType } from '../utils/componentDefaults';\nimport { resolveComponentDefaults } from '../utils/resolveComponentTree';\nimport { mergeWithDefaults } from '@json-to-office/shared';\n\nexport async function renderPresentation(\n processed: ProcessedPresentation,\n warnings?: PipelineWarning[],\n pendingFills?: PendingXmlFill[]\n): Promise<PptxGenJS> {\n const pptx = new PptxGenJS();\n\n // Set presentation metadata\n if (processed.metadata.title) pptx.title = processed.metadata.title;\n if (processed.metadata.author) pptx.author = processed.metadata.author;\n if (processed.metadata.subject) pptx.subject = processed.metadata.subject;\n if (processed.metadata.company) pptx.company = processed.metadata.company;\n\n // Set layout dimensions\n pptx.defineLayout({\n name: 'CUSTOM',\n width: processed.slideWidth,\n height: processed.slideHeight,\n });\n pptx.layout = 'CUSTOM';\n\n // Set RTL mode\n if (processed.rtlMode) {\n pptx.rtlMode = true;\n }\n\n // Set theme fonts\n pptx.theme = {\n headFontFace: processed.theme.fonts.heading,\n bodyFontFace: processed.theme.fonts.body,\n };\n\n // Register template slides\n const templateMap = new Map(\n processed.templates?.map((m) => [m.name, m]) ?? []\n );\n if (processed.templates) {\n for (const templateDef of processed.templates) {\n const templateProps = buildSlideTemplateProps(\n templateDef,\n processed.theme,\n warnings\n );\n pptx.defineSlideMaster(templateProps as any);\n }\n }\n\n // Render each slide\n const totalSlides = processed.slides.length;\n for (let slideIdx = 0; slideIdx < totalSlides; slideIdx++) {\n const slideData = processed.slides[slideIdx];\n const slideCtx: SlideContext = {\n slideNumber: slideIdx + 1,\n totalSlides,\n pageNumberFormat: processed.pageNumberFormat,\n language: processed.language,\n };\n const renderCtx: SlideRenderContext = {\n slideCtx,\n services: processed.services,\n slideWidth: processed.slideWidth,\n slideHeight: processed.slideHeight,\n pendingFills,\n };\n const slide = slideData.template\n ? pptx.addSlide({ masterName: slideData.template })\n : pptx.addSlide();\n\n // Determine effective grid for this slide (template grid merged with presentation grid)\n const templateDef = slideData.template\n ? templateMap.get(slideData.template)\n : undefined;\n if (slideData.template && !templateDef) {\n warn(\n warnings,\n W.MISSING_TEMPLATE,\n `Unknown template \"${slideData.template}\". Available: ${[...templateMap.keys()].join(', ')}`,\n { slide: slideIdx }\n );\n }\n\n // Apply slide background. Gradients can't be expressed through pptxgenjs's\n // bkgd, so a background gradient renders as a full-bleed rect placed at\n // the very back (added first) with the shape gradient-fill mechanism. The\n // slide's own background wins over the template's.\n const backgroundGradient =\n slideData.background?.gradient ??\n (slideData.background ? undefined : templateDef?.background?.gradient);\n if (backgroundGradient) {\n renderShapeComponent(\n slide,\n {\n type: 'rect',\n x: 0,\n y: 0,\n w: processed.slideWidth,\n h: processed.slideHeight,\n fill: { gradient: backgroundGradient },\n },\n processed.theme,\n pptx,\n warnings,\n renderCtx\n );\n } else if (slideData.background) {\n if (slideData.background.color) {\n slide.background = {\n color: resolveColor(\n slideData.background.color,\n processed.theme,\n warnings\n ),\n };\n } else if (slideData.background.image) {\n if (slideData.background.image.path) {\n slide.background = { path: slideData.background.image.path };\n } else if (slideData.background.image.base64) {\n slide.background = { data: slideData.background.image.base64 };\n }\n }\n }\n\n // Apply hidden flag\n if (slideData.hidden) {\n slide.hidden = true;\n }\n const effectiveGrid = mergeGridConfigs(processed.grid, templateDef?.grid);\n\n // Render template fixed objects (grid already resolved in structure.ts)\n if (templateDef?.objects) {\n for (const obj of templateDef.objects) {\n await renderComponent(\n slide,\n obj,\n processed.theme,\n pptx,\n warnings,\n renderCtx\n );\n }\n }\n\n // Render slide components (resolve grid positions first)\n for (const component of slideData.components) {\n const resolved = resolveComponentGridPosition(\n component,\n effectiveGrid,\n processed.slideWidth,\n processed.slideHeight,\n warnings\n );\n await renderComponent(\n slide,\n resolved,\n processed.theme,\n pptx,\n warnings,\n renderCtx\n );\n }\n\n // Render placeholder content\n if (slideData.placeholders) {\n if (templateDef) {\n const phMap = new Map(\n templateDef.placeholders?.map((p) => [p.name, p]) ?? []\n );\n\n for (const [phName, component] of Object.entries(\n slideData.placeholders\n )) {\n const phDef = phMap.get(phName);\n if (!phDef) {\n warn(\n warnings,\n W.UNKNOWN_PLACEHOLDER,\n `Unknown placeholder \"${phName}\" in template \"${slideData.template}\". Available: ${[...phMap.keys()].join(', ')}`,\n { slide: slideIdx }\n );\n continue;\n }\n\n const gridResolved = resolveComponentGridPosition(\n component,\n effectiveGrid,\n processed.slideWidth,\n processed.slideHeight,\n warnings\n );\n\n // Precedence: componentDefaults < phDef position < phDef defaults < component props\n const typeDefaults = getDefaultsForType(\n component.name,\n processed.theme\n );\n const posDefaults: Record<string, any> = {};\n if (phDef.x != null) posDefaults.x = phDef.x;\n if (phDef.y != null) posDefaults.y = phDef.y;\n if (phDef.w != null) posDefaults.w = phDef.w;\n if (phDef.h != null) posDefaults.h = phDef.h;\n\n let props = mergeWithDefaults(posDefaults, typeDefaults);\n props = mergeWithDefaults(phDef.defaults?.props ?? {}, props);\n props = mergeWithDefaults(gridResolved.props, props);\n await renderComponent(\n slide,\n { ...gridResolved, props },\n processed.theme,\n pptx,\n warnings,\n renderCtx\n );\n }\n } else {\n // No template found — render placeholders at their own positions if available\n for (const [phName, component] of Object.entries(\n slideData.placeholders\n )) {\n const defaulted = resolveComponentDefaults(\n component,\n processed.theme\n );\n const hasPosition =\n defaulted.props.x != null ||\n defaulted.props.y != null ||\n defaulted.props.grid;\n if (hasPosition) {\n const resolved = resolveComponentGridPosition(\n defaulted,\n effectiveGrid,\n processed.slideWidth,\n processed.slideHeight,\n warnings\n );\n await renderComponent(\n slide,\n resolved,\n processed.theme,\n pptx,\n warnings,\n renderCtx\n );\n } else {\n warn(\n warnings,\n W.PLACEHOLDER_NO_POSITION,\n `Placeholder \"${phName}\" has no template and no explicit position — skipped`,\n { slide: slideIdx }\n );\n }\n }\n }\n }\n\n // Add speaker notes\n if (slideData.notes) {\n slide.addNotes(slideData.notes);\n }\n }\n\n return pptx;\n}\n","/**\n * Color utilities for PPTX generation.\n * pptxgenjs expects bare 6-char hex (e.g. 'FF0000'), but our theme\n * convention uses '#'-prefixed values (e.g. '#FF0000').\n */\n\nimport type { PptxThemeConfig, PipelineWarning } from '../types';\nimport { SEMANTIC_COLOR_NAMES } from '@json-to-office/shared-pptx';\nimport { DEFAULT_CHART_THEME_COLORS } from '@json-to-office/shared';\nimport { warn, W } from './warn';\n\n// Build identity entries from the shared source of truth, then add aliases\nconst SEMANTIC_TO_THEME_KEY: Record<string, keyof PptxThemeConfig['colors']> = {\n ...Object.fromEntries(SEMANTIC_COLOR_NAMES.map((n) => [n, n])),\n // Aliases (PowerPoint XML compat)\n accent1: 'primary',\n accent2: 'secondary',\n accent3: 'accent',\n tx1: 'text',\n tx2: 'text2',\n bg1: 'background',\n bg2: 'background2',\n};\n\n/**\n * Default series-color tokens for charts, used by the native `chart` component\n * and the `highcharts` component. Defined in @json-to-office/shared so the DOCX\n * `highcharts` component resolves the same tokens; re-exported here because\n * every PPTX call site already imports colors from this module.\n */\nexport { DEFAULT_CHART_THEME_COLORS };\n\n/**\n * Follow a stored theme color value to bare hex, or undefined when it never\n * reaches one. The theme schema lets a slot name another slot\n * (`\"accent4\": \"primary\"`), so a stored value is only a color once the\n * reference chain has been walked — without this, `accent4` resolved to the\n * literal string `primary` and pptxgenjs silently painted the series black.\n *\n * Mirrors DOCX `toChartColor`/`resolveColor` (core-docx colorUtils) on casing:\n * the stored value passes through verbatim when it is already hex, and anything\n * reached by following a reference is normalized to uppercase. Two deliberate\n * divergences: `seen` turns a reference cycle into \"unresolvable\" instead of the\n * stack overflow the DOCX version would hit, and 3-char shorthand is expanded\n * here but not by DOCX, so `\"accent4\": \"#abc\"` fills the slot in a deck and\n * drops it in a document.\n */\nfunction chainToHex(\n value: string,\n theme: PptxThemeConfig,\n seen: Set<string>\n): string | undefined {\n const bare = value.startsWith('#') ? value.slice(1) : value;\n if (/^[0-9A-Fa-f]{6}$/.test(bare)) return bare;\n // Expand 3-char hex shorthand (e.g. 'FFF' → 'FFFFFF')\n if (/^[0-9A-Fa-f]{3}$/.test(bare)) {\n return bare[0] + bare[0] + bare[1] + bare[1] + bare[2] + bare[2];\n }\n const themeKey = SEMANTIC_TO_THEME_KEY[value];\n if (!themeKey || seen.has(themeKey)) return undefined;\n seen.add(themeKey);\n const next = theme?.colors?.[themeKey];\n if (typeof next !== 'string' || next.length === 0) return undefined;\n return chainToHex(next, theme, seen)?.toUpperCase();\n}\n\n/**\n * The default chart palette narrowed to the tokens this theme actually defines\n * *and* can resolve to a color. Both PPTX chart paths build their implicit\n * palette from this, so an unset accent4-6 is skipped — matching DOCX — instead\n * of resolving to `primary` six times over, and a slot holding an unresolvable\n * value is dropped rather than posted as `#primary`. Author-supplied colors must\n * NOT go through here: naming an undefined token stays a loud `resolveColor`\n * fallback + warning.\n */\nexport function definedChartColorTokens(theme: PptxThemeConfig): string[] {\n const colors = theme?.colors as\n | Record<string, string | undefined>\n | undefined;\n if (!colors) return [];\n return DEFAULT_CHART_THEME_COLORS.filter((token) => {\n const themeKey = SEMANTIC_TO_THEME_KEY[token] ?? token;\n const value = colors[themeKey];\n if (typeof value !== 'string' || value.length === 0) return false;\n return chainToHex(value, theme, new Set([themeKey])) !== undefined;\n });\n}\n\n/**\n * Resolve a color value to bare hex (no '#' prefix).\n * Accepts hex colors (with or without '#') or semantic theme color names.\n */\nexport function resolveColor(\n color: string,\n theme: PptxThemeConfig,\n warnings?: PipelineWarning[]\n): string {\n const themeKey = SEMANTIC_TO_THEME_KEY[color];\n if (themeKey) {\n const resolved = theme.colors[themeKey];\n if (resolved) {\n const hex = chainToHex(resolved, theme, new Set([themeKey]));\n if (hex) return hex;\n // Defined but not a color (e.g. a name reference that goes nowhere).\n // Never hand the literal on to pptxgenjs — it renders black in silence.\n warn(\n warnings,\n W.UNKNOWN_COLOR,\n `Theme color \"${themeKey}\" is \"${resolved}\", which is not a hex color or a theme color name; falling back to primary`\n );\n return resolvePrimary(theme);\n }\n // Fall back to primary for unset optional colors\n warn(\n warnings,\n W.THEME_COLOR_FALLBACK,\n `Theme color \"${themeKey}\" not defined, falling back to primary`\n );\n return resolvePrimary(theme);\n }\n // Not a semantic name — treat as literal hex\n const bare = color.startsWith('#') ? color.slice(1) : color;\n // Expand 3-char hex shorthand (e.g. 'FFF' → 'FFFFFF')\n if (/^[0-9A-Fa-f]{3}$/.test(bare)) {\n return bare[0] + bare[0] + bare[1] + bare[1] + bare[2] + bare[2];\n }\n if (!/^[0-9A-Fa-f]{6}$/.test(bare)) {\n warn(\n warnings,\n W.UNKNOWN_COLOR,\n `Unknown color value: \"${color}\", treating as literal`\n );\n }\n return bare;\n}\n\n/** The `primary` fallback, itself chain-resolved so it can't leak a token name. */\nfunction resolvePrimary(theme: PptxThemeConfig): string {\n const primary = theme.colors.primary;\n return (\n chainToHex(primary, theme, new Set(['primary'])) ??\n (primary.startsWith('#') ? primary.slice(1) : primary)\n );\n}\n","/**\n * Resolve (family, weight, italic) into the PPTX run's final `(fontFace,\n * bold, italic)` triple. Non-RIBBI weights are rewritten to synthetic\n * sub-family names (e.g. \"Inter Light\") so PowerPoint / LibreOffice can\n * resolve the matching installed face; RIBBI stays on the canonical\n * family and uses native bold/italic toggles.\n *\n * Mirrors the DOCX `applyFontWeightAlias` helper so both cores coerce\n * fontWeight identically.\n */\n\nimport { synthesizeFamilyName } from '@json-to-office/shared';\n\nexport function applyFontWeight(params: {\n family?: string;\n fontWeight?: number;\n italic?: boolean;\n bold?: boolean;\n}): { fontFace?: string; bold?: boolean; italic?: boolean } {\n if (!params.family) {\n const weight =\n params.fontWeight ?? (params.bold === true ? 700 : undefined);\n return {\n bold: weight != null ? weight >= 600 : params.bold,\n italic: params.italic,\n };\n }\n const weight = params.fontWeight ?? (params.bold === true ? 700 : undefined);\n const synth = synthesizeFamilyName(\n params.family,\n weight,\n params.italic === true\n );\n return { fontFace: synth.family, bold: synth.bold, italic: synth.italic };\n}\n","/**\n * Text Component Renderer\n */\n\nimport type PptxGenJS from 'pptxgenjs';\nimport type {\n PptxThemeConfig,\n StyleName,\n PipelineWarning,\n SlideContext,\n} from '../types';\nimport { resolveColor } from '../utils/color';\nimport { applyFontWeight } from '../utils/fontAliasContext';\nimport { applyHyperlink, type HyperlinkProps } from '../utils/hyperlink';\nimport { warn, W } from '../utils/warn';\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\ninterface TextComponentProps {\n text?: string;\n runs?: TextRunProps[];\n x?: number | string;\n y?: number | string;\n w?: number | string;\n h?: number | string;\n fontSize?: number;\n fontFace?: string;\n color?: string;\n bold?: boolean;\n fontWeight?: number;\n italic?: boolean;\n underline?: boolean | { style?: string; color?: string };\n strike?: boolean;\n language?: string;\n align?: string;\n valign?: string;\n breakLine?: boolean;\n bullet?: boolean | { type?: string; style?: string; startAt?: number };\n margin?: number | number[];\n rotate?: number;\n shadow?: {\n type?: string;\n color?: string;\n blur?: number;\n offset?: number;\n angle?: number;\n opacity?: number;\n };\n fill?: { color: string; transparency?: number };\n hyperlink?: HyperlinkProps;\n lineSpacing?: number;\n lineSpacingMultiple?: number;\n charSpacing?: number;\n paraSpaceBefore?: number;\n paraSpaceAfter?: number;\n style?: StyleName;\n}\n\nfunction resolvePagePlaceholders(text: string, ctx: SlideContext): string {\n const { slideNumber, totalSlides, pageNumberFormat } = ctx;\n const fmt = (n: number) =>\n pageNumberFormat === '09'\n ? String(n).padStart(String(totalSlides).length, '0')\n : String(n);\n return text\n .replace(/\\{PAGE_NUMBER\\}/g, fmt(slideNumber))\n .replace(/\\{PAGE_COUNT\\}/g, fmt(totalSlides));\n}\n\nexport function renderTextComponent(\n slide: PptxGenJS.Slide,\n props: TextComponentProps,\n theme: PptxThemeConfig,\n warnings?: PipelineWarning[],\n slideCtx?: SlideContext\n): void {\n // Exactly one of `text`/`runs` carries the content. Validation enforces the\n // rule up front; this guard covers validation-disabled runs.\n const runs = props.runs && props.runs.length > 0 ? props.runs : undefined;\n if (props.text === undefined && !runs) {\n warn(\n warnings,\n W.TEXT_NO_CONTENT,\n 'Text component has neither \"text\" nor \"runs\" — skipped',\n { component: 'text' }\n );\n return;\n }\n\n // Resolve named style as defaults\n const style = props.style ? theme.styles?.[props.style] : undefined;\n const isHeadingStyle = props.style && /^(title|heading)/.test(props.style);\n\n const opts: Record<string, unknown> = {};\n\n // Position\n if (props.x !== undefined) opts.x = props.x;\n if (props.y !== undefined) opts.y = props.y;\n if (props.w !== undefined) opts.w = props.w;\n if (props.h !== undefined) opts.h = props.h;\n\n // When height is not explicitly set, provide a reasonable default based on\n // font size so that LibreOffice (which renders cy=\"0\" as blank) can display\n // the text. Also mark as textBox for proper auto-sizing in PowerPoint.\n if (props.h === undefined) {\n const fontSize = props.fontSize ?? theme.defaults.fontSize ?? 18;\n const lines = runs\n ? runs.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!.match(/\\n/g)?.length ?? 0) + 1;\n opts.h = Math.max(0.5, (fontSize / 72) * 1.6 * lines);\n opts.isTextBox = true;\n }\n\n // Font — cascade: component props → style → theme defaults\n opts.fontSize = props.fontSize ?? style?.fontSize ?? theme.defaults.fontSize;\n opts.fontFace =\n props.fontFace ??\n style?.fontFace ??\n (isHeadingStyle ? theme.fonts.heading : theme.fonts.body);\n opts.color = resolveColor(\n props.color ?? style?.fontColor ?? theme.defaults.fontColor,\n theme,\n warnings\n );\n\n // Formatting — preserve the pre-alias family so runs that set their own\n // weight resolve their alias from the base family, not an\n // already-synthesized name (e.g. \"Inter Light\").\n const preAliasFamily = opts.fontFace as string | undefined;\n const bold = props.bold ?? style?.bold;\n const italic = props.italic ?? style?.italic;\n const fontWeight = props.fontWeight ?? style?.fontWeight;\n if (bold != null) opts.bold = bold;\n if (italic != null) opts.italic = italic;\n if (fontWeight != null || bold === true) {\n const w = applyFontWeight({\n family: opts.fontFace as string | undefined,\n fontWeight,\n italic,\n bold,\n });\n if (w.fontFace !== undefined) opts.fontFace = w.fontFace;\n if (w.bold !== undefined) opts.bold = w.bold;\n if (w.italic !== undefined) opts.italic = w.italic;\n }\n if (props.strike) opts.strike = true;\n\n // Proofing language: component override → presentation default. When neither\n // is set, pptxgenjs falls back to its own 'en-US' default.\n const lang = props.language ?? slideCtx?.language;\n if (lang) opts.lang = lang;\n\n if (props.underline !== undefined) {\n if (typeof props.underline === 'boolean') {\n opts.underline = { style: 'sng' };\n } else {\n opts.underline = props.underline;\n }\n }\n\n // Alignment\n const align = props.align ?? style?.align;\n if (align) opts.align = align;\n opts.valign = props.valign ?? 'top';\n\n // Bullet\n if (props.bullet !== undefined) opts.bullet = props.bullet;\n\n // Margin — default to 0 so text aligns exactly to grid positions\n opts.margin = props.margin ?? 0;\n\n // Rotation\n if (props.rotate !== undefined) opts.rotate = props.rotate;\n\n // Shadow\n if (props.shadow) {\n opts.shadow = {\n type: props.shadow.type ?? 'outer',\n color: resolveColor(props.shadow.color ?? '000000', theme, warnings),\n blur: props.shadow.blur ?? 3,\n offset: props.shadow.offset ?? 3,\n angle: props.shadow.angle ?? 45,\n opacity: props.shadow.opacity ?? 0.5,\n };\n }\n\n // Fill\n if (props.fill) {\n opts.fill = { color: resolveColor(props.fill.color, theme, warnings) };\n if (props.fill.transparency !== undefined) {\n (opts.fill as Record<string, unknown>).transparency =\n props.fill.transparency;\n }\n }\n\n // Hyperlink\n applyHyperlink(opts, props.hyperlink, 'text', warnings);\n\n // Line spacing\n const lineSpacing = props.lineSpacing ?? style?.lineSpacing;\n if (props.lineSpacingMultiple !== undefined) {\n opts.lineSpacingMultiple = props.lineSpacingMultiple;\n } else if (lineSpacing !== undefined) {\n opts.lineSpacing = lineSpacing;\n }\n const charSpacing = props.charSpacing ?? style?.charSpacing;\n if (charSpacing !== undefined) opts.charSpacing = charSpacing;\n if (props.paraSpaceBefore !== undefined)\n opts.paraSpaceBefore = props.paraSpaceBefore;\n const paraSpaceAfter = props.paraSpaceAfter ?? style?.paraSpaceAfter;\n if (paraSpaceAfter !== undefined) opts.paraSpaceAfter = paraSpaceAfter;\n\n // Break line handling\n if (props.breakLine) opts.breakLine = true;\n\n if (runs) {\n // Rich text runs — pptxgenjs natively accepts [{ text, options }] and\n // merges each run's options over the block-level opts, so run options\n // override component-level defaults per run.\n const runSegments = runs.map((run) => {\n const runOpts: Record<string, unknown> = {};\n if (run.fontSize != null) runOpts.fontSize = run.fontSize;\n if (run.fontFace != null) runOpts.fontFace = run.fontFace;\n if (run.color != null)\n runOpts.color = resolveColor(run.color, theme, warnings);\n if (run.strike != null) runOpts.strike = run.strike;\n if (run.underline !== undefined) {\n if (typeof run.underline === 'boolean') {\n if (run.underline) runOpts.underline = { style: 'sng' };\n } else {\n runOpts.underline = run.underline;\n }\n }\n if (run.superscript != null) runOpts.superscript = run.superscript;\n if (run.subscript != null) runOpts.subscript = run.subscript;\n if (run.charSpacing != null) runOpts.charSpacing = run.charSpacing;\n if (run.breakLine != null) runOpts.breakLine = run.breakLine;\n\n const effWeight = run.fontWeight ?? fontWeight;\n const effBold = run.bold ?? bold;\n const effItalic = run.italic ?? italic;\n if (effBold != null) runOpts.bold = effBold;\n if (effItalic != null) runOpts.italic = effItalic;\n if (effWeight != null || effBold === true) {\n // Only alias when the run inherits the component's family; if the run\n // explicitly sets its own fontFace, the author has already picked the\n // face they want and re-aliasing would double up the suffix.\n if (run.fontFace == null) {\n const w = applyFontWeight({\n family: preAliasFamily,\n fontWeight: effWeight,\n italic: effItalic,\n bold: effBold,\n });\n if (w.fontFace !== undefined) runOpts.fontFace = w.fontFace;\n if (w.bold !== undefined) runOpts.bold = w.bold;\n if (w.italic !== undefined) runOpts.italic = w.italic;\n }\n }\n\n const runText = slideCtx\n ? resolvePagePlaceholders(run.text, slideCtx)\n : run.text;\n return { text: runText, options: runOpts };\n });\n slide.addText(runSegments as any, opts as any);\n return;\n }\n\n const text = slideCtx\n ? resolvePagePlaceholders(props.text!, slideCtx)\n : props.text!;\n slide.addText(text, opts as any);\n}\n","/**\n * Image Component Renderer\n */\n\nimport path from 'path';\nimport probe from 'probe-image-size';\nimport type PptxGenJS from 'pptxgenjs';\nimport type { PptxThemeConfig, PipelineWarning } from '../types';\nimport { resolveColor } from '../utils/color';\nimport { resolveImageSource } from '../utils/imageSource';\nimport { warn, W } from '../utils/warn';\nimport { applyHyperlink, type HyperlinkProps } from '../utils/hyperlink';\n\n/** Block requests to private/loopback/link-local hosts. */\nfunction isPrivateUrl(urlStr: string): boolean {\n try {\n const { hostname } = new URL(urlStr);\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 if (hostname.startsWith('172.')) {\n const second = 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\ninterface ImageComponentProps {\n path?: string;\n base64?: string;\n svg?: string;\n x?: number | string;\n y?: number | string;\n w?: number | string;\n h?: number | string;\n sizing?: { type: string; w?: number | string; h?: number | string };\n rotate?: number;\n rounding?: boolean;\n shadow?: {\n type?: string;\n color?: string;\n blur?: number;\n offset?: number;\n angle?: number;\n opacity?: number;\n };\n hyperlink?: HyperlinkProps;\n alt?: string;\n}\n\n/**\n * Probe the intrinsic dimensions of an image (URL, file path, or base64).\n * Returns width/height in pixels, or undefined on failure.\n */\nasync function probeImageSize(\n imagePath: string,\n warnings?: PipelineWarning[]\n): Promise<{ width: number; height: number } | undefined> {\n try {\n if (/^data:image\\//.test(imagePath)) {\n const base64Data = imagePath.split(',')[1];\n if (!base64Data) return undefined;\n const buf = Buffer.from(base64Data, 'base64');\n const result = probe.sync(buf);\n return result\n ? { width: result.width, height: result.height }\n : undefined;\n }\n\n if (/^https?:\\/\\//.test(imagePath)) {\n if (isPrivateUrl(imagePath)) return undefined;\n const result = await probe(imagePath, { timeout: 5000 });\n return { width: result.width, height: result.height };\n }\n\n // Local file — restrict to CWD to prevent path traversal\n const resolved = path.resolve(imagePath);\n if (!resolved.startsWith(process.cwd())) 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 (err) {\n warn(\n warnings,\n W.IMAGE_PROBE_FAILED,\n `Image probe failed: ${err instanceof Error ? err.message : String(err)}`,\n { component: 'image' }\n );\n return undefined;\n }\n}\n\n/**\n * Parse a dimension value. If it ends with '%', resolve it against the given\n * slide axis length (in inches) and return inches. Otherwise parse as a plain\n * number (already inches).\n */\nfunction resolveDimension(value: number | string, axisLength: number): number {\n if (typeof value === 'number') return value;\n if (value.endsWith('%')) {\n const pct = parseFloat(value);\n return !Number.isNaN(pct) && pct >= 0 ? (pct / 100) * axisLength : 0;\n }\n const n = Number(value);\n return Number.isNaN(n) ? 0 : n;\n}\n\nexport async function renderImageComponent(\n slide: PptxGenJS.Slide,\n props: ImageComponentProps,\n theme: PptxThemeConfig,\n warnings?: PipelineWarning[],\n slideWidth = 10,\n slideHeight = 7.5\n): Promise<void> {\n const opts: Record<string, unknown> = {};\n\n // Source — precedence svg > base64 > path (raw SVG wrapped into a data URI).\n const source = resolveImageSource(props);\n if (!source) {\n warn(\n warnings,\n W.IMAGE_NO_SOURCE,\n 'Image component missing path, base64, and svg',\n { component: 'image' }\n );\n return;\n }\n // pptxgenjs routes data URIs through `data` and file paths/URLs through `path`.\n if (source.startsWith('data:')) {\n opts.data = source;\n } else {\n opts.path = source;\n }\n\n // Position\n if (props.x !== undefined) opts.x = props.x;\n if (props.y !== undefined) opts.y = props.y;\n if (props.w !== undefined) opts.w = props.w;\n if (props.h !== undefined) opts.h = props.h;\n\n // Probe intrinsic dimensions only when needed (auto-calc or contain/cover)\n const hasW = props.w !== undefined;\n const hasH = props.h !== undefined;\n const needsProbe =\n (hasW !== hasH && !props.sizing) ||\n props.sizing?.type === 'contain' ||\n props.sizing?.type === 'cover';\n const intrinsic = needsProbe\n ? await probeImageSize(source, warnings)\n : undefined;\n\n // Auto-calculate missing dimension from intrinsic aspect ratio\n if (hasW !== hasH && !props.sizing) {\n if (intrinsic && intrinsic.width > 0 && intrinsic.height > 0) {\n const aspect = intrinsic.width / intrinsic.height;\n if (hasW && !hasH) {\n const wInches = resolveDimension(props.w!, slideWidth);\n opts.w = wInches;\n opts.h = wInches / aspect;\n } else {\n const hInches = resolveDimension(props.h!, slideHeight);\n opts.h = hInches;\n opts.w = hInches * aspect;\n }\n }\n }\n\n // Sizing — pptxgenjs's contain implementation produces negative srcRect\n // values when the image aspect ratio differs from the box, causing\n // stretching. We handle contain ourselves: probe intrinsic dimensions,\n // calculate fitted size, and center within the box. Cover is delegated to\n // pptxgenjs with correct intrinsic dimensions.\n if (\n props.sizing &&\n (props.sizing.type === 'contain' || props.sizing.type === 'cover')\n ) {\n const boxW = resolveDimension(props.sizing.w ?? props.w ?? 0, slideWidth);\n const boxH = resolveDimension(props.sizing.h ?? props.h ?? 0, slideHeight);\n\n if (boxW <= 0 || boxH <= 0) {\n warn(\n warnings,\n W.IMAGE_ZERO_BOX,\n `Image sizing box resolved to zero (${boxW}x${boxH})`,\n { component: 'image' }\n );\n }\n\n if (\n intrinsic &&\n intrinsic.width > 0 &&\n intrinsic.height > 0 &&\n boxW > 0 &&\n boxH > 0\n ) {\n const imgAspect = intrinsic.width / intrinsic.height;\n\n if (props.sizing.type === 'contain') {\n // Fit image inside box, preserving aspect ratio, centered\n const boxAspect = boxW / boxH;\n let fitW: number, fitH: number;\n if (imgAspect > boxAspect) {\n // Image is wider than box — width-limited\n fitW = boxW;\n fitH = boxW / imgAspect;\n } else {\n // Image is taller than box — height-limited\n fitH = boxH;\n fitW = boxH * imgAspect;\n }\n // Center within the box\n const baseX = resolveDimension(props.x ?? 0, slideWidth);\n const baseY = resolveDimension(props.y ?? 0, slideHeight);\n opts.x = baseX + (boxW - fitW) / 2;\n opts.y = baseY + (boxH - fitH) / 2;\n opts.w = fitW;\n opts.h = fitH;\n // No sizing — element is already the correct size\n } else {\n // Cover: pptxgenjs handles this correctly with real intrinsic dims\n opts.w = intrinsic.width;\n opts.h = intrinsic.height;\n opts.sizing = { type: 'cover', w: boxW, h: boxH };\n }\n } else {\n // Fallback: pass sizing through with w/h auto-filled from outer dims\n opts.sizing = { ...props.sizing, w: boxW, h: boxH };\n }\n } else if (props.sizing) {\n opts.sizing = {\n ...props.sizing,\n w: resolveDimension(props.sizing.w ?? props.w ?? 0, slideWidth),\n h: resolveDimension(props.sizing.h ?? props.h ?? 0, slideHeight),\n };\n }\n\n // Rotation\n if (props.rotate !== undefined) opts.rotate = props.rotate;\n\n // Rounding\n if (props.rounding) opts.rounding = true;\n\n // Shadow\n if (props.shadow) {\n opts.shadow = {\n type: props.shadow.type ?? 'outer',\n color: resolveColor(props.shadow.color ?? '000000', theme, warnings),\n blur: props.shadow.blur ?? 3,\n offset: props.shadow.offset ?? 3,\n angle: props.shadow.angle ?? 45,\n opacity: props.shadow.opacity ?? 0.5,\n };\n }\n\n // Hyperlink\n applyHyperlink(opts, props.hyperlink, 'image', warnings);\n\n // Alt text\n if (props.alt) opts.altText = props.alt;\n\n slide.addImage(opts as any);\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 */\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 * Shape Component Renderer\n */\n\nimport type PptxGenJS from 'pptxgenjs';\nimport type {\n PptxThemeConfig,\n StyleName,\n PipelineWarning,\n PendingXmlFill,\n SlideRenderContext,\n} from '../types';\nimport type {\n TextSegment,\n GradientFill,\n PatternFill,\n} from '@json-to-office/shared-pptx';\nimport { PATTERN_FILL_PRESETS } from '@json-to-office/shared-pptx';\nimport { applyFontWeight } from '../utils/fontAliasContext';\nimport { resolveColor } from '../utils/color';\nimport { buildGradientFillXml, buildPatternFillXml } from '../utils/fillXml';\nimport { warn, W } from '../utils/warn';\n\nexport interface ShapeFillProps {\n color?: string;\n transparency?: number;\n gradient?: GradientFill;\n pattern?: PatternFill;\n}\n\ninterface ShapeComponentProps {\n type: string;\n x?: number | string;\n y?: number | string;\n w?: number | string;\n h?: number | string;\n fill?: ShapeFillProps;\n line?: { color?: string; width?: number; dashType?: string };\n text?: string | TextSegment[];\n fontSize?: number;\n fontFace?: string;\n fontColor?: string;\n charSpacing?: number;\n bold?: boolean;\n fontWeight?: number;\n italic?: boolean;\n align?: string;\n valign?: string;\n rotate?: number;\n angleRange?: [number, number];\n flipH?: boolean;\n flipV?: boolean;\n shadow?: {\n type?: string;\n color?: string;\n blur?: number;\n offset?: number;\n angle?: number;\n opacity?: number;\n };\n rectRadius?: number;\n style?: StyleName;\n}\n\nconst SHAPE_TYPE_MAP: Record<string, string> = {\n rect: 'rect',\n roundRect: 'roundRect',\n ellipse: 'ellipse',\n triangle: 'triangle',\n diamond: 'diamond',\n pentagon: 'pentagon',\n hexagon: 'hexagon',\n star5: 'star5',\n star6: 'star6',\n line: 'line',\n arrow: 'rightArrow',\n chevron: 'chevron',\n cloud: 'cloud',\n heart: 'heart',\n lightning: 'lightningBolt',\n};\n\n/**\n * Apply a shape fill to pptxgenjs opts. Gradient and pattern fills are not\n * expressible through pptxgenjs, so they render as a sentinel solid fill on a\n * shape tagged with a unique `objectName`; the real fill XML is registered in\n * `pendingFills` and spliced in by packagePresentationBuffer. Without a\n * registry (direct render outside the buffer pipeline) they degrade to the\n * sentinel solid color with a warning.\n */\nexport function applyShapeFill(\n opts: Record<string, unknown>,\n fill: ShapeFillProps,\n theme: PptxThemeConfig,\n warnings?: PipelineWarning[],\n pendingFills?: PendingXmlFill[]\n): void {\n let gradient = fill.gradient;\n let pattern = fill.pattern;\n if (gradient && pattern) {\n warn(\n 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 // An unrecognised preset degrades to the pattern's own foreground, so the\n // shape still reads as authored rather than picking up the pptxgenjs\n // default. `fill.color`, when set, stays authoritative.\n let unknownPresetForeground: string | undefined;\n if (\n pattern &&\n !(PATTERN_FILL_PRESETS as readonly string[]).includes(pattern.preset)\n ) {\n warn(\n 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 || pattern) {\n // Sentinel color: keeps the deck presentable if the splice cannot run.\n const sentinel = resolveColor(\n fill.color ?? (gradient ? gradient.stops[0].color : pattern!.foreground),\n theme,\n warnings\n );\n if (pendingFills) {\n const xml = gradient\n ? buildGradientFillXml(gradient, theme, warnings)\n : buildPatternFillXml(pattern!, theme, warnings);\n const objectName = `__jto_fill_${pendingFills.length}__`;\n pendingFills.push({ objectName, xml });\n opts.objectName = objectName;\n } else {\n warn(\n warnings,\n W.ADVANCED_FILL_FALLBACK,\n `${gradient ? 'Gradient' : 'Pattern'} fill requires the buffer generation pipeline — rendering a solid fill instead`,\n { component: 'shape' }\n );\n }\n opts.fill = { color: sentinel };\n return;\n }\n\n const solid = fill.color ?? unknownPresetForeground;\n if (solid !== undefined) {\n opts.fill = { color: resolveColor(solid, theme, warnings) };\n if (fill.transparency !== undefined) {\n (opts.fill as Record<string, unknown>).transparency = fill.transparency;\n }\n }\n}\n\nfunction buildShapeOpts(\n props: ShapeComponentProps,\n theme: PptxThemeConfig,\n warnings?: PipelineWarning[],\n pendingFills?: PendingXmlFill[]\n): Record<string, unknown> {\n const opts: Record<string, unknown> = {};\n\n if (props.x !== undefined) opts.x = props.x;\n if (props.y !== undefined) opts.y = props.y;\n if (props.w !== undefined) opts.w = props.w;\n if (props.h !== undefined) opts.h = props.h;\n\n if (props.fill) {\n applyShapeFill(opts, props.fill, theme, warnings, pendingFills);\n }\n\n if (props.line) {\n opts.line = {};\n if (props.line.color)\n (opts.line as Record<string, unknown>).color = resolveColor(\n props.line.color,\n theme,\n warnings\n );\n if (props.line.width)\n (opts.line as Record<string, unknown>).width = props.line.width;\n if (props.line.dashType)\n (opts.line as Record<string, unknown>).dashType = props.line.dashType;\n }\n\n if (props.rotate !== undefined) opts.rotate = props.rotate;\n if (props.angleRange !== undefined) opts.angleRange = props.angleRange;\n if (props.flipH !== undefined) opts.flipH = props.flipH;\n if (props.flipV !== undefined) opts.flipV = props.flipV;\n if (props.rectRadius !== undefined) opts.rectRadius = props.rectRadius;\n\n if (props.shadow) {\n opts.shadow = {\n type: props.shadow.type ?? 'outer',\n color: resolveColor(props.shadow.color ?? '000000', theme, warnings),\n blur: props.shadow.blur ?? 3,\n offset: props.shadow.offset ?? 3,\n angle: props.shadow.angle ?? 45,\n opacity: props.shadow.opacity ?? 0.5,\n };\n }\n\n return opts;\n}\n\nexport function renderShapeComponent(\n slide: PptxGenJS.Slide,\n props: ShapeComponentProps,\n theme: PptxThemeConfig,\n pptx: PptxGenJS,\n warnings?: PipelineWarning[],\n ctx?: SlideRenderContext\n): void {\n // Resolve shape type from pptxgenjs ShapeType enum\n const shapeTypeName = SHAPE_TYPE_MAP[props.type] || props.type;\n const shapeType = (pptx.ShapeType as Record<string, any>)[shapeTypeName];\n\n if (!shapeType) {\n warn(warnings, W.UNKNOWN_SHAPE, `Unknown shape type: ${props.type}`, {\n component: 'shape',\n });\n return;\n }\n\n // Resolve named style\n const style = props.style ? theme.styles?.[props.style] : undefined;\n const isHeadingStyle = props.style && /^(title|heading)/.test(props.style);\n\n const opts = buildShapeOpts(props, theme, warnings, ctx?.pendingFills);\n\n // If shape has text, use addText with shape option\n if (props.text && (!Array.isArray(props.text) || props.text.length > 0)) {\n opts.shape = shapeType;\n\n opts.fontSize =\n props.fontSize ?? style?.fontSize ?? theme.defaults.fontSize;\n opts.fontFace =\n props.fontFace ??\n style?.fontFace ??\n (isHeadingStyle ? theme.fonts.heading : theme.fonts.body);\n // Preserve pre-alias family so segments that inherit it don't feed an\n // already-synthesized name (e.g. \"Inter Light\") back into applyFontWeight\n // and double-alias to \"Inter Light Medium\".\n const preAliasFamily = opts.fontFace as string | undefined;\n opts.color = resolveColor(\n props.fontColor ?? style?.fontColor ?? theme.defaults.fontColor,\n theme,\n warnings\n );\n const bold = props.bold ?? style?.bold;\n const italic = props.italic ?? style?.italic;\n const fontWeight = props.fontWeight ?? style?.fontWeight;\n const charSpacing = props.charSpacing ?? style?.charSpacing;\n if (charSpacing !== undefined) opts.charSpacing = charSpacing;\n const align = props.align ?? style?.align;\n if (align) opts.align = align;\n opts.valign = props.valign ?? 'top';\n\n if (Array.isArray(props.text)) {\n // For segmented text, resolve the aliased family per-segment using the\n // effective (weight, italic, bold) = segment value ?? shape value. Keep\n // shape-level `opts.fontFace` at the un-aliased family so segments that\n // don't set their own fontFace don't accidentally inherit an\n // already-synthesized name (e.g. \"Inter Light\") from the shape.\n if (bold != null) opts.bold = bold;\n if (italic != null) opts.italic = italic;\n const textSegments = props.text.map((seg) => {\n const segOpts: {\n fontSize?: number;\n fontFace?: string;\n color?: string;\n bold?: boolean;\n italic?: boolean;\n breakLine?: boolean;\n charSpacing?: number;\n paraSpaceBefore?: number;\n paraSpaceAfter?: number;\n } = {};\n if (seg.fontSize != null) segOpts.fontSize = seg.fontSize;\n if (seg.fontFace != null) segOpts.fontFace = seg.fontFace;\n if (seg.color != null)\n segOpts.color = resolveColor(seg.color, theme, warnings);\n if (seg.breakLine != null) segOpts.breakLine = seg.breakLine;\n if (seg.charSpacing != null) segOpts.charSpacing = seg.charSpacing;\n if (seg.spaceBefore != null) segOpts.paraSpaceBefore = seg.spaceBefore;\n if (seg.spaceAfter != null) segOpts.paraSpaceAfter = seg.spaceAfter;\n const segWeight = (seg as TextSegment & { fontWeight?: number })\n .fontWeight;\n const effWeight = segWeight ?? fontWeight;\n const effBold = seg.bold ?? bold;\n const effItalic = seg.italic ?? italic;\n if (effBold != null) segOpts.bold = effBold;\n if (effItalic != null) segOpts.italic = effItalic;\n if (effWeight != null || effBold === true) {\n // Only alias when the segment inherits the shape's family; if the\n // segment explicitly sets its own fontFace, the author has already\n // picked the face they want (possibly an already-synthesized name\n // like \"Inter Light\") and re-aliasing would double up the suffix.\n if (seg.fontFace == null) {\n const w = applyFontWeight({\n family: preAliasFamily,\n fontWeight: effWeight,\n italic: effItalic,\n bold: effBold,\n });\n if (w.fontFace !== undefined) segOpts.fontFace = w.fontFace;\n if (w.bold !== undefined) segOpts.bold = w.bold;\n if (w.italic !== undefined) segOpts.italic = w.italic;\n }\n }\n return { text: seg.text, options: segOpts };\n });\n slide.addText(textSegments, opts as any);\n } else {\n if (bold != null) opts.bold = bold;\n if (italic != null) opts.italic = italic;\n if (fontWeight != null || bold === true) {\n const w = applyFontWeight({\n family: preAliasFamily,\n fontWeight,\n italic,\n bold,\n });\n if (w.fontFace !== undefined) opts.fontFace = w.fontFace;\n if (w.bold !== undefined) opts.bold = w.bold;\n if (w.italic !== undefined) opts.italic = w.italic;\n }\n slide.addText(props.text, opts as any);\n }\n } else {\n // Pure shape without text\n slide.addShape(shapeType, opts as any);\n }\n}\n","/**\n * OOXML fill XML builders for fills pptxgenjs cannot express.\n *\n * Gradient and pattern fills are rendered as a sentinel solid fill tagged with\n * a unique `objectName`; packagePresentationBuffer then swaps the sentinel\n * `<a:solidFill>` for the XML built here. Colors are resolved (theme tokens →\n * hex) before the XML is built, so the packaging step is a pure string splice.\n */\n\nimport type { GradientFill, PatternFill } from '@json-to-office/shared-pptx';\nimport type { PptxThemeConfig, PipelineWarning } from '../types';\nimport { resolveColor } from './color';\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 l/t/r/b values (in 1000ths of a percent) per focus corner. */\nconst RADIAL_FOCUS_RECTS: Record<\n NonNullable<GradientFill['focus']>,\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\nfunction gradientStopXml(\n color: string,\n pos: number,\n transparency: number | undefined,\n theme: PptxThemeConfig,\n warnings?: PipelineWarning[]\n): string {\n const hex = resolveColor(color, theme, warnings).toUpperCase();\n const alpha =\n transparency !== undefined\n ? `<a:alpha val=\"${Math.round((100 - transparency) * PCT_UNIT)}\"/>`\n : '';\n return `<a:gs pos=\"${Math.round(pos * PCT_UNIT)}\"><a:srgbClr val=\"${hex}\">${alpha}</a:srgbClr></a:gs>`;\n}\n\n/**\n * Build an `<a:gradFill>` element from a gradient fill definition.\n */\nexport function buildGradientFillXml(\n gradient: GradientFill,\n theme: PptxThemeConfig,\n warnings?: PipelineWarning[]\n): string {\n const stops = gradient.stops\n .map((stop) =>\n gradientStopXml(stop.color, stop.pos, stop.transparency, theme, warnings)\n )\n .join('');\n\n let shade: string;\n if (gradient.type === 'radial') {\n const rect = RADIAL_FOCUS_RECTS[gradient.focus ?? 'center'];\n shade = `<a:path path=\"circle\"><a:fillToRect l=\"${rect.l}\" t=\"${rect.t}\" r=\"${rect.r}\" b=\"${rect.b}\"/></a:path>`;\n } else {\n const angle = (((gradient.angle ?? 0) % 360) + 360) % 360;\n shade = `<a:lin ang=\"${Math.round(angle * ANGLE_UNIT)}\" scaled=\"1\"/>`;\n }\n\n return `<a:gradFill rotWithShape=\"1\"><a:gsLst>${stops}</a:gsLst>${shade}</a:gradFill>`;\n}\n\n/**\n * Build an `<a:pattFill>` element from a pattern fill definition.\n */\nexport function buildPatternFillXml(\n pattern: PatternFill,\n theme: PptxThemeConfig,\n warnings?: PipelineWarning[]\n): string {\n const fg = resolveColor(pattern.foreground, theme, warnings).toUpperCase();\n const bg = resolveColor(pattern.background, theme, warnings).toUpperCase();\n return `<a:pattFill prst=\"${pattern.preset}\"><a:fgClr><a:srgbClr val=\"${fg}\"/></a:fgClr><a:bgClr><a:srgbClr val=\"${bg}\"/></a:bgClr></a:pattFill>`;\n}\n","/**\n * Table Component Renderer\n */\n\nimport type PptxGenJS from 'pptxgenjs';\nimport type { PptxThemeConfig, PipelineWarning } from '../types';\nimport { resolveColor } from '../utils/color';\nimport { applyFontWeight } from '../utils/fontAliasContext';\n\n/**\n * Characters that PowerPoint may render as color emoji.\n * Appending VS15 (U+FE0E) forces text-mode rendering.\n */\nconst EMOJI_PRONE_CHARS = /[✓✔✗✘☐☑☒★☆●○■□▶◀▲▼⚡⚠❌❓❗]/gu;\n\nfunction applyTextVariationSelector(text: string): string {\n return text.replace(EMOJI_PRONE_CHARS, (ch) => ch + '\\uFE0E');\n}\n\ninterface TableCell {\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\ninterface TableComponentProps {\n rows: (string | TableCell)[][];\n x?: number | string;\n y?: number | string;\n w?: number | string;\n h?: number | string;\n colW?: number | number[];\n rowH?: number | number[];\n border?: { type?: string; pt?: number; color?: string };\n fill?: string;\n fontSize?: number;\n fontFace?: string;\n color?: string;\n align?: string;\n valign?: string;\n autoPage?: boolean;\n autoPageRepeatHeader?: boolean;\n margin?: number | number[];\n borderRadius?: number;\n}\n\nexport function renderTableComponent(\n slide: PptxGenJS.Slide,\n props: TableComponentProps,\n theme: PptxThemeConfig,\n pptx?: PptxGenJS,\n warnings?: PipelineWarning[]\n): void {\n // Pre-compute fills and width for borderRadius feature\n let bgFill: string | undefined;\n let headerFill: string | undefined;\n let borderRadiusTableW: number | undefined;\n if (props.borderRadius && pptx && props.rows.length >= 2) {\n const lastRow = props.rows[props.rows.length - 1];\n const lastCell = lastRow?.[0];\n bgFill = props.fill\n ? resolveColor(props.fill, theme, warnings)\n : typeof lastCell === 'object' && lastCell.fill\n ? resolveColor(lastCell.fill, theme, warnings)\n : 'FFFFFF';\n const firstCell = props.rows[0]?.[0];\n headerFill =\n typeof firstCell === 'object' && firstCell.fill\n ? resolveColor(firstCell.fill, theme, warnings)\n : bgFill;\n // Derive width from colW (actual cell widths) so shapes match the table exactly\n borderRadiusTableW = Array.isArray(props.colW)\n ? props.colW.reduce((sum, w) => sum + w, 0)\n : typeof props.colW === 'number'\n ? props.colW * (props.rows[0]?.length ?? 1) // assumes uniform column count\n : typeof props.w === 'number'\n ? props.w\n : 5;\n }\n\n // Pre-compute inner border for per-cell border assignment\n const innerBorder = props.border\n ? {\n type: props.border.type ?? 'solid',\n pt: props.border.pt ?? 1,\n color: resolveColor(props.border.color ?? '000000', theme, warnings),\n }\n : undefined;\n\n // Helper: build per-cell border array when borderRadius is active\n const buildBorderRadiusBorders = (\n rowIndex: number,\n colIndex: number,\n colCount: number\n ) => {\n const isTop = rowIndex === 0;\n const isBottom = rowIndex === props.rows.length - 1;\n const isLeft = colIndex === 0;\n const isRight = colIndex === colCount - 1;\n const zeroBorder = { type: 'none', pt: 0 };\n const hInner = innerBorder ?? zeroBorder;\n return [\n isTop || rowIndex === 1 ? zeroBorder : hInner, // top: outer + header-body seam\n isRight ? zeroBorder : hInner, // right\n isBottom || rowIndex === 0 ? zeroBorder : hInner, // bottom: outer + header-body seam\n isLeft ? zeroBorder : hInner, // left\n ];\n };\n\n // Convert rows to pptxgenjs format\n const lastRowIdx = props.rows.length - 1;\n const tableRows = props.rows.map((row, rowIndex) =>\n row.map((cell, colIndex) => {\n const lastColIdx = row.length - 1;\n // Corner cells: first/last col of header or last row — transparent\n // so background roundRect shapes show rounded corners through them.\n // All other cells: opaque fill to prevent seam artifacts.\n const isCorner =\n bgFill &&\n (rowIndex === 0 || rowIndex === lastRowIdx) &&\n (colIndex === 0 || colIndex === lastColIdx);\n\n if (typeof cell === 'string') {\n if (!bgFill) return { text: applyTextVariationSelector(cell) };\n const isHeader = rowIndex === 0;\n const opts: Record<string, unknown> = {\n border: buildBorderRadiusBorders(rowIndex, colIndex, row.length),\n };\n if (!isCorner) opts.fill = { color: isHeader ? headerFill : bgFill };\n return { text: applyTextVariationSelector(cell), options: opts };\n }\n const cellOpts: Record<string, unknown> = {};\n if (cell.color)\n cellOpts.color = resolveColor(cell.color, theme, warnings);\n if (bgFill) {\n const isHeader = rowIndex === 0;\n if (!isCorner) {\n const resolvedFill = cell.fill\n ? resolveColor(cell.fill, theme, warnings)\n : isHeader\n ? headerFill\n : bgFill;\n cellOpts.fill = { color: resolvedFill };\n }\n cellOpts.border = buildBorderRadiusBorders(\n rowIndex,\n colIndex,\n row.length\n );\n } else if (cell.fill) {\n cellOpts.fill = { color: resolveColor(cell.fill, theme, warnings) };\n }\n if (cell.fontSize) cellOpts.fontSize = cell.fontSize;\n if (cell.fontFace) cellOpts.fontFace = cell.fontFace;\n if (cell.bold) cellOpts.bold = true;\n if (cell.italic) cellOpts.italic = true;\n if (cell.fontWeight != null || cell.bold === true) {\n const w = applyFontWeight({\n family:\n (cellOpts.fontFace as string | undefined) ??\n props.fontFace ??\n theme.fonts.body,\n fontWeight: cell.fontWeight,\n italic: cell.italic,\n bold: cell.bold,\n });\n if (w.fontFace !== undefined) cellOpts.fontFace = w.fontFace;\n if (w.bold !== undefined) cellOpts.bold = w.bold;\n if (w.italic !== undefined) cellOpts.italic = w.italic;\n }\n if (cell.align) cellOpts.align = cell.align;\n if (cell.valign) cellOpts.valign = cell.valign;\n if (cell.colspan) cellOpts.colspan = cell.colspan;\n if (cell.rowspan) cellOpts.rowspan = cell.rowspan;\n if (cell.margin !== undefined) cellOpts.margin = cell.margin;\n\n return { text: applyTextVariationSelector(cell.text), options: cellOpts };\n })\n );\n\n const opts: Record<string, unknown> = {};\n\n // Position\n if (props.x !== undefined) opts.x = props.x;\n if (props.y !== undefined) opts.y = props.y;\n if (props.w !== undefined) opts.w = props.w;\n if (props.h !== undefined) opts.h = props.h;\n\n // Column/row sizing\n if (props.colW !== undefined) opts.colW = props.colW;\n if (props.rowH !== undefined) opts.rowH = props.rowH;\n\n // Border — skip table-level border when borderRadius is active (per-cell borders handle it)\n if (props.border && !bgFill) {\n opts.border = {\n type: props.border.type ?? 'solid',\n pt: props.border.pt ?? 1,\n color: resolveColor(props.border.color ?? '000000', theme, warnings),\n };\n }\n\n // Fill\n if (props.fill)\n opts.fill = { color: resolveColor(props.fill, theme, warnings) };\n\n // Font defaults\n opts.fontSize = props.fontSize ?? theme.defaults.fontSize;\n opts.fontFace = props.fontFace ?? theme.fonts.body;\n if (props.color) opts.color = resolveColor(props.color, theme, warnings);\n\n // Alignment\n if (props.align) opts.align = props.align;\n opts.valign = props.valign ?? 'middle';\n\n // Auto-paging\n if (props.autoPage) opts.autoPage = true;\n if (props.autoPageRepeatHeader) {\n opts.autoPageRepeatHeader = true;\n opts.autoPageHeaderRows = 1;\n }\n\n // Margin\n if (props.margin !== undefined) opts.margin = props.margin;\n\n // Background roundRect shapes — placed BEFORE the table.\n // Corner cells are transparent so these shapes show through at the corners.\n // Non-corner cells are opaque to prevent seam artifacts.\n if (\n props.borderRadius &&\n pptx &&\n typeof props.x === 'number' &&\n typeof props.y === 'number'\n ) {\n let tableH: number = (props.h as number) ?? 2;\n if (typeof props.rowH === 'number') {\n tableH = props.rowH * props.rows.length;\n } else if (Array.isArray(props.rowH)) {\n tableH = props.rowH.reduce((sum, h) => sum + h, 0);\n }\n const headerH =\n typeof props.rowH === 'number'\n ? props.rowH\n : Array.isArray(props.rowH)\n ? props.rowH[0]\n : 0.45;\n const tableW = borderRadiusTableW!;\n // Suppress shape outlines completely\n const noLine = { type: 'none' };\n\n // Header roundRect (rounded top corners)\n slide.addShape(pptx.ShapeType.roundRect, {\n x: props.x,\n y: props.y,\n w: tableW,\n h: headerH,\n fill: { color: headerFill },\n rectRadius: props.borderRadius,\n line: noLine,\n } as any);\n // Header flat rect — covers the rounded bottom corners of header\n slide.addShape(pptx.ShapeType.rect, {\n x: props.x,\n y: (props.y as number) + headerH - props.borderRadius,\n w: tableW,\n h: props.borderRadius,\n fill: { color: headerFill },\n line: noLine,\n } as any);\n\n // Body roundRect (rounded bottom corners)\n const bodyY = (props.y as number) + headerH;\n const bodyH = tableH - headerH;\n slide.addShape(pptx.ShapeType.roundRect, {\n x: props.x,\n y: bodyY,\n w: tableW,\n h: bodyH,\n fill: { color: bgFill },\n rectRadius: props.borderRadius,\n line: noLine,\n } as any);\n // Body flat rect — covers the rounded top corners of body\n slide.addShape(pptx.ShapeType.rect, {\n x: props.x,\n y: bodyY,\n w: tableW,\n h: props.borderRadius,\n fill: { color: bgFill },\n line: noLine,\n } as any);\n }\n\n // When borderRadius is active, override opts.w to match colW sum\n // and suppress any table-level border/outline\n if (bgFill && borderRadiusTableW !== undefined) {\n opts.w = borderRadiusTableW;\n opts.border = [\n { type: 'none' },\n { type: 'none' },\n { type: 'none' },\n { type: 'none' },\n ];\n }\n\n slide.addTable(tableRows as any, opts as any);\n}\n","/**\n * Environment detection utilities\n */\n\n/**\n * Check if the current environment is Node.js\n */\nexport function isNodeEnvironment(): boolean {\n return (\n typeof process !== 'undefined' &&\n process.versions != null &&\n process.versions.node != null &&\n typeof process.versions.node === 'string'\n );\n}\n","/**\n * Highcharts Component Renderer (PPTX)\n */\n\nimport type PptxGenJS from 'pptxgenjs';\nimport type { PptxThemeConfig, PipelineWarning } from '../types';\nimport type { PptxHighchartsProps } from '@json-to-office/shared-pptx';\nimport type { HighchartsServiceConfig } from '@json-to-office/shared';\nimport { isNodeEnvironment } from '../utils/environment';\nimport { resolveColor, definedChartColorTokens } from '../utils/color';\n\nconst PX_PER_INCH = 96;\nconst DEFAULT_EXPORT_SERVER_URL = 'http://localhost:7801';\n\nfunction getExportServerUrl(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 * Generate chart via Highcharts Export Server\n */\nasync function generateChart(\n config: PptxHighchartsProps,\n servicesConfig?: HighchartsServiceConfig\n): Promise<{ base64DataUri: string; width: number; height: number }> {\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 = getExportServerUrl(\n config.serverUrl,\n servicesConfig?.serverUrl\n );\n\n const requestBody = {\n infile: config.options,\n type: 'png',\n b64: true,\n scale: config.scale,\n // Forward resources verbatim only when present so the payload stays\n // byte-identical to before for callers that omit it.\n ...(config.resources ? { resources: config.resources } : {}),\n };\n\n const resolvedHeaders =\n typeof servicesConfig?.headers === 'function'\n ? await servicesConfig.headers(requestBody)\n : servicesConfig?.headers;\n\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n ...resolvedHeaders,\n };\n\n const response = await fetch(`${serverUrl}/export`, {\n method: 'POST',\n headers,\n body: JSON.stringify(requestBody),\n }).catch((error) => {\n throw new Error(\n `Highcharts Export Server is not running at ${serverUrl}. ` +\n 'Start it with: npx highcharts-export-server --enableServer true\\n' +\n `Cause: ${error instanceof Error ? error.message : String(error)}`\n );\n });\n\n if (!response.ok) {\n throw new Error(\n `Highcharts export server returned ${response.status}: ${response.statusText}`\n );\n }\n\n const base64Data = await response.text();\n\n return {\n base64DataUri: `data:image/png;base64,${base64Data}`,\n width: config.options.chart?.width ?? 960,\n height: config.options.chart?.height ?? 720,\n };\n}\n\n/**\n * When the Highcharts config sets no top-level `colors`, series render in the\n * Highcharts default palette (blue-first) and ignore the document theme. Inject\n * the theme's chart palette (same tokens as the native `chart` component) so\n * both chart paths follow the theme by default. accent4-6 are optional in the\n * theme schema; slots the theme leaves unset are skipped, in both formats, so\n * the palette never repeats primary and Highcharts wraps the shorter list (see\n * DEFAULT_CHART_THEME_COLORS). 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 {\n ...props,\n options: { ...props.options, colors: palette },\n };\n}\n\nexport async function renderHighchartsComponent(\n slide: PptxGenJS.Slide,\n props: PptxHighchartsProps,\n theme: PptxThemeConfig,\n warnings?: PipelineWarning[],\n servicesConfig?: HighchartsServiceConfig\n): Promise<void> {\n const chart = await generateChart(\n withThemeColors(props, theme, warnings),\n servicesConfig\n );\n\n const w = props.w ?? chart.width / PX_PER_INCH;\n const h = props.h ?? chart.height / PX_PER_INCH;\n\n slide.addImage({\n data: chart.base64DataUri,\n x: props.x ?? 0,\n y: props.y ?? 0,\n w,\n h,\n } as any);\n}\n","/**\n * Chart Component Renderer — native PowerPoint charts via pptxgenjs slide.addChart()\n */\n\nimport type PptxGenJS from 'pptxgenjs';\nimport type { PptxThemeConfig, PipelineWarning } from '../types';\nimport { resolveColor, definedChartColorTokens } from '../utils/color';\nimport { warn, W } from '../utils/warn';\n\ninterface ChartDataSeries {\n name?: string;\n labels?: string[];\n values?: number[];\n sizes?: number[];\n}\n\ninterface ChartComponentProps {\n type: string;\n data: ChartDataSeries[];\n\n showLegend?: boolean;\n showTitle?: boolean;\n showValue?: boolean;\n showPercent?: boolean;\n showLabel?: boolean;\n showSerName?: boolean;\n\n title?: string;\n titleFontSize?: number;\n titleColor?: string;\n titleFontFace?: string;\n\n chartColors?: string[];\n\n dataBorder?: { pt: number; color: string };\n\n legendPos?: string;\n legendFontSize?: number;\n legendFontFace?: string;\n legendColor?: string;\n\n catAxisTitle?: string;\n catAxisHidden?: boolean;\n catAxisLabelRotate?: number;\n catAxisLabelFontSize?: number;\n catAxisLabelColor?: string;\n catAxisLabelFontFace?: string;\n catGridLine?: { style?: string; size?: number; color?: string };\n\n valAxisTitle?: string;\n valAxisHidden?: boolean;\n valAxisMinVal?: number;\n valAxisMaxVal?: number;\n valAxisLabelFormatCode?: string;\n valAxisMajorUnit?: number;\n valAxisLabelColor?: string;\n valAxisLabelFontFace?: string;\n valAxisLabelFontSize?: number;\n valGridLine?: { style?: string; size?: number; color?: string };\n catAxisLineShow?: boolean;\n valAxisLineShow?: boolean;\n\n barDir?: string;\n barGrouping?: string;\n barGapWidthPct?: number;\n barOverlapPct?: number;\n\n lineSmooth?: boolean;\n lineDataSymbol?: string;\n lineSize?: number;\n lineDataSymbolSize?: number;\n\n firstSliceAng?: number;\n holeSize?: number;\n\n radarStyle?: string;\n\n dataLabelColor?: string;\n dataLabelFontSize?: number;\n dataLabelFontFace?: string;\n dataLabelFontBold?: boolean;\n dataLabelPosition?: string;\n\n x?: number | string;\n y?: number | string;\n w?: number | string;\n h?: number | string;\n}\n\n// Map our type strings to pptxgenjs CHART_NAME values\nconst CHART_TYPE_MAP: Record<string, string> = {\n area: 'area',\n bar: 'bar',\n bar3D: 'bar3D',\n bubble: 'bubble',\n doughnut: 'doughnut',\n line: 'line',\n pie: 'pie',\n radar: 'radar',\n scatter: 'scatter',\n};\n\nfunction resolveGridLine(\n gridLine: { style?: string; size?: number; color?: string },\n theme: PptxThemeConfig,\n warnings?: PipelineWarning[]\n): Record<string, unknown> {\n const resolved: Record<string, unknown> = {};\n if (gridLine.style !== undefined) resolved.style = gridLine.style;\n if (gridLine.size !== undefined) resolved.size = gridLine.size;\n if (gridLine.color !== undefined)\n resolved.color = resolveColor(gridLine.color, theme, warnings);\n return resolved;\n}\n\nexport function renderChartComponent(\n slide: PptxGenJS.Slide,\n props: ChartComponentProps,\n theme: PptxThemeConfig,\n _pptx: PptxGenJS,\n warnings?: PipelineWarning[]\n): void {\n const chartType = CHART_TYPE_MAP[props.type];\n if (!chartType) {\n warn(warnings, W.UNKNOWN_CHART_TYPE, `Unknown chart type: ${props.type}`, {\n component: 'chart',\n });\n return;\n }\n\n // Validate data\n if (!props.data || props.data.length === 0) {\n warn(warnings, W.CHART_NO_DATA, 'Chart component has no data series', {\n component: 'chart',\n });\n return;\n }\n for (const series of props.data) {\n if (!series.labels || !series.values) {\n warn(\n warnings,\n W.CHART_INVALID_SERIES,\n `Chart series \"${series.name ?? '(unnamed)'}\" missing labels or values`,\n { component: 'chart' }\n );\n return;\n }\n }\n if (\n (chartType === 'pie' || chartType === 'doughnut') &&\n props.data.length > 1\n ) {\n warn(\n warnings,\n W.CHART_MULTI_SERIES,\n `${props.type} chart has ${props.data.length} series — only the first will render`,\n { component: 'chart' }\n );\n }\n\n // Build data array\n const data = props.data.map((series) => {\n const d: Record<string, unknown> = {};\n if (series.name !== undefined) d.name = series.name;\n if (series.labels) d.labels = series.labels;\n if (series.values) d.values = series.values;\n if (series.sizes) d.sizes = series.sizes;\n return d;\n });\n\n // Build chart options\n const opts: Record<string, unknown> = {};\n\n // Position\n if (props.x !== undefined) opts.x = props.x;\n if (props.y !== undefined) opts.y = props.y;\n if (props.w !== undefined) opts.w = props.w;\n if (props.h !== undefined) opts.h = props.h;\n\n // Colors — resolve semantic names to hex, following any token-to-token\n // reference the theme sets up. The implicit palette skips tokens the theme\n // leaves unset or leaves unresolvable (DOCX does the same); an explicit\n // chartColors entry naming one keeps the loud fallback + warning. Only hex\n // reaches pptxgenjs: it answers a stray token name with black. An empty list\n // is left unset rather than passed on — pptxgenjs indexes `chartColors[i % 0]`\n // and paints every series black, so its own palette is the better fallback.\n const colorSources = props.chartColors ?? definedChartColorTokens(theme);\n if (colorSources.length > 0) {\n opts.chartColors = colorSources.map((c) =>\n resolveColor(c, theme, warnings)\n );\n }\n\n // Auto-default chart text colors from theme to prevent dark-on-dark / light-on-light\n const themeTextColor = resolveColor('text', theme, warnings);\n opts.titleColor = props.titleColor\n ? resolveColor(props.titleColor, theme, warnings)\n : themeTextColor;\n opts.legendColor = props.legendColor\n ? resolveColor(props.legendColor, theme, warnings)\n : themeTextColor;\n opts.catAxisLabelColor = props.catAxisLabelColor\n ? resolveColor(props.catAxisLabelColor, theme, warnings)\n : themeTextColor;\n opts.valAxisLabelColor = props.valAxisLabelColor\n ? resolveColor(props.valAxisLabelColor, theme, warnings)\n : themeTextColor;\n if (props.valAxisLabelFontSize !== undefined)\n opts.valAxisLabelFontSize = props.valAxisLabelFontSize;\n if (props.catAxisLineShow !== undefined)\n opts.catAxisLineShow = props.catAxisLineShow;\n if (props.valAxisLineShow !== undefined)\n opts.valAxisLineShow = props.valAxisLineShow;\n\n // Data element border (bars/slices/areas)\n if (props.dataBorder !== undefined) {\n opts.dataBorder = {\n pt: props.dataBorder.pt,\n color: resolveColor(props.dataBorder.color, theme, warnings),\n };\n }\n\n // Display toggles\n if (props.showLegend !== undefined) opts.showLegend = props.showLegend;\n if (props.showTitle !== undefined) opts.showTitle = props.showTitle;\n if (props.showValue !== undefined) opts.showValue = props.showValue;\n if (props.showPercent !== undefined) opts.showPercent = props.showPercent;\n if (props.showLabel !== undefined) opts.showLabel = props.showLabel;\n if (props.showSerName !== undefined) opts.showSerName = props.showSerName;\n\n // Title\n if (props.title !== undefined) opts.title = props.title;\n if (props.titleFontSize !== undefined)\n opts.titleFontSize = props.titleFontSize;\n if (props.titleFontFace !== undefined)\n opts.titleFontFace = props.titleFontFace;\n\n // Legend\n if (props.legendPos !== undefined) opts.legendPos = props.legendPos;\n if (props.legendFontSize !== undefined)\n opts.legendFontSize = props.legendFontSize;\n if (props.legendFontFace !== undefined)\n opts.legendFontFace = props.legendFontFace;\n\n // Category axis\n if (props.catAxisTitle !== undefined) {\n opts.catAxisTitle = props.catAxisTitle;\n opts.showCatAxisTitle = true;\n }\n if (props.catAxisHidden !== undefined)\n opts.catAxisHidden = props.catAxisHidden;\n if (props.catAxisLabelRotate !== undefined)\n opts.catAxisLabelRotate = props.catAxisLabelRotate;\n if (props.catAxisLabelFontSize !== undefined)\n opts.catAxisLabelFontSize = props.catAxisLabelFontSize;\n if (props.catAxisLabelFontFace !== undefined)\n opts.catAxisLabelFontFace = props.catAxisLabelFontFace;\n if (props.catGridLine !== undefined)\n opts.catGridLine = resolveGridLine(props.catGridLine, theme, warnings);\n\n // Value axis\n if (props.valAxisTitle !== undefined) {\n opts.valAxisTitle = props.valAxisTitle;\n opts.showValAxisTitle = true;\n }\n if (props.valAxisHidden !== undefined)\n opts.valAxisHidden = props.valAxisHidden;\n if (props.valAxisMinVal !== undefined)\n opts.valAxisMinVal = props.valAxisMinVal;\n if (props.valAxisMaxVal !== undefined)\n opts.valAxisMaxVal = props.valAxisMaxVal;\n if (props.valAxisLabelFormatCode !== undefined)\n opts.valAxisLabelFormatCode = props.valAxisLabelFormatCode;\n if (props.valAxisMajorUnit !== undefined)\n opts.valAxisMajorUnit = props.valAxisMajorUnit;\n if (props.valAxisLabelFontFace !== undefined)\n opts.valAxisLabelFontFace = props.valAxisLabelFontFace;\n if (props.valGridLine !== undefined)\n opts.valGridLine = resolveGridLine(props.valGridLine, theme, warnings);\n\n // Bar-specific\n if (props.barDir !== undefined) opts.barDir = props.barDir;\n if (props.barGrouping !== undefined) opts.barGrouping = props.barGrouping;\n if (props.barGapWidthPct !== undefined)\n opts.barGapWidthPct = props.barGapWidthPct;\n if (props.barOverlapPct !== undefined)\n opts.barOverlapPct = props.barOverlapPct;\n\n // Line-specific\n if (props.lineSmooth !== undefined) opts.lineSmooth = props.lineSmooth;\n if (props.lineDataSymbol !== undefined)\n opts.lineDataSymbol = props.lineDataSymbol;\n if (props.lineSize !== undefined) opts.lineSize = props.lineSize;\n if (props.lineDataSymbolSize !== undefined)\n opts.lineDataSymbolSize = props.lineDataSymbolSize;\n\n // Pie/doughnut\n if (props.firstSliceAng !== undefined)\n opts.firstSliceAng = props.firstSliceAng;\n if (props.holeSize !== undefined) opts.holeSize = props.holeSize;\n\n // Radar\n if (props.radarStyle !== undefined) opts.radarStyle = props.radarStyle;\n\n // Data labels\n opts.dataLabelColor = props.dataLabelColor\n ? resolveColor(props.dataLabelColor, theme, warnings)\n : themeTextColor;\n if (props.dataLabelFontSize !== undefined)\n opts.dataLabelFontSize = props.dataLabelFontSize;\n if (props.dataLabelFontFace !== undefined)\n opts.dataLabelFontFace = props.dataLabelFontFace;\n if (props.dataLabelFontBold !== undefined)\n opts.dataLabelFontBold = props.dataLabelFontBold;\n if (props.dataLabelPosition !== undefined)\n opts.dataLabelPosition = props.dataLabelPosition;\n\n slide.addChart(chartType as any, data as any[], opts as any);\n}\n","/**\n * PPTX Component Renderers\n */\n\nimport type PptxGenJS from 'pptxgenjs';\nimport type {\n PptxThemeConfig,\n PptxComponentInput,\n PipelineWarning,\n SlideRenderContext,\n} from '../types';\nimport { warn, W } from '../utils/warn';\nimport { renderTextComponent } from './text';\nimport { renderImageComponent } from './image';\nimport { renderShapeComponent } from './shape';\nimport { renderTableComponent } from './table';\nimport { renderHighchartsComponent } from './highcharts';\nimport { renderChartComponent } from './chart';\n\nexport { renderTextComponent } from './text';\nexport { renderImageComponent } from './image';\nexport { renderShapeComponent } from './shape';\nexport { renderTableComponent } from './table';\nexport { renderHighchartsComponent } from './highcharts';\nexport { renderChartComponent } from './chart';\n\nexport async function renderComponent(\n slide: PptxGenJS.Slide,\n component: PptxComponentInput,\n theme: PptxThemeConfig,\n pptx: PptxGenJS,\n warnings?: PipelineWarning[],\n ctx?: SlideRenderContext\n): Promise<void> {\n if (component.enabled === false) return;\n\n const { name, props } = component;\n const p = props as any;\n\n switch (name) {\n case 'text':\n renderTextComponent(slide, p, theme, warnings, ctx?.slideCtx);\n break;\n case 'image':\n await renderImageComponent(\n slide,\n p,\n theme,\n warnings,\n ctx?.slideWidth,\n ctx?.slideHeight\n );\n break;\n case 'shape':\n renderShapeComponent(slide, p, theme, pptx, warnings, ctx);\n break;\n case 'table':\n renderTableComponent(slide, p, theme, pptx, warnings);\n break;\n case 'highcharts':\n await renderHighchartsComponent(\n slide,\n p,\n theme,\n warnings,\n ctx?.services?.highcharts\n );\n break;\n case 'chart':\n renderChartComponent(slide, p, theme, pptx, warnings);\n break;\n default:\n warn(\n warnings,\n W.UNKNOWN_COMPONENT,\n `Unknown PPTX component type: ${name}`,\n { component: name }\n );\n }\n}\n","/**\n * Template Slide Builder\n * Converts internal TemplateSlideDefinition to pptxgenjs SlideMasterProps\n *\n * Fixed objects (shapes, text, images) are no longer rendered here — they use\n * the unified component pipeline and are rendered per-slide in render.ts.\n */\n\nimport type { TemplateSlideDefinition, PptxThemeConfig, PipelineWarning } from '../types';\nimport { resolveColor } from '../utils/color';\n\nexport function buildSlideTemplateProps(\n def: TemplateSlideDefinition,\n theme: PptxThemeConfig,\n warnings?: PipelineWarning[]\n): Record<string, any> {\n const result: Record<string, any> = { title: def.name };\n\n // Background\n if (def.background) {\n if (def.background.color) {\n result.background = { color: resolveColor(def.background.color, theme, warnings) };\n } else if (def.background.image) {\n if (def.background.image.path) {\n result.background = { path: def.background.image.path };\n } else if (def.background.image.base64) {\n result.background = { data: def.background.image.base64 };\n }\n }\n }\n\n // Margin\n if (def.margin !== undefined) result.margin = def.margin;\n\n // Slide number\n if (def.slideNumber) {\n result.slideNumber = {\n x: def.slideNumber.x,\n y: def.slideNumber.y,\n };\n if (def.slideNumber.w !== undefined) result.slideNumber.w = def.slideNumber.w;\n if (def.slideNumber.h !== undefined) result.slideNumber.h = def.slideNumber.h;\n if (def.slideNumber.color) result.slideNumber.color = resolveColor(def.slideNumber.color, theme, warnings);\n if (def.slideNumber.fontSize) result.slideNumber.fontSize = def.slideNumber.fontSize;\n }\n\n return result;\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} from '@json-to-office/shared';\nimport {\n loadFileFontSource,\n FontDiskCache,\n fetchVariableFontSource,\n} from '@json-to-office/shared/fonts/node';\nimport type {\n PipelineWarning,\n PresentationComponentDefinition,\n} from '../types';\nimport type { PptxThemeConfig } from '../types';\nimport { warn, W } from '../utils/warn';\n\nexport async function resolveDocumentFonts(\n document: PresentationComponentDefinition,\n theme: PptxThemeConfig,\n warnings: PipelineWarning[],\n fonts?: FontRuntimeOpts\n): Promise<ResolvedFont[]> {\n const names = new Set<string>();\n for (const n of collectFontNamesFromPptx(document)) names.add(n);\n for (const n of collectFontNamesFromPptx(theme as unknown)) names.add(n);\n if (names.size === 0) return [];\n\n // 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: fonts?.extraEntries,\n });\n if (validation.warnings.length > 0) {\n if (fonts?.strict) {\n throw new Error(\n `Unresolved font references (strict mode):\\n` +\n validation.warnings.map((w) => ` - ${w.message}`).join('\\n')\n );\n }\n for (const w of validation.warnings) {\n warn(warnings, W.FONT_UNRESOLVED, w.message, {\n component: 'fontRegistry',\n });\n }\n }\n\n // Registry resolution (Google/URL/file fetches) only runs when a consumer\n // is listening via onResolved — typically the LibreOffice preview stager.\n // Office output never embeds bytes, so skipping fetches when nobody cares\n // keeps library callers from paying network cost.\n if (!fonts?.onResolved) return [];\n\n const registry = new FontRegistry({\n opts: fonts,\n fileLoader: loadFileFontSource,\n variableLoader: fetchVariableFontSource,\n diskCache: fonts?.googleFonts?.cacheDir\n ? new FontDiskCache(fonts.googleFonts.cacheDir)\n : undefined,\n });\n const resolved = await registry.resolveMany(names);\n for (const r of resolved) {\n for (const msg of r.warnings) {\n warn(warnings, W.FONT_UNRESOLVED, msg, {\n component: 'fontRegistry',\n });\n }\n }\n // Fire the side-channel here so callers never have to remember. The\n // short-circuit above guarantees we only reach this point when a\n // listener is registered.\n fonts.onResolved(resolved);\n return resolved;\n}\n","/**\n * Shared generation prologue.\n *\n * Both entry points — `generateBufferWithWarnings` (core) and\n * `createPresentationGenerator` (plugin) — must resolve the same theme, run\n * the same export-mode pre-pass, and derive the same cache key before slide\n * processing runs. Keeping two 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, scopedThemeName } from '@json-to-office/shared';\nimport { getPptxTheme } from '../themes/defaults';\n\nexport interface ThemeContextOptions {\n customThemes?: Record<string, PptxThemeConfig>;\n fonts?: FontRuntimeOpts;\n warnings?: PipelineWarning[];\n /**\n * Base theme name when the document doesn't name one. The plugin builder\n * passes its constructor-supplied string theme; defaults to 'default'.\n */\n defaultThemeName?: string;\n /**\n * Theme lookup for the base `props.theme` name. The plugin builder passes\n * its own (customThemes → constructor theme object → built-in); omit it to\n * use customThemes → built-in.\n */\n resolveNamedTheme?: (name: string) => 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 * Cache key: base theme name + export-mode scope. Nothing in PPTX consumes\n * a theme by name after the prologue today; this is the key a future\n * theme-keyed cache must use (a substitute-mode run rewrites the theme in\n * place, so it must never share a slot with a custom-mode run of the same\n * base name — the DOCX layout cache is keyed exactly this way).\n */\n themeName: string;\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 baseThemeName = inlineTheme\n ? inlineTheme.name || 'inline-theme'\n : (document.props.theme as string | undefined) ??\n defaultThemeName ??\n 'default';\n let theme =\n inlineTheme ??\n (resolveNamedTheme\n ? resolveNamedTheme(baseThemeName)\n : customThemes?.[baseThemeName] ?? getPptxTheme(baseThemeName));\n\n // Export-mode pre-pass: substitute rewrites non-safe families in place;\n // custom leaves refs untouched and resolution short-circuits to empty.\n const mode = applyExportMode({ doc: document, theme, fonts });\n document = mode.doc;\n theme = mode.theme;\n for (const w of mode.warnings) {\n warnings?.push({\n code: w.code,\n message: w.message,\n component: 'fontRegistry',\n });\n }\n\n return {\n document,\n theme,\n themeName: scopedThemeName(baseThemeName, fonts?.mode),\n };\n}\n","import JSZip from 'jszip';\nimport type { PendingXmlFill } from '../types';\n\nconst MEDIUM_STYLE_2_ACCENT_1 = '{5C22544A-7EE6-4342-B048-85BDC9FD1C3A}';\nconst NO_STYLE_NO_GRID = '{2D5ABB26-0587-4C30-8999-92F81FD0307C}';\n\n/** Stable default shared by package entries and OOXML core metadata. */\nexport const DEFAULT_GENERATED_AT = '2000-01-01T00:00:00.000Z';\n\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 * 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?: PendingXmlFill[];\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\nfunction 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\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/**\n * Apply post-generation OOXML fixes and deterministic package metadata.\n *\n * PptxGenJS stamps both core.xml and ZIP entries with the wall clock. Rewriting\n * both layers makes equivalent inputs byte-identical across invocations.\n */\nexport async function packagePresentationBuffer(\n buffer: Buffer,\n options: PresentationPackagingOptions = {}\n): Promise<Buffer> {\n const zip = await JSZip.loadAsync(buffer);\n let changed = false;\n\n for (const [path, entry] of Object.entries(zip.files)) {\n if (!path.match(/^ppt\\/slides\\/slide\\d+\\.xml$/)) 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 if (options.deterministic !== false) {\n const generatedAt = resolveGeneratedAt(options.generatedAt);\n await canonicalizeChartIds(zip);\n await canonicalizePackage(zip, generatedAt);\n changed = true;\n }\n\n if (!changed) return buffer;\n\n return generateZip(zip);\n}\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 PendingXmlFill,\n} from '../types';\nimport type {\n ExtendedPresentationComponent,\n PresentationGeneratorBuilder,\n BufferGenerationResult,\n FileGenerationResult,\n GenerateFileOptions,\n GenerateOptions,\n GenerationValidationOptions,\n ValidationResult,\n} from './types';\nimport { validatePresentation, cleanComponentProps } from './validation';\nimport { generatePluginPresentationSchema, exportPluginSchema } from './schema';\nimport { processPresentation } from '../core/structure';\nimport { renderPresentation } from '../core/render';\nimport { getPptxTheme } from '../themes';\nimport type { ServicesConfig, FontRuntimeOpts } from '@json-to-office/shared';\nimport { resolveDocumentFonts } from '../core/fontResolution';\nimport { resolveThemeContext } from '../core/generationContext';\nimport { assertNoContentConflicts } from '../core/generator';\nimport {\n packagePresentationBuffer,\n type PresentationPackagingOptions,\n} from '../core/packagePresentation';\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\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}\n\ntype ValidateEmitted = (\n emitted: PptxComponentInput[],\n componentLabel: string,\n parentName?: string\n) => void;\n\n/**\n * Create the builder implementation with the given state\n */\nfunction createBuilderImpl<\n TComponents extends readonly CustomComponent<any, any, any>[],\n>(state: BuilderState): PresentationGeneratorBuilder<TComponents> {\n const componentMap = new Map(state.components.map((c) => [c.name, c]));\n\n /**\n * Process custom components in slide children, recursively resolving them\n * to standard PptxComponentInput elements.\n */\n async function processSlideComponents(\n components: PptxComponentInput[],\n warningsCollector: PipelineWarning[],\n theme: PptxThemeConfig,\n validateEmitted: ValidateEmitted | undefined,\n parentName?: string,\n depth = 0\n ): Promise<PptxComponentInput[]> {\n if (depth > 20) {\n throw new Error(\n 'Maximum component nesting depth exceeded (20). Check for circular component references.'\n );\n }\n const processed: PptxComponentInput[] = [];\n\n for (const componentData of components) {\n const customComponent = componentMap.get(componentData.name);\n\n if (customComponent) {\n try {\n if (!componentData.props) {\n throw new Error(\n `Custom component '${componentData.name}' must have a 'props' property. ` +\n `Use format: { name: '${componentData.name}', props: {...} }`\n );\n }\n\n const componentWithVersion = componentData as {\n name: string;\n version?: string;\n props: Record<string, any>;\n children?: PptxComponentInput[];\n };\n\n // Resolve version\n const versionEntry = resolveComponentVersion(\n customComponent.name,\n customComponent.versions,\n componentWithVersion.version\n );\n\n // Validate and clean props\n const cleanedProps = cleanComponentProps(\n versionEntry,\n componentWithVersion.props\n );\n\n // Process nested children if container\n let nestedChildren: unknown[] | undefined;\n if (\n componentWithVersion.children &&\n Array.isArray(componentWithVersion.children)\n ) {\n nestedChildren = await processSlideComponents(\n componentWithVersion.children,\n warningsCollector,\n theme,\n validateEmitted,\n undefined,\n depth + 1\n );\n }\n\n // Create addWarning callback\n const versionLabel = componentWithVersion.version\n ? `${customComponent.name}@${componentWithVersion.version}`\n : customComponent.name;\n\n const addWarning = (\n message: string,\n context?: Record<string, unknown>\n ) => {\n warningsCollector.push({\n code: (context?.code as string) ?? 'PLUGIN_WARNING',\n message,\n component: versionLabel,\n slide: context?.slide as number | undefined,\n });\n };\n\n // Call render\n const result = await versionEntry.render({\n props: cleanedProps,\n theme,\n addWarning,\n children: nestedChildren,\n });\n\n const resultComponents = (\n Array.isArray(result) ? result : [result]\n ) as PptxComponentInput[];\n\n validateEmitted?.(resultComponents, versionLabel, parentName);\n\n // Recursively process in case result contains more custom components\n const processedResult = await processSlideComponents(\n resultComponents,\n warningsCollector,\n theme,\n validateEmitted,\n parentName,\n depth + 1\n );\n processed.push(...processedResult);\n\n if (state.debug) {\n console.log(\n `Processed custom component '${versionLabel}':`,\n processedResult\n );\n }\n } catch (error) {\n if (error instanceof ComponentValidationError) {\n throw error;\n }\n throw new Error(\n `Error processing custom component '${customComponent.name}': ${\n error instanceof Error ? error.message : String(error)\n }`\n );\n }\n } else {\n // Standard component — process children recursively\n if (componentData.children && Array.isArray(componentData.children)) {\n const processedChildren = await processSlideComponents(\n componentData.children,\n warningsCollector,\n theme,\n validateEmitted,\n componentData.name,\n depth + 1\n );\n processed.push({\n ...componentData,\n children: processedChildren,\n });\n } else {\n processed.push(componentData);\n }\n }\n }\n\n return processed;\n }\n\n /**\n * Add a custom component to the generator\n */\n function addComponent<TNewComponent extends CustomComponent<any, any, any>>(\n component: TNewComponent\n ): PresentationGeneratorBuilder<readonly [...TComponents, TNewComponent]> {\n if (!component.name) {\n throw new Error('Component name is required');\n }\n\n if (state.componentNames.has(component.name)) {\n throw new DuplicateComponentError(component.name);\n }\n\n const newComponentNames = new Set(state.componentNames);\n newComponentNames.add(component.name);\n\n const newState: BuilderState = {\n components: [...state.components, component],\n componentNames: newComponentNames,\n theme: state.theme,\n customThemes: state.customThemes,\n debug: state.debug,\n services: state.services,\n fonts: state.fonts,\n validation: state.validation,\n packaging: state.packaging,\n };\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\n const validationOptions: GenerationValidationOptions = {\n ...state.validation,\n ...options?.validation,\n };\n if (validationOptions.enabled !== false) {\n const result = validatePresentation(\n internalDocument,\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), export-mode pre-pass\n // and cache-key scoping — 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] → constructor `state.theme`\n // object → built-in, with the lookup name taken from doc-level\n // `props.theme` (or `defaultThemeName` when the doc names none). The\n // constructor object fills in for ANY customThemes miss — a doc-named\n // built-in included — matching the DOCX plugin (resolveDocumentTheme)\n // exactly; it never shadows a customThemes entry (a doc naming\n // \"wiseair\" must not render as `themes.minimal`). Whether a doc-named\n // built-in should instead beat the constructor object is #141 — a\n // cross-format decision, not taken here.\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) =>\n state.customThemes?.[name] ??\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 = { ...modedRoot, children: emitted };\n } else if (parentName === 'slide') {\n validationDocument = {\n ...modedRoot,\n children: [{ name: 'slide', props: {}, children: emitted }],\n };\n } else {\n // Custom container semantics are plugin-defined. The complete\n // expanded-tree pass below validates the final standard tree.\n return;\n }\n\n const result = validatePresentation(\n validationDocument,\n state.components as unknown as CustomComponent<TSchema>[],\n { allowUnknownFields: validationOptions.allowUnknownFields }\n );\n if (!result.valid) {\n throw new ComponentValidationError(\n result.errors.map((error) => ({\n ...error,\n message: `custom component '${componentLabel}' emitted invalid output — ${error.message}`,\n })),\n emitted\n );\n }\n };\n\n // Process custom components in all slide children\n const processedChildren = modedRoot.children\n ? await processAllSlides(\n modedRoot.children,\n warnings,\n resolvedTheme,\n validateEmitted\n )\n : [];\n\n const processedDocument: PresentationComponentDefinition = {\n ...modedRoot,\n children: processedChildren,\n };\n\n // Validate the fully expanded tree once more. This covers output from\n // nested custom containers whose intermediate parent semantics are\n // plugin-defined and therefore cannot be checked at render time.\n if (validationOptions.enabled !== false) {\n const result = validatePresentation(processedDocument, [], {\n allowUnknownFields: validationOptions.allowUnknownFields,\n });\n if (!result.valid) {\n throw new ComponentValidationError(\n result.errors.map((error) => ({\n ...error,\n message: `expanded plugin output failed validation — ${error.message}`,\n })),\n processedDocument\n );\n }\n }\n\n // resolveDocumentFonts fires `fonts.onResolved` internally when a\n // listener is registered (LibreOffice preview stager). The PPTX\n // itself never embeds bytes.\n await resolveDocumentFonts(\n processedDocument,\n resolvedTheme,\n warnings,\n state.fonts\n );\n\n // Unconditional conflict gate on the expanded tree — the tree that\n // reaches the renderer, so it also covers payloads emitted by custom\n // components. The validators above collect the same conflicts with\n // richer paths when validation is enabled; this is the net for\n // `validation: { enabled: false }`, where the core path already threw\n // and this path silently resolved by runtime precedence.\n assertNoContentConflicts(processedDocument);\n\n // processPresentation takes the resolved (post-substitute) theme by\n // value — the document's `props.theme` stays as authored and is not\n // consulted again.\n const processed = processPresentation(processedDocument, {\n theme: resolvedTheme,\n services: state.services,\n });\n const pendingFills: PendingXmlFill[] = [];\n const pptx = await renderPresentation(processed, warnings, pendingFills);\n const data = await pptx.write({ outputType: 'nodebuffer' });\n const buffer = await packagePresentationBuffer(data as Buffer, {\n deterministic: options?.deterministic ?? state.packaging.deterministic,\n generatedAt: options?.generatedAt ?? state.packaging.generatedAt,\n pendingFills,\n });\n\n return { buffer, warnings };\n } catch (error) {\n if (state.debug) {\n console.error('Presentation generation error:', error);\n }\n throw error;\n }\n }\n\n /**\n * Process custom components inside all slides.\n * Walks the top-level children (slides), then processes each slide's children.\n */\n async function processAllSlides(\n children: PptxComponentInput[],\n warnings: PipelineWarning[],\n theme: PptxThemeConfig,\n validateEmitted: ValidateEmitted | undefined\n ): Promise<PptxComponentInput[]> {\n const result: PptxComponentInput[] = [];\n\n for (const child of children) {\n if (child.name === 'slide' && child.children) {\n const processedSlideChildren = await processSlideComponents(\n child.children,\n warnings,\n theme,\n validateEmitted,\n 'slide'\n );\n result.push({ ...child, children: processedSlideChildren });\n } else {\n // Non-slide top-level children — process in case they're custom\n const processedTopLevel = await processSlideComponents(\n [child],\n warnings,\n theme,\n validateEmitted,\n 'pptx'\n );\n result.push(...processedTopLevel);\n }\n }\n\n return result;\n }\n\n /**\n * Generate and save to file\n */\n async function generateFile(\n document: ExtendedPresentationComponent<TComponents>,\n outputPath: string,\n options?: GenerateFileOptions\n ): Promise<FileGenerationResult> {\n const { buffer, warnings } = await generate(document, options);\n const fs = await import('fs/promises');\n await fs.writeFile(outputPath, new Uint8Array(buffer));\n return { warnings };\n }\n\n /**\n * Get registered component names\n */\n function getComponentNames(): string[] {\n return Array.from(state.componentNames);\n }\n\n /**\n * Validate a document without generating it\n */\n function validate(\n document: ExtendedPresentationComponent<TComponents>\n ): ValidationResult {\n try {\n const internalDocument =\n document as unknown as PresentationComponentDefinition;\n const result = validatePresentation(\n internalDocument,\n state.components as unknown as CustomComponent<TSchema>[]\n );\n if (!result.valid) {\n return {\n valid: false,\n errors: result.errors.map((e) => ({\n path: e.path,\n message: e.message,\n })),\n };\n }\n return { valid: true };\n } catch (error) {\n if (error instanceof ComponentValidationError) {\n return {\n valid: false,\n errors: error.errors.map((e) => ({\n path: e.path,\n message: e.message,\n })),\n };\n }\n return {\n valid: false,\n errors: [\n {\n path: 'document',\n message: error instanceof Error ? error.message : String(error),\n },\n ],\n };\n }\n }\n\n /**\n * Generate the extended JSON schema\n */\n function generateSchema(): TSchema {\n return generatePluginPresentationSchema(\n state.components as unknown as CustomComponent<TSchema>[]\n );\n }\n\n /**\n * Export the schema to a file\n */\n async function exportSchemaToFile(\n outputPath: string,\n options?: { prettyPrint?: boolean }\n ): Promise<void> {\n await exportPluginSchema(\n state.components as unknown as CustomComponent<TSchema>[],\n outputPath,\n options\n );\n }\n\n return Object.freeze({\n addComponent,\n generate,\n generateBuffer: generate,\n generateFile,\n getComponentNames,\n validate,\n generateSchema,\n exportSchema: exportSchemaToFile,\n });\n}\n\n/**\n * Create a presentation generator with chainable component registration.\n */\nexport function createPresentationGenerator(\n options: PresentationGeneratorOptions = {}\n): PresentationGeneratorBuilder<readonly []> {\n const initialState: BuilderState = {\n components: [],\n componentNames: new Set(),\n theme: options.theme,\n customThemes: options.customThemes,\n debug: options.debug ?? false,\n services: options.services,\n fonts: options.fonts,\n validation: options.validation,\n packaging: {\n deterministic: options.deterministic,\n generatedAt: options.generatedAt,\n },\n };\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","// Version information\nexport function getPptxCoreVersion(): string {\n return 'PptxCore v1.0.0';\n}\n\n// Core API\nexport {\n generatePresentation,\n generateBufferFromJson,\n generateBufferWithWarnings,\n generateAndSaveFromJson,\n generateFromFile,\n savePresentation,\n isPresentationComponentDefinition,\n PresentationValidationError,\n PresentationGenerator,\n} from './core/generator';\n\nexport type {\n GenerationOptions,\n GenerationResult,\n GenerationValidationOptions,\n} from './core/generator';\nexport {\n DEFAULT_GENERATED_AT,\n packagePresentationBuffer,\n} from './core/packagePresentation';\nexport type { PresentationPackagingOptions } from './core/packagePresentation';\n\n// Types\nexport type {\n PptxComponentInput,\n PresentationComponentDefinition,\n SlideComponentDefinition,\n ProcessedPresentation,\n ProcessedSlide,\n PptxThemeConfig,\n PipelineWarning,\n SlideContext,\n SlideRenderContext,\n} from './types';\n\nexport { isPresentationComponent, isSlideComponent } from './types';\n\n// Warning utilities\nexport { W as WarningCodes } from './utils/warn';\nexport type { WarningCode } from './utils/warn';\n\n// Themes\nexport { DEFAULT_PPTX_THEME, getPptxTheme, pptxThemes } from './themes';\n\n// Plugin system\nexport {\n createComponent,\n createVersion,\n createPresentationGenerator,\n resolveComponentVersion,\n validateComponentProps,\n validatePresentation,\n cleanComponentProps,\n ComponentValidationError,\n DuplicateComponentError,\n generatePluginPresentationSchema,\n exportPluginSchema,\n} from './plugin';\n\nexport type {\n CustomComponent,\n ComponentVersion,\n ComponentVersionMap,\n RenderFunction,\n RenderContext,\n PresentationGeneratorOptions,\n PresentationGenerator as PluginPresentationGenerator,\n PresentationGeneratorBuilder,\n BufferGenerationResult as PluginBufferGenerationResult,\n FileGenerationResult as PluginFileGenerationResult,\n GenerateFileOptions as PluginGenerateFileOptions,\n GenerateOptions as PluginGenerateOptions,\n GenerationValidationOptions as PluginGenerationValidationOptions,\n ValidationResult as PluginValidationResult,\n ExtractCustomComponentType,\n CustomComponentUnion,\n ExtendedPptxComponentInput,\n ExtendedPresentationComponent,\n InferBuilderComponents,\n InferDocumentType,\n InferComponentDefinition,\n ComponentValidationResult,\n ValidationError as PluginValidationError,\n} from './plugin';\n\n// Component renderers\nexport {\n renderTextComponent,\n renderImageComponent,\n renderShapeComponent,\n renderTableComponent,\n renderHighchartsComponent,\n renderComponent,\n} from './components';\n"],"mappings":";AAMA,SAAS,qBAAqB;;;ACsOvB,SAAS,wBACd,WAC8C;AAC9C,SACE,OAAO,cAAc,YACrB,cAAc,QACb,UAAkB,SAAS;AAEhC;AAEO,SAAS,iBACd,WACuC;AACvC,SACE,OAAO,cAAc,YACrB,cAAc,QACb,UAAkB,SAAS;AAEhC;;;AC5PO,IAAM,IAAI;AAAA,EACf,mBAAmB;AAAA,EACnB,oBAAoB;AAAA,EACpB,eAAe;AAAA,EACf,eAAe;AAAA,EACf,sBAAsB;AAAA,EACtB,oBAAoB;AAAA,EACpB,iBAAiB;AAAA,EACjB,oBAAoB;AAAA,EACpB,kBAAkB;AAAA,EAClB,qBAAqB;AAAA,EACrB,yBAAyB;AAAA,EACzB,sBAAsB;AAAA,EACtB,eAAe;AAAA,EACf,uBAAuB;AAAA,EACvB,iBAAiB;AAAA,EACjB,wBAAwB;AAAA,EACxB,wBAAwB;AAAA,EACxB,gBAAgB;AAAA,EAChB,iBAAiB;AACnB;AAIO,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;;;AC7BO,IAAM,sBAKR;AAAA,EACH,SAAS;AAAA,EACT,MAAM;AAAA,EACN,QAAQ,EAAE,KAAK,KAAK,OAAO,KAAK,QAAQ,KAAK,MAAM,IAAI;AAAA,EACvD,QAAQ,EAAE,QAAQ,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SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAAA,UAChE;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAKA,WAAS,iBAA0B;AACjC,WAAO;AAAA,MACL,MAAM;AAAA,IACR;AAAA,EACF;AAKA,iBAAe,mBACb,YACA,SACe;AACf,UAAM;AAAA,MACJ,MAAM;AAAA,MACN;AAAA,MACA;AAAA,IACF;AAAA,EACF;AAEA,SAAO,OAAO,OAAO;AAAA,IACnB;AAAA,IACA;AAAA,IACA,gBAAgB;AAAA,IAChB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,cAAc;AAAA,EAChB,CAAC;AACH;AAKO,SAAS,4BACd,UAAwC,CAAC,GACE;AAC3C,QAAM,eAA6B;AAAA,IACjC,YAAY,CAAC;AAAA,IACb,gBAAgB,oBAAI,IAAI;AAAA,IACxB,OAAO,QAAQ;AAAA,IACf,cAAc,QAAQ;AAAA,IACtB,OAAO,QAAQ,SAAS;AAAA,IACxB,UAAU,QAAQ;AAAA,IAClB,OAAO,QAAQ;AAAA,IACf,YAAY,QAAQ;AAAA,IACpB,WAAW;AAAA,MACT,eAAe,QAAQ;AAAA,MACvB,aAAa,QAAQ;AAAA,IACvB;AAAA,EACF;AAEA,SAAO,kBAA+B,YAAY;AACpD;;;ADhhBA,SAAS,2BAAAE,gCAA+B;;;AI5EjC,SAAS,qBAA6B;AAC3C,SAAO;AACT;","names":["mergeWithDefaults","weight","result","opts","mergeWithDefaults","path","resolveComponentVersion","DuplicateComponentError","ComponentValidationError","validatePresentationDocument","ComponentValidationError","resolveComponentVersion","ComponentValidationError","DuplicateComponentError","resolveComponentVersion"]}
|
|
1
|
+
{"version":3,"sources":["../src/core/generator.ts","../src/types.ts","../src/utils/warn.ts","../src/core/grid.ts","../src/themes/defaults.ts","../src/utils/componentDefaults.ts","../src/utils/resolveComponentTree.ts","../src/utils/hyperlink.ts","../src/core/structure.ts","../src/core/render.ts","../src/utils/color.ts","../src/utils/fontAliasContext.ts","../src/components/text.ts","../src/components/image.ts","../src/utils/imageSource.ts","../src/utils/baseDirContext.ts","../src/components/shape.ts","../src/utils/fillXml.ts","../src/components/table.ts","../src/utils/environment.ts","../src/components/highcharts.ts","../src/components/chart.ts","../src/components/index.ts","../src/core/template.ts","../src/core/fontResolution.ts","../src/core/generationContext.ts","../src/core/packagePresentation.ts","../src/plugin/index.ts","../src/plugin/createPresentationGenerator.ts","../src/plugin/validation.ts","../src/plugin/schema.ts","../src/index.ts"],"sourcesContent":["/**\n * Presentation Generator\n * Main orchestration functions for the PPTX generation pipeline\n */\n\nimport PptxGenJS from 'pptxgenjs';\nimport { writeFileSync } from 'fs';\nimport type {\n PresentationComponentDefinition,\n PptxThemeConfig,\n PipelineWarning,\n PendingXmlFill,\n} from '../types';\nimport { isPresentationComponent } from '../types';\nimport type { ServicesConfig, FontRuntimeOpts } from '@json-to-office/shared';\nimport { processPresentation } from './structure';\nimport { renderPresentation } from './render';\nimport { resolveDocumentFonts } from './fontResolution';\nimport { resolveThemeContext } from './generationContext';\nimport {\n collectImageSourceConflicts,\n collectTextContentConflicts,\n validateJsonPresentationDocument,\n validatePresentationDocument,\n type ValidationError,\n} from '@json-to-office/shared-pptx';\nimport { runWithBaseDir } from '../utils/baseDirContext';\nimport {\n packagePresentationBuffer,\n type PresentationPackagingOptions,\n} from './packagePresentation';\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\n/**\n * Options for the generation pipeline\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\n// Font resolution shared with the plugin path — see ./fontResolution.ts\n\n/**\n * Result from generateBufferWithWarnings\n */\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\nfunction assertValidPresentation(\n input: string | unknown,\n validation?: GenerationValidationOptions\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 if (!result.valid) {\n throw new PresentationValidationError(result.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/**\n * Type guard for presentation component\n */\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/**\n * Generate a PptxGenJS instance from a presentation component definition\n */\nexport async function generatePresentation(\n document: PresentationComponentDefinition,\n options?: GenerationOptions,\n warnings?: PipelineWarning[],\n pendingFills?: PendingXmlFill[]\n): Promise<PptxGenJS> {\n assertValidPresentation(document, options?.validation);\n\n if (!document || document.name !== 'pptx') {\n throw new Error('Top-level component must be a pptx component');\n }\n\n assertNoContentConflicts(document);\n\n // Scope the document base directory over process+render: relative asset\n // paths are rewritten eagerly here — pptxgenjs reads them later, during\n // write(), from whatever cwd it happens to have (#142).\n return runWithBaseDir(options?.baseDir, async () => {\n const processed = processPresentation(document, options);\n return await renderPresentation(processed, warnings, pendingFills);\n });\n}\n\n/**\n * Generate a buffer from JSON 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 buffer from JSON definition, returning warnings alongside the buffer\n */\nexport async function generateBufferWithWarnings(\n jsonConfig: string | PresentationComponentDefinition,\n options?: GenerationOptions\n): Promise<GenerationResult> {\n assertValidPresentation(jsonConfig, options?.validation);\n\n let component: PresentationComponentDefinition;\n\n if (typeof jsonConfig === 'string') {\n const parsed = JSON.parse(jsonConfig);\n if (!isPresentationComponent(parsed)) {\n throw new Error('Parsed JSON must be a presentation component');\n }\n component = parsed;\n } else {\n component = jsonConfig;\n }\n\n const warnings: PipelineWarning[] = [];\n\n // Props defaulting, inline-theme normalization, theme resolution,\n // export-mode pre-pass and cache-key scoping — shared with the plugin\n // pipeline so the two cannot drift (see core/generationContext.ts).\n const context = resolveThemeContext(component, {\n customThemes: options?.customThemes,\n fonts: options?.fonts,\n warnings,\n });\n component = context.document;\n // resolveDocumentFonts fires `fonts.onResolved` internally when a\n // listener is registered (LibreOffice preview stager). The PPTX itself\n // never embeds bytes.\n await resolveDocumentFonts(\n component,\n context.theme,\n warnings,\n options?.fonts\n );\n // processPresentation takes the resolved theme by value — the document's\n // `props.theme` stays as authored and is not consulted again.\n const effectiveOptions: GenerationOptions = {\n ...options,\n theme: context.theme,\n };\n // Gradient/pattern fills render as sentinel solid fills during generation;\n // packagePresentationBuffer splices the real fill XML in afterwards.\n const pendingFills: PendingXmlFill[] = [];\n const pptx = await generatePresentation(\n component,\n effectiveOptions,\n warnings,\n pendingFills\n );\n const data = await pptx.write({ outputType: 'nodebuffer' });\n const buffer = await packagePresentationBuffer(data as Buffer, {\n ...options,\n pendingFills,\n });\n return { buffer, warnings };\n}\n\n/**\n * Generate and save a .pptx file from JSON 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\n/**\n * Save a PptxGenJS instance to file\n */\nexport async function savePresentation(\n pptx: PptxGenJS,\n outputPath: string,\n options?: PresentationPackagingOptions\n): Promise<void> {\n const data = await pptx.write({ outputType: 'nodebuffer' });\n const buffer = await packagePresentationBuffer(data as Buffer, options);\n writeFileSync(outputPath, buffer);\n}\n\n/**\n * Export the main API\n */\nexport const PresentationGenerator = {\n generate: generatePresentation,\n generateBufferFromJson,\n generateBufferWithWarnings,\n generateAndSaveFromJson,\n generateFromFile,\n save: savePresentation,\n isPresentationComponentDefinition,\n};\n","/**\n * PPTX Core Types\n */\n\nimport type { ServicesConfig } from '@json-to-office/shared';\nimport type {\n GradientFill,\n PptxComponentDefaults,\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 id?: string;\n props: {\n title?: string;\n author?: string;\n subject?: string;\n company?: string;\n theme?: string;\n slideWidth?: number;\n slideHeight?: number;\n rtlMode?: boolean;\n language?: string;\n pageNumberFormat?: '9' | '09';\n componentDefaults?: PptxComponentDefaults;\n grid?: GridConfig;\n templates?: TemplateSlideDefinition[];\n };\n children?: PptxComponentInput[];\n}\n\nexport interface SlideComponentDefinition {\n name: 'slide';\n id?: string;\n props: {\n background?: {\n color?: string;\n gradient?: GradientFill;\n image?: { path?: string; base64?: string };\n };\n transition?: {\n type?: string;\n speed?: string;\n };\n notes?: string;\n layout?: string;\n hidden?: boolean;\n template?: string;\n placeholders?: Record<string, PptxComponentInput>;\n };\n children?: PptxComponentInput[];\n}\n\nexport interface ProcessedPresentation {\n metadata: {\n title?: string;\n author?: string;\n subject?: string;\n company?: string;\n };\n theme: PptxThemeConfig;\n grid?: GridConfig;\n slideWidth: number;\n slideHeight: number;\n rtlMode: boolean;\n /** Default presentation language (BCP-47) for spell-checking */\n language?: string;\n pageNumberFormat: '9' | '09';\n slides: ProcessedSlide[];\n templates?: TemplateSlideDefinition[];\n services?: ServicesConfig;\n}\n\nexport interface ProcessedSlide {\n components: PptxComponentInput[];\n background?: {\n color?: string;\n gradient?: GradientFill;\n image?: { path?: string; base64?: string };\n };\n notes?: string;\n layout?: string;\n hidden?: boolean;\n template?: string;\n placeholders?: Record<string, PptxComponentInput>;\n}\n\nexport interface GridConfig {\n columns?: number;\n rows?: number;\n margin?:\n | number\n | { top: number; right: number; bottom: number; left: number };\n gutter?: number | { column: number; row: number };\n}\n\nexport interface GridPosition {\n column: number;\n row: number;\n columnSpan?: number;\n rowSpan?: number;\n}\n\nexport interface TextStyle {\n fontSize?: number;\n fontFace?: string;\n fontColor?: string;\n bold?: boolean;\n /**\n * Per-style weight (100–900). Overrides `bold` when set — renderer picks\n * the closest embedded variant via CSS font-matching and emits the run\n * under a synthetic family alias (e.g. \"Inter Light\" for weight 300).\n */\n fontWeight?: number;\n italic?: boolean;\n align?: string;\n lineSpacing?: number;\n charSpacing?: number;\n paraSpaceAfter?: number;\n}\n\nexport type StyleName =\n | 'title'\n | 'subtitle'\n | 'heading1'\n | 'heading2'\n | 'heading3'\n | 'body'\n | 'caption';\n\nexport interface PptxThemeConfig {\n name: string;\n colors: {\n primary: string;\n secondary: string;\n accent: string;\n background: string;\n text: string;\n text2?: string;\n background2?: string;\n accent4?: string;\n accent5?: string;\n accent6?: string;\n };\n fonts: {\n heading: string;\n body: string;\n };\n defaults: {\n fontSize: number;\n fontColor: string;\n };\n styles?: Partial<Record<StyleName, TextStyle>>;\n componentDefaults?: PptxComponentDefaults;\n}\n\nexport interface PlaceholderDefinition {\n name: string;\n x?: number;\n y?: number;\n w?: number;\n h?: number;\n grid?: GridPosition;\n defaults?: PptxComponentInput;\n}\n\nexport interface TemplateSlideDefinition {\n name: string;\n background?: {\n color?: string;\n gradient?: GradientFill;\n image?: { path?: string; base64?: string };\n };\n margin?: number | [number, number, number, number];\n slideNumber?: {\n x: number;\n y: number;\n w?: number;\n h?: number;\n color?: string;\n fontSize?: number;\n };\n objects?: PptxComponentInput[];\n placeholders?: PlaceholderDefinition[];\n grid?: GridConfig;\n}\n\nexport interface SlideContext {\n slideNumber: number;\n totalSlides: number;\n pageNumberFormat: '9' | '09';\n /** Default presentation language (BCP-47); text runs inherit it unless overridden */\n language?: string;\n}\n\nexport interface SlideRenderContext {\n slideCtx?: SlideContext;\n services?: ServicesConfig;\n slideWidth: number;\n slideHeight: number;\n /**\n * Per-generation registry of fills (gradient/pattern) that pptxgenjs cannot\n * express. Components render a sentinel solid fill tagged with a unique\n * objectName; packagePresentationBuffer 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","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 IMAGE_NO_SOURCE: 'IMAGE_NO_SOURCE',\n IMAGE_PROBE_FAILED: 'IMAGE_PROBE_FAILED',\n IMAGE_PATH_OUTSIDE_ROOTS: 'IMAGE_PATH_OUTSIDE_ROOTS',\n MISSING_TEMPLATE: 'MISSING_TEMPLATE',\n UNKNOWN_PLACEHOLDER: 'UNKNOWN_PLACEHOLDER',\n PLACEHOLDER_NO_POSITION: 'PLACEHOLDER_NO_POSITION',\n THEME_COLOR_FALLBACK: 'THEME_COLOR_FALLBACK',\n UNKNOWN_COLOR: 'UNKNOWN_COLOR',\n GRID_POSITION_CLAMPED: 'GRID_POSITION_CLAMPED',\n TEXT_NO_CONTENT: 'TEXT_NO_CONTENT',\n UNKNOWN_PATTERN_PRESET: 'UNKNOWN_PATTERN_PRESET',\n ADVANCED_FILL_FALLBACK: 'ADVANCED_FILL_FALLBACK',\n IMAGE_ZERO_BOX: 'IMAGE_ZERO_BOX',\n FONT_UNRESOLVED: 'FONT_UNRESOLVED',\n} as const;\n\nexport type WarningCode = (typeof W)[keyof typeof W];\n\nexport function warn(\n warnings: PipelineWarning[] | undefined,\n code: WarningCode,\n message: string,\n extra?: Partial<PipelineWarning>\n): void {\n if (warnings) {\n warnings.push({ code, message, ...extra });\n } else {\n console.warn(message);\n }\n}\n","/**\n * Grid Layout Resolution\n * Converts grid coordinates to absolute x/y/w/h positions\n */\n\nimport type { GridConfig, GridPosition, PptxComponentInput, PipelineWarning } from '../types';\nimport { warn, W } from '../utils/warn';\n\nexport const DEFAULT_GRID_CONFIG: Required<{\n columns: number;\n rows: number;\n margin: { top: number; right: number; bottom: number; left: number };\n gutter: { column: number; row: number };\n}> = {\n columns: 12,\n rows: 6,\n margin: { top: 0.5, right: 0.5, bottom: 0.5, left: 0.5 },\n gutter: { column: 0.2, row: 0.2 },\n};\n\nfunction resolveMargin(margin: GridConfig['margin']) {\n if (margin == null) return DEFAULT_GRID_CONFIG.margin;\n if (typeof margin === 'number') return { top: margin, right: margin, bottom: margin, left: margin };\n return margin;\n}\n\nfunction resolveGutter(gutter: GridConfig['gutter']) {\n if (gutter == null) return DEFAULT_GRID_CONFIG.gutter;\n if (typeof gutter === 'number') return { column: gutter, row: gutter };\n return gutter;\n}\n\n/**\n * Merge a template-level grid override on top of the presentation grid.\n * Template fields take precedence; nested margin/gutter objects are shallow-merged.\n * Both sides are normalized to object form before merging so that a shorthand\n * base (e.g. margin: 0.5) combined with a partial override (e.g. { top: 1.1 })\n * doesn't lose the other sides.\n */\nexport function mergeGridConfigs(\n base: GridConfig | undefined,\n override: GridConfig | undefined\n): GridConfig | undefined {\n if (!override) return base;\n if (!base) return override;\n\n const merged: GridConfig = {\n columns: override.columns ?? base.columns,\n rows: override.rows ?? base.rows,\n };\n\n // Merge margin — normalize both to object form first\n if (override.margin !== undefined) {\n if (typeof override.margin === 'number') {\n merged.margin = override.margin;\n } else {\n merged.margin = { ...resolveMargin(base.margin), ...override.margin };\n }\n } else {\n merged.margin = base.margin;\n }\n\n // Merge gutter — same normalization\n if (override.gutter !== undefined) {\n if (typeof override.gutter === 'number') {\n merged.gutter = override.gutter;\n } else {\n merged.gutter = { ...resolveGutter(base.gutter), ...override.gutter };\n }\n } else {\n merged.gutter = base.gutter;\n }\n\n return merged;\n}\n\nexport function resolveGridPosition(\n gridPos: GridPosition,\n gridConfig: GridConfig | undefined,\n slideWidth: number,\n slideHeight: number,\n warnings?: PipelineWarning[]\n): { x: number; y: number; w: number; h: number } {\n const cols = Math.max(1, gridConfig?.columns ?? DEFAULT_GRID_CONFIG.columns);\n const rows = Math.max(1, gridConfig?.rows ?? DEFAULT_GRID_CONFIG.rows);\n const margin = resolveMargin(gridConfig?.margin);\n const gutter = resolveGutter(gridConfig?.gutter);\n\n const col = Math.max(0, Math.min(gridPos.column, cols - 1));\n const row = Math.max(0, Math.min(gridPos.row, rows - 1));\n const colSpan = Math.max(1, Math.min(gridPos.columnSpan ?? 1, cols - col));\n const rowSpan = Math.max(1, Math.min(gridPos.rowSpan ?? 1, rows - row));\n\n if (gridPos.column !== col || gridPos.row !== row) {\n warn(warnings, W.GRID_POSITION_CLAMPED,\n `Grid position clamped: column ${gridPos.column}→${col}, row ${gridPos.row}→${row} (grid: ${cols}×${rows})`\n );\n }\n\n const availableW = slideWidth - margin.left - margin.right;\n const availableH = slideHeight - margin.top - margin.bottom;\n const trackW = (availableW - (cols - 1) * gutter.column) / cols;\n const trackH = (availableH - (rows - 1) * gutter.row) / rows;\n\n const x = margin.left + col * (trackW + gutter.column);\n const y = margin.top + row * (trackH + gutter.row);\n const w = colSpan * trackW + (colSpan - 1) * gutter.column;\n const h = rowSpan * trackH + (rowSpan - 1) * gutter.row;\n\n return { x, y, w, h };\n}\n\nexport function resolveComponentGridPosition(\n component: PptxComponentInput,\n gridConfig: GridConfig | undefined,\n slideWidth: number,\n slideHeight: number,\n warnings?: PipelineWarning[]\n): PptxComponentInput {\n const gridPos = component.props.grid as GridPosition | undefined;\n if (!gridPos) return component;\n\n const resolved = resolveGridPosition(gridPos, gridConfig, slideWidth, slideHeight, warnings);\n\n const { grid: _grid, ...restProps } = component.props; // eslint-disable-line no-unused-vars, @typescript-eslint/no-unused-vars\n const newProps = { ...restProps };\n\n // When explicit values use percentage strings, convert grid-resolved inches\n // to percentages too so pptxgenjs receives consistent units per element.\n const hasPercentX = typeof newProps.x === 'string' || typeof newProps.w === 'string';\n const hasPercentY = typeof newProps.y === 'string' || typeof newProps.h === 'string';\n\n const toPercX = (v: number) => `${+((v / slideWidth) * 100).toFixed(2)}%`;\n const toPercY = (v: number) => `${+((v / slideHeight) * 100).toFixed(2)}%`;\n\n // Grid sets x/y/w/h, but explicit values on the element override individually\n if (newProps.x == null) newProps.x = hasPercentX ? toPercX(resolved.x) : resolved.x;\n if (newProps.y == null) newProps.y = hasPercentY ? toPercY(resolved.y) : resolved.y;\n if (newProps.w == null) newProps.w = hasPercentX ? toPercX(resolved.w) : resolved.w;\n if (newProps.h == null) newProps.h = hasPercentY ? toPercY(resolved.h) : resolved.h;\n\n return { ...component, props: newProps };\n}\n","/**\n * PPTX Theme Defaults\n */\n\nimport type { PptxThemeConfig, TextStyle, StyleName } from '../types';\n\nconst DEFAULT_STYLES: Partial<Record<StyleName, TextStyle>> = {\n title: { fontSize: 36, bold: true, fontColor: 'text', align: 'center' },\n subtitle: { fontSize: 20, italic: true, fontColor: 'text2', align: 'center' },\n heading1: { fontSize: 28, bold: true, fontColor: 'primary' },\n heading2: { fontSize: 22, bold: true, fontColor: 'primary' },\n heading3: { fontSize: 18, bold: true, fontColor: 'text' },\n body: { fontSize: 14 },\n caption: { fontSize: 10, italic: true, fontColor: 'text2' },\n};\n\nexport const DEFAULT_PPTX_THEME: PptxThemeConfig = {\n name: 'default',\n colors: {\n primary: '#4472C4',\n secondary: '#ED7D31',\n accent: '#70AD47',\n background: '#FFFFFF',\n text: '#333333',\n text2: '#44546A',\n background2: '#E7E6E6',\n accent4: '#FFC000',\n accent5: '#5B9BD5',\n accent6: '#70AD47',\n },\n fonts: {\n heading: 'Arial',\n body: 'Arial',\n },\n defaults: {\n fontSize: 18,\n fontColor: '#333333',\n },\n styles: DEFAULT_STYLES,\n};\n\nconst PPTX_THEMES: Record<string, PptxThemeConfig> = {\n default: DEFAULT_PPTX_THEME,\n dark: {\n name: 'dark',\n colors: {\n primary: '#5B9BD5',\n secondary: '#FF6F61',\n accent: '#6BCB77',\n background: '#2D2D2D',\n text: '#FFFFFF',\n text2: '#CCCCCC',\n background2: '#3D3D3D',\n accent4: '#FFB347',\n accent5: '#77DD77',\n accent6: '#AEC6CF',\n },\n fonts: {\n heading: 'Arial',\n body: 'Arial',\n },\n defaults: {\n fontSize: 18,\n fontColor: '#FFFFFF',\n },\n styles: DEFAULT_STYLES,\n },\n minimal: {\n name: 'minimal',\n colors: {\n primary: '#000000',\n secondary: '#666666',\n accent: '#999999',\n background: '#FFFFFF',\n text: '#000000',\n text2: '#444444',\n background2: '#F5F5F5',\n accent4: '#BBBBBB',\n accent5: '#DDDDDD',\n accent6: '#888888',\n },\n fonts: {\n heading: 'Helvetica',\n body: 'Helvetica',\n },\n defaults: {\n fontSize: 18,\n fontColor: '#000000',\n },\n styles: DEFAULT_STYLES,\n },\n};\n\nexport function getPptxTheme(name: string): PptxThemeConfig {\n return PPTX_THEMES[name] || DEFAULT_PPTX_THEME;\n}\n\n/**\n * Whether `name` is a known built-in theme. `getPptxTheme` never misses (it\n * falls back to the default theme), so callers that need to distinguish \"a\n * real built-in\" from \"an unknown name\" must check here first.\n */\nexport function hasPptxTheme(name: string): boolean {\n return Object.prototype.hasOwnProperty.call(PPTX_THEMES, name);\n}\n\nexport const pptxThemes = PPTX_THEMES;\n","/**\n * 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 * Slide-targeted hyperlinks\n *\n * `hyperlink.slide` is 1-based over the slides *as authored* in the JSON —\n * slides carrying `enabled: false` still count. Structure processing remaps\n * every ref to the position its target ends up at in the generated deck, so\n * toggling one slide off never silently retargets the links after it.\n *\n * A ref that cannot be resolved — target dropped, or index outside the\n * authored range — is marked unresolved here and dropped by the writer with a\n * warning. It must never reach pptxgenjs: it would emit a relationship to a\n * `slideN.xml` part that is not in the archive, which PowerPoint reports as a\n * damaged file.\n */\n\nimport type { PipelineWarning, PptxComponentInput } from '../types';\n\nexport const HYPERLINK_SLIDE_UNRESOLVED = 'HYPERLINK_SLIDE_UNRESOLVED';\n\nexport interface HyperlinkProps {\n url?: string;\n slide?: number;\n tooltip?: string;\n /** Internal: authored `slide` ref that resolves to no rendered slide. */\n unresolvedSlideRef?: number;\n}\n\n/** Authored 1-based slide number -> rendered 1-based slide number. */\nexport type SlideIndexMap = ReadonlyMap<number, number>;\n\nfunction remapHyperlink(\n hyperlink: HyperlinkProps,\n map: SlideIndexMap\n): HyperlinkProps {\n // `url` wins over `slide` at write time, so leave those refs alone.\n if (hyperlink.url || hyperlink.slide == null) return hyperlink;\n\n const rendered = map.get(hyperlink.slide);\n if (rendered === undefined) {\n const { slide, ...rest } = hyperlink;\n return { ...rest, unresolvedSlideRef: slide };\n }\n return rendered === hyperlink.slide\n ? hyperlink\n : { ...hyperlink, slide: rendered };\n}\n\n/**\n * Rewrite `hyperlink.slide` in a bare props bag. Template placeholder\n * `defaults` are merged into a component at render time without ever being a\n * component themselves, so they need rebasing on their own — otherwise a\n * `defaults.props.hyperlink.slide` reaches the writer as a raw authored index.\n */\nexport function remapHyperlinkProps<T extends Record<string, unknown>>(\n props: T,\n map: SlideIndexMap\n): T {\n const hyperlink = props.hyperlink as HyperlinkProps | undefined;\n if (!hyperlink || typeof hyperlink !== 'object') return props;\n\n const remapped = remapHyperlink(hyperlink, map);\n return remapped === hyperlink ? props : { ...props, hyperlink: remapped };\n}\n\n/** Rewrite every `hyperlink.slide` in a component subtree. Returns a new tree. */\nexport function remapHyperlinkSlideRefs(\n component: PptxComponentInput,\n map: SlideIndexMap\n): PptxComponentInput {\n const hyperlink = component.props?.hyperlink as HyperlinkProps | undefined;\n let next = component;\n\n if (hyperlink && typeof hyperlink === 'object') {\n const remapped = remapHyperlink(hyperlink, map);\n if (remapped !== hyperlink) {\n next = { ...next, props: { ...next.props, hyperlink: remapped } };\n }\n }\n\n if (next.children && next.children.length > 0) {\n next = {\n ...next,\n children: next.children.map((child) =>\n remapHyperlinkSlideRefs(child, map)\n ),\n };\n }\n\n return next;\n}\n\n/**\n * Write the pptxgenjs `hyperlink` option, dropping unresolvable slide refs.\n * Shared by every component that accepts a hyperlink.\n */\nexport function applyHyperlink(\n opts: Record<string, unknown>,\n hyperlink: HyperlinkProps | undefined,\n componentName: string,\n warnings?: PipelineWarning[]\n): void {\n if (!hyperlink) return;\n\n if (hyperlink.url) {\n opts.hyperlink = { url: hyperlink.url, tooltip: hyperlink.tooltip };\n return;\n }\n\n if (hyperlink.unresolvedSlideRef != null) {\n const message =\n `hyperlink.slide ${hyperlink.unresolvedSlideRef} matches no slide in the generated ` +\n `presentation (slide disabled, or index out of range) — hyperlink dropped`;\n if (warnings) {\n warnings.push({\n code: HYPERLINK_SLIDE_UNRESOLVED,\n message,\n component: componentName,\n });\n } else {\n console.warn(message);\n }\n return;\n }\n\n if (hyperlink.slide) {\n opts.hyperlink = { slide: hyperlink.slide, tooltip: hyperlink.tooltip };\n }\n}\n","/**\n * Structure Processing\n * JSON -> internal model\n */\n\nimport type {\n PptxComponentInput,\n PptxThemeConfig,\n PresentationComponentDefinition,\n ProcessedPresentation,\n ProcessedSlide,\n TemplateSlideDefinition,\n} from '../types';\nimport { isSlideComponent } from '../types';\nimport {\n resolveGridPosition,\n resolveComponentGridPosition,\n mergeGridConfigs,\n} from './grid';\nimport { getPptxTheme } from '../themes';\nimport type { GenerationOptions } from './generator';\nimport { resolveComponentTree } from '../utils/resolveComponentTree';\nimport {\n remapHyperlinkProps,\n remapHyperlinkSlideRefs,\n} from '../utils/hyperlink';\nimport { mergeWithDefaults } from '@json-to-office/shared';\n\n/** A slide child is rendered unless it carries `enabled: false`. */\nfunction isSlideEnabled(child: object): boolean {\n return !(\n 'enabled' in child && (child as { enabled?: boolean }).enabled === false\n );\n}\n\n/**\n * Map authored 1-based slide numbers (disabled slides included) to their\n * position in the generated deck. Dropped slides are absent from the map, so\n * hyperlinks pointing at them resolve to nothing instead of to whichever slide\n * happened to shift into that number.\n */\nfunction buildSlideIndexMap(\n children: PptxComponentInput[]\n): Map<number, number> {\n const map = new Map<number, number>();\n let authored = 0;\n let rendered = 0;\n for (const child of children) {\n if (!isSlideComponent(child)) continue;\n authored++;\n if (isSlideEnabled(child)) map.set(authored, ++rendered);\n }\n return map;\n}\n\nexport function processPresentation(\n document: PresentationComponentDefinition,\n options?: GenerationOptions\n): ProcessedPresentation {\n const { props, children = [] } = document;\n\n // The generation prologue hands the resolved theme over directly — after\n // the export-mode pre-pass, so a name lookup here would resurrect\n // pre-substitute font families. The `props.theme` resolution below (a name,\n // or an inline theme config object embedded in the document itself —\n // self-contained documents-as-data) is the fallback for direct callers.\n const baseTheme =\n options?.theme ??\n (typeof props.theme === 'object' && props.theme !== null\n ? (props.theme as PptxThemeConfig)\n : options?.customThemes?.[props.theme ?? 'default'] ??\n getPptxTheme(props.theme ?? 'default'));\n\n // Merge presentation-level componentDefaults on top of theme-level ones\n const presDefaults = props.componentDefaults;\n const theme = presDefaults\n ? {\n ...baseTheme,\n componentDefaults: mergeWithDefaults(\n presDefaults,\n baseTheme.componentDefaults || {}\n ),\n }\n : baseTheme;\n\n const slideWidth = props.slideWidth ?? 10;\n const slideHeight = props.slideHeight ?? 7.5;\n\n const slideIndexMap = buildSlideIndexMap(children);\n\n // Process template slide definitions\n let templates: TemplateSlideDefinition[] | undefined;\n if (props.templates && props.templates.length > 0) {\n templates = props.templates.map((m: TemplateSlideDefinition) => {\n const effectiveGrid = mergeGridConfigs(props.grid, m.grid);\n\n // Rebase slide refs in placeholder `defaults`, then resolve grid\n // positions. `defaults.props` is merged into the rendered component by\n // core/render.ts, so it reaches the writer just like a component's own\n // props and needs the same remapping.\n const resolvedPhs = m.placeholders?.map((ph) => {\n const phDefaults = ph.defaults;\n const defaultProps = phDefaults?.props\n ? remapHyperlinkProps(phDefaults.props, slideIndexMap)\n : undefined;\n const base =\n phDefaults && defaultProps && defaultProps !== phDefaults.props\n ? { ...ph, defaults: { ...phDefaults, props: defaultProps } }\n : ph;\n\n if (!base.grid) return base;\n const abs = resolveGridPosition(\n base.grid,\n effectiveGrid,\n slideWidth,\n slideHeight\n );\n return {\n ...base,\n x: base.x ?? abs.x,\n y: base.y ?? abs.y,\n w: base.w ?? abs.w,\n h: base.h ?? abs.h,\n grid: undefined,\n };\n });\n\n // Resolve componentDefaults then grid positions on fixed objects\n const defaultedObjects = m.objects\n ? resolveComponentTree(m.objects, theme)\n : undefined;\n const resolvedObjects = defaultedObjects?.map((obj) =>\n remapHyperlinkSlideRefs(\n resolveComponentGridPosition(\n obj,\n effectiveGrid,\n slideWidth,\n slideHeight\n ),\n slideIndexMap\n )\n );\n\n return { ...m, placeholders: resolvedPhs, objects: resolvedObjects };\n });\n }\n\n const slides: ProcessedSlide[] = [];\n\n for (const child of children) {\n if (isSlideComponent(child)) {\n // `enabled: false` drops the slide entirely; absent means enabled\n if (!isSlideEnabled(child)) continue;\n\n const slideComponents: PptxComponentInput[] = [];\n if (child.children) {\n for (const slideChild of child.children) {\n slideComponents.push(slideChild);\n }\n }\n\n // Resolve componentDefaults on all slide components, then rebase\n // slide-targeted hyperlinks onto the generated slide numbering\n const resolvedComponents = resolveComponentTree(\n slideComponents,\n theme\n ).map((component) => remapHyperlinkSlideRefs(component, slideIndexMap));\n\n const placeholders = child.props.placeholders as\n | Record<string, PptxComponentInput>\n | undefined;\n\n slides.push({\n components: resolvedComponents,\n background: child.props.background,\n notes: child.props.notes,\n layout: child.props.layout,\n hidden: child.props.hidden,\n template: child.props.template,\n placeholders: placeholders\n ? Object.fromEntries(\n Object.entries(placeholders).map(([name, component]) => [\n name,\n remapHyperlinkSlideRefs(component, slideIndexMap),\n ])\n )\n : undefined,\n });\n }\n }\n\n return {\n metadata: {\n title: props.title,\n author: props.author,\n subject: props.subject,\n company: props.company,\n },\n theme,\n grid: props.grid,\n slideWidth,\n slideHeight,\n rtlMode: props.rtlMode ?? false,\n language: props.language,\n pageNumberFormat: props.pageNumberFormat ?? '9',\n slides,\n templates,\n services: options?.services,\n };\n}\n","/**\n * Render Pipeline\n * Internal model -> pptxgenjs calls\n */\n\nimport PptxGenJS from 'pptxgenjs';\nimport type {\n ProcessedPresentation,\n PipelineWarning,\n PendingXmlFill,\n SlideContext,\n SlideRenderContext,\n} from '../types';\nimport { renderComponent, renderShapeComponent } from '../components';\nimport { resolveComponentGridPosition, mergeGridConfigs } from './grid';\nimport { resolveColor } from '../utils/color';\nimport { warn, W } from '../utils/warn';\nimport { buildSlideTemplateProps } from './template';\nimport { safeLocalPath } from '../utils/imageSource';\nimport { getDefaultsForType } from '../utils/componentDefaults';\nimport { resolveComponentDefaults } from '../utils/resolveComponentTree';\nimport { mergeWithDefaults } from '@json-to-office/shared';\n\nexport async function renderPresentation(\n processed: ProcessedPresentation,\n warnings?: PipelineWarning[],\n pendingFills?: PendingXmlFill[]\n): Promise<PptxGenJS> {\n const pptx = new PptxGenJS();\n\n // Set presentation metadata\n if (processed.metadata.title) pptx.title = processed.metadata.title;\n if (processed.metadata.author) pptx.author = processed.metadata.author;\n if (processed.metadata.subject) pptx.subject = processed.metadata.subject;\n if (processed.metadata.company) pptx.company = processed.metadata.company;\n\n // Set layout dimensions\n pptx.defineLayout({\n name: 'CUSTOM',\n width: processed.slideWidth,\n height: processed.slideHeight,\n });\n pptx.layout = 'CUSTOM';\n\n // Set RTL mode\n if (processed.rtlMode) {\n pptx.rtlMode = true;\n }\n\n // Set theme fonts\n pptx.theme = {\n headFontFace: processed.theme.fonts.heading,\n bodyFontFace: processed.theme.fonts.body,\n };\n\n // Register template slides\n const templateMap = new Map(\n processed.templates?.map((m) => [m.name, m]) ?? []\n );\n if (processed.templates) {\n for (const templateDef of processed.templates) {\n const templateProps = buildSlideTemplateProps(\n templateDef,\n processed.theme,\n warnings\n );\n pptx.defineSlideMaster(templateProps as any);\n }\n }\n\n // Render each slide\n const totalSlides = processed.slides.length;\n for (let slideIdx = 0; slideIdx < totalSlides; slideIdx++) {\n const slideData = processed.slides[slideIdx];\n const slideCtx: SlideContext = {\n slideNumber: slideIdx + 1,\n totalSlides,\n pageNumberFormat: processed.pageNumberFormat,\n language: processed.language,\n };\n const renderCtx: SlideRenderContext = {\n slideCtx,\n services: processed.services,\n slideWidth: processed.slideWidth,\n slideHeight: processed.slideHeight,\n pendingFills,\n };\n const slide = slideData.template\n ? pptx.addSlide({ masterName: slideData.template })\n : pptx.addSlide();\n\n // Determine effective grid for this slide (template grid merged with presentation grid)\n const templateDef = slideData.template\n ? templateMap.get(slideData.template)\n : undefined;\n if (slideData.template && !templateDef) {\n warn(\n warnings,\n W.MISSING_TEMPLATE,\n `Unknown template \"${slideData.template}\". Available: ${[...templateMap.keys()].join(', ')}`,\n { slide: slideIdx }\n );\n }\n\n // Apply slide background. Gradients can't be expressed through pptxgenjs's\n // bkgd, so a background gradient renders as a full-bleed rect placed at\n // the very back (added first) with the shape gradient-fill mechanism. The\n // slide's own background wins over the template's.\n const backgroundGradient =\n slideData.background?.gradient ??\n (slideData.background ? undefined : templateDef?.background?.gradient);\n if (backgroundGradient) {\n renderShapeComponent(\n slide,\n {\n type: 'rect',\n x: 0,\n y: 0,\n w: processed.slideWidth,\n h: processed.slideHeight,\n fill: { gradient: backgroundGradient },\n },\n processed.theme,\n pptx,\n warnings,\n renderCtx\n );\n } else if (slideData.background) {\n if (slideData.background.color) {\n slide.background = {\n color: resolveColor(\n slideData.background.color,\n processed.theme,\n warnings\n ),\n };\n } else if (slideData.background.image) {\n if (slideData.background.image.path) {\n const bgPath = safeLocalPath(slideData.background.image.path);\n if (bgPath !== undefined) slide.background = { path: bgPath };\n } else if (slideData.background.image.base64) {\n slide.background = { data: slideData.background.image.base64 };\n }\n }\n }\n\n // Apply hidden flag\n if (slideData.hidden) {\n slide.hidden = true;\n }\n const effectiveGrid = mergeGridConfigs(processed.grid, templateDef?.grid);\n\n // Render template fixed objects (grid already resolved in structure.ts)\n if (templateDef?.objects) {\n for (const obj of templateDef.objects) {\n await renderComponent(\n slide,\n obj,\n processed.theme,\n pptx,\n warnings,\n renderCtx\n );\n }\n }\n\n // Render slide components (resolve grid positions first)\n for (const component of slideData.components) {\n const resolved = resolveComponentGridPosition(\n component,\n effectiveGrid,\n processed.slideWidth,\n processed.slideHeight,\n warnings\n );\n await renderComponent(\n slide,\n resolved,\n processed.theme,\n pptx,\n warnings,\n renderCtx\n );\n }\n\n // Render placeholder content\n if (slideData.placeholders) {\n if (templateDef) {\n const phMap = new Map(\n templateDef.placeholders?.map((p) => [p.name, p]) ?? []\n );\n\n for (const [phName, component] of Object.entries(\n slideData.placeholders\n )) {\n const phDef = phMap.get(phName);\n if (!phDef) {\n warn(\n warnings,\n W.UNKNOWN_PLACEHOLDER,\n `Unknown placeholder \"${phName}\" in template \"${slideData.template}\". Available: ${[...phMap.keys()].join(', ')}`,\n { slide: slideIdx }\n );\n continue;\n }\n\n const gridResolved = resolveComponentGridPosition(\n component,\n effectiveGrid,\n processed.slideWidth,\n processed.slideHeight,\n warnings\n );\n\n // Precedence: componentDefaults < phDef position < phDef defaults < component props\n const typeDefaults = getDefaultsForType(\n component.name,\n processed.theme\n );\n const posDefaults: Record<string, any> = {};\n if (phDef.x != null) posDefaults.x = phDef.x;\n if (phDef.y != null) posDefaults.y = phDef.y;\n if (phDef.w != null) posDefaults.w = phDef.w;\n if (phDef.h != null) posDefaults.h = phDef.h;\n\n let props = mergeWithDefaults(posDefaults, typeDefaults);\n props = mergeWithDefaults(phDef.defaults?.props ?? {}, props);\n props = mergeWithDefaults(gridResolved.props, props);\n await renderComponent(\n slide,\n { ...gridResolved, props },\n processed.theme,\n pptx,\n warnings,\n renderCtx\n );\n }\n } else {\n // No template found — render placeholders at their own positions if available\n for (const [phName, component] of Object.entries(\n slideData.placeholders\n )) {\n const defaulted = resolveComponentDefaults(\n component,\n processed.theme\n );\n const hasPosition =\n defaulted.props.x != null ||\n defaulted.props.y != null ||\n defaulted.props.grid;\n if (hasPosition) {\n const resolved = resolveComponentGridPosition(\n defaulted,\n effectiveGrid,\n processed.slideWidth,\n processed.slideHeight,\n warnings\n );\n await renderComponent(\n slide,\n resolved,\n processed.theme,\n pptx,\n warnings,\n renderCtx\n );\n } else {\n warn(\n warnings,\n W.PLACEHOLDER_NO_POSITION,\n `Placeholder \"${phName}\" has no template and no explicit position — skipped`,\n { slide: slideIdx }\n );\n }\n }\n }\n }\n\n // Add speaker notes\n if (slideData.notes) {\n slide.addNotes(slideData.notes);\n }\n }\n\n return pptx;\n}\n","/**\n * Color utilities for PPTX generation.\n * pptxgenjs expects bare 6-char hex (e.g. 'FF0000'), but our theme\n * convention uses '#'-prefixed values (e.g. '#FF0000').\n */\n\nimport type { PptxThemeConfig, PipelineWarning } from '../types';\nimport { SEMANTIC_COLOR_NAMES } from '@json-to-office/shared-pptx';\nimport { DEFAULT_CHART_THEME_COLORS } from '@json-to-office/shared';\nimport { warn, W } from './warn';\n\n// Build identity entries from the shared source of truth, then add aliases\nconst SEMANTIC_TO_THEME_KEY: Record<string, keyof PptxThemeConfig['colors']> = {\n ...Object.fromEntries(SEMANTIC_COLOR_NAMES.map((n) => [n, n])),\n // Aliases (PowerPoint XML compat)\n accent1: 'primary',\n accent2: 'secondary',\n accent3: 'accent',\n tx1: 'text',\n tx2: 'text2',\n bg1: 'background',\n bg2: 'background2',\n};\n\n/**\n * Default series-color tokens for charts, used by the native `chart` component\n * and the `highcharts` component. Defined in @json-to-office/shared so the DOCX\n * `highcharts` component resolves the same tokens; re-exported here because\n * every PPTX call site already imports colors from this module.\n */\nexport { DEFAULT_CHART_THEME_COLORS };\n\n/**\n * Follow a stored theme color value to bare hex, or undefined when it never\n * reaches one. The theme schema lets a slot name another slot\n * (`\"accent4\": \"primary\"`), so a stored value is only a color once the\n * reference chain has been walked — without this, `accent4` resolved to the\n * literal string `primary` and pptxgenjs silently painted the series black.\n *\n * Mirrors DOCX `toChartColor`/`resolveColor` (core-docx colorUtils) on casing:\n * the stored value passes through verbatim when it is already hex, and anything\n * reached by following a reference is normalized to uppercase. Two deliberate\n * divergences: `seen` turns a reference cycle into \"unresolvable\" instead of the\n * stack overflow the DOCX version would hit, and 3-char shorthand is expanded\n * here but not by DOCX, so `\"accent4\": \"#abc\"` fills the slot in a deck and\n * drops it in a document.\n */\nfunction chainToHex(\n value: string,\n theme: PptxThemeConfig,\n seen: Set<string>\n): string | undefined {\n const bare = value.startsWith('#') ? value.slice(1) : value;\n if (/^[0-9A-Fa-f]{6}$/.test(bare)) return bare;\n // Expand 3-char hex shorthand (e.g. 'FFF' → 'FFFFFF')\n if (/^[0-9A-Fa-f]{3}$/.test(bare)) {\n return bare[0] + bare[0] + bare[1] + bare[1] + bare[2] + bare[2];\n }\n const themeKey = SEMANTIC_TO_THEME_KEY[value];\n if (!themeKey || seen.has(themeKey)) return undefined;\n seen.add(themeKey);\n const next = theme?.colors?.[themeKey];\n if (typeof next !== 'string' || next.length === 0) return undefined;\n return chainToHex(next, theme, seen)?.toUpperCase();\n}\n\n/**\n * The default chart palette narrowed to the tokens this theme actually defines\n * *and* can resolve to a color. Both PPTX chart paths build their implicit\n * palette from this, so an unset accent4-6 is skipped — matching DOCX — instead\n * of resolving to `primary` six times over, and a slot holding an unresolvable\n * value is dropped rather than posted as `#primary`. Author-supplied colors must\n * NOT go through here: naming an undefined token stays a loud `resolveColor`\n * fallback + warning.\n */\nexport function definedChartColorTokens(theme: PptxThemeConfig): string[] {\n const colors = theme?.colors as\n | Record<string, string | undefined>\n | undefined;\n if (!colors) return [];\n return DEFAULT_CHART_THEME_COLORS.filter((token) => {\n const themeKey = SEMANTIC_TO_THEME_KEY[token] ?? token;\n const value = colors[themeKey];\n if (typeof value !== 'string' || value.length === 0) return false;\n return chainToHex(value, theme, new Set([themeKey])) !== undefined;\n });\n}\n\n/**\n * Resolve a color value to bare hex (no '#' prefix).\n * Accepts hex colors (with or without '#') or semantic theme color names.\n */\nexport function resolveColor(\n color: string,\n theme: PptxThemeConfig,\n warnings?: PipelineWarning[]\n): string {\n const themeKey = SEMANTIC_TO_THEME_KEY[color];\n if (themeKey) {\n const resolved = theme.colors[themeKey];\n if (resolved) {\n const hex = chainToHex(resolved, theme, new Set([themeKey]));\n if (hex) return hex;\n // Defined but not a color (e.g. a name reference that goes nowhere).\n // Never hand the literal on to pptxgenjs — it renders black in silence.\n warn(\n warnings,\n W.UNKNOWN_COLOR,\n `Theme color \"${themeKey}\" is \"${resolved}\", which is not a hex color or a theme color name; falling back to primary`\n );\n return resolvePrimary(theme);\n }\n // Fall back to primary for unset optional colors\n warn(\n warnings,\n W.THEME_COLOR_FALLBACK,\n `Theme color \"${themeKey}\" not defined, falling back to primary`\n );\n return resolvePrimary(theme);\n }\n // Not a semantic name — treat as literal hex\n const bare = color.startsWith('#') ? color.slice(1) : color;\n // Expand 3-char hex shorthand (e.g. 'FFF' → 'FFFFFF')\n if (/^[0-9A-Fa-f]{3}$/.test(bare)) {\n return bare[0] + bare[0] + bare[1] + bare[1] + bare[2] + bare[2];\n }\n if (!/^[0-9A-Fa-f]{6}$/.test(bare)) {\n warn(\n warnings,\n W.UNKNOWN_COLOR,\n `Unknown color value: \"${color}\", treating as literal`\n );\n }\n return bare;\n}\n\n/** The `primary` fallback, itself chain-resolved so it can't leak a token name. */\nfunction resolvePrimary(theme: PptxThemeConfig): string {\n const primary = theme.colors.primary;\n return (\n chainToHex(primary, theme, new Set(['primary'])) ??\n (primary.startsWith('#') ? primary.slice(1) : primary)\n );\n}\n","/**\n * Resolve (family, weight, italic) into the PPTX run's final `(fontFace,\n * bold, italic)` triple. Non-RIBBI weights are rewritten to synthetic\n * sub-family names (e.g. \"Inter Light\") so PowerPoint / LibreOffice can\n * resolve the matching installed face; RIBBI stays on the canonical\n * family and uses native bold/italic toggles.\n *\n * Mirrors the DOCX `applyFontWeightAlias` helper so both cores coerce\n * fontWeight identically.\n */\n\nimport { synthesizeFamilyName } from '@json-to-office/shared';\n\nexport function applyFontWeight(params: {\n family?: string;\n fontWeight?: number;\n italic?: boolean;\n bold?: boolean;\n}): { fontFace?: string; bold?: boolean; italic?: boolean } {\n if (!params.family) {\n const weight =\n params.fontWeight ?? (params.bold === true ? 700 : undefined);\n return {\n bold: weight != null ? weight >= 600 : params.bold,\n italic: params.italic,\n };\n }\n const weight = params.fontWeight ?? (params.bold === true ? 700 : undefined);\n const synth = synthesizeFamilyName(\n params.family,\n weight,\n params.italic === true\n );\n return { fontFace: synth.family, bold: synth.bold, italic: synth.italic };\n}\n","/**\n * Text Component Renderer\n */\n\nimport type PptxGenJS from 'pptxgenjs';\nimport type {\n PptxThemeConfig,\n StyleName,\n PipelineWarning,\n SlideContext,\n} from '../types';\nimport { resolveColor } from '../utils/color';\nimport { applyFontWeight } from '../utils/fontAliasContext';\nimport { applyHyperlink, type HyperlinkProps } from '../utils/hyperlink';\nimport { warn, W } from '../utils/warn';\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\ninterface TextComponentProps {\n text?: string;\n runs?: TextRunProps[];\n x?: number | string;\n y?: number | string;\n w?: number | string;\n h?: number | string;\n fontSize?: number;\n fontFace?: string;\n color?: string;\n bold?: boolean;\n fontWeight?: number;\n italic?: boolean;\n underline?: boolean | { style?: string; color?: string };\n strike?: boolean;\n language?: string;\n align?: string;\n valign?: string;\n breakLine?: boolean;\n bullet?: boolean | { type?: string; style?: string; startAt?: number };\n margin?: number | number[];\n rotate?: number;\n shadow?: {\n type?: string;\n color?: string;\n blur?: number;\n offset?: number;\n angle?: number;\n opacity?: number;\n };\n fill?: { color: string; transparency?: number };\n hyperlink?: HyperlinkProps;\n lineSpacing?: number;\n lineSpacingMultiple?: number;\n charSpacing?: number;\n paraSpaceBefore?: number;\n paraSpaceAfter?: number;\n style?: StyleName;\n}\n\nfunction resolvePagePlaceholders(text: string, ctx: SlideContext): string {\n const { slideNumber, totalSlides, pageNumberFormat } = ctx;\n const fmt = (n: number) =>\n pageNumberFormat === '09'\n ? String(n).padStart(String(totalSlides).length, '0')\n : String(n);\n return text\n .replace(/\\{PAGE_NUMBER\\}/g, fmt(slideNumber))\n .replace(/\\{PAGE_COUNT\\}/g, fmt(totalSlides));\n}\n\nexport function renderTextComponent(\n slide: PptxGenJS.Slide,\n props: TextComponentProps,\n theme: PptxThemeConfig,\n warnings?: PipelineWarning[],\n slideCtx?: SlideContext\n): void {\n // Exactly one of `text`/`runs` carries the content. Validation enforces the\n // rule up front; this guard covers validation-disabled runs.\n const runs = props.runs && props.runs.length > 0 ? props.runs : undefined;\n if (props.text === undefined && !runs) {\n warn(\n warnings,\n W.TEXT_NO_CONTENT,\n 'Text component has neither \"text\" nor \"runs\" — skipped',\n { component: 'text' }\n );\n return;\n }\n\n // Resolve named style as defaults\n const style = props.style ? theme.styles?.[props.style] : undefined;\n const isHeadingStyle = props.style && /^(title|heading)/.test(props.style);\n\n const opts: Record<string, unknown> = {};\n\n // Position\n if (props.x !== undefined) opts.x = props.x;\n if (props.y !== undefined) opts.y = props.y;\n if (props.w !== undefined) opts.w = props.w;\n if (props.h !== undefined) opts.h = props.h;\n\n // When height is not explicitly set, provide a reasonable default based on\n // font size so that LibreOffice (which renders cy=\"0\" as blank) can display\n // the text. Also mark as textBox for proper auto-sizing in PowerPoint.\n if (props.h === undefined) {\n const fontSize = props.fontSize ?? theme.defaults.fontSize ?? 18;\n const lines = runs\n ? runs.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!.match(/\\n/g)?.length ?? 0) + 1;\n opts.h = Math.max(0.5, (fontSize / 72) * 1.6 * lines);\n opts.isTextBox = true;\n }\n\n // Font — cascade: component props → style → theme defaults\n opts.fontSize = props.fontSize ?? style?.fontSize ?? theme.defaults.fontSize;\n opts.fontFace =\n props.fontFace ??\n style?.fontFace ??\n (isHeadingStyle ? theme.fonts.heading : theme.fonts.body);\n opts.color = resolveColor(\n props.color ?? style?.fontColor ?? theme.defaults.fontColor,\n theme,\n warnings\n );\n\n // Formatting — preserve the pre-alias family so runs that set their own\n // weight resolve their alias from the base family, not an\n // already-synthesized name (e.g. \"Inter Light\").\n const preAliasFamily = opts.fontFace as string | undefined;\n const bold = props.bold ?? style?.bold;\n const italic = props.italic ?? style?.italic;\n const fontWeight = props.fontWeight ?? style?.fontWeight;\n if (bold != null) opts.bold = bold;\n if (italic != null) opts.italic = italic;\n if (fontWeight != null || bold === true) {\n const w = applyFontWeight({\n family: opts.fontFace as string | undefined,\n fontWeight,\n italic,\n bold,\n });\n if (w.fontFace !== undefined) opts.fontFace = w.fontFace;\n if (w.bold !== undefined) opts.bold = w.bold;\n if (w.italic !== undefined) opts.italic = w.italic;\n }\n if (props.strike) opts.strike = true;\n\n // Proofing language: component override → presentation default. When neither\n // is set, pptxgenjs falls back to its own 'en-US' default.\n const lang = props.language ?? slideCtx?.language;\n if (lang) opts.lang = lang;\n\n if (props.underline !== undefined) {\n if (typeof props.underline === 'boolean') {\n opts.underline = { style: 'sng' };\n } else {\n opts.underline = props.underline;\n }\n }\n\n // Alignment\n const align = props.align ?? style?.align;\n if (align) opts.align = align;\n opts.valign = props.valign ?? 'top';\n\n // Bullet\n if (props.bullet !== undefined) opts.bullet = props.bullet;\n\n // Margin — default to 0 so text aligns exactly to grid positions\n opts.margin = props.margin ?? 0;\n\n // Rotation\n if (props.rotate !== undefined) opts.rotate = props.rotate;\n\n // Shadow\n if (props.shadow) {\n opts.shadow = {\n type: props.shadow.type ?? 'outer',\n color: resolveColor(props.shadow.color ?? '000000', theme, warnings),\n blur: props.shadow.blur ?? 3,\n offset: props.shadow.offset ?? 3,\n angle: props.shadow.angle ?? 45,\n opacity: props.shadow.opacity ?? 0.5,\n };\n }\n\n // Fill\n if (props.fill) {\n opts.fill = { color: resolveColor(props.fill.color, theme, warnings) };\n if (props.fill.transparency !== undefined) {\n (opts.fill as Record<string, unknown>).transparency =\n props.fill.transparency;\n }\n }\n\n // Hyperlink\n applyHyperlink(opts, props.hyperlink, 'text', warnings);\n\n // Line spacing\n const lineSpacing = props.lineSpacing ?? style?.lineSpacing;\n if (props.lineSpacingMultiple !== undefined) {\n opts.lineSpacingMultiple = props.lineSpacingMultiple;\n } else if (lineSpacing !== undefined) {\n opts.lineSpacing = lineSpacing;\n }\n const charSpacing = props.charSpacing ?? style?.charSpacing;\n if (charSpacing !== undefined) opts.charSpacing = charSpacing;\n if (props.paraSpaceBefore !== undefined)\n opts.paraSpaceBefore = props.paraSpaceBefore;\n const paraSpaceAfter = props.paraSpaceAfter ?? style?.paraSpaceAfter;\n if (paraSpaceAfter !== undefined) opts.paraSpaceAfter = paraSpaceAfter;\n\n // Break line handling\n if (props.breakLine) opts.breakLine = true;\n\n if (runs) {\n // Rich text runs — pptxgenjs natively accepts [{ text, options }] and\n // merges each run's options over the block-level opts, so run options\n // override component-level defaults per run.\n const runSegments = runs.map((run) => {\n const runOpts: Record<string, unknown> = {};\n if (run.fontSize != null) runOpts.fontSize = run.fontSize;\n if (run.fontFace != null) runOpts.fontFace = run.fontFace;\n if (run.color != null)\n runOpts.color = resolveColor(run.color, theme, warnings);\n if (run.strike != null) runOpts.strike = run.strike;\n if (run.underline !== undefined) {\n if (typeof run.underline === 'boolean') {\n if (run.underline) runOpts.underline = { style: 'sng' };\n } else {\n runOpts.underline = run.underline;\n }\n }\n if (run.superscript != null) runOpts.superscript = run.superscript;\n if (run.subscript != null) runOpts.subscript = run.subscript;\n if (run.charSpacing != null) runOpts.charSpacing = run.charSpacing;\n if (run.breakLine != null) runOpts.breakLine = run.breakLine;\n\n const effWeight = run.fontWeight ?? fontWeight;\n const effBold = run.bold ?? bold;\n const effItalic = run.italic ?? italic;\n if (effBold != null) runOpts.bold = effBold;\n if (effItalic != null) runOpts.italic = effItalic;\n if (effWeight != null || effBold === true) {\n // Only alias when the run inherits the component's family; if the run\n // explicitly sets its own fontFace, the author has already picked the\n // face they want and re-aliasing would double up the suffix.\n if (run.fontFace == null) {\n const w = applyFontWeight({\n family: preAliasFamily,\n fontWeight: effWeight,\n italic: effItalic,\n bold: effBold,\n });\n if (w.fontFace !== undefined) runOpts.fontFace = w.fontFace;\n if (w.bold !== undefined) runOpts.bold = w.bold;\n if (w.italic !== undefined) runOpts.italic = w.italic;\n }\n }\n\n const runText = slideCtx\n ? resolvePagePlaceholders(run.text, slideCtx)\n : run.text;\n return { text: runText, options: runOpts };\n });\n slide.addText(runSegments as any, opts as any);\n return;\n }\n\n const text = slideCtx\n ? resolvePagePlaceholders(props.text!, slideCtx)\n : props.text!;\n slide.addText(text, opts as any);\n}\n","/**\n * Image Component Renderer\n */\n\nimport path from 'path';\nimport probe from 'probe-image-size';\nimport type PptxGenJS from 'pptxgenjs';\nimport type { PptxThemeConfig, PipelineWarning } from '../types';\nimport { resolveColor } from '../utils/color';\nimport {\n resolveImageSource,\n isAllowedLocalPath,\n safeLocalPath,\n} from '../utils/imageSource';\nimport { resolveFromBaseDir } from '../utils/baseDirContext';\nimport { warn, W } from '../utils/warn';\nimport { applyHyperlink, type HyperlinkProps } from '../utils/hyperlink';\n\n/** Block requests to private/loopback/link-local hosts. */\nfunction isPrivateUrl(urlStr: string): boolean {\n try {\n const { hostname } = new URL(urlStr);\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 if (hostname.startsWith('172.')) {\n const second = 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\ninterface ImageComponentProps {\n path?: string;\n base64?: string;\n svg?: string;\n x?: number | string;\n y?: number | string;\n w?: number | string;\n h?: number | string;\n sizing?: { type: string; w?: number | string; h?: number | string };\n rotate?: number;\n rounding?: boolean;\n shadow?: {\n type?: string;\n color?: string;\n blur?: number;\n offset?: number;\n angle?: number;\n opacity?: number;\n };\n hyperlink?: HyperlinkProps;\n alt?: string;\n}\n\n/**\n * Probe the intrinsic dimensions of an image (URL, file path, or base64).\n * Returns width/height in pixels, or undefined on failure.\n */\nasync function probeImageSize(\n imagePath: string,\n warnings?: PipelineWarning[]\n): Promise<{ width: number; height: number } | undefined> {\n try {\n if (/^data:image\\//.test(imagePath)) {\n const base64Data = imagePath.split(',')[1];\n if (!base64Data) return undefined;\n const buf = Buffer.from(base64Data, 'base64');\n const result = probe.sync(buf);\n return result\n ? { width: result.width, height: result.height }\n : undefined;\n }\n\n if (/^https?:\\/\\//.test(imagePath)) {\n if (isPrivateUrl(imagePath)) return undefined;\n const result = await probe(imagePath, { timeout: 5000 });\n return { width: result.width, height: result.height };\n }\n\n // Local file — restrict to the document base directory (when set) or\n // CWD to prevent path traversal (#142).\n const resolved = path.resolve(resolveFromBaseDir(imagePath));\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 (err) {\n warn(\n warnings,\n W.IMAGE_PROBE_FAILED,\n `Image probe failed: ${err instanceof Error ? err.message : String(err)}`,\n { component: 'image' }\n );\n return undefined;\n }\n}\n\n/**\n * Parse a dimension value. If it ends with '%', resolve it against the given\n * slide axis length (in inches) and return inches. Otherwise parse as a plain\n * number (already inches).\n */\nfunction resolveDimension(value: number | string, axisLength: number): number {\n if (typeof value === 'number') return value;\n if (value.endsWith('%')) {\n const pct = parseFloat(value);\n return !Number.isNaN(pct) && pct >= 0 ? (pct / 100) * axisLength : 0;\n }\n const n = Number(value);\n return Number.isNaN(n) ? 0 : n;\n}\n\nexport async function renderImageComponent(\n slide: PptxGenJS.Slide,\n props: ImageComponentProps,\n theme: PptxThemeConfig,\n warnings?: PipelineWarning[],\n slideWidth = 10,\n slideHeight = 7.5\n): Promise<void> {\n const opts: Record<string, unknown> = {};\n\n // Source — precedence svg > base64 > path (raw SVG wrapped into a data URI).\n const source = resolveImageSource(props);\n if (!source) {\n warn(\n warnings,\n W.IMAGE_NO_SOURCE,\n 'Image component missing path, base64, and svg',\n { component: 'image' }\n );\n return;\n }\n // pptxgenjs routes data URIs through `data` and file paths/URLs through\n // `path`. Local paths resolve against the document's base directory when\n // the generation scope set one (falls back to cwd, #142) — eagerly,\n // because pptxgenjs reads the file later, during write().\n if (source.startsWith('data:')) {\n opts.data = source;\n } else {\n // Enforce the allowed-root policy before handing the path to pptxgenjs —\n // it reads the file during write() regardless of whether we probed it\n // here (explicit w+h skips the probe), so the probe-time check alone is\n // not enough (#142).\n const resolved = safeLocalPath(source);\n if (resolved === undefined) {\n warn(\n warnings,\n W.IMAGE_PATH_OUTSIDE_ROOTS,\n `Image path resolves outside the document base directory: ${source}`,\n { component: 'image' }\n );\n return;\n }\n opts.path = resolved;\n }\n\n // Position\n if (props.x !== undefined) opts.x = props.x;\n if (props.y !== undefined) opts.y = props.y;\n if (props.w !== undefined) opts.w = props.w;\n if (props.h !== undefined) opts.h = props.h;\n\n // Probe intrinsic dimensions only when needed (auto-calc or contain/cover)\n const hasW = props.w !== undefined;\n const hasH = props.h !== undefined;\n const needsProbe =\n (hasW !== hasH && !props.sizing) ||\n props.sizing?.type === 'contain' ||\n props.sizing?.type === 'cover';\n const intrinsic = needsProbe\n ? await probeImageSize(source, warnings)\n : undefined;\n\n // Auto-calculate missing dimension from intrinsic aspect ratio\n if (hasW !== hasH && !props.sizing) {\n if (intrinsic && intrinsic.width > 0 && intrinsic.height > 0) {\n const aspect = intrinsic.width / intrinsic.height;\n if (hasW && !hasH) {\n const wInches = resolveDimension(props.w!, slideWidth);\n opts.w = wInches;\n opts.h = wInches / aspect;\n } else {\n const hInches = resolveDimension(props.h!, slideHeight);\n opts.h = hInches;\n opts.w = hInches * aspect;\n }\n }\n }\n\n // Sizing — pptxgenjs's contain implementation produces negative srcRect\n // values when the image aspect ratio differs from the box, causing\n // stretching. We handle contain ourselves: probe intrinsic dimensions,\n // calculate fitted size, and center within the box. Cover is delegated to\n // pptxgenjs with correct intrinsic dimensions.\n if (\n props.sizing &&\n (props.sizing.type === 'contain' || props.sizing.type === 'cover')\n ) {\n const boxW = resolveDimension(props.sizing.w ?? props.w ?? 0, slideWidth);\n const boxH = resolveDimension(props.sizing.h ?? props.h ?? 0, slideHeight);\n\n if (boxW <= 0 || boxH <= 0) {\n warn(\n warnings,\n W.IMAGE_ZERO_BOX,\n `Image sizing box resolved to zero (${boxW}x${boxH})`,\n { component: 'image' }\n );\n }\n\n if (\n intrinsic &&\n intrinsic.width > 0 &&\n intrinsic.height > 0 &&\n boxW > 0 &&\n boxH > 0\n ) {\n const imgAspect = intrinsic.width / intrinsic.height;\n\n if (props.sizing.type === 'contain') {\n // Fit image inside box, preserving aspect ratio, centered\n const boxAspect = boxW / boxH;\n let fitW: number, fitH: number;\n if (imgAspect > boxAspect) {\n // Image is wider than box — width-limited\n fitW = boxW;\n fitH = boxW / imgAspect;\n } else {\n // Image is taller than box — height-limited\n fitH = boxH;\n fitW = boxH * imgAspect;\n }\n // Center within the box\n const baseX = resolveDimension(props.x ?? 0, slideWidth);\n const baseY = resolveDimension(props.y ?? 0, slideHeight);\n opts.x = baseX + (boxW - fitW) / 2;\n opts.y = baseY + (boxH - fitH) / 2;\n opts.w = fitW;\n opts.h = fitH;\n // No sizing — element is already the correct size\n } else {\n // Cover: pptxgenjs handles this correctly with real intrinsic dims\n opts.w = intrinsic.width;\n opts.h = intrinsic.height;\n opts.sizing = { type: 'cover', w: boxW, h: boxH };\n }\n } else {\n // Fallback: pass sizing through with w/h auto-filled from outer dims\n opts.sizing = { ...props.sizing, w: boxW, h: boxH };\n }\n } else if (props.sizing) {\n opts.sizing = {\n ...props.sizing,\n w: resolveDimension(props.sizing.w ?? props.w ?? 0, slideWidth),\n h: resolveDimension(props.sizing.h ?? props.h ?? 0, slideHeight),\n };\n }\n\n // Rotation\n if (props.rotate !== undefined) opts.rotate = props.rotate;\n\n // Rounding\n if (props.rounding) opts.rounding = true;\n\n // Shadow\n if (props.shadow) {\n opts.shadow = {\n type: props.shadow.type ?? 'outer',\n color: resolveColor(props.shadow.color ?? '000000', theme, warnings),\n blur: props.shadow.blur ?? 3,\n offset: props.shadow.offset ?? 3,\n angle: props.shadow.angle ?? 45,\n opacity: props.shadow.opacity ?? 0.5,\n };\n }\n\n // Hyperlink\n applyHyperlink(opts, props.hyperlink, 'image', warnings);\n\n // Alt text\n if (props.alt) opts.altText = props.alt;\n\n slide.addImage(opts as any);\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","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 * Shape Component Renderer\n */\n\nimport type PptxGenJS from 'pptxgenjs';\nimport type {\n PptxThemeConfig,\n StyleName,\n PipelineWarning,\n PendingXmlFill,\n SlideRenderContext,\n} from '../types';\nimport type {\n TextSegment,\n GradientFill,\n PatternFill,\n} from '@json-to-office/shared-pptx';\nimport { PATTERN_FILL_PRESETS } from '@json-to-office/shared-pptx';\nimport { applyFontWeight } from '../utils/fontAliasContext';\nimport { resolveColor } from '../utils/color';\nimport { buildGradientFillXml, buildPatternFillXml } from '../utils/fillXml';\nimport { warn, W } from '../utils/warn';\n\nexport interface ShapeFillProps {\n color?: string;\n transparency?: number;\n gradient?: GradientFill;\n pattern?: PatternFill;\n}\n\ninterface ShapeComponentProps {\n type: string;\n x?: number | string;\n y?: number | string;\n w?: number | string;\n h?: number | string;\n fill?: ShapeFillProps;\n line?: { color?: string; width?: number; dashType?: string };\n text?: string | TextSegment[];\n fontSize?: number;\n fontFace?: string;\n fontColor?: string;\n charSpacing?: number;\n bold?: boolean;\n fontWeight?: number;\n italic?: boolean;\n align?: string;\n valign?: string;\n rotate?: number;\n angleRange?: [number, number];\n flipH?: boolean;\n flipV?: boolean;\n shadow?: {\n type?: string;\n color?: string;\n blur?: number;\n offset?: number;\n angle?: number;\n opacity?: number;\n };\n rectRadius?: number;\n style?: StyleName;\n}\n\nconst SHAPE_TYPE_MAP: Record<string, string> = {\n rect: 'rect',\n roundRect: 'roundRect',\n ellipse: 'ellipse',\n triangle: 'triangle',\n diamond: 'diamond',\n pentagon: 'pentagon',\n hexagon: 'hexagon',\n star5: 'star5',\n star6: 'star6',\n line: 'line',\n arrow: 'rightArrow',\n chevron: 'chevron',\n cloud: 'cloud',\n heart: 'heart',\n lightning: 'lightningBolt',\n};\n\n/**\n * Apply a shape fill to pptxgenjs opts. Gradient and pattern fills are not\n * expressible through pptxgenjs, so they render as a sentinel solid fill on a\n * shape tagged with a unique `objectName`; the real fill XML is registered in\n * `pendingFills` and spliced in by packagePresentationBuffer. Without a\n * registry (direct render outside the buffer pipeline) they degrade to the\n * sentinel solid color with a warning.\n */\nexport function applyShapeFill(\n opts: Record<string, unknown>,\n fill: ShapeFillProps,\n theme: PptxThemeConfig,\n warnings?: PipelineWarning[],\n pendingFills?: PendingXmlFill[]\n): void {\n let gradient = fill.gradient;\n let pattern = fill.pattern;\n if (gradient && pattern) {\n warn(\n 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 // An unrecognised preset degrades to the pattern's own foreground, so the\n // shape still reads as authored rather than picking up the pptxgenjs\n // default. `fill.color`, when set, stays authoritative.\n let unknownPresetForeground: string | undefined;\n if (\n pattern &&\n !(PATTERN_FILL_PRESETS as readonly string[]).includes(pattern.preset)\n ) {\n warn(\n 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 || pattern) {\n // Sentinel color: keeps the deck presentable if the splice cannot run.\n const sentinel = resolveColor(\n fill.color ?? (gradient ? gradient.stops[0].color : pattern!.foreground),\n theme,\n warnings\n );\n if (pendingFills) {\n const xml = gradient\n ? buildGradientFillXml(gradient, theme, warnings)\n : buildPatternFillXml(pattern!, theme, warnings);\n const objectName = `__jto_fill_${pendingFills.length}__`;\n pendingFills.push({ objectName, xml });\n opts.objectName = objectName;\n } else {\n warn(\n warnings,\n W.ADVANCED_FILL_FALLBACK,\n `${gradient ? 'Gradient' : 'Pattern'} fill requires the buffer generation pipeline — rendering a solid fill instead`,\n { component: 'shape' }\n );\n }\n opts.fill = { color: sentinel };\n return;\n }\n\n const solid = fill.color ?? unknownPresetForeground;\n if (solid !== undefined) {\n opts.fill = { color: resolveColor(solid, theme, warnings) };\n if (fill.transparency !== undefined) {\n (opts.fill as Record<string, unknown>).transparency = fill.transparency;\n }\n }\n}\n\nfunction buildShapeOpts(\n props: ShapeComponentProps,\n theme: PptxThemeConfig,\n warnings?: PipelineWarning[],\n pendingFills?: PendingXmlFill[]\n): Record<string, unknown> {\n const opts: Record<string, unknown> = {};\n\n if (props.x !== undefined) opts.x = props.x;\n if (props.y !== undefined) opts.y = props.y;\n if (props.w !== undefined) opts.w = props.w;\n if (props.h !== undefined) opts.h = props.h;\n\n if (props.fill) {\n applyShapeFill(opts, props.fill, theme, warnings, pendingFills);\n }\n\n if (props.line) {\n opts.line = {};\n if (props.line.color)\n (opts.line as Record<string, unknown>).color = resolveColor(\n props.line.color,\n theme,\n warnings\n );\n if (props.line.width)\n (opts.line as Record<string, unknown>).width = props.line.width;\n if (props.line.dashType)\n (opts.line as Record<string, unknown>).dashType = props.line.dashType;\n }\n\n if (props.rotate !== undefined) opts.rotate = props.rotate;\n if (props.angleRange !== undefined) opts.angleRange = props.angleRange;\n if (props.flipH !== undefined) opts.flipH = props.flipH;\n if (props.flipV !== undefined) opts.flipV = props.flipV;\n if (props.rectRadius !== undefined) opts.rectRadius = props.rectRadius;\n\n if (props.shadow) {\n opts.shadow = {\n type: props.shadow.type ?? 'outer',\n color: resolveColor(props.shadow.color ?? '000000', theme, warnings),\n blur: props.shadow.blur ?? 3,\n offset: props.shadow.offset ?? 3,\n angle: props.shadow.angle ?? 45,\n opacity: props.shadow.opacity ?? 0.5,\n };\n }\n\n return opts;\n}\n\nexport function renderShapeComponent(\n slide: PptxGenJS.Slide,\n props: ShapeComponentProps,\n theme: PptxThemeConfig,\n pptx: PptxGenJS,\n warnings?: PipelineWarning[],\n ctx?: SlideRenderContext\n): void {\n // Resolve shape type from pptxgenjs ShapeType enum\n const shapeTypeName = SHAPE_TYPE_MAP[props.type] || props.type;\n const shapeType = (pptx.ShapeType as Record<string, any>)[shapeTypeName];\n\n if (!shapeType) {\n warn(warnings, W.UNKNOWN_SHAPE, `Unknown shape type: ${props.type}`, {\n component: 'shape',\n });\n return;\n }\n\n // Resolve named style\n const style = props.style ? theme.styles?.[props.style] : undefined;\n const isHeadingStyle = props.style && /^(title|heading)/.test(props.style);\n\n const opts = buildShapeOpts(props, theme, warnings, ctx?.pendingFills);\n\n // If shape has text, use addText with shape option\n if (props.text && (!Array.isArray(props.text) || props.text.length > 0)) {\n opts.shape = shapeType;\n\n opts.fontSize =\n props.fontSize ?? style?.fontSize ?? theme.defaults.fontSize;\n opts.fontFace =\n props.fontFace ??\n style?.fontFace ??\n (isHeadingStyle ? theme.fonts.heading : theme.fonts.body);\n // Preserve pre-alias family so segments that inherit it don't feed an\n // already-synthesized name (e.g. \"Inter Light\") back into applyFontWeight\n // and double-alias to \"Inter Light Medium\".\n const preAliasFamily = opts.fontFace as string | undefined;\n opts.color = resolveColor(\n props.fontColor ?? style?.fontColor ?? theme.defaults.fontColor,\n theme,\n warnings\n );\n const bold = props.bold ?? style?.bold;\n const italic = props.italic ?? style?.italic;\n const fontWeight = props.fontWeight ?? style?.fontWeight;\n const charSpacing = props.charSpacing ?? style?.charSpacing;\n if (charSpacing !== undefined) opts.charSpacing = charSpacing;\n const align = props.align ?? style?.align;\n if (align) opts.align = align;\n opts.valign = props.valign ?? 'top';\n\n if (Array.isArray(props.text)) {\n // For segmented text, resolve the aliased family per-segment using the\n // effective (weight, italic, bold) = segment value ?? shape value. Keep\n // shape-level `opts.fontFace` at the un-aliased family so segments that\n // don't set their own fontFace don't accidentally inherit an\n // already-synthesized name (e.g. \"Inter Light\") from the shape.\n if (bold != null) opts.bold = bold;\n if (italic != null) opts.italic = italic;\n const textSegments = props.text.map((seg) => {\n const segOpts: {\n fontSize?: number;\n fontFace?: string;\n color?: string;\n bold?: boolean;\n italic?: boolean;\n breakLine?: boolean;\n charSpacing?: number;\n paraSpaceBefore?: number;\n paraSpaceAfter?: number;\n } = {};\n if (seg.fontSize != null) segOpts.fontSize = seg.fontSize;\n if (seg.fontFace != null) segOpts.fontFace = seg.fontFace;\n if (seg.color != null)\n segOpts.color = resolveColor(seg.color, theme, warnings);\n if (seg.breakLine != null) segOpts.breakLine = seg.breakLine;\n if (seg.charSpacing != null) segOpts.charSpacing = seg.charSpacing;\n if (seg.spaceBefore != null) segOpts.paraSpaceBefore = seg.spaceBefore;\n if (seg.spaceAfter != null) segOpts.paraSpaceAfter = seg.spaceAfter;\n const segWeight = (seg as TextSegment & { fontWeight?: number })\n .fontWeight;\n const effWeight = segWeight ?? fontWeight;\n const effBold = seg.bold ?? bold;\n const effItalic = seg.italic ?? italic;\n if (effBold != null) segOpts.bold = effBold;\n if (effItalic != null) segOpts.italic = effItalic;\n if (effWeight != null || effBold === true) {\n // Only alias when the segment inherits the shape's family; if the\n // segment explicitly sets its own fontFace, the author has already\n // picked the face they want (possibly an already-synthesized name\n // like \"Inter Light\") and re-aliasing would double up the suffix.\n if (seg.fontFace == null) {\n const w = applyFontWeight({\n family: preAliasFamily,\n fontWeight: effWeight,\n italic: effItalic,\n bold: effBold,\n });\n if (w.fontFace !== undefined) segOpts.fontFace = w.fontFace;\n if (w.bold !== undefined) segOpts.bold = w.bold;\n if (w.italic !== undefined) segOpts.italic = w.italic;\n }\n }\n return { text: seg.text, options: segOpts };\n });\n slide.addText(textSegments, opts as any);\n } else {\n if (bold != null) opts.bold = bold;\n if (italic != null) opts.italic = italic;\n if (fontWeight != null || bold === true) {\n const w = applyFontWeight({\n family: preAliasFamily,\n fontWeight,\n italic,\n bold,\n });\n if (w.fontFace !== undefined) opts.fontFace = w.fontFace;\n if (w.bold !== undefined) opts.bold = w.bold;\n if (w.italic !== undefined) opts.italic = w.italic;\n }\n slide.addText(props.text, opts as any);\n }\n } else {\n // Pure shape without text\n slide.addShape(shapeType, opts as any);\n }\n}\n","/**\n * OOXML fill XML builders for fills pptxgenjs cannot express.\n *\n * Gradient and pattern fills are rendered as a sentinel solid fill tagged with\n * a unique `objectName`; packagePresentationBuffer then swaps the sentinel\n * `<a:solidFill>` for the XML built here. Colors are resolved (theme tokens →\n * hex) before the XML is built, so the packaging step is a pure string splice.\n */\n\nimport type { GradientFill, PatternFill } from '@json-to-office/shared-pptx';\nimport type { PptxThemeConfig, PipelineWarning } from '../types';\nimport { resolveColor } from './color';\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 l/t/r/b values (in 1000ths of a percent) per focus corner. */\nconst RADIAL_FOCUS_RECTS: Record<\n NonNullable<GradientFill['focus']>,\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\nfunction gradientStopXml(\n color: string,\n pos: number,\n transparency: number | undefined,\n theme: PptxThemeConfig,\n warnings?: PipelineWarning[]\n): string {\n const hex = resolveColor(color, theme, warnings).toUpperCase();\n const alpha =\n transparency !== undefined\n ? `<a:alpha val=\"${Math.round((100 - transparency) * PCT_UNIT)}\"/>`\n : '';\n return `<a:gs pos=\"${Math.round(pos * PCT_UNIT)}\"><a:srgbClr val=\"${hex}\">${alpha}</a:srgbClr></a:gs>`;\n}\n\n/**\n * Build an `<a:gradFill>` element from a gradient fill definition.\n */\nexport function buildGradientFillXml(\n gradient: GradientFill,\n theme: PptxThemeConfig,\n warnings?: PipelineWarning[]\n): string {\n const stops = gradient.stops\n .map((stop) =>\n gradientStopXml(stop.color, stop.pos, stop.transparency, theme, warnings)\n )\n .join('');\n\n let shade: string;\n if (gradient.type === 'radial') {\n const rect = RADIAL_FOCUS_RECTS[gradient.focus ?? 'center'];\n shade = `<a:path path=\"circle\"><a:fillToRect l=\"${rect.l}\" t=\"${rect.t}\" r=\"${rect.r}\" b=\"${rect.b}\"/></a:path>`;\n } else {\n const angle = (((gradient.angle ?? 0) % 360) + 360) % 360;\n shade = `<a:lin ang=\"${Math.round(angle * ANGLE_UNIT)}\" scaled=\"1\"/>`;\n }\n\n return `<a:gradFill rotWithShape=\"1\"><a:gsLst>${stops}</a:gsLst>${shade}</a:gradFill>`;\n}\n\n/**\n * Build an `<a:pattFill>` element from a pattern fill definition.\n */\nexport function buildPatternFillXml(\n pattern: PatternFill,\n theme: PptxThemeConfig,\n warnings?: PipelineWarning[]\n): string {\n const fg = resolveColor(pattern.foreground, theme, warnings).toUpperCase();\n const bg = resolveColor(pattern.background, theme, warnings).toUpperCase();\n return `<a:pattFill prst=\"${pattern.preset}\"><a:fgClr><a:srgbClr val=\"${fg}\"/></a:fgClr><a:bgClr><a:srgbClr val=\"${bg}\"/></a:bgClr></a:pattFill>`;\n}\n","/**\n * Table Component Renderer\n */\n\nimport type PptxGenJS from 'pptxgenjs';\nimport type { PptxThemeConfig, PipelineWarning } from '../types';\nimport { resolveColor } from '../utils/color';\nimport { applyFontWeight } from '../utils/fontAliasContext';\n\n/**\n * Characters that PowerPoint may render as color emoji.\n * Appending VS15 (U+FE0E) forces text-mode rendering.\n */\nconst EMOJI_PRONE_CHARS = /[✓✔✗✘☐☑☒★☆●○■□▶◀▲▼⚡⚠❌❓❗]/gu;\n\nfunction applyTextVariationSelector(text: string): string {\n return text.replace(EMOJI_PRONE_CHARS, (ch) => ch + '\\uFE0E');\n}\n\ninterface TableCell {\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\ninterface TableComponentProps {\n rows: (string | TableCell)[][];\n x?: number | string;\n y?: number | string;\n w?: number | string;\n h?: number | string;\n colW?: number | number[];\n rowH?: number | number[];\n border?: { type?: string; pt?: number; color?: string };\n fill?: string;\n fontSize?: number;\n fontFace?: string;\n color?: string;\n align?: string;\n valign?: string;\n autoPage?: boolean;\n autoPageRepeatHeader?: boolean;\n margin?: number | number[];\n borderRadius?: number;\n}\n\nexport function renderTableComponent(\n slide: PptxGenJS.Slide,\n props: TableComponentProps,\n theme: PptxThemeConfig,\n pptx?: PptxGenJS,\n warnings?: PipelineWarning[]\n): void {\n // Pre-compute fills and width for borderRadius feature\n let bgFill: string | undefined;\n let headerFill: string | undefined;\n let borderRadiusTableW: number | undefined;\n if (props.borderRadius && pptx && props.rows.length >= 2) {\n const lastRow = props.rows[props.rows.length - 1];\n const lastCell = lastRow?.[0];\n bgFill = props.fill\n ? resolveColor(props.fill, theme, warnings)\n : typeof lastCell === 'object' && lastCell.fill\n ? resolveColor(lastCell.fill, theme, warnings)\n : 'FFFFFF';\n const firstCell = props.rows[0]?.[0];\n headerFill =\n typeof firstCell === 'object' && firstCell.fill\n ? resolveColor(firstCell.fill, theme, warnings)\n : bgFill;\n // Derive width from colW (actual cell widths) so shapes match the table exactly\n borderRadiusTableW = Array.isArray(props.colW)\n ? props.colW.reduce((sum, w) => sum + w, 0)\n : typeof props.colW === 'number'\n ? props.colW * (props.rows[0]?.length ?? 1) // assumes uniform column count\n : typeof props.w === 'number'\n ? props.w\n : 5;\n }\n\n // Pre-compute inner border for per-cell border assignment\n const innerBorder = props.border\n ? {\n type: props.border.type ?? 'solid',\n pt: props.border.pt ?? 1,\n color: resolveColor(props.border.color ?? '000000', theme, warnings),\n }\n : undefined;\n\n // Helper: build per-cell border array when borderRadius is active\n const buildBorderRadiusBorders = (\n rowIndex: number,\n colIndex: number,\n colCount: number\n ) => {\n const isTop = rowIndex === 0;\n const isBottom = rowIndex === props.rows.length - 1;\n const isLeft = colIndex === 0;\n const isRight = colIndex === colCount - 1;\n const zeroBorder = { type: 'none', pt: 0 };\n const hInner = innerBorder ?? zeroBorder;\n return [\n isTop || rowIndex === 1 ? zeroBorder : hInner, // top: outer + header-body seam\n isRight ? zeroBorder : hInner, // right\n isBottom || rowIndex === 0 ? zeroBorder : hInner, // bottom: outer + header-body seam\n isLeft ? zeroBorder : hInner, // left\n ];\n };\n\n // Convert rows to pptxgenjs format\n const lastRowIdx = props.rows.length - 1;\n const tableRows = props.rows.map((row, rowIndex) =>\n row.map((cell, colIndex) => {\n const lastColIdx = row.length - 1;\n // Corner cells: first/last col of header or last row — transparent\n // so background roundRect shapes show rounded corners through them.\n // All other cells: opaque fill to prevent seam artifacts.\n const isCorner =\n bgFill &&\n (rowIndex === 0 || rowIndex === lastRowIdx) &&\n (colIndex === 0 || colIndex === lastColIdx);\n\n if (typeof cell === 'string') {\n if (!bgFill) return { text: applyTextVariationSelector(cell) };\n const isHeader = rowIndex === 0;\n const opts: Record<string, unknown> = {\n border: buildBorderRadiusBorders(rowIndex, colIndex, row.length),\n };\n if (!isCorner) opts.fill = { color: isHeader ? headerFill : bgFill };\n return { text: applyTextVariationSelector(cell), options: opts };\n }\n const cellOpts: Record<string, unknown> = {};\n if (cell.color)\n cellOpts.color = resolveColor(cell.color, theme, warnings);\n if (bgFill) {\n const isHeader = rowIndex === 0;\n if (!isCorner) {\n const resolvedFill = cell.fill\n ? resolveColor(cell.fill, theme, warnings)\n : isHeader\n ? headerFill\n : bgFill;\n cellOpts.fill = { color: resolvedFill };\n }\n cellOpts.border = buildBorderRadiusBorders(\n rowIndex,\n colIndex,\n row.length\n );\n } else if (cell.fill) {\n cellOpts.fill = { color: resolveColor(cell.fill, theme, warnings) };\n }\n if (cell.fontSize) cellOpts.fontSize = cell.fontSize;\n if (cell.fontFace) cellOpts.fontFace = cell.fontFace;\n if (cell.bold) cellOpts.bold = true;\n if (cell.italic) cellOpts.italic = true;\n if (cell.fontWeight != null || cell.bold === true) {\n const w = applyFontWeight({\n family:\n (cellOpts.fontFace as string | undefined) ??\n props.fontFace ??\n theme.fonts.body,\n fontWeight: cell.fontWeight,\n italic: cell.italic,\n bold: cell.bold,\n });\n if (w.fontFace !== undefined) cellOpts.fontFace = w.fontFace;\n if (w.bold !== undefined) cellOpts.bold = w.bold;\n if (w.italic !== undefined) cellOpts.italic = w.italic;\n }\n if (cell.align) cellOpts.align = cell.align;\n if (cell.valign) cellOpts.valign = cell.valign;\n if (cell.colspan) cellOpts.colspan = cell.colspan;\n if (cell.rowspan) cellOpts.rowspan = cell.rowspan;\n if (cell.margin !== undefined) cellOpts.margin = cell.margin;\n\n return { text: applyTextVariationSelector(cell.text), options: cellOpts };\n })\n );\n\n const opts: Record<string, unknown> = {};\n\n // Position\n if (props.x !== undefined) opts.x = props.x;\n if (props.y !== undefined) opts.y = props.y;\n if (props.w !== undefined) opts.w = props.w;\n if (props.h !== undefined) opts.h = props.h;\n\n // Column/row sizing\n if (props.colW !== undefined) opts.colW = props.colW;\n if (props.rowH !== undefined) opts.rowH = props.rowH;\n\n // Border — skip table-level border when borderRadius is active (per-cell borders handle it)\n if (props.border && !bgFill) {\n opts.border = {\n type: props.border.type ?? 'solid',\n pt: props.border.pt ?? 1,\n color: resolveColor(props.border.color ?? '000000', theme, warnings),\n };\n }\n\n // Fill\n if (props.fill)\n opts.fill = { color: resolveColor(props.fill, theme, warnings) };\n\n // Font defaults\n opts.fontSize = props.fontSize ?? theme.defaults.fontSize;\n opts.fontFace = props.fontFace ?? theme.fonts.body;\n if (props.color) opts.color = resolveColor(props.color, theme, warnings);\n\n // Alignment\n if (props.align) opts.align = props.align;\n opts.valign = props.valign ?? 'middle';\n\n // Auto-paging\n if (props.autoPage) opts.autoPage = true;\n if (props.autoPageRepeatHeader) {\n opts.autoPageRepeatHeader = true;\n opts.autoPageHeaderRows = 1;\n }\n\n // Margin\n if (props.margin !== undefined) opts.margin = props.margin;\n\n // Background roundRect shapes — placed BEFORE the table.\n // Corner cells are transparent so these shapes show through at the corners.\n // Non-corner cells are opaque to prevent seam artifacts.\n if (\n props.borderRadius &&\n pptx &&\n typeof props.x === 'number' &&\n typeof props.y === 'number'\n ) {\n let tableH: number = (props.h as number) ?? 2;\n if (typeof props.rowH === 'number') {\n tableH = props.rowH * props.rows.length;\n } else if (Array.isArray(props.rowH)) {\n tableH = props.rowH.reduce((sum, h) => sum + h, 0);\n }\n const headerH =\n typeof props.rowH === 'number'\n ? props.rowH\n : Array.isArray(props.rowH)\n ? props.rowH[0]\n : 0.45;\n const tableW = borderRadiusTableW!;\n // Suppress shape outlines completely\n const noLine = { type: 'none' };\n\n // Header roundRect (rounded top corners)\n slide.addShape(pptx.ShapeType.roundRect, {\n x: props.x,\n y: props.y,\n w: tableW,\n h: headerH,\n fill: { color: headerFill },\n rectRadius: props.borderRadius,\n line: noLine,\n } as any);\n // Header flat rect — covers the rounded bottom corners of header\n slide.addShape(pptx.ShapeType.rect, {\n x: props.x,\n y: (props.y as number) + headerH - props.borderRadius,\n w: tableW,\n h: props.borderRadius,\n fill: { color: headerFill },\n line: noLine,\n } as any);\n\n // Body roundRect (rounded bottom corners)\n const bodyY = (props.y as number) + headerH;\n const bodyH = tableH - headerH;\n slide.addShape(pptx.ShapeType.roundRect, {\n x: props.x,\n y: bodyY,\n w: tableW,\n h: bodyH,\n fill: { color: bgFill },\n rectRadius: props.borderRadius,\n line: noLine,\n } as any);\n // Body flat rect — covers the rounded top corners of body\n slide.addShape(pptx.ShapeType.rect, {\n x: props.x,\n y: bodyY,\n w: tableW,\n h: props.borderRadius,\n fill: { color: bgFill },\n line: noLine,\n } as any);\n }\n\n // When borderRadius is active, override opts.w to match colW sum\n // and suppress any table-level border/outline\n if (bgFill && borderRadiusTableW !== undefined) {\n opts.w = borderRadiusTableW;\n opts.border = [\n { type: 'none' },\n { type: 'none' },\n { type: 'none' },\n { type: 'none' },\n ];\n }\n\n slide.addTable(tableRows as any, opts as any);\n}\n","/**\n * Environment detection utilities\n */\n\n/**\n * Check if the current environment is Node.js\n */\nexport function isNodeEnvironment(): boolean {\n return (\n typeof process !== 'undefined' &&\n process.versions != null &&\n process.versions.node != null &&\n typeof process.versions.node === 'string'\n );\n}\n","/**\n * Highcharts Component Renderer (PPTX)\n */\n\nimport type PptxGenJS from 'pptxgenjs';\nimport type { PptxThemeConfig, PipelineWarning } from '../types';\nimport type { PptxHighchartsProps } from '@json-to-office/shared-pptx';\nimport type { HighchartsServiceConfig } from '@json-to-office/shared';\nimport { isNodeEnvironment } from '../utils/environment';\nimport { resolveColor, definedChartColorTokens } from '../utils/color';\n\nconst PX_PER_INCH = 96;\nconst DEFAULT_EXPORT_SERVER_URL = 'http://localhost:7801';\n\nfunction getExportServerUrl(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 * Generate chart via Highcharts Export Server\n */\nasync function generateChart(\n config: PptxHighchartsProps,\n servicesConfig?: HighchartsServiceConfig\n): Promise<{ base64DataUri: string; width: number; height: number }> {\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 = getExportServerUrl(\n config.serverUrl,\n servicesConfig?.serverUrl\n );\n\n const requestBody = {\n infile: config.options,\n type: 'png',\n b64: true,\n scale: config.scale,\n // Forward resources verbatim only when present so the payload stays\n // byte-identical to before for callers that omit it.\n ...(config.resources ? { resources: config.resources } : {}),\n };\n\n const resolvedHeaders =\n typeof servicesConfig?.headers === 'function'\n ? await servicesConfig.headers(requestBody)\n : servicesConfig?.headers;\n\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n ...resolvedHeaders,\n };\n\n const response = await fetch(`${serverUrl}/export`, {\n method: 'POST',\n headers,\n body: JSON.stringify(requestBody),\n }).catch((error) => {\n throw new Error(\n `Highcharts Export Server is not running at ${serverUrl}. ` +\n 'Start it with: npx highcharts-export-server --enableServer true\\n' +\n `Cause: ${error instanceof Error ? error.message : String(error)}`\n );\n });\n\n if (!response.ok) {\n throw new Error(\n `Highcharts export server returned ${response.status}: ${response.statusText}`\n );\n }\n\n const base64Data = await response.text();\n\n return {\n base64DataUri: `data:image/png;base64,${base64Data}`,\n width: config.options.chart?.width ?? 960,\n height: config.options.chart?.height ?? 720,\n };\n}\n\n/**\n * When the Highcharts config sets no top-level `colors`, series render in the\n * Highcharts default palette (blue-first) and ignore the document theme. Inject\n * the theme's chart palette (same tokens as the native `chart` component) so\n * both chart paths follow the theme by default. accent4-6 are optional in the\n * theme schema; slots the theme leaves unset are skipped, in both formats, so\n * the palette never repeats primary and Highcharts wraps the shorter list (see\n * DEFAULT_CHART_THEME_COLORS). 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 {\n ...props,\n options: { ...props.options, colors: palette },\n };\n}\n\nexport async function renderHighchartsComponent(\n slide: PptxGenJS.Slide,\n props: PptxHighchartsProps,\n theme: PptxThemeConfig,\n warnings?: PipelineWarning[],\n servicesConfig?: HighchartsServiceConfig\n): Promise<void> {\n const chart = await generateChart(\n withThemeColors(props, theme, warnings),\n servicesConfig\n );\n\n const w = props.w ?? chart.width / PX_PER_INCH;\n const h = props.h ?? chart.height / PX_PER_INCH;\n\n slide.addImage({\n data: chart.base64DataUri,\n x: props.x ?? 0,\n y: props.y ?? 0,\n w,\n h,\n } as any);\n}\n","/**\n * Chart Component Renderer — native PowerPoint charts via pptxgenjs slide.addChart()\n */\n\nimport type PptxGenJS from 'pptxgenjs';\nimport type { PptxThemeConfig, PipelineWarning } from '../types';\nimport { resolveColor, definedChartColorTokens } from '../utils/color';\nimport { warn, W } from '../utils/warn';\n\ninterface ChartDataSeries {\n name?: string;\n labels?: string[];\n values?: number[];\n sizes?: number[];\n}\n\ninterface ChartComponentProps {\n type: string;\n data: ChartDataSeries[];\n\n showLegend?: boolean;\n showTitle?: boolean;\n showValue?: boolean;\n showPercent?: boolean;\n showLabel?: boolean;\n showSerName?: boolean;\n\n title?: string;\n titleFontSize?: number;\n titleColor?: string;\n titleFontFace?: string;\n\n chartColors?: string[];\n\n dataBorder?: { pt: number; color: string };\n\n legendPos?: string;\n legendFontSize?: number;\n legendFontFace?: string;\n legendColor?: string;\n\n catAxisTitle?: string;\n catAxisHidden?: boolean;\n catAxisLabelRotate?: number;\n catAxisLabelFontSize?: number;\n catAxisLabelColor?: string;\n catAxisLabelFontFace?: string;\n catGridLine?: { style?: string; size?: number; color?: string };\n\n valAxisTitle?: string;\n valAxisHidden?: boolean;\n valAxisMinVal?: number;\n valAxisMaxVal?: number;\n valAxisLabelFormatCode?: string;\n valAxisMajorUnit?: number;\n valAxisLabelColor?: string;\n valAxisLabelFontFace?: string;\n valAxisLabelFontSize?: number;\n valGridLine?: { style?: string; size?: number; color?: string };\n catAxisLineShow?: boolean;\n valAxisLineShow?: boolean;\n\n barDir?: string;\n barGrouping?: string;\n barGapWidthPct?: number;\n barOverlapPct?: number;\n\n lineSmooth?: boolean;\n lineDataSymbol?: string;\n lineSize?: number;\n lineDataSymbolSize?: number;\n\n firstSliceAng?: number;\n holeSize?: number;\n\n radarStyle?: string;\n\n dataLabelColor?: string;\n dataLabelFontSize?: number;\n dataLabelFontFace?: string;\n dataLabelFontBold?: boolean;\n dataLabelPosition?: string;\n\n x?: number | string;\n y?: number | string;\n w?: number | string;\n h?: number | string;\n}\n\n// Map our type strings to pptxgenjs CHART_NAME values\nconst CHART_TYPE_MAP: Record<string, string> = {\n area: 'area',\n bar: 'bar',\n bar3D: 'bar3D',\n bubble: 'bubble',\n doughnut: 'doughnut',\n line: 'line',\n pie: 'pie',\n radar: 'radar',\n scatter: 'scatter',\n};\n\nfunction resolveGridLine(\n gridLine: { style?: string; size?: number; color?: string },\n theme: PptxThemeConfig,\n warnings?: PipelineWarning[]\n): Record<string, unknown> {\n const resolved: Record<string, unknown> = {};\n if (gridLine.style !== undefined) resolved.style = gridLine.style;\n if (gridLine.size !== undefined) resolved.size = gridLine.size;\n if (gridLine.color !== undefined)\n resolved.color = resolveColor(gridLine.color, theme, warnings);\n return resolved;\n}\n\nexport function renderChartComponent(\n slide: PptxGenJS.Slide,\n props: ChartComponentProps,\n theme: PptxThemeConfig,\n _pptx: PptxGenJS,\n warnings?: PipelineWarning[]\n): void {\n const chartType = CHART_TYPE_MAP[props.type];\n if (!chartType) {\n warn(warnings, W.UNKNOWN_CHART_TYPE, `Unknown chart type: ${props.type}`, {\n component: 'chart',\n });\n return;\n }\n\n // Validate data\n if (!props.data || props.data.length === 0) {\n warn(warnings, W.CHART_NO_DATA, 'Chart component has no data series', {\n component: 'chart',\n });\n return;\n }\n for (const series of props.data) {\n if (!series.labels || !series.values) {\n warn(\n warnings,\n W.CHART_INVALID_SERIES,\n `Chart series \"${series.name ?? '(unnamed)'}\" missing labels or values`,\n { component: 'chart' }\n );\n return;\n }\n }\n if (\n (chartType === 'pie' || chartType === 'doughnut') &&\n props.data.length > 1\n ) {\n warn(\n warnings,\n W.CHART_MULTI_SERIES,\n `${props.type} chart has ${props.data.length} series — only the first will render`,\n { component: 'chart' }\n );\n }\n\n // Build data array\n const data = props.data.map((series) => {\n const d: Record<string, unknown> = {};\n if (series.name !== undefined) d.name = series.name;\n if (series.labels) d.labels = series.labels;\n if (series.values) d.values = series.values;\n if (series.sizes) d.sizes = series.sizes;\n return d;\n });\n\n // Build chart options\n const opts: Record<string, unknown> = {};\n\n // Position\n if (props.x !== undefined) opts.x = props.x;\n if (props.y !== undefined) opts.y = props.y;\n if (props.w !== undefined) opts.w = props.w;\n if (props.h !== undefined) opts.h = props.h;\n\n // Colors — resolve semantic names to hex, following any token-to-token\n // reference the theme sets up. The implicit palette skips tokens the theme\n // leaves unset or leaves unresolvable (DOCX does the same); an explicit\n // chartColors entry naming one keeps the loud fallback + warning. Only hex\n // reaches pptxgenjs: it answers a stray token name with black. An empty list\n // is left unset rather than passed on — pptxgenjs indexes `chartColors[i % 0]`\n // and paints every series black, so its own palette is the better fallback.\n const colorSources = props.chartColors ?? definedChartColorTokens(theme);\n if (colorSources.length > 0) {\n opts.chartColors = colorSources.map((c) =>\n resolveColor(c, theme, warnings)\n );\n }\n\n // Auto-default chart text colors from theme to prevent dark-on-dark / light-on-light\n const themeTextColor = resolveColor('text', theme, warnings);\n opts.titleColor = props.titleColor\n ? resolveColor(props.titleColor, theme, warnings)\n : themeTextColor;\n opts.legendColor = props.legendColor\n ? resolveColor(props.legendColor, theme, warnings)\n : themeTextColor;\n opts.catAxisLabelColor = props.catAxisLabelColor\n ? resolveColor(props.catAxisLabelColor, theme, warnings)\n : themeTextColor;\n opts.valAxisLabelColor = props.valAxisLabelColor\n ? resolveColor(props.valAxisLabelColor, theme, warnings)\n : themeTextColor;\n if (props.valAxisLabelFontSize !== undefined)\n opts.valAxisLabelFontSize = props.valAxisLabelFontSize;\n if (props.catAxisLineShow !== undefined)\n opts.catAxisLineShow = props.catAxisLineShow;\n if (props.valAxisLineShow !== undefined)\n opts.valAxisLineShow = props.valAxisLineShow;\n\n // Data element border (bars/slices/areas)\n if (props.dataBorder !== undefined) {\n opts.dataBorder = {\n pt: props.dataBorder.pt,\n color: resolveColor(props.dataBorder.color, theme, warnings),\n };\n }\n\n // Display toggles\n if (props.showLegend !== undefined) opts.showLegend = props.showLegend;\n if (props.showTitle !== undefined) opts.showTitle = props.showTitle;\n if (props.showValue !== undefined) opts.showValue = props.showValue;\n if (props.showPercent !== undefined) opts.showPercent = props.showPercent;\n if (props.showLabel !== undefined) opts.showLabel = props.showLabel;\n if (props.showSerName !== undefined) opts.showSerName = props.showSerName;\n\n // Title\n if (props.title !== undefined) opts.title = props.title;\n if (props.titleFontSize !== undefined)\n opts.titleFontSize = props.titleFontSize;\n if (props.titleFontFace !== undefined)\n opts.titleFontFace = props.titleFontFace;\n\n // Legend\n if (props.legendPos !== undefined) opts.legendPos = props.legendPos;\n if (props.legendFontSize !== undefined)\n opts.legendFontSize = props.legendFontSize;\n if (props.legendFontFace !== undefined)\n opts.legendFontFace = props.legendFontFace;\n\n // Category axis\n if (props.catAxisTitle !== undefined) {\n opts.catAxisTitle = props.catAxisTitle;\n opts.showCatAxisTitle = true;\n }\n if (props.catAxisHidden !== undefined)\n opts.catAxisHidden = props.catAxisHidden;\n if (props.catAxisLabelRotate !== undefined)\n opts.catAxisLabelRotate = props.catAxisLabelRotate;\n if (props.catAxisLabelFontSize !== undefined)\n opts.catAxisLabelFontSize = props.catAxisLabelFontSize;\n if (props.catAxisLabelFontFace !== undefined)\n opts.catAxisLabelFontFace = props.catAxisLabelFontFace;\n if (props.catGridLine !== undefined)\n opts.catGridLine = resolveGridLine(props.catGridLine, theme, warnings);\n\n // Value axis\n if (props.valAxisTitle !== undefined) {\n opts.valAxisTitle = props.valAxisTitle;\n opts.showValAxisTitle = true;\n }\n if (props.valAxisHidden !== undefined)\n opts.valAxisHidden = props.valAxisHidden;\n if (props.valAxisMinVal !== undefined)\n opts.valAxisMinVal = props.valAxisMinVal;\n if (props.valAxisMaxVal !== undefined)\n opts.valAxisMaxVal = props.valAxisMaxVal;\n if (props.valAxisLabelFormatCode !== undefined)\n opts.valAxisLabelFormatCode = props.valAxisLabelFormatCode;\n if (props.valAxisMajorUnit !== undefined)\n opts.valAxisMajorUnit = props.valAxisMajorUnit;\n if (props.valAxisLabelFontFace !== undefined)\n opts.valAxisLabelFontFace = props.valAxisLabelFontFace;\n if (props.valGridLine !== undefined)\n opts.valGridLine = resolveGridLine(props.valGridLine, theme, warnings);\n\n // Bar-specific\n if (props.barDir !== undefined) opts.barDir = props.barDir;\n if (props.barGrouping !== undefined) opts.barGrouping = props.barGrouping;\n if (props.barGapWidthPct !== undefined)\n opts.barGapWidthPct = props.barGapWidthPct;\n if (props.barOverlapPct !== undefined)\n opts.barOverlapPct = props.barOverlapPct;\n\n // Line-specific\n if (props.lineSmooth !== undefined) opts.lineSmooth = props.lineSmooth;\n if (props.lineDataSymbol !== undefined)\n opts.lineDataSymbol = props.lineDataSymbol;\n if (props.lineSize !== undefined) opts.lineSize = props.lineSize;\n if (props.lineDataSymbolSize !== undefined)\n opts.lineDataSymbolSize = props.lineDataSymbolSize;\n\n // Pie/doughnut\n if (props.firstSliceAng !== undefined)\n opts.firstSliceAng = props.firstSliceAng;\n if (props.holeSize !== undefined) opts.holeSize = props.holeSize;\n\n // Radar\n if (props.radarStyle !== undefined) opts.radarStyle = props.radarStyle;\n\n // Data labels\n opts.dataLabelColor = props.dataLabelColor\n ? resolveColor(props.dataLabelColor, theme, warnings)\n : themeTextColor;\n if (props.dataLabelFontSize !== undefined)\n opts.dataLabelFontSize = props.dataLabelFontSize;\n if (props.dataLabelFontFace !== undefined)\n opts.dataLabelFontFace = props.dataLabelFontFace;\n if (props.dataLabelFontBold !== undefined)\n opts.dataLabelFontBold = props.dataLabelFontBold;\n if (props.dataLabelPosition !== undefined)\n opts.dataLabelPosition = props.dataLabelPosition;\n\n slide.addChart(chartType as any, data as any[], opts as any);\n}\n","/**\n * PPTX Component Renderers\n */\n\nimport type PptxGenJS from 'pptxgenjs';\nimport type {\n PptxThemeConfig,\n PptxComponentInput,\n PipelineWarning,\n SlideRenderContext,\n} from '../types';\nimport { warn, W } from '../utils/warn';\nimport { renderTextComponent } from './text';\nimport { renderImageComponent } from './image';\nimport { renderShapeComponent } from './shape';\nimport { renderTableComponent } from './table';\nimport { renderHighchartsComponent } from './highcharts';\nimport { renderChartComponent } from './chart';\n\nexport { renderTextComponent } from './text';\nexport { renderImageComponent } from './image';\nexport { renderShapeComponent } from './shape';\nexport { renderTableComponent } from './table';\nexport { renderHighchartsComponent } from './highcharts';\nexport { renderChartComponent } from './chart';\n\nexport async function renderComponent(\n slide: PptxGenJS.Slide,\n component: PptxComponentInput,\n theme: PptxThemeConfig,\n pptx: PptxGenJS,\n warnings?: PipelineWarning[],\n ctx?: SlideRenderContext\n): Promise<void> {\n if (component.enabled === false) return;\n\n const { name, props } = component;\n const p = props as any;\n\n switch (name) {\n case 'text':\n renderTextComponent(slide, p, theme, warnings, ctx?.slideCtx);\n break;\n case 'image':\n await renderImageComponent(\n slide,\n p,\n theme,\n warnings,\n ctx?.slideWidth,\n ctx?.slideHeight\n );\n break;\n case 'shape':\n renderShapeComponent(slide, p, theme, pptx, warnings, ctx);\n break;\n case 'table':\n renderTableComponent(slide, p, theme, pptx, warnings);\n break;\n case 'highcharts':\n await renderHighchartsComponent(\n slide,\n p,\n theme,\n warnings,\n ctx?.services?.highcharts\n );\n break;\n case 'chart':\n renderChartComponent(slide, p, theme, pptx, warnings);\n break;\n default:\n warn(\n warnings,\n W.UNKNOWN_COMPONENT,\n `Unknown PPTX component type: ${name}`,\n { component: name }\n );\n }\n}\n","/**\n * Template Slide Builder\n * Converts internal TemplateSlideDefinition to pptxgenjs SlideMasterProps\n *\n * Fixed objects (shapes, text, images) are no longer rendered here — they use\n * the unified component pipeline and are rendered per-slide in render.ts.\n */\n\nimport type {\n TemplateSlideDefinition,\n PptxThemeConfig,\n PipelineWarning,\n} from '../types';\nimport { resolveColor } from '../utils/color';\nimport { safeLocalPath } from '../utils/imageSource';\n\nexport function buildSlideTemplateProps(\n def: TemplateSlideDefinition,\n theme: PptxThemeConfig,\n warnings?: PipelineWarning[]\n): Record<string, any> {\n const result: Record<string, any> = { title: def.name };\n\n // Background\n if (def.background) {\n if (def.background.color) {\n result.background = {\n color: resolveColor(def.background.color, theme, warnings),\n };\n } else if (def.background.image) {\n if (def.background.image.path) {\n const bgPath = safeLocalPath(def.background.image.path);\n if (bgPath !== undefined) result.background = { path: bgPath };\n } else if (def.background.image.base64) {\n result.background = { data: def.background.image.base64 };\n }\n }\n }\n\n // Margin\n if (def.margin !== undefined) result.margin = def.margin;\n\n // Slide number\n if (def.slideNumber) {\n result.slideNumber = {\n x: def.slideNumber.x,\n y: def.slideNumber.y,\n };\n if (def.slideNumber.w !== undefined)\n result.slideNumber.w = def.slideNumber.w;\n if (def.slideNumber.h !== undefined)\n result.slideNumber.h = def.slideNumber.h;\n if (def.slideNumber.color)\n result.slideNumber.color = resolveColor(\n def.slideNumber.color,\n theme,\n warnings\n );\n if (def.slideNumber.fontSize)\n result.slideNumber.fontSize = def.slideNumber.fontSize;\n }\n\n return result;\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} from '@json-to-office/shared';\nimport {\n loadFileFontSource,\n FontDiskCache,\n fetchVariableFontSource,\n} from '@json-to-office/shared/fonts/node';\nimport type {\n PipelineWarning,\n PresentationComponentDefinition,\n} from '../types';\nimport type { PptxThemeConfig } from '../types';\nimport { warn, W } from '../utils/warn';\n\nexport async function resolveDocumentFonts(\n document: PresentationComponentDefinition,\n theme: PptxThemeConfig,\n warnings: PipelineWarning[],\n fonts?: FontRuntimeOpts\n): Promise<ResolvedFont[]> {\n const names = new Set<string>();\n for (const n of collectFontNamesFromPptx(document)) names.add(n);\n for (const n of collectFontNamesFromPptx(theme as unknown)) names.add(n);\n if (names.size === 0) return [];\n\n // 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: fonts?.extraEntries,\n });\n if (validation.warnings.length > 0) {\n if (fonts?.strict) {\n throw new Error(\n `Unresolved font references (strict mode):\\n` +\n validation.warnings.map((w) => ` - ${w.message}`).join('\\n')\n );\n }\n for (const w of validation.warnings) {\n warn(warnings, W.FONT_UNRESOLVED, w.message, {\n component: 'fontRegistry',\n });\n }\n }\n\n // Registry resolution (Google/URL/file fetches) only runs when a consumer\n // is listening via onResolved — typically the LibreOffice preview stager.\n // Office output never embeds bytes, so skipping fetches when nobody cares\n // keeps library callers from paying network cost.\n if (!fonts?.onResolved) return [];\n\n const registry = new FontRegistry({\n opts: fonts,\n fileLoader: loadFileFontSource,\n variableLoader: fetchVariableFontSource,\n diskCache: fonts?.googleFonts?.cacheDir\n ? new FontDiskCache(fonts.googleFonts.cacheDir)\n : undefined,\n });\n const resolved = await registry.resolveMany(names);\n for (const r of resolved) {\n for (const msg of r.warnings) {\n warn(warnings, W.FONT_UNRESOLVED, msg, {\n component: 'fontRegistry',\n });\n }\n }\n // Fire the side-channel here so callers never have to remember. The\n // short-circuit above guarantees we only reach this point when a\n // listener is registered.\n fonts.onResolved(resolved);\n return resolved;\n}\n","/**\n * Shared generation prologue.\n *\n * Both entry points — `generateBufferWithWarnings` (core) and\n * `createPresentationGenerator` (plugin) — must resolve the same theme, run\n * the same export-mode pre-pass, and derive the same cache key before slide\n * processing runs. Keeping two 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, scopedThemeName } from '@json-to-office/shared';\nimport { getPptxTheme } from '../themes/defaults';\n\nexport interface ThemeContextOptions {\n customThemes?: Record<string, PptxThemeConfig>;\n fonts?: FontRuntimeOpts;\n warnings?: PipelineWarning[];\n /**\n * Base theme name when the document doesn't name one. The plugin builder\n * passes its constructor-supplied string theme; defaults to 'default'.\n */\n defaultThemeName?: string;\n /**\n * Theme lookup for the base `props.theme` name. The plugin builder passes\n * its own (customThemes → doc-named built-in → constructor theme object →\n * built-in); omit it to use customThemes → built-in. `authored` is true\n * when the name came from the document's own `props.theme` (as opposed to\n * `defaultThemeName` or the 'default' fallback), so the lookup can honor\n * an explicitly doc-named built-in without the constructor object\n * swallowing the default name too (#141).\n */\n resolveNamedTheme?: (name: string, authored: boolean) => PptxThemeConfig;\n}\n\nexport interface GenerationThemeContext {\n /**\n * The document after the export-mode pre-pass rewrote font references.\n * `props.theme` stays as authored (name or inline object) — callers hand\n * `theme` to `processPresentation` by value instead of round-tripping it\n * through a name lookup (#135).\n */\n document: PresentationComponentDefinition;\n theme: PptxThemeConfig;\n /**\n * Cache key: base theme name + export-mode scope. Nothing in PPTX consumes\n * a theme by name after the prologue today; this is the key a future\n * theme-keyed cache must use (a substitute-mode run rewrites the theme in\n * place, so it must never share a slot with a custom-mode run of the same\n * base name — the DOCX layout cache is keyed exactly this way).\n */\n themeName: string;\n}\n\nexport function resolveThemeContext(\n documentIn: PresentationComponentDefinition,\n options: ThemeContextOptions = {}\n): GenerationThemeContext {\n const { customThemes, fonts, warnings, defaultThemeName, resolveNamedTheme } =\n options;\n\n // A root written without a `props` key is defaulted here — otherwise the\n // first downstream `document.props.*` read throws a raw TypeError. Only\n // `undefined` is defaulted: `props: null` is malformed and must be rejected\n // rather than quietly rewritten into a valid shape. Both entry points\n // validate before reaching here when validation is enabled (the PPTX\n // validator rejects a missing `props`); this covers the\n // `validation: { enabled: false }` route. Matches DOCX.\n if (documentIn.props === null) {\n throw new Error(\n 'Document `props` is null. Omit it, or provide an object — ' +\n 'a null props cannot carry a theme.'\n );\n }\n let document =\n documentIn.props === undefined ? { ...documentIn, props: {} } : documentIn;\n\n // An inline theme object (self-contained document) resolves directly and\n // wins over any customThemes entry sharing its name, on both paths. The\n // document keeps the authored object — nothing downstream resolves the\n // theme by name anymore.\n let inlineTheme: PptxThemeConfig | undefined;\n if (\n typeof document.props.theme === 'object' &&\n document.props.theme !== null\n ) {\n inlineTheme = document.props.theme as PptxThemeConfig;\n }\n\n const authoredThemeName =\n typeof document.props.theme === 'string' ? document.props.theme : undefined;\n const baseThemeName = inlineTheme\n ? inlineTheme.name || 'inline-theme'\n : authoredThemeName ?? defaultThemeName ?? 'default';\n let theme =\n inlineTheme ??\n (resolveNamedTheme\n ? resolveNamedTheme(baseThemeName, authoredThemeName !== undefined)\n : customThemes?.[baseThemeName] ?? getPptxTheme(baseThemeName));\n\n // Export-mode pre-pass: substitute rewrites non-safe families in place;\n // custom leaves refs untouched and resolution short-circuits to empty.\n const mode = applyExportMode({ doc: document, theme, fonts });\n document = mode.doc;\n theme = mode.theme;\n for (const w of mode.warnings) {\n warnings?.push({\n code: w.code,\n message: w.message,\n component: 'fontRegistry',\n });\n }\n\n return {\n document,\n theme,\n themeName: scopedThemeName(baseThemeName, fonts?.mode),\n };\n}\n","import JSZip from 'jszip';\nimport type { PendingXmlFill } from '../types';\n\nconst MEDIUM_STYLE_2_ACCENT_1 = '{5C22544A-7EE6-4342-B048-85BDC9FD1C3A}';\nconst NO_STYLE_NO_GRID = '{2D5ABB26-0587-4C30-8999-92F81FD0307C}';\n\n/** Stable default shared by package entries and OOXML core metadata. */\nexport const DEFAULT_GENERATED_AT = '2000-01-01T00:00:00.000Z';\n\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 * 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?: PendingXmlFill[];\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\nfunction 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\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/**\n * Apply post-generation OOXML fixes and deterministic package metadata.\n *\n * PptxGenJS stamps both core.xml and ZIP entries with the wall clock. Rewriting\n * both layers makes equivalent inputs byte-identical across invocations.\n */\nexport async function packagePresentationBuffer(\n buffer: Buffer,\n options: PresentationPackagingOptions = {}\n): Promise<Buffer> {\n const zip = await JSZip.loadAsync(buffer);\n let changed = false;\n\n for (const [path, entry] of Object.entries(zip.files)) {\n if (!path.match(/^ppt\\/slides\\/slide\\d+\\.xml$/)) 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 if (options.deterministic !== false) {\n const generatedAt = resolveGeneratedAt(options.generatedAt);\n await canonicalizeChartIds(zip);\n await canonicalizePackage(zip, generatedAt);\n changed = true;\n }\n\n if (!changed) return buffer;\n\n return generateZip(zip);\n}\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 PendingXmlFill,\n} from '../types';\nimport type {\n ExtendedPresentationComponent,\n PresentationGeneratorBuilder,\n BufferGenerationResult,\n FileGenerationResult,\n GenerateFileOptions,\n GenerateOptions,\n GenerationValidationOptions,\n ValidationResult,\n} from './types';\nimport { validatePresentation, cleanComponentProps } from './validation';\nimport { generatePluginPresentationSchema, exportPluginSchema } from './schema';\nimport { processPresentation } from '../core/structure';\nimport { renderPresentation } from '../core/render';\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';\nimport {\n packagePresentationBuffer,\n type PresentationPackagingOptions,\n} from '../core/packagePresentation';\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\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}\n\ntype ValidateEmitted = (\n emitted: PptxComponentInput[],\n componentLabel: string,\n parentName?: string\n) => void;\n\n/**\n * Create the builder implementation with the given state\n */\nfunction createBuilderImpl<\n TComponents extends readonly CustomComponent<any, any, any>[],\n>(state: BuilderState): PresentationGeneratorBuilder<TComponents> {\n const componentMap = new Map(state.components.map((c) => [c.name, c]));\n\n /**\n * Process custom components in slide children, recursively resolving them\n * to standard PptxComponentInput elements.\n */\n async function processSlideComponents(\n components: PptxComponentInput[],\n warningsCollector: PipelineWarning[],\n theme: PptxThemeConfig,\n validateEmitted: ValidateEmitted | undefined,\n parentName?: string,\n depth = 0\n ): Promise<PptxComponentInput[]> {\n if (depth > 20) {\n throw new Error(\n 'Maximum component nesting depth exceeded (20). Check for circular component references.'\n );\n }\n const processed: PptxComponentInput[] = [];\n\n for (const componentData of components) {\n const customComponent = componentMap.get(componentData.name);\n\n if (customComponent) {\n try {\n if (!componentData.props) {\n throw new Error(\n `Custom component '${componentData.name}' must have a 'props' property. ` +\n `Use format: { name: '${componentData.name}', props: {...} }`\n );\n }\n\n const componentWithVersion = componentData as {\n name: string;\n version?: string;\n props: Record<string, any>;\n children?: PptxComponentInput[];\n };\n\n // Resolve version\n const versionEntry = resolveComponentVersion(\n customComponent.name,\n customComponent.versions,\n componentWithVersion.version\n );\n\n // Validate and clean props\n const cleanedProps = cleanComponentProps(\n versionEntry,\n componentWithVersion.props\n );\n\n // Process nested children if container\n let nestedChildren: unknown[] | undefined;\n if (\n componentWithVersion.children &&\n Array.isArray(componentWithVersion.children)\n ) {\n nestedChildren = await processSlideComponents(\n componentWithVersion.children,\n warningsCollector,\n theme,\n validateEmitted,\n undefined,\n depth + 1\n );\n }\n\n // Create addWarning callback\n const versionLabel = componentWithVersion.version\n ? `${customComponent.name}@${componentWithVersion.version}`\n : customComponent.name;\n\n const addWarning = (\n message: string,\n context?: Record<string, unknown>\n ) => {\n warningsCollector.push({\n code: (context?.code as string) ?? 'PLUGIN_WARNING',\n message,\n component: versionLabel,\n slide: context?.slide as number | undefined,\n });\n };\n\n // Call render\n const result = await versionEntry.render({\n props: cleanedProps,\n theme,\n addWarning,\n children: nestedChildren,\n });\n\n const resultComponents = (\n Array.isArray(result) ? result : [result]\n ) as PptxComponentInput[];\n\n validateEmitted?.(resultComponents, versionLabel, parentName);\n\n // Recursively process in case result contains more custom components\n const processedResult = await processSlideComponents(\n resultComponents,\n warningsCollector,\n theme,\n validateEmitted,\n parentName,\n depth + 1\n );\n processed.push(...processedResult);\n\n if (state.debug) {\n console.log(\n `Processed custom component '${versionLabel}':`,\n processedResult\n );\n }\n } catch (error) {\n if (error instanceof ComponentValidationError) {\n throw error;\n }\n throw new Error(\n `Error processing custom component '${customComponent.name}': ${\n error instanceof Error ? error.message : String(error)\n }`\n );\n }\n } else {\n // Standard component — process children recursively\n if (componentData.children && Array.isArray(componentData.children)) {\n const processedChildren = await processSlideComponents(\n componentData.children,\n warningsCollector,\n theme,\n validateEmitted,\n componentData.name,\n depth + 1\n );\n processed.push({\n ...componentData,\n children: processedChildren,\n });\n } else {\n processed.push(componentData);\n }\n }\n }\n\n return processed;\n }\n\n /**\n * Add a custom component to the generator\n */\n function addComponent<TNewComponent extends CustomComponent<any, any, any>>(\n component: TNewComponent\n ): PresentationGeneratorBuilder<readonly [...TComponents, TNewComponent]> {\n if (!component.name) {\n throw new Error('Component name is required');\n }\n\n if (state.componentNames.has(component.name)) {\n throw new DuplicateComponentError(component.name);\n }\n\n const newComponentNames = new Set(state.componentNames);\n newComponentNames.add(component.name);\n\n const newState: BuilderState = {\n components: [...state.components, component],\n componentNames: newComponentNames,\n theme: state.theme,\n customThemes: state.customThemes,\n debug: state.debug,\n services: state.services,\n fonts: state.fonts,\n validation: state.validation,\n packaging: state.packaging,\n baseDir: state.baseDir,\n };\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\n const validationOptions: GenerationValidationOptions = {\n ...state.validation,\n ...options?.validation,\n };\n if (validationOptions.enabled !== false) {\n const result = validatePresentation(\n internalDocument,\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), export-mode pre-pass\n // and cache-key scoping — 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 = { ...modedRoot, children: emitted };\n } else if (parentName === 'slide') {\n validationDocument = {\n ...modedRoot,\n children: [{ name: 'slide', props: {}, children: emitted }],\n };\n } else {\n // Custom container semantics are plugin-defined. The complete\n // expanded-tree pass below validates the final standard tree.\n return;\n }\n\n const result = validatePresentation(\n validationDocument,\n state.components as unknown as CustomComponent<TSchema>[],\n { allowUnknownFields: validationOptions.allowUnknownFields }\n );\n if (!result.valid) {\n throw new ComponentValidationError(\n result.errors.map((error) => ({\n ...error,\n message: `custom component '${componentLabel}' emitted invalid output — ${error.message}`,\n })),\n emitted\n );\n }\n };\n\n // Process custom components in all slide children\n const processedChildren = modedRoot.children\n ? await processAllSlides(\n modedRoot.children,\n warnings,\n resolvedTheme,\n validateEmitted\n )\n : [];\n\n const processedDocument: PresentationComponentDefinition = {\n ...modedRoot,\n children: processedChildren,\n };\n\n // Validate the fully expanded tree once more. This covers output from\n // nested custom containers whose intermediate parent semantics are\n // plugin-defined and therefore cannot be checked at render time.\n if (validationOptions.enabled !== false) {\n const result = validatePresentation(processedDocument, [], {\n allowUnknownFields: validationOptions.allowUnknownFields,\n });\n if (!result.valid) {\n throw new ComponentValidationError(\n result.errors.map((error) => ({\n ...error,\n message: `expanded plugin output failed validation — ${error.message}`,\n })),\n processedDocument\n );\n }\n }\n\n // resolveDocumentFonts fires `fonts.onResolved` internally when a\n // listener is registered (LibreOffice preview stager). The PPTX\n // itself never embeds bytes.\n await resolveDocumentFonts(\n processedDocument,\n resolvedTheme,\n warnings,\n state.fonts\n );\n\n // Unconditional conflict gate on the expanded tree — the tree that\n // reaches the renderer, so it also covers payloads emitted by custom\n // components. The validators above collect the same conflicts with\n // richer paths when validation is enabled; this is the net for\n // `validation: { enabled: false }`, where the core path already threw\n // and this path silently resolved by runtime precedence.\n assertNoContentConflicts(processedDocument);\n\n // processPresentation takes the resolved (post-substitute) theme by\n // value — the document's `props.theme` stays as authored and is not\n // consulted again.\n // Scope the document base directory over process+render: relative\n // asset paths are rewritten eagerly there — pptxgenjs reads them\n // later, during write() (#142). Matches the core pipeline.\n const { pendingFills, pptx } = await runWithBaseDir(\n options?.baseDir ?? state.baseDir,\n async () => {\n const processed = processPresentation(processedDocument, {\n theme: resolvedTheme,\n services: state.services,\n });\n const pendingFills: PendingXmlFill[] = [];\n const pptx = await renderPresentation(\n processed,\n warnings,\n pendingFills\n );\n return { pendingFills, pptx };\n }\n );\n const data = await pptx.write({ outputType: 'nodebuffer' });\n const buffer = await packagePresentationBuffer(data as Buffer, {\n deterministic: options?.deterministic ?? state.packaging.deterministic,\n generatedAt: options?.generatedAt ?? state.packaging.generatedAt,\n pendingFills,\n });\n\n return { buffer, warnings };\n } catch (error) {\n if (state.debug) {\n console.error('Presentation generation error:', error);\n }\n throw error;\n }\n }\n\n /**\n * Process custom components inside all slides.\n * Walks the top-level children (slides), then processes each slide's children.\n */\n async function processAllSlides(\n children: PptxComponentInput[],\n warnings: PipelineWarning[],\n theme: PptxThemeConfig,\n validateEmitted: ValidateEmitted | undefined\n ): Promise<PptxComponentInput[]> {\n const result: PptxComponentInput[] = [];\n\n for (const child of children) {\n if (child.name === 'slide' && child.children) {\n const processedSlideChildren = await processSlideComponents(\n child.children,\n warnings,\n theme,\n validateEmitted,\n 'slide'\n );\n result.push({ ...child, children: processedSlideChildren });\n } else {\n // Non-slide top-level children — process in case they're custom\n const processedTopLevel = await processSlideComponents(\n [child],\n warnings,\n theme,\n validateEmitted,\n 'pptx'\n );\n result.push(...processedTopLevel);\n }\n }\n\n return result;\n }\n\n /**\n * Generate and save to file\n */\n async function generateFile(\n document: ExtendedPresentationComponent<TComponents>,\n outputPath: string,\n options?: GenerateFileOptions\n ): Promise<FileGenerationResult> {\n const { buffer, warnings } = await generate(document, options);\n const fs = await import('fs/promises');\n await fs.writeFile(outputPath, new Uint8Array(buffer));\n return { warnings };\n }\n\n /**\n * Get registered component names\n */\n function getComponentNames(): string[] {\n return Array.from(state.componentNames);\n }\n\n /**\n * Validate a document without generating it\n */\n function validate(\n document: ExtendedPresentationComponent<TComponents>\n ): ValidationResult {\n try {\n const internalDocument =\n document as unknown as PresentationComponentDefinition;\n const result = validatePresentation(\n internalDocument,\n state.components as unknown as CustomComponent<TSchema>[]\n );\n if (!result.valid) {\n return {\n valid: false,\n errors: result.errors.map((e) => ({\n path: e.path,\n message: e.message,\n })),\n };\n }\n return { valid: true };\n } catch (error) {\n if (error instanceof ComponentValidationError) {\n return {\n valid: false,\n errors: error.errors.map((e) => ({\n path: e.path,\n message: e.message,\n })),\n };\n }\n return {\n valid: false,\n errors: [\n {\n path: 'document',\n message: error instanceof Error ? error.message : String(error),\n },\n ],\n };\n }\n }\n\n /**\n * Generate the extended JSON schema\n */\n function generateSchema(): TSchema {\n return generatePluginPresentationSchema(\n state.components as unknown as CustomComponent<TSchema>[]\n );\n }\n\n /**\n * Export the schema to a file\n */\n async function exportSchemaToFile(\n outputPath: string,\n options?: { prettyPrint?: boolean }\n ): Promise<void> {\n await exportPluginSchema(\n state.components as unknown as CustomComponent<TSchema>[],\n outputPath,\n options\n );\n }\n\n return Object.freeze({\n addComponent,\n generate,\n generateBuffer: generate,\n generateFile,\n getComponentNames,\n validate,\n generateSchema,\n exportSchema: exportSchemaToFile,\n });\n}\n\n/**\n * Create a presentation generator with chainable component registration.\n */\nexport function createPresentationGenerator(\n options: PresentationGeneratorOptions = {}\n): PresentationGeneratorBuilder<readonly []> {\n const initialState: BuilderState = {\n components: [],\n componentNames: new Set(),\n theme: options.theme,\n customThemes: options.customThemes,\n debug: options.debug ?? false,\n services: options.services,\n fonts: options.fonts,\n validation: options.validation,\n packaging: {\n deterministic: options.deterministic,\n generatedAt: options.generatedAt,\n },\n baseDir: options.baseDir,\n };\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","// Version information\nexport function getPptxCoreVersion(): string {\n return 'PptxCore v1.0.0';\n}\n\n// Core API\nexport {\n generatePresentation,\n generateBufferFromJson,\n generateBufferWithWarnings,\n generateAndSaveFromJson,\n generateFromFile,\n savePresentation,\n isPresentationComponentDefinition,\n PresentationValidationError,\n PresentationGenerator,\n} from './core/generator';\n\nexport type {\n GenerationOptions,\n GenerationResult,\n GenerationValidationOptions,\n} from './core/generator';\nexport {\n DEFAULT_GENERATED_AT,\n packagePresentationBuffer,\n} from './core/packagePresentation';\nexport type { PresentationPackagingOptions } from './core/packagePresentation';\n\n// Types\nexport type {\n PptxComponentInput,\n PresentationComponentDefinition,\n SlideComponentDefinition,\n ProcessedPresentation,\n ProcessedSlide,\n PptxThemeConfig,\n PipelineWarning,\n SlideContext,\n SlideRenderContext,\n} from './types';\n\nexport { isPresentationComponent, isSlideComponent } from './types';\n\n// Warning utilities\nexport { W as WarningCodes } from './utils/warn';\nexport type { WarningCode } from './utils/warn';\n\n// Themes\nexport { DEFAULT_PPTX_THEME, getPptxTheme, pptxThemes } from './themes';\n\n// Plugin system\nexport {\n createComponent,\n createVersion,\n createPresentationGenerator,\n resolveComponentVersion,\n validateComponentProps,\n validatePresentation,\n cleanComponentProps,\n ComponentValidationError,\n DuplicateComponentError,\n generatePluginPresentationSchema,\n exportPluginSchema,\n} from './plugin';\n\nexport type {\n CustomComponent,\n ComponentVersion,\n ComponentVersionMap,\n RenderFunction,\n RenderContext,\n PresentationGeneratorOptions,\n PresentationGenerator as PluginPresentationGenerator,\n PresentationGeneratorBuilder,\n BufferGenerationResult as PluginBufferGenerationResult,\n FileGenerationResult as PluginFileGenerationResult,\n GenerateFileOptions as PluginGenerateFileOptions,\n GenerateOptions as PluginGenerateOptions,\n GenerationValidationOptions as PluginGenerationValidationOptions,\n ValidationResult as PluginValidationResult,\n ExtractCustomComponentType,\n CustomComponentUnion,\n ExtendedPptxComponentInput,\n ExtendedPresentationComponent,\n InferBuilderComponents,\n InferDocumentType,\n InferComponentDefinition,\n ComponentValidationResult,\n ValidationError as PluginValidationError,\n} from './plugin';\n\n// Component renderers\nexport {\n renderTextComponent,\n renderImageComponent,\n renderShapeComponent,\n renderTableComponent,\n renderHighchartsComponent,\n renderComponent,\n} from './components';\n"],"mappings":";AAMA,SAAS,qBAAqB;;;ACsOvB,SAAS,wBACd,WAC8C;AAC9C,SACE,OAAO,cAAc,YACrB,cAAc,QACb,UAAkB,SAAS;AAEhC;AAEO,SAAS,iBACd,WAC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A,UAChE;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAKA,WAAS,iBAA0B;AACjC,WAAO;AAAA,MACL,MAAM;AAAA,IACR;AAAA,EACF;AAKA,iBAAe,mBACb,YACA,SACe;AACf,UAAM;AAAA,MACJ,MAAM;AAAA,MACN;AAAA,MACA;AAAA,IACF;AAAA,EACF;AAEA,SAAO,OAAO,OAAO;AAAA,IACnB;AAAA,IACA;AAAA,IACA,gBAAgB;AAAA,IAChB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,cAAc;AAAA,EAChB,CAAC;AACH;AAKO,SAAS,4BACd,UAAwC,CAAC,GACE;AAC3C,QAAM,eAA6B;AAAA,IACjC,YAAY,CAAC;AAAA,IACb,gBAAgB,oBAAI,IAAI;AAAA,IACxB,OAAO,QAAQ;AAAA,IACf,cAAc,QAAQ;AAAA,IACtB,OAAO,QAAQ,SAAS;AAAA,IACxB,UAAU,QAAQ;AAAA,IAClB,OAAO,QAAQ;AAAA,IACf,YAAY,QAAQ;AAAA,IACpB,WAAW;AAAA,MACT,eAAe,QAAQ;AAAA,MACvB,aAAa,QAAQ;AAAA,IACvB;AAAA,IACA,SAAS,QAAQ;AAAA,EACnB;AAEA,SAAO,kBAA+B,YAAY;AACpD;;;AD3iBA,SAAS,2BAAAI,gCAA+B;;;AI5EjC,SAAS,qBAA6B;AAC3C,SAAO;AACT;","names":["mergeWithDefaults","weight","path","result","path","opts","mergeWithDefaults","path","resolveComponentVersion","DuplicateComponentError","ComponentValidationError","validatePresentationDocument","ComponentValidationError","resolveComponentVersion","ComponentValidationError","DuplicateComponentError","pendingFills","pptx","resolveComponentVersion"]}
|