@ncukondo/slide-generation 0.2.3 → 0.2.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/cli/index.ts","../../src/core/parser.ts","../../src/core/transformer.ts","../../src/core/renderer.ts","../../src/core/pipeline.ts","../../src/templates/engine.ts","../../src/templates/loader.ts","../../src/templates/validators.ts","../../src/icons/registry.ts","../../src/icons/schema.ts","../../src/icons/resolver.ts","../../src/references/manager.ts","../../src/references/extractor.ts","../../src/references/formatter.ts","../../src/index.ts","../../src/cli/commands/convert.ts","../../src/config/loader.ts","../../src/config/schema.ts","../../src/images/constants.ts","../../src/images/schema.ts","../../src/images/processing-schema.ts","../../src/images/metadata-loader.ts","../../src/images/validator.ts","../../src/images/processor.ts","../../src/images/processing-pipeline.ts","../../src/cli/commands/validate.ts","../../src/cli/commands/templates.ts","../../src/cli/commands/preview.ts","../../src/cli/commands/icons.ts","../../src/icons/fetcher.ts","../../src/cli/commands/init.ts","../../src/sources/manager.ts","../../src/sources/schema.ts","../../src/sources/importer.ts","../../src/sources/explorer.ts","../../src/cli/templates/ai/skill-md.ts","../../src/cli/templates/ai/claude-md.ts","../../src/cli/templates/ai/agents-md.ts","../../src/cli/templates/ai/opencode-agent.ts","../../src/cli/templates/ai/references/templates-ref.ts","../../src/cli/templates/ai/references/workflows-ref.ts","../../src/cli/templates/ai/commands/slide-create.ts","../../src/cli/templates/ai/commands/slide-validate.ts","../../src/cli/templates/ai/commands/slide-preview.ts","../../src/cli/templates/ai/commands/slide-screenshot.ts","../../src/cli/templates/ai/commands/slide-theme.ts","../../src/cli/commands/watch.ts","../../src/cli/commands/images.ts","../../src/cli/commands/screenshot.ts","../../src/cli/commands/sources.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport { Command } from 'commander';\nimport { VERSION } from '../index.js';\nimport { createConvertCommand } from './commands/convert.js';\nimport { createValidateCommand } from './commands/validate.js';\nimport { createTemplatesCommand } from './commands/templates.js';\nimport { createIconsCommand } from './commands/icons.js';\nimport { createInitCommand } from './commands/init.js';\nimport { createWatchCommand } from './commands/watch.js';\nimport { createPreviewCommand } from './commands/preview.js';\nimport { createImagesCommand } from './commands/images.js';\nimport { createScreenshotCommand } from './commands/screenshot.js';\nimport { createSourcesCommand } from './commands/sources.js';\n\nconst program = new Command();\n\nprogram\n .name('slide-gen')\n .description('Generate Marp-compatible Markdown from YAML source files')\n .version(VERSION);\n\n// Add convert command\nprogram.addCommand(createConvertCommand());\n\n// Add validate command\nprogram.addCommand(createValidateCommand());\n\n// Add templates command\nprogram.addCommand(createTemplatesCommand());\n\n// Add icons command\nprogram.addCommand(createIconsCommand());\n\n// Add init command\nprogram.addCommand(createInitCommand());\n\n// Add watch command\nprogram.addCommand(createWatchCommand());\n\n// Add preview command\nprogram.addCommand(createPreviewCommand());\n\n// Add images command\nprogram.addCommand(createImagesCommand());\n\n// Add screenshot command\nprogram.addCommand(createScreenshotCommand());\n\n// Add sources command\nprogram.addCommand(createSourcesCommand());\n\nprogram.parse();\n","import { z } from 'zod';\nimport { parse as parseYaml, parseDocument, isSeq, isMap, isNode, LineCounter } from 'yaml';\nimport { readFile } from 'fs/promises';\n\n// References config schema\nconst referencesConfigSchema = z.object({\n enabled: z.boolean().default(true),\n style: z.string().default('author-year-pmid'),\n});\n\n// Meta schema\nconst metaSchema = z.object({\n title: z.string(),\n author: z.string().optional(),\n date: z.string().optional(),\n theme: z.string().default('default'),\n references: referencesConfigSchema.optional(),\n});\n\n// Slide schema\nconst slideSchema = z.object({\n template: z.string(),\n content: z.record(z.unknown()).default({}),\n class: z.string().optional(),\n notes: z.string().optional(),\n raw: z.string().optional(),\n});\n\n// Presentation schema\nexport const presentationSchema = z.object({\n meta: metaSchema,\n slides: z.array(slideSchema).default([]),\n});\n\nexport type PresentationMeta = z.infer<typeof metaSchema>;\nexport type ParsedSlide = z.infer<typeof slideSchema>;\nexport type ParsedPresentation = z.infer<typeof presentationSchema>;\n\nexport interface ParseResultWithLines extends ParsedPresentation {\n slideLines: number[];\n}\n\nexport class ParseError extends Error {\n constructor(\n message: string,\n public details?: unknown\n ) {\n super(message);\n this.name = 'ParseError';\n }\n}\n\nexport class ValidationError extends Error {\n constructor(\n message: string,\n public details?: unknown\n ) {\n super(message);\n this.name = 'ValidationError';\n }\n}\n\nexport class Parser {\n parse(yamlContent: string): ParsedPresentation {\n let rawData: unknown;\n\n try {\n rawData = parseYaml(yamlContent);\n } catch (error) {\n throw new ParseError('Failed to parse YAML', error);\n }\n\n const result = presentationSchema.safeParse(rawData);\n\n if (!result.success) {\n throw new ValidationError(\n 'Schema validation failed',\n result.error.format()\n );\n }\n\n return result.data;\n }\n\n async parseFile(filePath: string): Promise<ParsedPresentation> {\n let content: string;\n\n try {\n content = await readFile(filePath, 'utf-8');\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n throw new ParseError(`File not found: ${filePath}`);\n }\n throw new ParseError(`Failed to read file: ${filePath}`, error);\n }\n\n return this.parse(content);\n }\n\n parseWithLineInfo(yamlContent: string): ParseResultWithLines {\n const lineCounter = new LineCounter();\n const doc = parseDocument(yamlContent, { lineCounter });\n\n // Check for YAML parsing errors\n if (doc.errors && doc.errors.length > 0) {\n throw new ParseError('Failed to parse YAML', doc.errors);\n }\n\n // Extract line numbers for slides\n const slideLines: number[] = [];\n const contents = doc.contents;\n\n if (isMap(contents)) {\n const slidesNode = contents.get('slides', true);\n if (isSeq(slidesNode)) {\n for (const item of slidesNode.items) {\n if (isNode(item) && item.range) {\n const pos = lineCounter.linePos(item.range[0]);\n slideLines.push(pos.line);\n }\n }\n }\n }\n\n // Validate with schema\n const rawData = doc.toJSON();\n const result = presentationSchema.safeParse(rawData);\n\n if (!result.success) {\n throw new ValidationError(\n 'Schema validation failed',\n result.error.format()\n );\n }\n\n return {\n ...result.data,\n slideLines,\n };\n }\n\n async parseFileWithLineInfo(filePath: string): Promise<ParseResultWithLines> {\n let content: string;\n\n try {\n content = await readFile(filePath, 'utf-8');\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n throw new ParseError(`File not found: ${filePath}`);\n }\n throw new ParseError(`Failed to read file: ${filePath}`, error);\n }\n\n return this.parseWithLineInfo(content);\n }\n}\n","import type { TemplateEngine, IconsHelper, RefsHelper } from '../templates/engine';\nimport type { TemplateLoader } from '../templates/loader';\nimport type { IconResolver } from '../icons/resolver';\nimport type { CitationFormatter } from '../references/formatter';\nimport type { ParsedSlide, ParsedPresentation, PresentationMeta } from './parser';\n\n// Placeholder patterns for async resolution\nconst ICON_PLACEHOLDER_PREFIX = '___ICON_PLACEHOLDER_';\nconst ICON_PLACEHOLDER_SUFFIX = '___';\nconst REFS_CITE_PLACEHOLDER_PREFIX = '___REFS_CITE_PLACEHOLDER_';\nconst REFS_CITE_PLACEHOLDER_SUFFIX = '___';\nconst REFS_EXPAND_PLACEHOLDER_PREFIX = '___REFS_EXPAND_PLACEHOLDER_';\nconst REFS_EXPAND_PLACEHOLDER_SUFFIX = '___';\n\n/**\n * Context passed to each slide transformation\n */\nexport interface TransformContext {\n meta: PresentationMeta;\n slideIndex: number;\n totalSlides: number;\n}\n\n/**\n * Error thrown when transformation fails\n */\nexport class TransformError extends Error {\n constructor(\n message: string,\n public slide?: ParsedSlide,\n public details?: unknown\n ) {\n super(message);\n this.name = 'TransformError';\n }\n}\n\n/**\n * Pending async operations collected during template rendering\n */\ninterface PendingOperations {\n icons: Map<string, { name: string; options: Record<string, unknown> | undefined }>;\n cites: Map<string, string>;\n expands: Map<string, string>;\n}\n\n/**\n * Transformer applies templates to slides and generates HTML content\n */\nexport class Transformer {\n constructor(\n private templateEngine: TemplateEngine,\n private templateLoader: TemplateLoader,\n private iconResolver: IconResolver,\n private citationFormatter: CitationFormatter\n ) {}\n\n /**\n * Transform a single slide using its template\n */\n async transform(slide: ParsedSlide, context: TransformContext): Promise<string> {\n // Handle raw template - return raw content directly\n if (slide.template === 'raw') {\n return slide.raw ?? '';\n }\n\n // Get the template definition\n const template = this.templateLoader.get(slide.template);\n if (!template) {\n throw new TransformError(\n `Template \"${slide.template}\" not found`,\n slide\n );\n }\n\n // Validate content against template schema\n const validationResult = this.templateLoader.validateContent(\n slide.template,\n slide.content\n );\n if (!validationResult.valid) {\n throw new TransformError(\n `Slide content validation failed: ${validationResult.errors?.join(', ')}`,\n slide,\n validationResult.errors\n );\n }\n\n // Build template context with helpers that use placeholders\n const pending: PendingOperations = {\n icons: new Map(),\n cites: new Map(),\n expands: new Map(),\n };\n const templateContext = this.buildTemplateContext(slide, context, pending);\n\n // Render the template (synchronous, with placeholders)\n let output = this.templateEngine.render(template.output, templateContext);\n\n // Resolve all async operations and replace placeholders\n output = await this.resolvePlaceholders(output, pending);\n\n // Add CSS class directive if specified\n if (slide.class) {\n output = `<!-- _class: ${slide.class} -->\\n${output}`;\n }\n\n return output.trim();\n }\n\n /**\n * Transform all slides in a presentation\n */\n async transformAll(presentation: ParsedPresentation): Promise<string[]> {\n const results: string[] = [];\n const totalSlides = presentation.slides.length;\n\n for (let i = 0; i < presentation.slides.length; i++) {\n const slide = presentation.slides[i]!;\n const context: TransformContext = {\n meta: presentation.meta,\n slideIndex: i,\n totalSlides,\n };\n\n const transformed = await this.transform(slide, context);\n results.push(transformed);\n }\n\n return results;\n }\n\n /**\n * Build the full template context with helpers that collect async operations\n */\n private buildTemplateContext(\n slide: ParsedSlide,\n context: TransformContext,\n pending: PendingOperations\n ): Record<string, unknown> {\n let iconCounter = 0;\n let citeCounter = 0;\n let expandCounter = 0;\n\n // Create icons helper that returns placeholders\n const icons: IconsHelper = {\n render: (name: string, options?: Record<string, unknown>) => {\n const id = `${iconCounter++}`;\n const placeholder = `${ICON_PLACEHOLDER_PREFIX}${id}${ICON_PLACEHOLDER_SUFFIX}`;\n pending.icons.set(id, { name, options });\n return placeholder;\n },\n };\n\n // Create refs helper that returns placeholders\n const refs: RefsHelper = {\n cite: (id: string) => {\n const counterId = `${citeCounter++}`;\n const placeholder = `${REFS_CITE_PLACEHOLDER_PREFIX}${counterId}${REFS_CITE_PLACEHOLDER_SUFFIX}`;\n pending.cites.set(counterId, id);\n return placeholder;\n },\n expand: (text: string) => {\n const counterId = `${expandCounter++}`;\n const placeholder = `${REFS_EXPAND_PLACEHOLDER_PREFIX}${counterId}${REFS_EXPAND_PLACEHOLDER_SUFFIX}`;\n pending.expands.set(counterId, text);\n return placeholder;\n },\n };\n\n return {\n content: slide.content,\n meta: {\n title: context.meta.title,\n author: context.meta.author,\n theme: context.meta.theme,\n },\n slide: {\n index: context.slideIndex,\n total: context.totalSlides,\n },\n icons,\n refs,\n };\n }\n\n /**\n * Resolve all placeholders by executing async operations\n */\n private async resolvePlaceholders(\n output: string,\n pending: PendingOperations\n ): Promise<string> {\n // Resolve icons\n const iconResults = new Map<string, string>();\n for (const [id, { name, options }] of pending.icons) {\n const rendered = await this.iconResolver.render(\n name,\n options as { size?: string; color?: string; class?: string } | undefined\n );\n iconResults.set(id, rendered);\n }\n\n // Resolve citations\n const citeResults = new Map<string, string>();\n for (const [counterId, id] of pending.cites) {\n const formatted = await this.citationFormatter.formatInline(id);\n citeResults.set(counterId, formatted);\n }\n\n // Resolve citation expansions\n const expandResults = new Map<string, string>();\n for (const [counterId, text] of pending.expands) {\n const expanded = await this.citationFormatter.expandCitations(text);\n expandResults.set(counterId, expanded);\n }\n\n // Replace all placeholders\n let result = output;\n\n for (const [id, rendered] of iconResults) {\n const placeholder = `${ICON_PLACEHOLDER_PREFIX}${id}${ICON_PLACEHOLDER_SUFFIX}`;\n result = result.replace(placeholder, rendered);\n }\n\n for (const [counterId, formatted] of citeResults) {\n const placeholder = `${REFS_CITE_PLACEHOLDER_PREFIX}${counterId}${REFS_CITE_PLACEHOLDER_SUFFIX}`;\n result = result.replace(placeholder, formatted);\n }\n\n for (const [counterId, expanded] of expandResults) {\n const placeholder = `${REFS_EXPAND_PLACEHOLDER_PREFIX}${counterId}${REFS_EXPAND_PLACEHOLDER_SUFFIX}`;\n result = result.replace(placeholder, expanded);\n }\n\n return result;\n }\n}\n","import type { PresentationMeta } from './parser';\n\n/**\n * Options for rendering the final Marp markdown\n */\nexport interface RenderOptions {\n /** Include theme in front matter (default: true) */\n includeTheme?: boolean;\n /** Speaker notes for each slide (indexed by slide position) */\n notes?: (string | undefined)[];\n /** Additional front matter properties */\n additionalFrontMatter?: Record<string, unknown>;\n}\n\n/**\n * Renderer combines transformed slides into Marp-compatible Markdown\n */\nexport class Renderer {\n /**\n * Render slides and metadata into final Marp markdown\n */\n render(\n slides: string[],\n meta: PresentationMeta,\n options?: RenderOptions\n ): string {\n const frontMatter = this.renderFrontMatter(meta, options);\n const slidesContent = this.joinSlides(slides, options?.notes);\n\n if (slides.length === 0) {\n return frontMatter;\n }\n\n return `${frontMatter}\\n\\n${slidesContent}`;\n }\n\n /**\n * Render the YAML front matter block\n */\n private renderFrontMatter(\n meta: PresentationMeta,\n options?: RenderOptions\n ): string {\n const lines: string[] = ['---', 'marp: true'];\n\n // Add title\n lines.push(`title: ${meta.title}`);\n\n // Add author if present\n if (meta.author) {\n lines.push(`author: ${meta.author}`);\n }\n\n // Add date if present\n if (meta.date) {\n lines.push(`date: ${meta.date}`);\n }\n\n // Add theme if enabled (default: true)\n const includeTheme = options?.includeTheme ?? true;\n if (includeTheme && meta.theme) {\n lines.push(`theme: ${meta.theme}`);\n }\n\n // Add additional front matter properties\n if (options?.additionalFrontMatter) {\n for (const [key, value] of Object.entries(options.additionalFrontMatter)) {\n lines.push(`${key}: ${this.formatFrontMatterValue(value)}`);\n }\n }\n\n lines.push('---');\n\n return lines.join('\\n');\n }\n\n /**\n * Format a front matter value for YAML\n */\n private formatFrontMatterValue(value: unknown): string {\n if (typeof value === 'boolean') {\n return value ? 'true' : 'false';\n }\n if (typeof value === 'number') {\n return String(value);\n }\n if (typeof value === 'string') {\n // Quote if contains special characters\n if (/[:#[\\]{}|>]/.test(value)) {\n return `\"${value.replace(/\"/g, '\\\\\"')}\"`;\n }\n return value;\n }\n return String(value);\n }\n\n /**\n * Join slides with Marp slide separator\n */\n private joinSlides(\n slides: string[],\n notes?: (string | undefined)[]\n ): string {\n const parts: string[] = [];\n\n for (let i = 0; i < slides.length; i++) {\n let slideContent = slides[i]!;\n\n // Add speaker notes if present\n const note = notes?.[i];\n if (note && note.trim()) {\n slideContent = `${slideContent}\\n\\n${this.renderSpeakerNotes(note)}`;\n }\n\n parts.push(slideContent);\n }\n\n // Join with Marp slide separator (---)\n return parts.map(slide => `---\\n\\n${slide}`).join('\\n\\n');\n }\n\n /**\n * Render speaker notes as HTML comment\n */\n private renderSpeakerNotes(notes: string): string {\n return `<!--\\n${notes}\\n-->`;\n }\n}\n","import { writeFile } from 'fs/promises';\nimport { Parser, type ParsedPresentation } from './parser';\nimport { Transformer } from './transformer';\nimport { Renderer, type RenderOptions } from './renderer';\nimport { TemplateEngine } from '../templates/engine';\nimport { TemplateLoader } from '../templates/loader';\nimport { IconRegistryLoader } from '../icons/registry';\nimport { IconResolver } from '../icons/resolver';\nimport { ReferenceManager, type CSLItem } from '../references/manager';\nimport { CitationExtractor } from '../references/extractor';\nimport { CitationFormatter } from '../references/formatter';\nimport type { Config } from '../config/schema';\n\n/**\n * Options for the Pipeline\n */\nexport interface PipelineOptions {\n /** Custom config path override */\n configPath?: string;\n /** Output file path (if not specified, returns string only) */\n outputPath?: string;\n /** Enable verbose/progress output */\n verbose?: boolean;\n}\n\n/**\n * Result of a pipeline run\n */\nexport interface PipelineResult {\n /** Generated Marp markdown */\n output: string;\n /** Citation IDs found in the presentation */\n citations: string[];\n /** Warnings generated during processing */\n warnings: string[];\n /** Number of slides processed */\n slideCount: number;\n}\n\n/**\n * Error thrown when pipeline processing fails\n */\nexport class PipelineError extends Error {\n constructor(\n message: string,\n public stage: string,\n public details?: unknown\n ) {\n super(message);\n this.name = 'PipelineError';\n }\n}\n\n/**\n * Pipeline orchestrates the full YAML to Marp markdown conversion\n *\n * Stages:\n * 1. Parse Source - Load and validate YAML\n * 2. Collect Citations - Extract citation IDs from all slides\n * 3. Resolve References - Fetch bibliography data\n * 4. Transform Slides - Apply templates and resolve icons/citations\n * 5. Render Output - Generate final Marp markdown\n */\nexport class Pipeline {\n private parser: Parser;\n private templateEngine: TemplateEngine;\n private templateLoader: TemplateLoader;\n private iconRegistry: IconRegistryLoader;\n private iconResolver: IconResolver;\n private referenceManager: ReferenceManager;\n private citationExtractor: CitationExtractor;\n private citationFormatter: CitationFormatter;\n private transformer: Transformer;\n private renderer: Renderer;\n private warnings: string[] = [];\n\n constructor(private config: Config) {\n // Initialize all components\n this.parser = new Parser();\n this.templateEngine = new TemplateEngine();\n this.templateLoader = new TemplateLoader();\n this.iconRegistry = new IconRegistryLoader();\n this.iconResolver = new IconResolver(this.iconRegistry);\n this.referenceManager = new ReferenceManager(\n config.references.connection.command\n );\n this.citationExtractor = new CitationExtractor();\n this.citationFormatter = new CitationFormatter(\n this.referenceManager,\n {\n author: {\n maxAuthors: config.references.format.maxAuthors,\n etAl: config.references.format.etAl,\n etAlJa: config.references.format.etAlJa,\n },\n inline: {\n authorSep: config.references.format.authorSep,\n identifierSep: config.references.format.identifierSep,\n },\n }\n );\n this.transformer = new Transformer(\n this.templateEngine,\n this.templateLoader,\n this.iconResolver,\n this.citationFormatter\n );\n this.renderer = new Renderer();\n }\n\n /**\n * Run the full conversion pipeline\n */\n async run(inputPath: string, options?: PipelineOptions): Promise<string> {\n this.warnings = [];\n\n try {\n // Stage 1: Parse Source\n const presentation = await this.parseSource(inputPath);\n\n // Stage 2: Collect Citations\n const citationIds = this.collectCitations(presentation);\n\n // Stage 3: Resolve References\n await this.resolveReferences(citationIds);\n\n // Stage 4: Transform Slides\n const transformedSlides = await this.transformSlides(presentation);\n\n // Stage 5: Render Output\n const output = this.render(transformedSlides, presentation);\n\n // Write output file if specified\n if (options?.outputPath) {\n await writeFile(options.outputPath, output, 'utf-8');\n }\n\n return output;\n } catch (error) {\n if (error instanceof PipelineError) {\n throw error;\n }\n throw new PipelineError(\n error instanceof Error ? error.message : 'Unknown error',\n 'unknown',\n error\n );\n }\n }\n\n /**\n * Run the full pipeline with detailed result\n */\n async runWithResult(\n inputPath: string,\n options?: PipelineOptions\n ): Promise<PipelineResult> {\n this.warnings = [];\n\n try {\n // Stage 1: Parse Source\n const presentation = await this.parseSource(inputPath);\n\n // Stage 2: Collect Citations\n const citationIds = this.collectCitations(presentation);\n\n // Stage 3: Resolve References\n await this.resolveReferences(citationIds);\n\n // Stage 4: Transform Slides\n const transformedSlides = await this.transformSlides(presentation);\n\n // Stage 5: Render Output\n const output = this.render(transformedSlides, presentation);\n\n // Write output file if specified\n if (options?.outputPath) {\n await writeFile(options.outputPath, output, 'utf-8');\n }\n\n return {\n output,\n citations: citationIds,\n warnings: this.warnings,\n slideCount: presentation.slides.length,\n };\n } catch (error) {\n if (error instanceof PipelineError) {\n throw error;\n }\n throw new PipelineError(\n error instanceof Error ? error.message : 'Unknown error',\n 'unknown',\n error\n );\n }\n }\n\n /**\n * Initialize the pipeline by loading templates and icon registry\n */\n async initialize(): Promise<void> {\n try {\n // Load built-in templates\n await this.templateLoader.loadBuiltIn(this.config.templates.builtin);\n\n // Load custom templates if specified\n if (this.config.templates.custom) {\n await this.templateLoader.loadCustom(this.config.templates.custom);\n }\n\n // Load icon registry\n await this.iconRegistry.load(this.config.icons.registry);\n } catch (error) {\n throw new PipelineError(\n `Failed to initialize pipeline: ${error instanceof Error ? error.message : 'Unknown error'}`,\n 'initialize',\n error\n );\n }\n }\n\n /**\n * Get collected warnings\n */\n getWarnings(): string[] {\n return [...this.warnings];\n }\n\n // --- Private Stage Methods ---\n\n /**\n * Stage 1: Parse the YAML source file\n */\n private async parseSource(inputPath: string): Promise<ParsedPresentation> {\n try {\n return await this.parser.parseFile(inputPath);\n } catch (error) {\n throw new PipelineError(\n `Failed to parse source file: ${error instanceof Error ? error.message : 'Unknown error'}`,\n 'parse',\n error\n );\n }\n }\n\n /**\n * Stage 2: Collect all citation IDs from the presentation\n */\n private collectCitations(presentation: ParsedPresentation): string[] {\n const citations = this.citationExtractor.extractFromPresentation(presentation);\n return this.citationExtractor.getUniqueIds(citations);\n }\n\n /**\n * Stage 3: Resolve references from the reference manager\n */\n private async resolveReferences(ids: string[]): Promise<Map<string, CSLItem>> {\n if (!this.config.references.enabled || ids.length === 0) {\n return new Map();\n }\n\n try {\n const items = await this.referenceManager.getByIds(ids);\n\n // Warn about missing references\n for (const id of ids) {\n if (!items.has(id)) {\n this.warnings.push(`Reference not found: ${id}`);\n }\n }\n\n return items;\n } catch (error) {\n // Non-fatal: log warning and continue\n this.warnings.push(\n `Failed to resolve references: ${error instanceof Error ? error.message : 'Unknown error'}`\n );\n return new Map();\n }\n }\n\n /**\n * Stage 4: Transform all slides using templates\n */\n private async transformSlides(\n presentation: ParsedPresentation\n ): Promise<string[]> {\n try {\n return await this.transformer.transformAll(presentation);\n } catch (error) {\n throw new PipelineError(\n `Failed to transform slides: ${error instanceof Error ? error.message : 'Unknown error'}`,\n 'transform',\n error\n );\n }\n }\n\n /**\n * Stage 5: Render the final Marp markdown\n */\n private render(\n slides: string[],\n presentation: ParsedPresentation\n ): string {\n try {\n // Collect notes from slides\n const notes = presentation.slides.map((slide) => slide.notes);\n\n const renderOptions: RenderOptions = {\n includeTheme: true,\n notes,\n };\n\n return this.renderer.render(slides, presentation.meta, renderOptions);\n } catch (error) {\n throw new PipelineError(\n `Failed to render output: ${error instanceof Error ? error.message : 'Unknown error'}`,\n 'render',\n error\n );\n }\n }\n}\n","import nunjucks from \"nunjucks\";\n\n/**\n * Icons helper interface for template rendering\n */\nexport interface IconsHelper {\n render: (name: string, options?: Record<string, unknown>) => string;\n}\n\n/**\n * References helper interface for citation handling\n */\nexport interface RefsHelper {\n cite: (id: string) => string;\n expand: (text: string) => string;\n}\n\n/**\n * Slide context passed to templates\n */\nexport interface SlideContext {\n index: number;\n total: number;\n}\n\n/**\n * Meta context for presentation metadata\n */\nexport interface MetaContext {\n title: string;\n author?: string;\n theme: string;\n [key: string]: unknown;\n}\n\n/**\n * Full template context interface\n */\nexport interface TemplateContext {\n content: Record<string, unknown>;\n meta: MetaContext;\n slide: SlideContext;\n icons: IconsHelper;\n refs: RefsHelper;\n [key: string]: unknown;\n}\n\nexport class TemplateEngine {\n private env: nunjucks.Environment;\n\n constructor() {\n this.env = new nunjucks.Environment(null, {\n autoescape: false, // HTML output for Marp\n throwOnUndefined: false,\n });\n this.registerFilters();\n this.registerGlobals();\n }\n\n render(template: string, context: Record<string, unknown>): string {\n return this.env.renderString(template, context);\n }\n\n private registerFilters(): void {\n // Will be extended in later steps\n }\n\n private registerGlobals(): void {\n // Icon helper stub - will be replaced with real implementation\n const icons = {\n render: (name: string, options?: Record<string, unknown>): string => {\n const size = (options?.[\"size\"] as string) ?? \"24px\";\n const color = (options?.[\"color\"] as string) ?? \"currentColor\";\n return `<span class=\"icon icon-${name}\" style=\"font-size: ${size}; color: ${color};\">[${name}]</span>`;\n },\n };\n\n this.env.addGlobal(\"icons\", icons);\n\n // Reference helper stub - will be replaced with real implementation\n const refs = {\n cite: (id: string): string => {\n const cleanId = id.replace(\"@\", \"\");\n return `(${cleanId})`;\n },\n expand: (text: string): string => {\n // Simple stub - replace [@id] with (id)\n return text.replace(/\\[@(\\w+)\\]/g, \"($1)\");\n },\n };\n\n this.env.addGlobal(\"refs\", refs);\n }\n}\n","import { z } from \"zod\";\nimport * as yaml from \"yaml\";\nimport * as fs from \"node:fs/promises\";\nimport * as path from \"node:path\";\nimport {\n validateWithJsonSchema,\n type JsonSchema,\n type ValidationResult,\n} from \"./validators\";\n\n/**\n * JSON Schema-like structure for template content validation\n */\nconst jsonSchemaSchema = z.record(z.unknown());\n\n/**\n * Template definition schema - validates YAML template definition files\n */\nexport const templateDefSchema = z.object({\n name: z.string().min(1, \"Template name is required\"),\n description: z.string(),\n category: z.string(),\n schema: jsonSchemaSchema,\n example: z.record(z.unknown()).optional(),\n output: z.string().min(1, \"Template output is required\"),\n css: z.string().optional(),\n});\n\n/**\n * Template definition type derived from schema\n */\nexport type TemplateDefinition = z.infer<typeof templateDefSchema>;\n\n/**\n * Loads and manages template definitions from YAML files\n */\nexport class TemplateLoader {\n private templates: Map<string, TemplateDefinition>;\n\n constructor() {\n this.templates = new Map();\n }\n\n /**\n * Load a template from a YAML string\n */\n async loadFromString(yamlContent: string): Promise<void> {\n const parsed = yaml.parse(yamlContent);\n const result = templateDefSchema.safeParse(parsed);\n\n if (!result.success) {\n const errors = result.error.errors\n .map(e => `${e.path.join(\".\")}: ${e.message}`)\n .join(\", \");\n throw new Error(`Invalid template definition: ${errors}`);\n }\n\n this.templates.set(result.data.name, result.data);\n }\n\n /**\n * Load a template from a file\n */\n async loadFromFile(filePath: string): Promise<void> {\n const content = await fs.readFile(filePath, \"utf-8\");\n await this.loadFromString(content);\n }\n\n /**\n * Load all templates from a directory (recursively)\n */\n async loadBuiltIn(directory: string): Promise<void> {\n await this.loadDirectory(directory);\n }\n\n /**\n * Load custom templates from a directory (can override built-in)\n */\n async loadCustom(directory: string): Promise<void> {\n await this.loadDirectory(directory);\n }\n\n /**\n * Internal method to load templates from a directory\n */\n private async loadDirectory(directory: string): Promise<void> {\n const entries = await fs.readdir(directory, { withFileTypes: true });\n\n for (const entry of entries) {\n const fullPath = path.join(directory, entry.name);\n\n if (entry.isDirectory()) {\n await this.loadDirectory(fullPath);\n } else if (entry.isFile() && (entry.name.endsWith(\".yaml\") || entry.name.endsWith(\".yml\"))) {\n await this.loadFromFile(fullPath);\n }\n }\n }\n\n /**\n * Get a template by name\n */\n get(name: string): TemplateDefinition | undefined {\n return this.templates.get(name);\n }\n\n /**\n * List all loaded templates\n */\n list(): TemplateDefinition[] {\n return Array.from(this.templates.values());\n }\n\n /**\n * List templates filtered by category\n */\n listByCategory(category: string): TemplateDefinition[] {\n return this.list().filter(t => t.category === category);\n }\n\n /**\n * Validate content against a template's schema\n */\n validateContent(templateName: string, content: unknown): ValidationResult {\n const template = this.get(templateName);\n\n if (!template) {\n return {\n valid: false,\n errors: [`Template \"${templateName}\" not found`],\n };\n }\n\n return validateWithJsonSchema(template.schema as JsonSchema, content);\n }\n}\n\nexport type { ValidationResult };\n","import { z, type ZodTypeAny, type ZodIssue } from \"zod\";\n\n/**\n * JSON Schema type definition (subset used by templates)\n */\nexport interface JsonSchema {\n type?: string;\n required?: string[];\n properties?: Record<string, JsonSchema>;\n items?: JsonSchema;\n minItems?: number;\n maxItems?: number;\n pattern?: string;\n enum?: (string | number | boolean)[];\n default?: unknown;\n description?: string;\n oneOf?: JsonSchema[];\n}\n\n/**\n * Validation result for content against template schema\n */\nexport interface ValidationResult {\n valid: boolean;\n errors: string[];\n}\n\n/**\n * Convert a JSON Schema object to a Zod schema\n *\n * Supports a subset of JSON Schema used by template definitions:\n * - Basic types: string, number, boolean, array, object\n * - Required fields\n * - Nested objects and arrays\n * - Pattern validation for strings\n * - minItems/maxItems for arrays\n */\nexport function jsonSchemaToZod(schema: JsonSchema): ZodTypeAny {\n // Handle oneOf first (union type)\n if (schema.oneOf && schema.oneOf.length > 0) {\n const schemas = schema.oneOf.map((s) => jsonSchemaToZod(s));\n if (schemas.length === 1) {\n return schemas[0]!;\n }\n // z.union requires at least 2 schemas\n return z.union(schemas as [ZodTypeAny, ZodTypeAny, ...ZodTypeAny[]]);\n }\n\n const type = schema.type ?? \"object\";\n\n switch (type) {\n case \"string\": {\n // Handle enum first (enum values are always valid)\n if (schema.enum && schema.enum.length > 0) {\n const enumValues = schema.enum as [string, ...string[]];\n return z.enum(enumValues);\n }\n\n let zodSchema = z.string();\n if (schema.pattern) {\n zodSchema = zodSchema.regex(new RegExp(schema.pattern));\n }\n return zodSchema;\n }\n\n case \"number\":\n return z.number();\n\n case \"integer\":\n return z.number().int();\n\n case \"boolean\":\n return z.boolean();\n\n case \"array\": {\n const itemSchema = schema.items ? jsonSchemaToZod(schema.items) : z.unknown();\n let arraySchema = z.array(itemSchema);\n\n if (schema.minItems !== undefined) {\n arraySchema = arraySchema.min(schema.minItems);\n }\n if (schema.maxItems !== undefined) {\n arraySchema = arraySchema.max(schema.maxItems);\n }\n\n return arraySchema;\n }\n\n case \"object\": {\n if (!schema.properties) {\n return z.record(z.unknown());\n }\n\n const shape: Record<string, ZodTypeAny> = {};\n const required = new Set(schema.required ?? []);\n\n for (const [key, propSchema] of Object.entries(schema.properties)) {\n const propZod = jsonSchemaToZod(propSchema);\n shape[key] = required.has(key) ? propZod : propZod.optional();\n }\n\n return z.object(shape).passthrough();\n }\n\n default:\n return z.unknown();\n }\n}\n\n/**\n * Validate content against a JSON Schema\n */\nexport function validateWithJsonSchema(\n schema: JsonSchema,\n content: unknown\n): ValidationResult {\n const zodSchema = jsonSchemaToZod(schema);\n const result = zodSchema.safeParse(content);\n\n if (result.success) {\n return { valid: true, errors: [] };\n }\n\n const errors = result.error.errors.map((issue: ZodIssue) => {\n const path = issue.path.join(\".\");\n return path ? `${path}: ${issue.message}` : issue.message;\n });\n\n return { valid: false, errors };\n}\n","import * as fs from \"node:fs/promises\";\nimport { parse as parseYaml } from \"yaml\";\nimport {\n iconRegistrySchema,\n type IconRegistry,\n type IconSource,\n type IconDefaults,\n} from \"./schema.js\";\n\n/**\n * Parsed icon reference with prefix and name\n */\nexport interface ParsedIconReference {\n prefix: string;\n name: string;\n}\n\n/**\n * Icon Registry Loader - loads and manages icon registry configuration\n */\nexport class IconRegistryLoader {\n private registry: IconRegistry | null = null;\n private sourcesByPrefix: Map<string, IconSource> = new Map();\n private aliasMap: Map<string, string> = new Map();\n private colorMap: Map<string, string> = new Map();\n\n /**\n * Load registry from YAML file\n */\n async load(configPath: string): Promise<IconRegistry> {\n const content = await fs.readFile(configPath, \"utf-8\");\n const parsed = parseYaml(content);\n const validated = iconRegistrySchema.parse(parsed);\n\n this.registry = validated;\n this.buildMaps();\n\n return validated;\n }\n\n /**\n * Resolve an alias to its icon reference\n * @returns The resolved icon reference or the original name if not an alias\n */\n resolveAlias(nameOrAlias: string): string {\n return this.aliasMap.get(nameOrAlias) ?? nameOrAlias;\n }\n\n /**\n * Get icon source by prefix\n */\n getSource(prefix: string): IconSource | undefined {\n return this.sourcesByPrefix.get(prefix);\n }\n\n /**\n * Parse an icon reference string (e.g., \"mi:home\" or \"iconify:mdi:account\")\n * @returns Parsed reference or null if invalid format\n */\n parseIconReference(reference: string): ParsedIconReference | null {\n const colonIndex = reference.indexOf(\":\");\n if (colonIndex === -1) {\n return null;\n }\n\n const prefix = reference.substring(0, colonIndex);\n const name = reference.substring(colonIndex + 1);\n\n return { prefix, name };\n }\n\n /**\n * Get registry defaults\n */\n getDefaults(): IconDefaults {\n if (!this.registry) {\n return { size: \"24px\", color: \"currentColor\" };\n }\n return this.registry.defaults;\n }\n\n /**\n * Get color by name from color palette\n */\n getColor(name: string): string | undefined {\n return this.colorMap.get(name);\n }\n\n /**\n * Get all sources\n */\n getSources(): IconSource[] {\n return this.registry?.sources ?? [];\n }\n\n /**\n * Get all aliases\n */\n getAliases(): Record<string, string> {\n return this.registry?.aliases ?? {};\n }\n\n /**\n * Check if registry is loaded\n */\n isLoaded(): boolean {\n return this.registry !== null;\n }\n\n /**\n * Build internal lookup maps from registry\n */\n private buildMaps(): void {\n this.sourcesByPrefix.clear();\n this.aliasMap.clear();\n this.colorMap.clear();\n\n if (!this.registry) {\n return;\n }\n\n // Build sources map\n for (const source of this.registry.sources) {\n this.sourcesByPrefix.set(source.prefix, source);\n }\n\n // Build aliases map\n for (const [alias, target] of Object.entries(this.registry.aliases)) {\n this.aliasMap.set(alias, target);\n }\n\n // Build colors map\n if (this.registry.colors) {\n for (const [name, color] of Object.entries(this.registry.colors)) {\n this.colorMap.set(name, color);\n }\n }\n }\n}\n","import { z } from \"zod\";\n\n/**\n * Schema for icon source types\n */\nexport const iconSourceTypeSchema = z.enum([\n \"web-font\",\n \"svg-inline\",\n \"svg-sprite\",\n \"local-svg\",\n]);\n\nexport type IconSourceType = z.infer<typeof iconSourceTypeSchema>;\n\n/**\n * Schema for individual icon source definition\n */\nexport const iconSourceSchema = z.object({\n name: z.string(),\n type: iconSourceTypeSchema,\n prefix: z.string(),\n url: z.string().optional(),\n path: z.string().optional(),\n render: z.string().optional(),\n});\n\nexport type IconSource = z.infer<typeof iconSourceSchema>;\n\n/**\n * Schema for icon defaults\n */\nexport const iconDefaultsSchema = z.object({\n size: z.string().default(\"24px\"),\n color: z.string().default(\"currentColor\"),\n});\n\nexport type IconDefaults = z.infer<typeof iconDefaultsSchema>;\n\n/**\n * Schema for the full icon registry configuration\n */\nexport const iconRegistrySchema = z.object({\n sources: z.array(iconSourceSchema),\n aliases: z.record(z.string()).default({}),\n colors: z.record(z.string()).optional(),\n defaults: iconDefaultsSchema.default({}),\n});\n\nexport type IconRegistry = z.infer<typeof iconRegistrySchema>;\n","import * as fs from \"node:fs/promises\";\nimport * as path from \"node:path\";\nimport nunjucks from \"nunjucks\";\nimport { IconRegistryLoader } from \"./registry.js\";\nimport type { IconSource } from \"./schema.js\";\n\n/**\n * Options for rendering an icon\n */\nexport interface IconOptions {\n size?: string;\n color?: string;\n class?: string;\n}\n\n/**\n * Options for the IconResolver\n */\nexport interface IconResolverOptions {\n /** Use CSS variables for theme colors (e.g., var(--theme-primary)) */\n useThemeVariables?: boolean;\n}\n\n/**\n * Icon Resolver - renders icons from various sources\n */\nexport class IconResolver {\n private nunjucksEnv: nunjucks.Environment;\n private options: IconResolverOptions;\n\n constructor(private registry: IconRegistryLoader, options: IconResolverOptions = {}) {\n this.nunjucksEnv = new nunjucks.Environment(null, {\n autoescape: false,\n });\n this.options = options;\n }\n\n /**\n * Render an icon by name or alias\n */\n async render(nameOrAlias: string, options?: IconOptions): Promise<string> {\n // Resolve alias if needed\n const resolved = this.registry.resolveAlias(nameOrAlias);\n\n // Parse the icon reference\n const parsed = this.registry.parseIconReference(resolved);\n if (!parsed) {\n throw new Error(\n `Invalid icon reference format: \"${resolved}\". Expected format: \"prefix:name\"`\n );\n }\n\n // Get the source for this prefix\n const source = this.registry.getSource(parsed.prefix);\n if (!source) {\n throw new Error(`Unknown icon source prefix: \"${parsed.prefix}\"`);\n }\n\n // Get defaults and merge options\n const defaults = this.registry.getDefaults();\n const mergedOptions: Required<Omit<IconOptions, \"class\">> & Pick<IconOptions, \"class\"> = {\n size: options?.size ?? defaults.size,\n color: this.resolveColor(options?.color) ?? defaults.color,\n ...(options?.class !== undefined ? { class: options.class } : {}),\n };\n\n // Render based on source type\n switch (source.type) {\n case \"web-font\":\n return this.renderWebFont(source, parsed.name, mergedOptions);\n case \"local-svg\":\n return await this.renderLocalSvg(source, parsed.name, mergedOptions);\n case \"svg-inline\":\n return await this.renderSvgInline(source, parsed.name, mergedOptions);\n case \"svg-sprite\":\n return this.renderSvgSprite(source, parsed.name, mergedOptions);\n default:\n throw new Error(`Unsupported icon source type: \"${source.type}\"`);\n }\n }\n\n /**\n * Render a web-font icon\n */\n private renderWebFont(\n source: IconSource,\n name: string,\n options: IconOptions\n ): string {\n const style = this.buildStyle(options);\n const className = this.buildClassName(name, options);\n\n if (source.render) {\n // Use custom render template\n return this.nunjucksEnv.renderString(source.render, {\n name,\n style,\n class: className,\n size: options.size,\n color: options.color,\n });\n }\n\n // Default web-font render\n return `<span class=\"${className}\" style=\"${style}\">${name}</span>`;\n }\n\n /**\n * Render a local SVG icon\n */\n private async renderLocalSvg(\n source: IconSource,\n name: string,\n options: IconOptions\n ): Promise<string> {\n if (!source.path) {\n throw new Error(`Local SVG source \"${source.name}\" has no path defined`);\n }\n\n const svgPath = path.join(source.path, `${name}.svg`);\n\n try {\n const svgContent = await fs.readFile(svgPath, \"utf-8\");\n return this.processSvg(svgContent, name, options);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n throw new Error(`Icon file not found: ${svgPath}`);\n }\n throw error;\n }\n }\n\n /**\n * Render an SVG from external URL (placeholder without cache)\n */\n private async renderSvgInline(\n source: IconSource,\n name: string,\n options: IconOptions\n ): Promise<string> {\n // Without cache implementation, return a placeholder\n // Cache will be integrated in Step 4\n const className = this.buildClassName(name, options);\n const style = this.buildStyle(options);\n\n return `<span class=\"${className}\" style=\"${style}\" data-icon-source=\"${source.name}\" data-icon-name=\"${name}\">[${name}]</span>`;\n }\n\n /**\n * Render an SVG sprite reference\n */\n private renderSvgSprite(\n source: IconSource,\n name: string,\n options: IconOptions\n ): string {\n const className = this.buildClassName(name, options);\n const size = options.size ?? \"24px\";\n const color = options.color ?? \"currentColor\";\n\n const spriteUrl = source.url ?? \"\";\n\n return `<svg class=\"${className}\" width=\"${size}\" height=\"${size}\" fill=\"${color}\">\n <use xlink:href=\"${spriteUrl}#${name}\"/>\n</svg>`;\n }\n\n /**\n * Process SVG content and apply options\n */\n private processSvg(\n svgContent: string,\n name: string,\n options: IconOptions\n ): string {\n const className = this.buildClassName(name, options);\n const size = options.size ?? \"24px\";\n const color = options.color ?? \"currentColor\";\n\n // Parse and modify SVG attributes\n let processed = svgContent.trim();\n\n // Add/replace class attribute\n if (processed.includes(\"class=\")) {\n processed = processed.replace(/class=\"[^\"]*\"/, `class=\"${className}\"`);\n } else {\n processed = processed.replace(\"<svg\", `<svg class=\"${className}\"`);\n }\n\n // Add/replace width and height\n if (processed.includes(\"width=\")) {\n processed = processed.replace(/width=\"[^\"]*\"/, `width=\"${size}\"`);\n } else {\n processed = processed.replace(\"<svg\", `<svg width=\"${size}\"`);\n }\n\n if (processed.includes(\"height=\")) {\n processed = processed.replace(/height=\"[^\"]*\"/, `height=\"${size}\"`);\n } else {\n processed = processed.replace(\"<svg\", `<svg height=\"${size}\"`);\n }\n\n // Replace fill=\"currentColor\" with actual color\n if (color !== \"currentColor\") {\n processed = processed.replace(/fill=\"currentColor\"/g, `fill=\"${color}\"`);\n }\n\n return processed;\n }\n\n /**\n * Build CSS style string\n */\n private buildStyle(options: IconOptions): string {\n const styles: string[] = [];\n\n if (options.size) {\n styles.push(`font-size: ${options.size}`);\n }\n\n if (options.color) {\n styles.push(`color: ${options.color}`);\n }\n\n return styles.join(\"; \");\n }\n\n /**\n * Build class name string\n */\n private buildClassName(name: string, options: IconOptions): string {\n const classes = [\"icon\", `icon-${name}`];\n\n if (options.class) {\n classes.push(options.class);\n }\n\n return classes.join(\" \");\n }\n\n /**\n * Resolve color value, supporting palette names and CSS variables\n */\n private resolveColor(color?: string): string | undefined {\n if (!color) {\n return undefined;\n }\n\n // Check if it's a palette name\n const paletteColor = this.registry.getColor(color);\n if (paletteColor) {\n if (this.options.useThemeVariables) {\n return `var(--theme-${color})`;\n }\n return paletteColor;\n }\n\n // Pass through hex/rgb/other colors\n return color;\n }\n}\n","import { exec } from 'child_process';\n\nexport interface CSLAuthor {\n family: string;\n given?: string;\n}\n\nexport interface CSLItem {\n id: string;\n author?: CSLAuthor[];\n issued?: { 'date-parts': number[][] };\n title?: string;\n DOI?: string;\n PMID?: string;\n 'container-title'?: string;\n volume?: string;\n issue?: string;\n page?: string;\n URL?: string;\n type?: string;\n}\n\nexport class ReferenceManagerError extends Error {\n constructor(\n message: string,\n public cause?: unknown\n ) {\n super(message);\n this.name = 'ReferenceManagerError';\n }\n}\n\n/**\n * Client for reference-manager CLI\n */\nexport class ReferenceManager {\n constructor(private command: string = 'ref') {}\n\n /**\n * Check if reference-manager CLI is available\n */\n async isAvailable(): Promise<boolean> {\n try {\n await this.execCommand(`${this.command} --version`);\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * Get all references from the library\n */\n async getAll(): Promise<CSLItem[]> {\n const result = await this.execCommand(`${this.command} list --format json`);\n return this.parseJSON(result);\n }\n\n /**\n * Get a single reference by ID\n */\n async getById(id: string): Promise<CSLItem | null> {\n const result = await this.execCommand(\n `${this.command} list --id ${id} --format json`\n );\n const items = this.parseJSON(result);\n return items[0] || null;\n }\n\n /**\n * Get multiple references by IDs\n */\n async getByIds(ids: string[]): Promise<Map<string, CSLItem>> {\n if (ids.length === 0) {\n return new Map();\n }\n\n const result = await this.execCommand(`${this.command} list --format json`);\n const allItems = this.parseJSON(result);\n\n const idSet = new Set(ids);\n const map = new Map<string, CSLItem>();\n\n for (const item of allItems) {\n if (idSet.has(item.id)) {\n map.set(item.id, item);\n }\n }\n\n return map;\n }\n\n private execCommand(cmd: string): Promise<string> {\n return new Promise((resolve, reject) => {\n exec(cmd, (error, stdout) => {\n if (error) {\n reject(\n new ReferenceManagerError(`Failed to execute: ${cmd}`, error)\n );\n return;\n }\n resolve(stdout.toString());\n });\n });\n }\n\n private parseJSON(data: string): CSLItem[] {\n try {\n return JSON.parse(data) as CSLItem[];\n } catch (error) {\n throw new ReferenceManagerError(\n 'Failed to parse reference-manager output as JSON',\n error\n );\n }\n }\n}\n","import type { ParsedSlide, ParsedPresentation } from '../core/parser';\n\nexport interface ExtractedCitation {\n id: string;\n locator?: string | undefined;\n position: { start: number; end: number };\n}\n\n// Pattern to match citations like [@id], [@id, p.42], [@id1; @id2]\n// Matches: [@word-chars] or [@word-chars, locator]\nconst SINGLE_CITATION_PATTERN = /@([\\w-]+)(?:,\\s*([^;\\]]+))?/g;\nconst CITATION_BRACKET_PATTERN = /\\[(@[\\w-]+(?:,\\s*[^;\\]]+)?(?:;\\s*@[\\w-]+(?:,\\s*[^;\\]]+)?)*)\\]/g;\n\n// Pattern to extract @id from source field in structured citations\nconst SOURCE_CITATION_PATTERN = /^@([\\w-]+)$/;\n\nexport class CitationExtractor {\n /**\n * Extract citations from a text string\n */\n extract(text: string): ExtractedCitation[] {\n const citations: ExtractedCitation[] = [];\n\n // Find all bracketed citation groups\n let bracketMatch: RegExpExecArray | null;\n CITATION_BRACKET_PATTERN.lastIndex = 0;\n\n while ((bracketMatch = CITATION_BRACKET_PATTERN.exec(text)) !== null) {\n const bracketStart = bracketMatch.index;\n const bracketContent = bracketMatch[1];\n\n // Parse individual citations within the bracket\n SINGLE_CITATION_PATTERN.lastIndex = 0;\n let singleMatch: RegExpExecArray | null;\n\n while ((singleMatch = SINGLE_CITATION_PATTERN.exec(bracketContent!)) !== null) {\n const id = singleMatch[1]!;\n const locator = singleMatch[2]?.trim();\n\n citations.push({\n id,\n locator: locator ?? undefined,\n position: {\n start: bracketStart,\n end: bracketStart + bracketMatch[0].length,\n },\n });\n }\n }\n\n return citations;\n }\n\n /**\n * Extract citations from a slide's content\n */\n extractFromSlide(slide: ParsedSlide): ExtractedCitation[] {\n const allCitations: ExtractedCitation[] = [];\n const seenIds = new Set<string>();\n\n // Extract from content recursively\n const extractFromValue = (value: unknown): void => {\n if (typeof value === 'string') {\n // Check for structured source citation (e.g., source: \"@smith2024\")\n const sourceMatch = SOURCE_CITATION_PATTERN.exec(value);\n if (sourceMatch && sourceMatch[1]) {\n const id = sourceMatch[1];\n if (!seenIds.has(id)) {\n seenIds.add(id);\n allCitations.push({\n id,\n locator: undefined,\n position: { start: 0, end: value.length },\n });\n }\n return;\n }\n\n // Regular citation extraction\n const citations = this.extract(value);\n for (const citation of citations) {\n if (!seenIds.has(citation.id)) {\n seenIds.add(citation.id);\n allCitations.push(citation);\n }\n }\n } else if (Array.isArray(value)) {\n for (const item of value) {\n extractFromValue(item);\n }\n } else if (value && typeof value === 'object') {\n for (const v of Object.values(value)) {\n extractFromValue(v);\n }\n }\n };\n\n // Extract from content\n extractFromValue(slide.content);\n\n // Extract from notes if present\n if (slide.notes) {\n const notesCitations = this.extract(slide.notes);\n for (const citation of notesCitations) {\n if (!seenIds.has(citation.id)) {\n seenIds.add(citation.id);\n allCitations.push(citation);\n }\n }\n }\n\n return allCitations;\n }\n\n /**\n * Extract citations from all slides in a presentation\n */\n extractFromPresentation(presentation: ParsedPresentation): ExtractedCitation[] {\n const allCitations: ExtractedCitation[] = [];\n const seenIds = new Set<string>();\n\n for (const slide of presentation.slides) {\n const slideCitations = this.extractFromSlide(slide);\n for (const citation of slideCitations) {\n if (!seenIds.has(citation.id)) {\n seenIds.add(citation.id);\n allCitations.push(citation);\n }\n }\n }\n\n return allCitations;\n }\n\n /**\n * Get unique citation IDs in order of first appearance\n */\n getUniqueIds(citations: ExtractedCitation[]): string[] {\n const seen = new Set<string>();\n const uniqueIds: string[] = [];\n\n for (const citation of citations) {\n if (!seen.has(citation.id)) {\n seen.add(citation.id);\n uniqueIds.push(citation.id);\n }\n }\n\n return uniqueIds;\n }\n}\n","import type { ReferenceManager, CSLItem, CSLAuthor } from './manager';\n\nexport interface FormatterConfig {\n author?: {\n maxAuthors?: number;\n etAl?: string;\n etAlJa?: string;\n separatorJa?: string;\n };\n inline?: {\n authorSep?: string;\n identifierSep?: string;\n multiSep?: string;\n };\n}\n\nconst DEFAULT_CONFIG: Required<FormatterConfig> = {\n author: {\n maxAuthors: 2,\n etAl: 'et al.',\n etAlJa: 'ほか',\n separatorJa: '・',\n },\n inline: {\n authorSep: ', ',\n identifierSep: '; ',\n multiSep: '), (',\n },\n};\n\n// Pattern to detect Japanese characters\nconst JAPANESE_PATTERN = /[\\u3040-\\u309F\\u30A0-\\u30FF\\u4E00-\\u9FAF]/;\n\n// Citation patterns for expansion\nconst CITATION_BRACKET_PATTERN =\n /\\[(@[\\w-]+(?:,\\s*[^;\\]]+)?(?:;\\s*@[\\w-]+(?:,\\s*[^;\\]]+)?)*)\\]/g;\nconst SINGLE_CITATION_PATTERN = /@([\\w-]+)(?:,\\s*([^;\\]]+))?/g;\n\n/**\n * Formats citations for inline display and bibliography generation\n */\nexport class CitationFormatter {\n private config: Required<FormatterConfig>;\n\n constructor(\n private manager: ReferenceManager,\n config?: FormatterConfig\n ) {\n this.config = {\n author: { ...DEFAULT_CONFIG.author, ...config?.author },\n inline: { ...DEFAULT_CONFIG.inline, ...config?.inline },\n };\n }\n\n /**\n * Format an inline citation\n * e.g., \"(Smith et al., 2024; PMID: 12345678)\"\n */\n async formatInline(id: string): Promise<string> {\n const item = await this.manager.getById(id);\n if (!item) {\n return `[${id}]`;\n }\n\n return this.formatInlineItem(item);\n }\n\n /**\n * Format a full bibliography citation\n */\n async formatFull(id: string): Promise<string> {\n const item = await this.manager.getById(id);\n if (!item) {\n return `[${id}]`;\n }\n\n return this.formatFullItem(item);\n }\n\n /**\n * Expand all citations in text\n * e.g., \"[@smith2024]\" -> \"(Smith et al., 2024; PMID: 12345678)\"\n */\n async expandCitations(text: string): Promise<string> {\n // First, collect all citation IDs\n const ids = new Set<string>();\n CITATION_BRACKET_PATTERN.lastIndex = 0;\n\n let match: RegExpExecArray | null;\n while ((match = CITATION_BRACKET_PATTERN.exec(text)) !== null) {\n const content = match[1];\n SINGLE_CITATION_PATTERN.lastIndex = 0;\n\n let singleMatch: RegExpExecArray | null;\n while ((singleMatch = SINGLE_CITATION_PATTERN.exec(content!)) !== null) {\n ids.add(singleMatch[1]!);\n }\n }\n\n // Fetch all items at once\n const items = await this.manager.getByIds([...ids]);\n\n // Replace citations\n CITATION_BRACKET_PATTERN.lastIndex = 0;\n let result = text;\n\n // Reset and iterate again for replacement\n const matches: Array<{\n start: number;\n end: number;\n replacement: string;\n }> = [];\n\n CITATION_BRACKET_PATTERN.lastIndex = 0;\n while ((match = CITATION_BRACKET_PATTERN.exec(text)) !== null) {\n const content = match[1];\n const replacements: string[] = [];\n\n SINGLE_CITATION_PATTERN.lastIndex = 0;\n let singleMatch: RegExpExecArray | null;\n while ((singleMatch = SINGLE_CITATION_PATTERN.exec(content!)) !== null) {\n const id = singleMatch[1]!;\n const item = items.get(id);\n if (item) {\n replacements.push(this.formatInlineItem(item));\n } else {\n replacements.push(`[${id}]`);\n }\n }\n\n matches.push({\n start: match.index,\n end: match.index + match[0].length,\n replacement: replacements.join(', '),\n });\n }\n\n // Apply replacements from end to start to maintain positions\n for (const m of [...matches].reverse()) {\n result = result.slice(0, m.start) + m.replacement + result.slice(m.end);\n }\n\n return result;\n }\n\n /**\n * Generate bibliography entries\n */\n async generateBibliography(\n ids: string[],\n sort: 'author' | 'year' | 'citation-order' = 'citation-order'\n ): Promise<string[]> {\n if (ids.length === 0) {\n return [];\n }\n\n const items = await this.manager.getByIds(ids);\n let sortedItems: CSLItem[];\n\n if (sort === 'citation-order') {\n // Keep order of ids, filtering out non-existent\n sortedItems = ids\n .map((id) => items.get(id))\n .filter((item): item is CSLItem => item !== undefined);\n } else if (sort === 'author') {\n sortedItems = [...items.values()].sort((a, b) => {\n const authorA = this.getFirstAuthorFamily(a);\n const authorB = this.getFirstAuthorFamily(b);\n return authorA.localeCompare(authorB);\n });\n } else {\n // sort by year\n sortedItems = [...items.values()].sort((a, b) => {\n const yearA = this.getYear(a);\n const yearB = this.getYear(b);\n return yearA - yearB;\n });\n }\n\n return sortedItems.map((item) => this.formatFullItem(item));\n }\n\n private formatInlineItem(item: CSLItem): string {\n const author = this.formatAuthorInline(item.author);\n const year = this.getYear(item);\n const identifier = this.getIdentifier(item);\n\n if (identifier) {\n return `(${author}, ${year}; ${identifier})`;\n }\n return `(${author}, ${year})`;\n }\n\n private formatFullItem(item: CSLItem): string {\n const parts: string[] = [];\n\n // Authors\n const isJapanese = this.isJapaneseAuthors(item.author);\n const authors = this.formatAuthorsFull(item.author, isJapanese);\n parts.push(authors);\n\n // Year\n const year = this.getYear(item);\n parts.push(`(${year}).`);\n\n // Title\n if (item.title) {\n parts.push(`${item.title}.`);\n }\n\n // Container (journal)\n if (item['container-title']) {\n const journal = isJapanese\n ? item['container-title']\n : `*${item['container-title']}*`;\n\n // Volume, issue, pages\n let location = '';\n if (item.volume) {\n location = item.issue\n ? `${item.volume}(${item.issue})`\n : item.volume;\n }\n if (item.page) {\n location = location ? `${location}, ${item.page}` : item.page;\n }\n\n parts.push(location ? `${journal}, ${location}.` : `${journal}.`);\n }\n\n // Identifier\n const identifier = this.getIdentifier(item);\n if (identifier) {\n parts.push(identifier);\n }\n\n return parts.join(' ');\n }\n\n private formatAuthorInline(authors: CSLAuthor[] | undefined): string {\n if (!authors || authors.length === 0) {\n return 'Unknown';\n }\n\n const isJapanese = this.isJapaneseAuthors(authors);\n const { etAl, etAlJa, separatorJa } = this.config.author;\n const firstAuthor = authors[0]!;\n\n if (authors.length === 1) {\n return firstAuthor.family;\n }\n\n if (authors.length === 2) {\n const separator = isJapanese ? separatorJa : ' & ';\n return `${firstAuthor.family}${separator}${authors[1]!.family}`;\n }\n\n // 3+ authors\n const suffix = isJapanese ? etAlJa : ` ${etAl}`;\n return `${firstAuthor.family}${suffix}`;\n }\n\n private formatAuthorsFull(\n authors: CSLAuthor[] | undefined,\n isJapanese: boolean\n ): string {\n if (!authors || authors.length === 0) {\n return 'Unknown';\n }\n\n if (isJapanese) {\n // Japanese: 田中太郎, 山田花子\n return authors.map((a) => `${a.family}${a.given || ''}`).join(', ');\n }\n\n // English: Smith, J., Johnson, A., & Williams, B.\n if (authors.length === 1) {\n const a = authors[0]!;\n const initial = a.given ? `${a.given.charAt(0)}.` : '';\n return `${a.family}, ${initial}`;\n }\n\n const formatted = authors.map((a, i) => {\n const initial = a.given ? `${a.given.charAt(0)}.` : '';\n if (i === authors.length - 1) {\n return `& ${a.family}, ${initial}`;\n }\n return `${a.family}, ${initial}`;\n });\n\n // Join with \", \" for 3+ authors, or \", \" for 2 authors\n return formatted.join(', ').replace(', &', ', &');\n }\n\n private isJapaneseAuthors(authors: CSLAuthor[] | undefined): boolean {\n if (!authors || authors.length === 0) {\n return false;\n }\n // Check first author's family name for Japanese characters\n return JAPANESE_PATTERN.test(authors[0]!.family);\n }\n\n private getFirstAuthorFamily(item: CSLItem): string {\n return item.author?.[0]?.family || '';\n }\n\n private getYear(item: CSLItem): number {\n const dateParts = item.issued?.['date-parts'];\n if (dateParts && dateParts[0] && dateParts[0][0]) {\n return dateParts[0][0];\n }\n return 0;\n }\n\n private getIdentifier(item: CSLItem): string | null {\n if (item.PMID) {\n return `PMID: ${item.PMID}`;\n }\n if (item.DOI) {\n return `DOI: ${item.DOI}`;\n }\n return null;\n }\n}\n","/**\n * slide-generation - A CLI tool to generate Marp-compatible Markdown from YAML source files\n */\n\ndeclare const __VERSION__: string;\nexport const VERSION = __VERSION__;\n\n// Core modules\nexport * from './core';\n// export * from './core/transformer';\n// export * from './core/renderer';\n// export * from './core/pipeline';\n\n// Template system\nexport * from './templates';\n","import { Command } from 'commander';\nimport { access, readFile } from 'fs/promises';\nimport { basename, dirname, join } from 'path';\nimport chalk from 'chalk';\nimport ora from 'ora';\nimport { parse as parseYaml } from 'yaml';\nimport { Pipeline, PipelineError } from '../../core/pipeline';\nimport { ConfigLoader } from '../../config/loader';\nimport { ImageProcessingPipeline } from '../../images';\n\n/**\n * Exit codes for CLI commands\n */\nexport const ExitCode = {\n Success: 0,\n GeneralError: 1,\n ArgumentError: 2,\n FileReadError: 3,\n ValidationError: 4,\n ConversionError: 5,\n ReferenceError: 6,\n} as const;\n\ninterface ConvertOptions {\n output?: string;\n config?: string;\n theme?: string;\n references?: boolean;\n verbose?: boolean;\n processImages?: boolean;\n}\n\n/**\n * Generate default output path from input path\n */\nfunction getDefaultOutputPath(inputPath: string): string {\n const dir = dirname(inputPath);\n const base = basename(inputPath, '.yaml');\n return join(dir, `${base}.md`);\n}\n\n/**\n * Extract unique image directories from presentation\n */\nasync function extractImageDirectories(\n inputPath: string,\n baseDir: string\n): Promise<string[]> {\n const content = await readFile(inputPath, 'utf-8');\n const parsed = parseYaml(content) as {\n slides?: Array<{ content?: Record<string, unknown> }>;\n };\n\n const imageDirs = new Set<string>();\n\n if (!parsed.slides) return [];\n\n for (const slide of parsed.slides) {\n const content = slide.content;\n if (!content) continue;\n\n // Collect image paths from various content fields\n const imagePaths: string[] = [];\n\n if (typeof content['image'] === 'string') {\n imagePaths.push(content['image']);\n }\n\n const before = content['before'] as { image?: string } | undefined;\n const after = content['after'] as { image?: string } | undefined;\n if (before?.image) imagePaths.push(before.image);\n if (after?.image) imagePaths.push(after.image);\n\n const images = content['images'] as Array<{ src?: string }> | undefined;\n if (images) {\n for (const img of images) {\n if (img.src) imagePaths.push(img.src);\n }\n }\n\n // Extract directory for each image path\n for (const imagePath of imagePaths) {\n const dir = dirname(imagePath);\n if (dir && dir !== '.') {\n imageDirs.add(join(baseDir, dir));\n }\n }\n }\n\n return Array.from(imageDirs);\n}\n\n/**\n * Process images based on metadata instructions\n */\nasync function processImages(\n inputPath: string,\n baseDir: string\n): Promise<number> {\n const imageDirs = await extractImageDirectories(inputPath, baseDir);\n let totalProcessed = 0;\n\n for (const imageDir of imageDirs) {\n try {\n await access(imageDir);\n const pipeline = new ImageProcessingPipeline(imageDir);\n const result = await pipeline.processDirectory();\n totalProcessed += result.processedImages;\n } catch {\n // Directory doesn't exist, skip\n }\n }\n\n return totalProcessed;\n}\n\n/**\n * Create the convert command\n */\nexport function createConvertCommand(): Command {\n return new Command('convert')\n .description('Convert YAML source to Marp Markdown')\n .argument('<input>', 'Input YAML file')\n .option('-o, --output <path>', 'Output file path')\n .option('-c, --config <path>', 'Config file path')\n .option('-t, --theme <name>', 'Theme name')\n .option('--no-references', 'Disable reference processing')\n .option('--process-images', 'Apply image processing from metadata')\n .option('-v, --verbose', 'Verbose output')\n .action(async (input: string, options: ConvertOptions) => {\n await executeConvert(input, options);\n });\n}\n\n/**\n * Execute the convert command\n */\nasync function executeConvert(\n inputPath: string,\n options: ConvertOptions\n): Promise<void> {\n const spinner = options.verbose ? null : ora();\n const verbose = options.verbose ?? false;\n\n const updateSpinner = (text: string) => {\n if (spinner) {\n spinner.text = text;\n }\n };\n\n try {\n // Validate input file exists\n spinner?.start(`Reading ${inputPath}...`);\n try {\n await access(inputPath);\n } catch {\n spinner?.fail(`File not found: ${inputPath}`);\n console.error(chalk.red(`Error: Input file not found: ${inputPath}`));\n process.exitCode = ExitCode.FileReadError;\n return;\n }\n\n // Determine output path\n const outputPath = options.output ?? getDefaultOutputPath(inputPath);\n\n // Load configuration\n updateSpinner('Loading configuration...');\n const configLoader = new ConfigLoader();\n let configPath = options.config;\n\n if (!configPath) {\n configPath = await configLoader.findConfig(dirname(inputPath));\n }\n\n const config = await configLoader.load(configPath);\n\n // Override references if specified\n if (options.references === false) {\n config.references.enabled = false;\n }\n\n // Override theme if specified\n if (options.theme) {\n config.output.theme = options.theme;\n }\n\n // Create and initialize pipeline\n updateSpinner('Initializing pipeline...');\n const pipeline = new Pipeline(config);\n\n try {\n await pipeline.initialize();\n } catch (error) {\n spinner?.fail('Failed to initialize pipeline');\n if (error instanceof PipelineError) {\n console.error(chalk.red(`Error: ${error.message}`));\n } else {\n console.error(\n chalk.red(\n `Error: ${error instanceof Error ? error.message : 'Unknown error'}`\n )\n );\n }\n process.exitCode = ExitCode.ConversionError;\n return;\n }\n\n // Process images if requested\n let processedImageCount = 0;\n if (options.processImages) {\n updateSpinner('Processing images...');\n const baseDir = dirname(inputPath);\n processedImageCount = await processImages(inputPath, baseDir);\n }\n\n // Run pipeline\n updateSpinner(`Converting ${inputPath}...`);\n const result = await pipeline.runWithResult(inputPath, { outputPath });\n\n // Success!\n spinner?.succeed(`Converted ${inputPath}`);\n\n // Show stats in verbose mode or after completion\n if (verbose) {\n console.log('');\n console.log(chalk.green(' ✓') + ` Parsed ${result.slideCount} slides`);\n if (result.citations.length > 0) {\n console.log(\n chalk.green(' ✓') + ` Resolved ${result.citations.length} references`\n );\n }\n if (processedImageCount > 0) {\n console.log(\n chalk.green(' ✓') + ` Processed ${processedImageCount} image(s)`\n );\n }\n console.log(chalk.green(' ✓') + ' Generated output');\n }\n\n // Show warnings\n for (const warning of result.warnings) {\n console.log(chalk.yellow(' ⚠') + ` ${warning}`);\n }\n\n // Show output path\n console.log('');\n console.log(`Output: ${chalk.cyan(outputPath)}`);\n } catch (error) {\n spinner?.fail('Conversion failed');\n\n if (error instanceof PipelineError) {\n console.error(chalk.red(`\\nError (${error.stage}): ${error.message}`));\n\n // Set appropriate exit code based on stage\n switch (error.stage) {\n case 'parse':\n process.exitCode = ExitCode.FileReadError;\n break;\n case 'transform':\n process.exitCode = ExitCode.ValidationError;\n break;\n case 'render':\n process.exitCode = ExitCode.ConversionError;\n break;\n default:\n process.exitCode = ExitCode.GeneralError;\n }\n } else {\n console.error(\n chalk.red(\n `\\nError: ${error instanceof Error ? error.message : 'Unknown error'}`\n )\n );\n process.exitCode = ExitCode.GeneralError;\n }\n }\n}\n","import { access, readFile } from 'fs/promises';\nimport { join } from 'path';\nimport { parse as parseYaml } from 'yaml';\nimport { configSchema, type Config } from './schema';\n\nconst CONFIG_NAMES = ['config.yaml', 'slide-gen.yaml'];\n\nexport class ConfigLoader {\n async load(configPath?: string): Promise<Config> {\n const fileConfig = await this.loadFile(configPath);\n return configSchema.parse(fileConfig);\n }\n\n async findConfig(directory: string): Promise<string | undefined> {\n for (const name of CONFIG_NAMES) {\n const path = join(directory, name);\n try {\n await access(path);\n return path;\n } catch {\n // Continue to next\n }\n }\n return undefined;\n }\n\n private async loadFile(configPath?: string): Promise<unknown> {\n if (!configPath) return {};\n\n try {\n const content = await readFile(configPath, 'utf-8');\n return parseYaml(content) ?? {};\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n return {};\n }\n throw error;\n }\n }\n}\n","import { z } from 'zod';\n\nexport const configSchema = z.object({\n templates: z\n .object({\n builtin: z.string().default('./templates'),\n custom: z.string().optional(),\n })\n .default({}),\n\n icons: z\n .object({\n registry: z.string().default('./icons/registry.yaml'),\n cache: z\n .object({\n enabled: z.boolean().default(true),\n directory: z.string().default('.cache/icons'),\n ttl: z.number().default(86400),\n })\n .default({}),\n })\n .default({}),\n\n references: z\n .object({\n enabled: z.boolean().default(true),\n connection: z\n .object({\n type: z.literal('cli').default('cli'),\n command: z.string().default('ref'),\n })\n .default({}),\n format: z\n .object({\n locale: z.string().default('ja-JP'),\n authorSep: z.string().default(', '),\n identifierSep: z.string().default('; '),\n maxAuthors: z.number().default(2),\n etAl: z.string().default('et al.'),\n etAlJa: z.string().default('ほか'),\n })\n .default({}),\n })\n .default({}),\n\n output: z\n .object({\n theme: z.string().default('default'),\n inlineStyles: z.boolean().default(false),\n })\n .default({}),\n});\n\nexport type Config = z.infer<typeof configSchema>;\n","/**\n * Shared constants for image management\n */\n\n/**\n * Supported image file extensions\n */\nexport const IMAGE_EXTENSIONS = new Set([\n \".jpg\",\n \".jpeg\",\n \".png\",\n \".gif\",\n \".webp\",\n \".svg\",\n]);\n\n/**\n * Check if a file is an image file based on its extension\n */\nexport function isImageFile(filename: string): boolean {\n const ext = filename.slice(filename.lastIndexOf(\".\")).toLowerCase();\n return IMAGE_EXTENSIONS.has(ext);\n}\n\n/**\n * Default minimum resolution thresholds for image quality warnings\n */\nexport const DEFAULT_MIN_RESOLUTION = {\n width: 1280,\n height: 720,\n};\n","import { z } from \"zod\";\nimport { imageProcessingArraySchema } from \"./processing-schema\";\n\n/**\n * Permission status for images\n */\nexport const permissionStatusSchema = z.enum([\n \"approved\",\n \"pending\",\n \"restricted\",\n \"rejected\",\n]);\n\nexport type PermissionStatus = z.infer<typeof permissionStatusSchema>;\n\n/**\n * Permission information for images\n */\nexport const permissionsSchema = z.object({\n status: permissionStatusSchema,\n approved_by: z.string().optional(),\n approved_date: z.string().optional(),\n expires: z.string().nullable().optional(),\n conditions: z.array(z.string()).optional(),\n document: z.string().optional(),\n pending_contact: z.string().optional(),\n});\n\nexport type Permissions = z.infer<typeof permissionsSchema>;\n\n/**\n * Credit/attribution information\n */\nexport const creditsSchema = z.object({\n required: z.boolean().optional(),\n text: z.string().optional(),\n});\n\nexport type Credits = z.infer<typeof creditsSchema>;\n\n/**\n * Individual image metadata schema\n * Used for .meta.yaml files attached to individual images\n */\nexport const individualMetadataSchema = z.object({\n // Basic information\n description: z.string().optional(),\n captured_date: z.string().optional(),\n captured_by: z.string().optional(),\n location: z.string().optional(),\n\n // Subject information - can be string or array of strings\n subject: z.union([z.string(), z.array(z.string())]).optional(),\n\n // Permission information\n permissions: permissionsSchema.optional(),\n\n // Usage restrictions\n restrictions: z.array(z.string()).optional(),\n\n // Notes (supplementary information for AI)\n notes: z.string().optional(),\n\n // Credits\n credits: creditsSchema.optional(),\n\n // Tags for search/filtering\n tags: z.array(z.string()).optional(),\n\n // Image processing instructions (crop, blur, etc.)\n processing: imageProcessingArraySchema.optional(),\n});\n\nexport type ImageMetadata = z.infer<typeof individualMetadataSchema>;\n\n/**\n * Directory-level defaults schema\n */\nexport const directoryDefaultsSchema = z.object({\n permissions: permissionsSchema.optional(),\n credits: creditsSchema.optional(),\n tags: z.array(z.string()).optional(),\n});\n\nexport type DirectoryDefaults = z.infer<typeof directoryDefaultsSchema>;\n\n/**\n * Directory metadata entry schema\n * Can be either defaults or individual file metadata\n */\nexport const directoryMetadataEntrySchema = individualMetadataSchema;\n\n/**\n * Directory metadata schema (images.yaml)\n * Contains _defaults for directory-level settings and individual file entries\n * Uses a more permissive record type to allow any entry\n */\nexport const directoryMetadataSchema = z.record(\n z.string(),\n individualMetadataSchema.passthrough()\n);\n\nexport type DirectoryMetadata = z.infer<typeof directoryMetadataSchema>;\n\n/**\n * Merged metadata result (after applying defaults)\n */\nexport interface ResolvedImageMetadata extends ImageMetadata {\n // Path to the image file (relative to project root)\n path?: string;\n // Source of metadata (individual | directory | defaults)\n metadataSource?: \"individual\" | \"directory\" | \"defaults\" | \"none\";\n}\n","import { z } from \"zod\";\n\n/**\n * Edge crop options schema\n * Each edge is a percentage (0-50) to crop from that edge\n */\nexport const edgeCropOptionsSchema = z.object({\n left: z.number().min(0).max(50).optional(),\n right: z.number().min(0).max(50).optional(),\n top: z.number().min(0).max(50).optional(),\n bottom: z.number().min(0).max(50).optional(),\n});\n\nexport type EdgeCropOptions = z.infer<typeof edgeCropOptionsSchema>;\n\n/**\n * Region specification for crop or blur\n */\nexport const regionSchema = z.object({\n x: z.number().min(0),\n y: z.number().min(0),\n width: z.number().positive(),\n height: z.number().positive(),\n});\n\nexport type Region = z.infer<typeof regionSchema>;\n\n/**\n * Crop instruction schema\n * Can specify either edges (percentage) or region (pixels)\n */\nexport const cropInstructionSchema = z.object({\n type: z.literal(\"crop\"),\n edges: edgeCropOptionsSchema.optional(),\n region: regionSchema.optional(),\n});\n\nexport type CropInstruction = z.infer<typeof cropInstructionSchema>;\n\n/**\n * Blur instruction schema\n * Applies blur to a specified region\n */\nexport const blurInstructionSchema = z.object({\n type: z.literal(\"blur\"),\n region: regionSchema,\n radius: z.number().min(1).max(100).optional(),\n});\n\nexport type BlurInstruction = z.infer<typeof blurInstructionSchema>;\n\n/**\n * Combined processing instruction schema (discriminated union)\n */\nexport const imageProcessingSchema = z.discriminatedUnion(\"type\", [\n cropInstructionSchema,\n blurInstructionSchema,\n]);\n\nexport type ImageProcessingInstruction = z.infer<typeof imageProcessingSchema>;\n\n/**\n * Array of processing instructions\n */\nexport const imageProcessingArraySchema = z.array(imageProcessingSchema);\n\nexport type ImageProcessingInstructions = z.infer<\n typeof imageProcessingArraySchema\n>;\n","import * as fs from \"node:fs/promises\";\nimport * as path from \"node:path\";\nimport { parse as parseYaml } from \"yaml\";\nimport {\n individualMetadataSchema,\n directoryMetadataSchema,\n type ImageMetadata,\n type PermissionStatus,\n} from \"./schema\";\nimport { isImageFile } from \"./constants\";\n\n/**\n * Warning info for metadata loading issues\n */\nexport interface MetadataWarning {\n path: string;\n message: string;\n}\n\n/**\n * Collected warnings during metadata loading\n */\nlet metadataWarnings: MetadataWarning[] = [];\n\n/**\n * Get and clear collected warnings\n */\nexport function getAndClearMetadataWarnings(): MetadataWarning[] {\n const warnings = metadataWarnings;\n metadataWarnings = [];\n return warnings;\n}\n\n/**\n * Loader for image metadata files\n * Supports both individual .meta.yaml files and directory-level images.yaml files\n */\nexport class ImageMetadataLoader {\n constructor(private baseDir: string = \".\") {}\n\n /**\n * Load metadata for a specific image file\n * Priority: individual .meta.yaml > directory images.yaml entry > directory _defaults\n */\n async load(imagePath: string): Promise<ImageMetadata> {\n // Try loading individual metadata first\n const individualMetadata = await this.loadIndividualMetadata(imagePath);\n if (individualMetadata !== null) {\n return individualMetadata;\n }\n\n // Fall back to directory metadata\n const directoryMetadata = await this.loadFromDirectoryMetadata(imagePath);\n return directoryMetadata;\n }\n\n /**\n * Load all metadata for images in a directory\n */\n async loadDirectory(dirPath: string): Promise<Map<string, ImageMetadata>> {\n const result = new Map<string, ImageMetadata>();\n const fullDirPath = path.join(this.baseDir, dirPath);\n\n // Check if directory exists\n try {\n await fs.access(fullDirPath);\n } catch {\n return result;\n }\n\n // Get all image files in directory\n const files = await fs.readdir(fullDirPath);\n const imageFiles = files.filter((f) => isImageFile(f));\n\n // Load metadata for each image\n for (const file of imageFiles) {\n const imagePath = path.join(dirPath, file);\n const metadata = await this.load(imagePath);\n result.set(file, metadata);\n }\n\n return result;\n }\n\n /**\n * Check if metadata exists for an image\n */\n async hasMetadata(imagePath: string): Promise<boolean> {\n // Check individual metadata\n const individualPath = this.getIndividualMetadataPath(imagePath);\n try {\n await fs.access(individualPath);\n return true;\n } catch {\n // Continue to check directory metadata\n }\n\n // Check directory metadata\n const dirMetadata = await this.loadDirectoryMetadataFile(imagePath);\n if (dirMetadata === null) {\n return false;\n }\n\n const filename = path.basename(imagePath);\n return filename in dirMetadata && filename !== \"_defaults\";\n }\n\n /**\n * Get the permission status for an image\n */\n async getPermissionStatus(imagePath: string): Promise<PermissionStatus | null> {\n const metadata = await this.load(imagePath);\n return metadata.permissions?.status ?? null;\n }\n\n /**\n * Get the path to individual metadata file\n */\n private getIndividualMetadataPath(imagePath: string): string {\n return path.join(this.baseDir, `${imagePath}.meta.yaml`);\n }\n\n /**\n * Get the path to directory metadata file\n */\n private getDirectoryMetadataPath(imagePath: string): string {\n const dir = path.dirname(imagePath);\n return path.join(this.baseDir, dir, \"images.yaml\");\n }\n\n /**\n * Load individual metadata file (.meta.yaml)\n */\n private async loadIndividualMetadata(\n imagePath: string\n ): Promise<ImageMetadata | null> {\n const metadataPath = this.getIndividualMetadataPath(imagePath);\n\n // Check if file exists first\n try {\n await fs.access(metadataPath);\n } catch {\n // File doesn't exist - this is normal, not a warning\n return null;\n }\n\n // File exists, try to read and parse it\n try {\n const content = await fs.readFile(metadataPath, \"utf-8\");\n const parsed = parseYaml(content);\n const validated = individualMetadataSchema.safeParse(parsed);\n\n if (validated.success) {\n return validated.data;\n }\n // Schema validation failed\n metadataWarnings.push({\n path: metadataPath,\n message: `Invalid metadata schema: ${validated.error.issues.map((i) => i.message).join(\", \")}`,\n });\n return null;\n } catch (error) {\n // YAML parse error or read error\n const message =\n error instanceof Error ? error.message : \"Unknown parse error\";\n metadataWarnings.push({\n path: metadataPath,\n message: `Failed to parse metadata file: ${message}`,\n });\n return null;\n }\n }\n\n /**\n * Load directory metadata file (images.yaml)\n */\n private async loadDirectoryMetadataFile(\n imagePath: string\n ): Promise<Record<string, unknown> | null> {\n const metadataPath = this.getDirectoryMetadataPath(imagePath);\n\n // Check if file exists first\n try {\n await fs.access(metadataPath);\n } catch {\n // File doesn't exist - this is normal, not a warning\n return null;\n }\n\n // File exists, try to read and parse it\n try {\n const content = await fs.readFile(metadataPath, \"utf-8\");\n const parsed = parseYaml(content);\n const validated = directoryMetadataSchema.safeParse(parsed);\n\n if (validated.success) {\n return validated.data;\n }\n // Schema validation failed\n metadataWarnings.push({\n path: metadataPath,\n message: `Invalid metadata schema: ${validated.error.issues.map((i) => i.message).join(\", \")}`,\n });\n return null;\n } catch (error) {\n // YAML parse error or read error\n const message =\n error instanceof Error ? error.message : \"Unknown parse error\";\n metadataWarnings.push({\n path: metadataPath,\n message: `Failed to parse metadata file: ${message}`,\n });\n return null;\n }\n }\n\n /**\n * Load metadata from directory metadata file\n */\n private async loadFromDirectoryMetadata(\n imagePath: string\n ): Promise<ImageMetadata> {\n const dirMetadata = await this.loadDirectoryMetadataFile(imagePath);\n\n if (dirMetadata === null) {\n return {};\n }\n\n const filename = path.basename(imagePath);\n\n // Get defaults\n const defaults = (dirMetadata[\"_defaults\"] ?? {}) as Partial<ImageMetadata>;\n\n // Get file-specific metadata\n const fileMetadata = (dirMetadata[filename] ?? {}) as Partial<ImageMetadata>;\n\n // Merge defaults with file-specific metadata\n // File-specific values override defaults\n return this.mergeMetadata(defaults, fileMetadata);\n }\n\n /**\n * Merge two metadata objects, with override taking precedence\n */\n private mergeMetadata(\n defaults: Partial<ImageMetadata>,\n override: Partial<ImageMetadata>\n ): ImageMetadata {\n const result: ImageMetadata = { ...defaults };\n\n // Override with file-specific values\n for (const key of Object.keys(override) as (keyof ImageMetadata)[]) {\n const overrideValue = override[key];\n if (overrideValue !== undefined) {\n if (\n key === \"permissions\" &&\n typeof overrideValue === \"object\" &&\n typeof defaults.permissions === \"object\"\n ) {\n // Merge permissions objects\n result.permissions = {\n ...defaults.permissions,\n ...overrideValue,\n };\n } else if (\n key === \"credits\" &&\n typeof overrideValue === \"object\" &&\n typeof defaults.credits === \"object\"\n ) {\n // Merge credits objects\n result.credits = {\n ...defaults.credits,\n ...overrideValue,\n };\n } else {\n // Direct override for other fields\n (result as Record<string, unknown>)[key] = overrideValue;\n }\n }\n }\n\n return result;\n }\n}\n","import * as fs from \"node:fs/promises\";\nimport * as path from \"node:path\";\nimport imageSize from \"image-size\";\nimport { ImageMetadataLoader } from \"./metadata-loader\";\nimport { IMAGE_EXTENSIONS, DEFAULT_MIN_RESOLUTION } from \"./constants\";\n\n/**\n * Validation result for a single check\n */\nexport interface ImageValidationResult {\n valid: boolean;\n errors: string[];\n warnings: string[];\n}\n\n/**\n * Image dimensions info\n */\nexport interface ImageDimensions {\n width: number;\n height: number;\n type?: string;\n}\n\n/**\n * Options for presentation validation\n */\nexport interface ValidatePresentationOptions {\n checkImages?: boolean;\n checkResolution?: boolean;\n minResolution?: {\n width: number;\n height: number;\n };\n}\n\n/**\n * Image statistics by permission status\n */\nexport interface ImageStats {\n total: number;\n approved: number;\n pending: number;\n restricted: number;\n rejected: number;\n unknown: number;\n}\n\n/**\n * Slide content type (simplified for validation)\n */\ninterface SlideContent {\n template: string;\n content: Record<string, unknown>;\n}\n\n/**\n * Validator for images referenced in presentations\n */\nexport class ImageValidator {\n private metadataLoader: ImageMetadataLoader;\n\n constructor(private baseDir: string = \".\") {\n this.metadataLoader = new ImageMetadataLoader(baseDir);\n }\n\n /**\n * Validate that an image file exists and is a supported format\n */\n async validateImageExists(imagePath: string): Promise<ImageValidationResult> {\n const errors: string[] = [];\n const warnings: string[] = [];\n\n const fullPath = path.join(this.baseDir, imagePath);\n const ext = path.extname(imagePath).toLowerCase();\n\n // Check file extension\n if (!IMAGE_EXTENSIONS.has(ext)) {\n errors.push(`Unsupported image format: ${imagePath}`);\n return { valid: false, errors, warnings };\n }\n\n // Check file exists\n try {\n await fs.access(fullPath);\n } catch {\n errors.push(`Image not found: ${imagePath}`);\n return { valid: false, errors, warnings };\n }\n\n return { valid: true, errors, warnings };\n }\n\n /**\n * Get image dimensions\n */\n async getImageDimensions(imagePath: string): Promise<ImageDimensions | null> {\n const fullPath = path.join(this.baseDir, imagePath);\n\n try {\n const buffer = await fs.readFile(fullPath);\n const dimensions = imageSize(buffer);\n\n if (dimensions.width && dimensions.height) {\n return {\n width: dimensions.width,\n height: dimensions.height,\n ...(dimensions.type ? { type: dimensions.type } : {}),\n };\n }\n return null;\n } catch {\n return null;\n }\n }\n\n /**\n * Validate image resolution\n */\n async validateImageResolution(\n imagePath: string,\n minResolution: { width: number; height: number } = DEFAULT_MIN_RESOLUTION\n ): Promise<ImageValidationResult> {\n const errors: string[] = [];\n const warnings: string[] = [];\n\n const dimensions = await this.getImageDimensions(imagePath);\n\n if (!dimensions) {\n // Can't read dimensions - not an error, might be SVG or unsupported\n return { valid: true, errors, warnings };\n }\n\n const { width, height, type } = dimensions;\n const typeStr = type ? type.toUpperCase() : \"unknown\";\n\n if (width < minResolution.width || height < minResolution.height) {\n warnings.push(\n `Low resolution: ${imagePath} (${width}x${height}, ${typeStr}) - minimum recommended: ${minResolution.width}x${minResolution.height}`\n );\n }\n\n return { valid: true, errors, warnings };\n }\n\n /**\n * Extract all image references from slide content\n */\n extractImageReferences(slides: SlideContent[]): string[] {\n const images = new Set<string>();\n\n for (const slide of slides) {\n const content = slide.content;\n\n // Direct image field (image-text, image-full, image-caption)\n if (typeof content[\"image\"] === \"string\") {\n images.add(content[\"image\"]);\n }\n\n // Images array (gallery)\n const contentImages = content[\"images\"];\n if (Array.isArray(contentImages)) {\n for (const img of contentImages) {\n if (typeof img === \"object\" && img !== null && \"src\" in img) {\n images.add(img.src as string);\n }\n }\n }\n\n // Before/after images\n const beforeObj = content[\"before\"];\n if (typeof beforeObj === \"object\" && beforeObj !== null) {\n const before = beforeObj as Record<string, unknown>;\n if (typeof before[\"image\"] === \"string\") {\n images.add(before[\"image\"]);\n }\n }\n const afterObj = content[\"after\"];\n if (typeof afterObj === \"object\" && afterObj !== null) {\n const after = afterObj as Record<string, unknown>;\n if (typeof after[\"image\"] === \"string\") {\n images.add(after[\"image\"]);\n }\n }\n }\n\n return Array.from(images);\n }\n\n /**\n * Validate all images in a presentation\n */\n async validatePresentation(\n slides: SlideContent[],\n options: ValidatePresentationOptions = {}\n ): Promise<ImageValidationResult> {\n const {\n checkImages = false,\n checkResolution = false,\n minResolution = DEFAULT_MIN_RESOLUTION,\n } = options;\n const errors: string[] = [];\n const warnings: string[] = [];\n\n const imageRefs = this.extractImageReferences(slides);\n\n for (const imagePath of imageRefs) {\n // Check file exists\n const existsResult = await this.validateImageExists(imagePath);\n errors.push(...existsResult.errors);\n warnings.push(...existsResult.warnings);\n\n if (existsResult.valid) {\n // Check resolution if requested\n if (checkResolution) {\n const resResult = await this.validateImageResolution(\n imagePath,\n minResolution\n );\n warnings.push(...resResult.warnings);\n }\n\n // Check permissions if requested\n if (checkImages) {\n const permResult = await this.validateImagePermissions(imagePath);\n errors.push(...permResult.errors);\n warnings.push(...permResult.warnings);\n }\n }\n }\n\n return {\n valid: errors.length === 0,\n errors,\n warnings,\n };\n }\n\n /**\n * Validate image permissions from metadata\n */\n private async validateImagePermissions(\n imagePath: string\n ): Promise<ImageValidationResult> {\n const errors: string[] = [];\n const warnings: string[] = [];\n\n const status = await this.metadataLoader.getPermissionStatus(imagePath);\n\n if (status === null) {\n // No permission info - not an error by default\n return { valid: true, errors, warnings };\n }\n\n switch (status) {\n case \"approved\":\n // All good\n break;\n case \"pending\":\n warnings.push(`Pending permission: ${imagePath}`);\n break;\n case \"restricted\":\n warnings.push(`Restricted: ${imagePath}`);\n break;\n case \"rejected\":\n errors.push(`Rejected: ${imagePath}`);\n break;\n }\n\n return {\n valid: errors.length === 0,\n errors,\n warnings,\n };\n }\n\n /**\n * Get statistics about images by permission status\n */\n async getImageStats(slides: SlideContent[]): Promise<ImageStats> {\n const imageRefs = this.extractImageReferences(slides);\n\n const stats: ImageStats = {\n total: imageRefs.length,\n approved: 0,\n pending: 0,\n restricted: 0,\n rejected: 0,\n unknown: 0,\n };\n\n for (const imagePath of imageRefs) {\n const status = await this.metadataLoader.getPermissionStatus(imagePath);\n\n if (status === null) {\n stats.unknown++;\n } else {\n switch (status) {\n case \"approved\":\n stats.approved++;\n break;\n case \"pending\":\n stats.pending++;\n break;\n case \"restricted\":\n stats.restricted++;\n break;\n case \"rejected\":\n stats.rejected++;\n break;\n }\n }\n }\n\n return stats;\n }\n\n /**\n * Get list of missing images\n */\n async getMissingImages(slides: SlideContent[]): Promise<string[]> {\n const missing: string[] = [];\n const imageRefs = this.extractImageReferences(slides);\n\n for (const imagePath of imageRefs) {\n const result = await this.validateImageExists(imagePath);\n if (!result.valid) {\n missing.push(imagePath);\n }\n }\n\n return missing;\n }\n}\n","import sharp from \"sharp\";\n\n/**\n * Crop options for extracting a region from an image\n */\nexport interface CropOptions {\n left: number;\n top: number;\n width: number;\n height: number;\n}\n\n/**\n * Edge crop options for cropping percentage from edges\n */\nexport interface EdgeCropOptions {\n left?: number | undefined; // Percentage to crop from left (0-50)\n right?: number | undefined; // Percentage to crop from right (0-50)\n top?: number | undefined; // Percentage to crop from top (0-50)\n bottom?: number | undefined; // Percentage to crop from bottom (0-50)\n}\n\n/**\n * Blur region options\n */\nexport interface BlurRegionOptions {\n x: number;\n y: number;\n width: number;\n height: number;\n radius?: number | undefined; // Default: 10\n}\n\n/**\n * Result of image processing operation\n */\nexport interface ProcessResult {\n success: boolean;\n outputPath?: string;\n width?: number;\n height?: number;\n error?: string;\n}\n\n/**\n * Image metadata\n */\nexport interface ImageMetadataInfo {\n width: number;\n height: number;\n format?: string;\n}\n\n/**\n * Image processor for crop and blur operations\n */\nexport class ImageProcessor {\n private readonly defaultBlurRadius = 10;\n\n /**\n * Crop image with specified region\n */\n async crop(\n inputPath: string,\n options: CropOptions,\n outputPath: string\n ): Promise<ProcessResult> {\n try {\n const metadata = await sharp(inputPath).metadata();\n const imgWidth = metadata.width ?? 0;\n const imgHeight = metadata.height ?? 0;\n\n // Validate crop region\n if (\n options.left + options.width > imgWidth ||\n options.top + options.height > imgHeight\n ) {\n return {\n success: false,\n error: `Crop region exceeds image dimensions (${imgWidth}x${imgHeight})`,\n };\n }\n\n await sharp(inputPath)\n .extract({\n left: options.left,\n top: options.top,\n width: options.width,\n height: options.height,\n })\n .toFile(outputPath);\n\n return {\n success: true,\n outputPath,\n width: options.width,\n height: options.height,\n };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n }\n\n /**\n * Crop percentage from specified edges\n */\n async cropEdges(\n inputPath: string,\n options: EdgeCropOptions,\n outputPath: string\n ): Promise<ProcessResult> {\n try {\n // Validate percentages\n const edges = [\n options.left ?? 0,\n options.right ?? 0,\n options.top ?? 0,\n options.bottom ?? 0,\n ];\n for (const edge of edges) {\n if (edge > 50) {\n return {\n success: false,\n error: \"Edge crop percentage cannot exceed 50%\",\n };\n }\n }\n\n const metadata = await sharp(inputPath).metadata();\n const imgWidth = metadata.width ?? 0;\n const imgHeight = metadata.height ?? 0;\n\n const leftPixels = Math.round(imgWidth * ((options.left ?? 0) / 100));\n const rightPixels = Math.round(imgWidth * ((options.right ?? 0) / 100));\n const topPixels = Math.round(imgHeight * ((options.top ?? 0) / 100));\n const bottomPixels = Math.round(\n imgHeight * ((options.bottom ?? 0) / 100)\n );\n\n const newWidth = imgWidth - leftPixels - rightPixels;\n const newHeight = imgHeight - topPixels - bottomPixels;\n\n await sharp(inputPath)\n .extract({\n left: leftPixels,\n top: topPixels,\n width: newWidth,\n height: newHeight,\n })\n .toFile(outputPath);\n\n return {\n success: true,\n outputPath,\n width: newWidth,\n height: newHeight,\n };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n }\n\n /**\n * Apply blur to specified region\n */\n async blurRegion(\n inputPath: string,\n options: BlurRegionOptions,\n outputPath: string\n ): Promise<ProcessResult> {\n try {\n const metadata = await sharp(inputPath).metadata();\n const imgWidth = metadata.width ?? 0;\n const imgHeight = metadata.height ?? 0;\n\n // Validate region\n if (\n options.x + options.width > imgWidth ||\n options.y + options.height > imgHeight\n ) {\n return {\n success: false,\n error: `Blur region exceeds image dimensions (${imgWidth}x${imgHeight})`,\n };\n }\n\n const radius = options.radius ?? this.defaultBlurRadius;\n\n // Extract the region to blur\n const blurredRegion = await sharp(inputPath)\n .extract({\n left: options.x,\n top: options.y,\n width: options.width,\n height: options.height,\n })\n .blur(radius)\n .toBuffer();\n\n // Composite the blurred region back onto the original image\n await sharp(inputPath)\n .composite([\n {\n input: blurredRegion,\n left: options.x,\n top: options.y,\n },\n ])\n .toFile(outputPath);\n\n return {\n success: true,\n outputPath,\n width: imgWidth,\n height: imgHeight,\n };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n }\n\n /**\n * Get image metadata\n */\n async getMetadata(inputPath: string): Promise<ImageMetadataInfo> {\n const metadata = await sharp(inputPath).metadata();\n return {\n width: metadata.width ?? 0,\n height: metadata.height ?? 0,\n format: metadata.format,\n };\n }\n}\n","import * as fs from \"node:fs/promises\";\nimport * as path from \"node:path\";\nimport { ImageMetadataLoader } from \"./metadata-loader\";\nimport { ImageProcessor } from \"./processor\";\nimport { isImageFile } from \"./constants\";\nimport type { ImageProcessingInstruction } from \"./processing-schema\";\n\n/**\n * Result of processing a single image\n */\nexport interface ProcessImageResult {\n success: boolean;\n originalPath: string;\n processedPath?: string;\n skipped?: boolean;\n instructionsApplied?: number;\n error?: string;\n}\n\n/**\n * Result of processing a directory of images\n */\nexport interface ProcessDirectoryResult {\n totalImages: number;\n processedImages: number;\n skippedImages: number;\n errors: string[];\n imageMap: Map<string, string>; // original -> processed path mapping\n}\n\n/**\n * Options for the processing pipeline\n */\nexport interface ProcessingPipelineOptions {\n outputDir?: string;\n}\n\n/**\n * Pipeline for processing images based on metadata instructions\n */\nexport class ImageProcessingPipeline {\n private metadataLoader: ImageMetadataLoader;\n private processor: ImageProcessor;\n private outputDir: string;\n\n constructor(\n private baseDir: string,\n options?: ProcessingPipelineOptions\n ) {\n this.metadataLoader = new ImageMetadataLoader(baseDir);\n this.processor = new ImageProcessor();\n this.outputDir = options?.outputDir ?? path.join(baseDir, \".processed\");\n }\n\n /**\n * Process a single image based on its metadata instructions\n */\n async processImage(imagePath: string): Promise<ProcessImageResult> {\n const fullPath = path.join(this.baseDir, imagePath);\n const result: ProcessImageResult = {\n success: true,\n originalPath: fullPath,\n };\n\n try {\n // Load metadata\n const metadata = await this.metadataLoader.load(imagePath);\n\n // Check if processing instructions exist\n if (!metadata.processing || metadata.processing.length === 0) {\n result.skipped = true;\n return result;\n }\n\n // Ensure output directory exists\n await fs.mkdir(this.outputDir, { recursive: true });\n\n // Process image with each instruction\n const processedPath = await this.applyInstructions(\n fullPath,\n imagePath,\n metadata.processing\n );\n\n result.processedPath = processedPath;\n result.instructionsApplied = metadata.processing.length;\n return result;\n } catch (error) {\n return {\n success: false,\n originalPath: fullPath,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n }\n\n /**\n * Process all images in a directory\n */\n async processDirectory(): Promise<ProcessDirectoryResult> {\n const result: ProcessDirectoryResult = {\n totalImages: 0,\n processedImages: 0,\n skippedImages: 0,\n errors: [],\n imageMap: new Map(),\n };\n\n try {\n // Get all image files in directory\n const files = await fs.readdir(this.baseDir);\n const imageFiles = files.filter((f) => isImageFile(f));\n result.totalImages = imageFiles.length;\n\n // Process each image\n for (const imageFile of imageFiles) {\n const imageResult = await this.processImage(imageFile);\n\n if (!imageResult.success) {\n result.errors.push(`${imageFile}: ${imageResult.error}`);\n } else if (imageResult.skipped) {\n result.skippedImages++;\n } else if (imageResult.processedPath) {\n result.processedImages++;\n result.imageMap.set(imageResult.originalPath, imageResult.processedPath);\n }\n }\n\n return result;\n } catch (error) {\n result.errors.push(error instanceof Error ? error.message : String(error));\n return result;\n }\n }\n\n /**\n * Apply processing instructions to an image\n */\n private async applyInstructions(\n inputPath: string,\n relativePath: string,\n instructions: ImageProcessingInstruction[]\n ): Promise<string> {\n const outputFilename = path.basename(relativePath);\n const finalOutputPath = path.join(this.outputDir, outputFilename);\n\n // Use two temp files alternately for intermediate processing\n // This ensures input and output are always different files\n const tempPaths = [\n path.join(this.outputDir, `temp_${outputFilename}`),\n path.join(this.outputDir, `temp2_${outputFilename}`),\n ];\n let currentInputPath = inputPath;\n\n for (let i = 0; i < instructions.length; i++) {\n const instruction = instructions[i]!;\n const isLast = i === instructions.length - 1;\n const outputPath = isLast ? finalOutputPath : tempPaths[i % 2]!;\n\n await this.applyInstruction(currentInputPath, outputPath, instruction);\n\n // For next iteration, use the output as input\n if (!isLast) {\n currentInputPath = outputPath;\n }\n }\n\n // Clean up temp files\n try {\n await fs.unlink(path.join(this.outputDir, `temp_${outputFilename}`));\n } catch {\n // Ignore if doesn't exist\n }\n try {\n await fs.unlink(path.join(this.outputDir, `temp2_${outputFilename}`));\n } catch {\n // Ignore if doesn't exist\n }\n\n return finalOutputPath;\n }\n\n /**\n * Apply a single processing instruction\n */\n private async applyInstruction(\n inputPath: string,\n outputPath: string,\n instruction: ImageProcessingInstruction\n ): Promise<void> {\n switch (instruction.type) {\n case \"crop\":\n await this.applyCrop(inputPath, outputPath, instruction);\n break;\n case \"blur\":\n await this.applyBlur(inputPath, outputPath, instruction);\n break;\n }\n }\n\n /**\n * Apply crop instruction\n */\n private async applyCrop(\n inputPath: string,\n outputPath: string,\n instruction: ImageProcessingInstruction & { type: \"crop\" }\n ): Promise<void> {\n if (instruction.edges) {\n const result = await this.processor.cropEdges(\n inputPath,\n instruction.edges,\n outputPath\n );\n if (!result.success) {\n throw new Error(result.error);\n }\n } else if (instruction.region) {\n const result = await this.processor.crop(\n inputPath,\n {\n left: instruction.region.x,\n top: instruction.region.y,\n width: instruction.region.width,\n height: instruction.region.height,\n },\n outputPath\n );\n if (!result.success) {\n throw new Error(result.error);\n }\n }\n }\n\n /**\n * Apply blur instruction\n */\n private async applyBlur(\n inputPath: string,\n outputPath: string,\n instruction: ImageProcessingInstruction & { type: \"blur\" }\n ): Promise<void> {\n const result = await this.processor.blurRegion(\n inputPath,\n {\n x: instruction.region.x,\n y: instruction.region.y,\n width: instruction.region.width,\n height: instruction.region.height,\n radius: instruction.radius,\n },\n outputPath\n );\n if (!result.success) {\n throw new Error(result.error);\n }\n }\n}\n","import { Command } from 'commander';\nimport { access, readFile } from 'fs/promises';\nimport { dirname } from 'path';\nimport chalk from 'chalk';\nimport ora from 'ora';\nimport { parse as parseYaml, stringify as yamlStringify } from 'yaml';\nimport { Parser, ParseError, ValidationError, type ParseResultWithLines } from '../../core/parser';\nimport { TemplateLoader } from '../../templates/loader';\nimport { IconRegistryLoader } from '../../icons/registry';\nimport { ConfigLoader } from '../../config/loader';\nimport { ExitCode } from './convert';\n\n/**\n * Validation result structure\n */\ninterface ValidationResult {\n valid: boolean;\n errors: string[];\n warnings: string[];\n structuredErrors: StructuredValidationError[];\n slideLines: number[];\n stats: {\n yamlSyntax: boolean;\n metaValid: boolean;\n slideCount: number;\n templatesFound: boolean;\n iconsResolved: boolean;\n referencesCount: number;\n };\n}\n\ninterface ValidateOptions {\n config?: string;\n strict?: boolean;\n format?: 'text' | 'json' | 'llm';\n}\n\n/**\n * Structured validation error for LLM-friendly output\n */\nexport interface StructuredValidationError {\n slide: number;\n line?: number;\n template: string;\n field?: string;\n message: string;\n errorType: 'missing_field' | 'invalid_type' | 'unknown_template' | 'unknown_icon' | 'schema_error';\n fixExample?: string;\n}\n\n/**\n * Get contextual hint based on error type\n */\nexport function getHintForErrorType(errorType: string): string | null {\n switch (errorType) {\n case 'unknown_template':\n return 'Run `slide-gen templates list --format llm` to see available templates.';\n case 'unknown_icon':\n return 'Run `slide-gen icons search <query>` to find icons.';\n default:\n return null;\n }\n}\n\n/**\n * Format validation result for LLM consumption\n */\nexport function formatLlmValidationResult(\n errors: StructuredValidationError[],\n slideCount: number\n): string {\n if (errors.length === 0) {\n return `Validation passed. ${slideCount} slides validated.`;\n }\n\n const lines: string[] = ['Validation failed.', ''];\n\n for (let i = 0; i < errors.length; i++) {\n const error = errors[i]!;\n\n // Error header with line number (if available) and template\n const lineInfo = error.line ? `line ${error.line}, ` : '';\n lines.push(`Error at ${lineInfo}Slide ${error.slide} (${error.template}):`);\n lines.push(` ${error.message}`);\n\n // Fix example (if available)\n if (error.fixExample) {\n lines.push('');\n lines.push('Fix:');\n const exampleLines = error.fixExample.split('\\n');\n for (const line of exampleLines) {\n lines.push(` ${line}`);\n }\n }\n\n // Hint based on error type\n const hint = getHintForErrorType(error.errorType);\n if (hint) {\n lines.push('');\n lines.push(`Hint: ${hint}`);\n }\n\n // Separator between errors\n if (i < errors.length - 1) {\n lines.push('');\n lines.push('---');\n lines.push('');\n }\n }\n\n return lines.join('\\n');\n}\n\n/**\n * Format an example object as YAML string with indentation\n */\nfunction formatExampleAsYaml(example: Record<string, unknown>, indent: number): string {\n const yaml = yamlStringify(example, { indent: 2 });\n const spaces = ' '.repeat(indent);\n return yaml\n .split('\\n')\n .filter(line => line.trim() !== '')\n .map(line => spaces + line)\n .join('\\n');\n}\n\n/**\n * Create the validate command\n */\nexport function createValidateCommand(): Command {\n return new Command('validate')\n .description('Validate source file without conversion')\n .argument('<input>', 'Input YAML file')\n .option('-c, --config <path>', 'Config file path')\n .option('--strict', 'Treat warnings as errors')\n .option('--format <fmt>', 'Output format (text/json/llm)', 'text')\n .action(async (input: string, options: ValidateOptions) => {\n await executeValidate(input, options);\n });\n}\n\n/**\n * Execute the validate command\n */\nasync function executeValidate(\n inputPath: string,\n options: ValidateOptions\n): Promise<void> {\n const isJsonFormat = options.format === 'json';\n const isLlmFormat = options.format === 'llm';\n const spinner = (isJsonFormat || isLlmFormat) ? null : ora();\n\n const result: ValidationResult = {\n valid: true,\n errors: [],\n warnings: [],\n structuredErrors: [],\n slideLines: [],\n stats: {\n yamlSyntax: false,\n metaValid: false,\n slideCount: 0,\n templatesFound: false,\n iconsResolved: false,\n referencesCount: 0,\n },\n };\n\n try {\n // Check file exists\n spinner?.start(`Validating ${inputPath}...`);\n try {\n await access(inputPath);\n } catch {\n spinner?.fail(`File not found: ${inputPath}`);\n result.errors.push(`File not found: ${inputPath}`);\n result.valid = false;\n outputResult(result, options);\n process.exitCode = ExitCode.FileReadError;\n return;\n }\n\n // Read file content\n const content = await readFile(inputPath, 'utf-8');\n\n // Step 1: YAML syntax check\n try {\n parseYaml(content);\n result.stats.yamlSyntax = true;\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Unknown error';\n result.errors.push(`YAML syntax error: ${message}`);\n result.valid = false;\n spinner?.fail('YAML syntax invalid');\n outputResult(result, options);\n process.exitCode = ExitCode.ValidationError;\n return;\n }\n\n // Step 2: Schema validation with line info\n const parser = new Parser();\n let presentation: ParseResultWithLines;\n try {\n presentation = parser.parseWithLineInfo(content);\n result.stats.metaValid = true;\n result.stats.slideCount = presentation.slides.length;\n result.slideLines = presentation.slideLines;\n } catch (error) {\n if (error instanceof ParseError) {\n result.errors.push(`Parse error: ${error.message}`);\n } else if (error instanceof ValidationError) {\n result.errors.push(`Schema validation error: ${error.message}`);\n } else {\n const message = error instanceof Error ? error.message : 'Unknown error';\n result.errors.push(`Schema error: ${message}`);\n }\n result.valid = false;\n spinner?.fail('Schema validation failed');\n outputResult(result, options);\n process.exitCode = ExitCode.ValidationError;\n return;\n }\n\n // Load configuration\n const configLoader = new ConfigLoader();\n let configPath = options.config;\n\n if (!configPath) {\n configPath = await configLoader.findConfig(dirname(inputPath));\n }\n\n const config = await configLoader.load(configPath);\n\n // Step 3: Template validation\n const templateLoader = new TemplateLoader();\n try {\n await templateLoader.loadBuiltIn(config.templates.builtin);\n if (config.templates.custom) {\n try {\n await templateLoader.loadCustom(config.templates.custom);\n } catch {\n // Custom templates directory may not exist\n }\n }\n } catch (error) {\n result.warnings.push(\n `Could not load templates: ${error instanceof Error ? error.message : 'Unknown error'}`\n );\n }\n\n // Check all templates exist\n const missingTemplates: string[] = [];\n for (let i = 0; i < presentation.slides.length; i++) {\n const slide = presentation.slides[i]!;\n const slideNumber = i + 1;\n const slideLine = result.slideLines[i];\n const template = templateLoader.get(slide.template);\n\n if (!template) {\n missingTemplates.push(`Slide ${slideNumber}: Template \"${slide.template}\" not found`);\n const structuredError: StructuredValidationError = {\n slide: slideNumber,\n template: slide.template,\n message: `Template \"${slide.template}\" not found`,\n errorType: 'unknown_template',\n };\n if (slideLine !== undefined) {\n structuredError.line = slideLine;\n }\n result.structuredErrors.push(structuredError);\n } else {\n // Validate slide content against template schema\n const validationResult = templateLoader.validateContent(\n slide.template,\n slide.content\n );\n if (!validationResult.valid) {\n for (const err of validationResult.errors) {\n result.errors.push(`Slide ${slideNumber} (${slide.template}): ${err}`);\n\n // Determine error type and extract field from error message\n const isMissingField = err.toLowerCase().includes('required') || err.toLowerCase().includes('missing');\n const isInvalidType = err.toLowerCase().includes('type') || err.toLowerCase().includes('invalid');\n\n // Try to extract field name from error message\n const fieldMatch = err.match(/(?:field|property)\\s+['\"]?(\\w+)['\"]?/i) ||\n err.match(/^(\\w+)\\s+is\\s+required/i);\n const field = fieldMatch?.[1];\n\n // Get fix example from template\n const fixExample = template.example ?\n `content:\\n${formatExampleAsYaml(template.example, 2)}` : undefined;\n\n const structuredError: StructuredValidationError = {\n slide: slideNumber,\n template: slide.template,\n message: err,\n errorType: isMissingField ? 'missing_field' : isInvalidType ? 'invalid_type' : 'schema_error',\n };\n if (slideLine !== undefined) {\n structuredError.line = slideLine;\n }\n if (field !== undefined) {\n structuredError.field = field;\n }\n if (fixExample !== undefined) {\n structuredError.fixExample = fixExample;\n }\n result.structuredErrors.push(structuredError);\n }\n }\n }\n }\n\n if (missingTemplates.length > 0) {\n for (const msg of missingTemplates) {\n result.errors.push(msg);\n }\n result.valid = false;\n } else {\n result.stats.templatesFound = true;\n }\n\n // Step 4: Icon validation (check for icon references in content)\n const iconRegistry = new IconRegistryLoader();\n try {\n await iconRegistry.load(config.icons.registry);\n result.stats.iconsResolved = true;\n } catch (error) {\n result.warnings.push(\n `Could not load icon registry: ${error instanceof Error ? error.message : 'Unknown error'}`\n );\n }\n\n // Check icon references in slide content (simple pattern matching)\n const iconPattern = /icon\\(['\"]([^'\"]+)['\"]\\)/g;\n for (let i = 0; i < presentation.slides.length; i++) {\n const slide = presentation.slides[i]!;\n const slideNumber = i + 1;\n const slideLine = result.slideLines[i];\n const contentStr = JSON.stringify(slide.content);\n for (const match of contentStr.matchAll(iconPattern)) {\n const iconRef = match[1]!;\n // Try to resolve the icon\n const resolved = iconRegistry.resolveAlias(iconRef);\n const parsed = iconRegistry.parseIconReference(resolved);\n if (parsed) {\n const source = iconRegistry.getSource(parsed.prefix);\n if (!source) {\n result.warnings.push(\n `Slide ${slideNumber}: Unknown icon source \"${parsed.prefix}\" in \"${iconRef}\"`\n );\n const structuredError: StructuredValidationError = {\n slide: slideNumber,\n template: slide.template,\n message: `Unknown icon source \"${parsed.prefix}\" in \"${iconRef}\"`,\n errorType: 'unknown_icon',\n };\n if (slideLine !== undefined) {\n structuredError.line = slideLine;\n }\n result.structuredErrors.push(structuredError);\n }\n } else if (!iconRegistry.resolveAlias(iconRef)) {\n result.warnings.push(`Slide ${slideNumber}: Unknown icon \"${iconRef}\"`);\n const structuredError: StructuredValidationError = {\n slide: slideNumber,\n template: slide.template,\n message: `Unknown icon \"${iconRef}\"`,\n errorType: 'unknown_icon',\n };\n if (slideLine !== undefined) {\n structuredError.line = slideLine;\n }\n result.structuredErrors.push(structuredError);\n }\n }\n }\n\n // Step 5: Reference validation\n const citationPattern = /@([a-zA-Z0-9_-]+)/g;\n const references: Set<string> = new Set();\n for (const slide of presentation.slides) {\n const contentStr = JSON.stringify(slide.content);\n for (const match of contentStr.matchAll(citationPattern)) {\n references.add(match[1]!);\n }\n }\n result.stats.referencesCount = references.size;\n\n // Final validation result\n if (result.errors.length > 0) {\n result.valid = false;\n }\n\n // Strict mode: warnings become errors\n if (options.strict && result.warnings.length > 0) {\n result.valid = false;\n result.errors.push(...result.warnings);\n result.warnings = [];\n }\n\n // Output result\n if (result.valid) {\n spinner?.succeed(`Validated ${inputPath}`);\n } else {\n spinner?.fail(`Validation failed for ${inputPath}`);\n }\n\n outputResult(result, options);\n\n if (!result.valid) {\n process.exitCode = ExitCode.ValidationError;\n }\n } catch (error) {\n spinner?.fail('Validation failed');\n result.errors.push(\n `Unexpected error: ${error instanceof Error ? error.message : 'Unknown error'}`\n );\n result.valid = false;\n outputResult(result, options);\n process.exitCode = ExitCode.GeneralError;\n }\n}\n\n/**\n * Output validation result in the specified format\n */\nfunction outputResult(result: ValidationResult, options: ValidateOptions): void {\n if (options.format === 'json') {\n console.log(\n JSON.stringify(\n {\n valid: result.valid,\n errors: result.errors,\n warnings: result.warnings,\n stats: result.stats,\n },\n null,\n 2\n )\n );\n return;\n }\n\n if (options.format === 'llm') {\n // LLM-friendly output format\n const llmOutput = formatLlmValidationResult(\n result.structuredErrors,\n result.stats.slideCount\n );\n console.log(llmOutput);\n return;\n }\n\n // Text format output\n console.log('');\n\n // Stats\n if (result.stats.yamlSyntax) {\n console.log(chalk.green('✓') + ' YAML syntax valid');\n } else {\n console.log(chalk.red('✗') + ' YAML syntax invalid');\n }\n\n if (result.stats.metaValid) {\n console.log(chalk.green('✓') + ' Meta section valid');\n }\n\n if (result.stats.slideCount > 0) {\n console.log(chalk.green('✓') + ` ${result.stats.slideCount} slides validated`);\n }\n\n if (result.stats.templatesFound) {\n console.log(chalk.green('✓') + ' All templates found');\n }\n\n if (result.stats.iconsResolved) {\n console.log(chalk.green('✓') + ' All icons resolved');\n }\n\n if (result.stats.referencesCount > 0) {\n console.log(chalk.green('✓') + ` ${result.stats.referencesCount} references found`);\n }\n\n // Errors\n for (const error of result.errors) {\n console.log(chalk.red('✗') + ` ${error}`);\n }\n\n // Warnings\n for (const warning of result.warnings) {\n console.log(chalk.yellow('⚠') + ` ${warning}`);\n }\n\n // Summary\n console.log('');\n if (result.valid) {\n console.log(chalk.green('Validation passed!'));\n } else {\n const errorCount = result.errors.length;\n const warningCount = result.warnings.length;\n let summary = `Validation failed with ${errorCount} error${errorCount !== 1 ? 's' : ''}`;\n if (warningCount > 0) {\n summary += ` and ${warningCount} warning${warningCount !== 1 ? 's' : ''}`;\n }\n console.log(chalk.red(summary));\n }\n}\n","import { Command } from 'commander';\nimport chalk from 'chalk';\nimport * as yaml from 'yaml';\nimport { mkdir, writeFile, rm } from 'fs/promises';\nimport { join, basename } from 'path';\nimport { tmpdir } from 'os';\nimport { execFileSync } from 'child_process';\nimport type { Server } from 'http';\nimport { TemplateLoader, type TemplateDefinition } from '../../templates';\nimport { ConfigLoader } from '../../config/loader';\nimport { Pipeline, PipelineError } from '../../core/pipeline';\nimport { ExitCode } from './convert';\nimport { collectSlideInfo, startStaticServer, checkMarpCliAvailable } from './preview';\n\ntype OutputFormat = 'table' | 'json' | 'llm';\ntype InfoFormat = 'text' | 'json' | 'llm';\n\ninterface ListOptions {\n category?: string;\n format?: OutputFormat;\n config?: string;\n}\n\ninterface InfoOptions {\n format?: InfoFormat;\n config?: string;\n}\n\ninterface ExampleOptions {\n config?: string;\n}\n\n/**\n * Format template list for table output\n */\nfunction formatTableList(templates: TemplateDefinition[]): string {\n const byCategory = new Map<string, TemplateDefinition[]>();\n\n for (const template of templates) {\n const cat = template.category;\n if (!byCategory.has(cat)) {\n byCategory.set(cat, []);\n }\n byCategory.get(cat)!.push(template);\n }\n\n const lines: string[] = ['Templates:', ''];\n\n // Sort categories alphabetically\n const sortedCategories = Array.from(byCategory.keys()).sort();\n\n for (const category of sortedCategories) {\n lines.push(`${category}/`);\n const categoryTemplates = byCategory.get(category)!;\n\n // Sort templates by name within category\n categoryTemplates.sort((a, b) => a.name.localeCompare(b.name));\n\n for (const template of categoryTemplates) {\n // Pad name to align descriptions\n const paddedName = template.name.padEnd(16);\n lines.push(` ${paddedName}${template.description}`);\n }\n lines.push('');\n }\n\n return lines.join('\\n');\n}\n\n/**\n * Format template list for JSON output\n */\nfunction formatJsonList(templates: TemplateDefinition[]): string {\n const output = templates.map((t) => ({\n name: t.name,\n description: t.description,\n category: t.category,\n }));\n return JSON.stringify(output, null, 2);\n}\n\n/**\n * Format template list for LLM output\n */\nfunction formatLlmList(templates: TemplateDefinition[]): string {\n const byCategory = new Map<string, TemplateDefinition[]>();\n\n for (const template of templates) {\n const cat = template.category;\n if (!byCategory.has(cat)) {\n byCategory.set(cat, []);\n }\n byCategory.get(cat)!.push(template);\n }\n\n const lines: string[] = [];\n\n // Sort categories alphabetically\n const sortedCategories = Array.from(byCategory.keys()).sort();\n\n for (const category of sortedCategories) {\n lines.push(`[${category}]`);\n const categoryTemplates = byCategory.get(category)!;\n\n // Sort templates by name within category\n categoryTemplates.sort((a, b) => a.name.localeCompare(b.name));\n\n for (const template of categoryTemplates) {\n lines.push(`${template.name}: ${template.description}`);\n }\n lines.push('');\n }\n\n return lines.join('\\n').trim();\n}\n\n/**\n * Format template list in the specified format\n */\nexport function formatTemplateList(\n templates: TemplateDefinition[],\n format: OutputFormat\n): string {\n switch (format) {\n case 'json':\n return formatJsonList(templates);\n case 'llm':\n return formatLlmList(templates);\n case 'table':\n default:\n return formatTableList(templates);\n }\n}\n\n/**\n * Format schema property for text output\n */\nfunction formatSchemaProperty(\n name: string,\n prop: Record<string, unknown>,\n required: boolean,\n indent: string\n): string[] {\n const lines: string[] = [];\n const type = (prop['type'] as string) ?? 'unknown';\n const requiredStr = required ? ', required' : '';\n const description = prop['description'] as string | undefined;\n\n lines.push(`${indent}${name} (${type}${requiredStr})`);\n if (description) {\n lines.push(`${indent} ${description}`);\n }\n\n // Handle nested objects\n if (type === 'object' && prop['properties']) {\n const nestedRequired = (prop['required'] as string[]) ?? [];\n const properties = prop['properties'] as Record<string, Record<string, unknown>>;\n for (const [propName, propDef] of Object.entries(properties)) {\n lines.push(\n ...formatSchemaProperty(propName, propDef, nestedRequired.includes(propName), indent + ' ')\n );\n }\n }\n\n // Handle array items\n if (type === 'array' && prop['items']) {\n const items = prop['items'] as Record<string, unknown>;\n if (items['type'] === 'object' && items['properties']) {\n const itemRequired = (items['required'] as string[]) ?? [];\n const itemProps = items['properties'] as Record<string, Record<string, unknown>>;\n lines.push(`${indent} Items:`);\n for (const [propName, propDef] of Object.entries(itemProps)) {\n lines.push(\n ...formatSchemaProperty(propName, propDef, itemRequired.includes(propName), indent + ' ')\n );\n }\n }\n }\n\n return lines;\n}\n\n/**\n * Format template info for text output\n */\nfunction formatTextInfo(template: TemplateDefinition): string {\n const lines: string[] = [\n `Template: ${template.name}`,\n `Description: ${template.description}`,\n `Category: ${template.category}`,\n '',\n 'Schema:',\n ];\n\n const schema = template.schema as {\n type?: string;\n required?: string[];\n properties?: Record<string, Record<string, unknown>>;\n };\n\n if (schema.properties) {\n const required = schema.required ?? [];\n for (const [name, prop] of Object.entries(schema.properties)) {\n lines.push(...formatSchemaProperty(name, prop, required.includes(name), ' '));\n }\n }\n\n if (template.example) {\n lines.push('', 'Example:');\n const exampleYaml = yaml.stringify(template.example, { indent: 2 });\n lines.push(\n ...exampleYaml\n .split('\\n')\n .filter((l) => l.trim())\n .map((l) => ` ${l}`)\n );\n }\n\n return lines.join('\\n');\n}\n\n/**\n * Format template info for JSON output\n */\nfunction formatJsonInfo(template: TemplateDefinition): string {\n return JSON.stringify(\n {\n name: template.name,\n description: template.description,\n category: template.category,\n schema: template.schema,\n example: template.example,\n },\n null,\n 2\n );\n}\n\n/**\n * Format template info for LLM output\n */\nfunction formatLlmInfo(template: TemplateDefinition): string {\n const lines: string[] = [\n `Template: ${template.name}`,\n `Description: ${template.description}`,\n `Category: ${template.category}`,\n '',\n 'Schema:',\n ];\n\n const schema = template.schema as {\n type?: string;\n required?: string[];\n properties?: Record<string, Record<string, unknown>>;\n };\n\n if (schema.properties) {\n const required = schema.required ?? [];\n for (const [name, prop] of Object.entries(schema.properties)) {\n const type = (prop['type'] as string) ?? 'unknown';\n const reqStr = required.includes(name) ? ', required' : '';\n lines.push(` ${name} (${type}${reqStr})`);\n\n const description = prop['description'] as string | undefined;\n if (description) {\n lines.push(` ${description}`);\n }\n }\n }\n\n if (template.example) {\n lines.push('', 'Example:');\n const exampleYaml = yaml.stringify(\n { template: template.name, content: template.example },\n { indent: 2 }\n );\n lines.push(\n ...exampleYaml\n .split('\\n')\n .filter((l) => l.trim())\n .map((l) => ` ${l}`)\n );\n }\n\n return lines.join('\\n');\n}\n\n/**\n * Format template info in the specified format\n */\nexport function formatTemplateInfo(\n template: TemplateDefinition,\n format: InfoFormat\n): string {\n switch (format) {\n case 'json':\n return formatJsonInfo(template);\n case 'llm':\n return formatLlmInfo(template);\n case 'text':\n default:\n return formatTextInfo(template);\n }\n}\n\n/**\n * Format template example as slide YAML\n */\nexport function formatTemplateExample(template: TemplateDefinition): string {\n const slideYaml = yaml.stringify(\n [{ template: template.name, content: template.example ?? {} }],\n { indent: 2 }\n );\n return slideYaml;\n}\n\n/**\n * Load templates from config\n */\nasync function loadTemplates(configPath?: string): Promise<TemplateLoader> {\n const configLoader = new ConfigLoader();\n\n if (!configPath) {\n configPath = await configLoader.findConfig(process.cwd());\n }\n\n const config = await configLoader.load(configPath);\n const templateLoader = new TemplateLoader();\n\n try {\n await templateLoader.loadBuiltIn(config.templates.builtin);\n } catch {\n // Built-in templates may not exist in some environments\n }\n\n if (config.templates.custom) {\n try {\n await templateLoader.loadCustom(config.templates.custom);\n } catch {\n // Custom templates directory may not exist\n }\n }\n\n return templateLoader;\n}\n\n/**\n * Create the templates list subcommand\n */\nfunction createListCommand(): Command {\n return new Command('list')\n .description('List available templates')\n .option('--category <cat>', 'Filter by category')\n .option('--format <fmt>', 'Output format (table/json/llm)', 'table')\n .option('-c, --config <path>', 'Config file path')\n .action(async (options: ListOptions) => {\n try {\n const templateLoader = await loadTemplates(options.config);\n\n let templates = templateLoader.list();\n\n if (options.category) {\n templates = templateLoader.listByCategory(options.category);\n }\n\n if (templates.length === 0) {\n if (options.format === 'json') {\n console.log('[]');\n } else {\n console.log('No templates found.');\n }\n return;\n }\n\n const format = (options.format ?? 'table') as OutputFormat;\n const output = formatTemplateList(templates, format);\n console.log(output);\n } catch (error) {\n console.error(\n chalk.red(`Error: ${error instanceof Error ? error.message : 'Unknown error'}`)\n );\n process.exitCode = ExitCode.GeneralError;\n }\n });\n}\n\n/**\n * Create the templates info subcommand\n */\nfunction createInfoCommand(): Command {\n return new Command('info')\n .description('Show template details')\n .argument('<name>', 'Template name')\n .option('--format <fmt>', 'Output format (text/json/llm)', 'text')\n .option('-c, --config <path>', 'Config file path')\n .action(async (name: string, options: InfoOptions) => {\n try {\n const templateLoader = await loadTemplates(options.config);\n const template = templateLoader.get(name);\n\n if (!template) {\n console.error(chalk.red(`Error: Template \"${name}\" not found`));\n process.exitCode = ExitCode.GeneralError;\n return;\n }\n\n const format = (options.format ?? 'text') as InfoFormat;\n const output = formatTemplateInfo(template, format);\n console.log(output);\n } catch (error) {\n console.error(\n chalk.red(`Error: ${error instanceof Error ? error.message : 'Unknown error'}`)\n );\n process.exitCode = ExitCode.GeneralError;\n }\n });\n}\n\n/**\n * Create the templates example subcommand\n */\nfunction createExampleCommand(): Command {\n return new Command('example')\n .description('Output example YAML for a template')\n .argument('<name>', 'Template name')\n .option('-c, --config <path>', 'Config file path')\n .action(async (name: string, options: ExampleOptions) => {\n try {\n const templateLoader = await loadTemplates(options.config);\n const template = templateLoader.get(name);\n\n if (!template) {\n console.error(chalk.red(`Error: Template \"${name}\" not found`));\n process.exitCode = ExitCode.GeneralError;\n return;\n }\n\n const output = formatTemplateExample(template);\n console.log(output);\n } catch (error) {\n console.error(\n chalk.red(`Error: ${error instanceof Error ? error.message : 'Unknown error'}`)\n );\n process.exitCode = ExitCode.GeneralError;\n }\n });\n}\n\ninterface PreviewOptions {\n all?: boolean;\n category?: string;\n port?: number;\n config?: string;\n}\n\n/**\n * Create the templates preview subcommand\n */\nfunction createPreviewSubcommand(): Command {\n return new Command('preview')\n .description('Preview template in browser')\n .argument('[name]', 'Template name')\n .option('--all', 'Show all templates')\n .option('--category <cat>', 'Filter by category')\n .option('-p, --port <number>', 'Preview server port', '8080')\n .option('-c, --config <path>', 'Config file path')\n .action(async (name: string | undefined, options: PreviewOptions) => {\n try {\n await executeTemplatePreview(name, options);\n } catch (error) {\n console.error(\n chalk.red(`Error: ${error instanceof Error ? error.message : 'Unknown error'}`)\n );\n process.exitCode = ExitCode.GeneralError;\n }\n });\n}\n\n/**\n * Template preview information with schema details\n */\ninterface TemplatePreviewInfo {\n template: TemplateDefinition;\n imagePath: string;\n}\n\n/**\n * Escape HTML special characters to prevent XSS\n */\nfunction escapeHtml(str: string): string {\n return str\n .replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;')\n .replace(/'/g, '&#39;');\n}\n\n/**\n * Format schema property for HTML display\n */\nfunction formatSchemaPropertyHtml(\n name: string,\n prop: Record<string, unknown>,\n required: boolean\n): string {\n const type = (prop['type'] as string) ?? 'unknown';\n const description = prop['description'] as string | undefined;\n const requiredBadge = required\n ? '<span class=\"badge required\">required</span>'\n : '<span class=\"badge optional\">optional</span>';\n\n return `\n <div class=\"param\">\n <div class=\"param-header\">\n <code class=\"param-name\">${escapeHtml(name)}</code>\n <span class=\"param-type\">${escapeHtml(type)}</span>\n ${requiredBadge}\n </div>\n ${description ? `<div class=\"param-desc\">${escapeHtml(description)}</div>` : ''}\n </div>\n `;\n}\n\n/**\n * Generate HTML for template preview with parameter information\n */\nfunction generateTemplatePreviewHtml(previews: TemplatePreviewInfo[]): string {\n const templateCards = previews\n .map((p) => {\n const schema = p.template.schema as {\n type?: string;\n required?: string[];\n properties?: Record<string, Record<string, unknown>>;\n };\n\n const requiredFields = schema.required ?? [];\n const properties = schema.properties ?? {};\n\n const paramsHtml = Object.entries(properties)\n .map(([name, prop]) =>\n formatSchemaPropertyHtml(name, prop, requiredFields.includes(name))\n )\n .join('');\n\n return `\n <div class=\"template-card\">\n <div class=\"template-preview\">\n <img src=\"${escapeHtml(p.imagePath)}\" alt=\"${escapeHtml(p.template.name)}\" class=\"template-img\" data-template=\"${escapeHtml(p.template.name)}\">\n </div>\n <div class=\"template-info\">\n <h2 class=\"template-name\">${escapeHtml(p.template.name)}</h2>\n <p class=\"template-desc\">${escapeHtml(p.template.description)}</p>\n <div class=\"template-category\">Category: <code>${escapeHtml(p.template.category)}</code></div>\n <div class=\"template-params\">\n <h3>Parameters</h3>\n ${paramsHtml || '<p class=\"no-params\">No parameters</p>'}\n </div>\n </div>\n </div>\n `;\n })\n .join('');\n\n return `<!DOCTYPE html>\n<html>\n<head>\n <title>Template Preview</title>\n <style>\n * { box-sizing: border-box; margin: 0; padding: 0; }\n body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: #f5f5f5; color: #333; }\n h1 { text-align: center; padding: 24px; background: #fff; border-bottom: 1px solid #ddd; }\n .container { max-width: 1200px; margin: 0 auto; padding: 24px; }\n .template-card { display: grid; grid-template-columns: 1fr 1fr; gap: 24px; background: #fff; border-radius: 12px; padding: 24px; margin-bottom: 24px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); }\n .template-preview { display: flex; align-items: center; justify-content: center; }\n .template-img { max-width: 100%; height: auto; border: 1px solid #ddd; border-radius: 8px; cursor: pointer; transition: transform 0.2s; }\n .template-img:hover { transform: scale(1.02); }\n .template-info { padding: 12px 0; }\n .template-name { font-size: 24px; margin-bottom: 8px; color: #1a1a1a; }\n .template-desc { color: #666; margin-bottom: 16px; font-size: 16px; }\n .template-category { margin-bottom: 16px; font-size: 14px; color: #888; }\n .template-category code { background: #e8e8e8; padding: 2px 8px; border-radius: 4px; }\n .template-params h3 { font-size: 16px; margin-bottom: 12px; color: #444; border-bottom: 1px solid #eee; padding-bottom: 8px; }\n .param { margin-bottom: 12px; padding: 8px; background: #fafafa; border-radius: 6px; }\n .param-header { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }\n .param-name { font-size: 14px; font-weight: 600; color: #0066cc; }\n .param-type { font-size: 12px; color: #666; background: #e8e8e8; padding: 2px 6px; border-radius: 4px; }\n .badge { font-size: 11px; padding: 2px 6px; border-radius: 4px; text-transform: uppercase; }\n .badge.required { background: #fee2e2; color: #dc2626; }\n .badge.optional { background: #e0f2fe; color: #0284c7; }\n .param-desc { font-size: 13px; color: #666; margin-top: 4px; padding-left: 4px; }\n .no-params { color: #999; font-style: italic; }\n .modal { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.9); z-index: 1000; align-items: center; justify-content: center; }\n .modal.active { display: flex; }\n .modal img { max-width: 90%; max-height: 90%; object-fit: contain; }\n .modal-close { position: absolute; top: 20px; right: 30px; color: white; font-size: 40px; cursor: pointer; }\n @media (max-width: 768px) {\n .template-card { grid-template-columns: 1fr; }\n }\n </style>\n</head>\n<body>\n <h1>Template Preview</h1>\n <div class=\"container\">\n ${templateCards || '<p>No templates to preview</p>'}\n </div>\n <div class=\"modal\" id=\"modal\">\n <span class=\"modal-close\">&times;</span>\n <img id=\"modal-img\" src=\"\">\n </div>\n <script>\n // Click on image to show modal\n document.querySelectorAll('.template-img').forEach(img => {\n img.addEventListener('click', () => {\n document.getElementById('modal-img').src = img.src;\n document.getElementById('modal').classList.add('active');\n });\n });\n // Close modal\n document.getElementById('modal').addEventListener('click', (e) => {\n if (e.target.classList.contains('modal') || e.target.classList.contains('modal-close')) {\n document.getElementById('modal').classList.remove('active');\n }\n });\n document.addEventListener('keydown', (e) => {\n if (e.key === 'Escape') {\n document.getElementById('modal').classList.remove('active');\n }\n });\n </script>\n</body>\n</html>`;\n}\n\n/**\n * Generate sample YAML for a template\n */\nfunction generateSampleYaml(template: TemplateDefinition): string {\n const slide = {\n template: template.name,\n content: template.example ?? {},\n };\n return yaml.stringify({ slides: [slide] });\n}\n\n/**\n * Execute template preview\n */\nexport async function executeTemplatePreview(\n name: string | undefined,\n options: PreviewOptions\n): Promise<void> {\n // Validate: either name or --all must be specified\n if (!name && !options.all) {\n console.error(chalk.red('Error: Specify a template name or use --all'));\n process.exitCode = ExitCode.GeneralError;\n return;\n }\n\n const port = Number(options.port) || 8080;\n const previewDir = join(tmpdir(), `slide-gen-template-preview-${Date.now()}`);\n\n // Check marp-cli availability\n console.log('Checking for Marp CLI...');\n const marpAvailable = await checkMarpCliAvailable();\n if (!marpAvailable) {\n console.error(\n chalk.red(\n 'Error: Marp CLI not found. Install it with: npm install -g @marp-team/marp-cli'\n )\n );\n process.exitCode = ExitCode.GeneralError;\n return;\n }\n console.log(chalk.green('✓') + ' Marp CLI found');\n\n // Load configuration and templates\n const configLoader = new ConfigLoader();\n let configPath = options.config;\n\n if (!configPath) {\n configPath = await configLoader.findConfig(process.cwd());\n }\n\n const config = await configLoader.load(configPath);\n const templateLoader = await loadTemplates(options.config);\n\n // Get templates to preview\n let templates = templateLoader.list();\n if (name) {\n const template = templateLoader.get(name);\n if (!template) {\n console.error(chalk.red(`Error: Template \"${name}\" not found`));\n process.exitCode = ExitCode.GeneralError;\n return;\n }\n templates = [template];\n } else if (options.category) {\n templates = templateLoader.listByCategory(options.category);\n }\n\n if (templates.length === 0) {\n console.log('No templates found.');\n return;\n }\n\n console.log(`Found ${templates.length} template(s) to preview`);\n\n // Create preview directory\n await mkdir(previewDir, { recursive: true });\n\n // Initialize pipeline\n console.log('Initializing pipeline...');\n const pipeline = new Pipeline(config);\n\n try {\n await pipeline.initialize();\n } catch (error) {\n const message =\n error instanceof Error ? error.message : 'Unknown initialization error';\n console.error(chalk.red(`Error: Failed to initialize pipeline: ${message}`));\n process.exitCode = ExitCode.GeneralError;\n await rm(previewDir, { recursive: true, force: true });\n return;\n }\n\n // Generate screenshots for each template\n const templatePreviews: TemplatePreviewInfo[] = [];\n\n for (const template of templates) {\n console.log(`Processing template: ${chalk.cyan(template.name)}...`);\n\n // Generate sample YAML\n const sampleYaml = generateSampleYaml(template);\n const yamlPath = join(previewDir, `${template.name}.yaml`);\n await writeFile(yamlPath, sampleYaml);\n\n // Convert to markdown\n const mdPath = join(previewDir, `${template.name}.md`);\n try {\n await pipeline.runWithResult(yamlPath, { outputPath: mdPath });\n } catch (error) {\n const message =\n error instanceof PipelineError\n ? `${error.stage}: ${error.message}`\n : error instanceof Error\n ? error.message\n : 'Unknown error';\n console.warn(chalk.yellow(` Warning: Failed to convert ${template.name}: ${message}`));\n continue;\n }\n\n // Generate screenshot\n try {\n execFileSync('npx', ['marp', '--images', 'png', '-o', previewDir, mdPath], {\n stdio: 'pipe',\n });\n } catch {\n console.warn(chalk.yellow(` Warning: Failed to generate screenshot for ${template.name}`));\n continue;\n }\n\n // Collect slide info for this template (use first slide as preview)\n const templateSlides = await collectSlideInfo(previewDir, template.name, 'png');\n if (templateSlides.length > 0) {\n templatePreviews.push({\n template,\n imagePath: basename(templateSlides[0]!.path),\n });\n }\n\n console.log(chalk.green(' ✓') + ` ${template.name}`);\n }\n\n if (templatePreviews.length === 0) {\n console.error(chalk.red('Error: No template previews generated'));\n process.exitCode = ExitCode.GeneralError;\n await rm(previewDir, { recursive: true, force: true });\n return;\n }\n\n // Generate template preview HTML with parameter info\n const previewHtml = generateTemplatePreviewHtml(templatePreviews);\n await writeFile(join(previewDir, 'index.html'), previewHtml);\n\n // Start preview server\n console.log(`\\nStarting preview server on port ${chalk.cyan(port)}...`);\n\n let server: Server;\n try {\n server = await startStaticServer(previewDir, port, {\n messagePrefix: 'Template preview server',\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Failed to start server';\n console.error(chalk.red(`Error: ${message}`));\n process.exitCode = ExitCode.GeneralError;\n await rm(previewDir, { recursive: true, force: true });\n return;\n }\n\n // Open browser\n const url = `http://localhost:${port}`;\n try {\n // Dynamic import for optional 'open' package (ESM)\n // Use variable to prevent TypeScript from checking module existence at compile time\n const moduleName = 'open';\n const openModule = (await import(moduleName)) as { default: (target: string) => Promise<unknown> };\n await openModule.default(url);\n } catch {\n console.log(`Open ${chalk.cyan(url)} in your browser`);\n }\n\n console.log(`\\nShowing ${templatePreviews.length} template preview(s)`);\n console.log('Press Ctrl+C to stop the server');\n\n // Cleanup on exit\n const cleanup = async () => {\n server.close();\n await rm(previewDir, { recursive: true, force: true });\n };\n\n const signalHandler = async () => {\n console.log('\\n' + chalk.yellow('Template preview server stopped.'));\n await cleanup();\n process.exit(0);\n };\n\n process.on('SIGINT', signalHandler);\n process.on('SIGTERM', signalHandler);\n\n // Wait for server to close\n await new Promise<void>((resolve) => {\n server.on('close', () => resolve());\n });\n}\n\n/**\n * Create the templates command with subcommands\n */\nexport function createTemplatesCommand(): Command {\n const cmd = new Command('templates')\n .description('Manage and list templates');\n\n cmd.addCommand(createListCommand());\n cmd.addCommand(createInfoCommand());\n cmd.addCommand(createExampleCommand());\n cmd.addCommand(createPreviewSubcommand());\n\n return cmd;\n}\n","import { Command } from 'commander';\nimport { access, unlink, readdir, mkdir, writeFile, readFile, rm } from 'fs/promises';\nimport { basename, dirname, join, extname } from 'path';\nimport * as path from 'path';\nimport { tmpdir } from 'os';\nimport { spawn, execSync, execFileSync } from 'child_process';\nimport { createServer, Server } from 'http';\nimport chalk from 'chalk';\nimport { watch as chokidarWatch, FSWatcher } from 'chokidar';\nimport { Pipeline, PipelineError } from '../../core/pipeline';\nimport { ConfigLoader } from '../../config/loader';\nimport { ExitCode } from './convert';\n\nexport interface PreviewOptions {\n port?: number;\n watch?: boolean;\n config?: string;\n verbose?: boolean;\n signal?: AbortSignal;\n gallery?: boolean;\n slide?: number;\n}\n\nexport interface PreviewResult {\n success: boolean;\n errors: string[];\n}\n\nexport interface SlideInfo {\n path: string;\n title: string;\n index: number;\n}\n\n/**\n * Escape HTML special characters to prevent XSS\n */\nfunction escapeHtml(str: string): string {\n return str\n .replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;')\n .replace(/'/g, '&#39;');\n}\n\n/**\n * Generate HTML for gallery view with slide thumbnails\n */\nexport function generateGalleryHtml(slides: SlideInfo[]): string {\n const slideItems =\n slides.length > 0\n ? slides\n .map(\n (s) => `\n <div class=\"slide\" data-index=\"${s.index}\" data-path=\"${escapeHtml(s.path)}\">\n <img src=\"${escapeHtml(s.path)}\" alt=\"Slide ${s.index}\">\n <div class=\"slide-title\">${escapeHtml(s.title)}</div>\n </div>\n `\n )\n .join('')\n : '<p class=\"no-slides\">No slides available</p>';\n\n return `<!DOCTYPE html>\n<html>\n<head>\n <title>Slide Gallery</title>\n <style>\n * { box-sizing: border-box; margin: 0; padding: 0; }\n body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: #f5f5f5; }\n h1 { text-align: center; padding: 24px; color: #333; }\n .gallery { display: grid; grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); gap: 20px; padding: 20px; max-width: 1400px; margin: 0 auto; }\n .slide { cursor: pointer; border: 1px solid #ddd; border-radius: 8px; overflow: hidden; background: white; transition: transform 0.2s, box-shadow 0.2s; }\n .slide:hover { transform: translateY(-4px); box-shadow: 0 8px 16px rgba(0,0,0,0.1); }\n .slide img { width: 100%; height: auto; display: block; }\n .slide-title { padding: 12px; text-align: center; font-size: 14px; color: #666; border-top: 1px solid #eee; }\n .no-slides { text-align: center; padding: 40px; color: #999; }\n .modal { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.9); z-index: 1000; }\n .modal.active { display: flex; align-items: center; justify-content: center; }\n .modal img { max-width: 90%; max-height: 90%; object-fit: contain; }\n .modal-close { position: absolute; top: 20px; right: 30px; color: white; font-size: 40px; cursor: pointer; }\n .modal-nav { position: absolute; top: 50%; color: white; font-size: 60px; cursor: pointer; user-select: none; }\n .modal-nav.prev { left: 20px; }\n .modal-nav.next { right: 20px; }\n </style>\n</head>\n<body>\n <h1>Slide Gallery</h1>\n <div class=\"gallery\">\n ${slideItems}\n </div>\n <div class=\"modal\" id=\"modal\">\n <span class=\"modal-close\">&times;</span>\n <span class=\"modal-nav prev\">&lt;</span>\n <img id=\"modal-img\" src=\"\">\n <span class=\"modal-nav next\">&gt;</span>\n </div>\n <script>\n const slides = ${JSON.stringify(slides).replace(/<\\//g, '<\\\\/')};\n let currentIndex = 0;\n\n function showSlide(index, path) {\n currentIndex = slides.findIndex(s => s.index === index);\n document.getElementById('modal-img').src = path;\n document.getElementById('modal').classList.add('active');\n }\n\n function hideSlide(event) {\n if (event.target.classList.contains('modal') || event.target.classList.contains('modal-close')) {\n document.getElementById('modal').classList.remove('active');\n }\n }\n\n function navigateSlide(direction) {\n currentIndex = (currentIndex + direction + slides.length) % slides.length;\n const slide = slides[currentIndex];\n document.getElementById('modal-img').src = slide.path;\n }\n\n // Event delegation for slide clicks\n document.querySelector('.gallery').addEventListener('click', (e) => {\n const slideEl = e.target.closest('.slide');\n if (slideEl) {\n const index = parseInt(slideEl.dataset.index, 10);\n const path = slideEl.dataset.path;\n showSlide(index, path);\n }\n });\n\n // Modal event handlers\n document.getElementById('modal').addEventListener('click', hideSlide);\n document.querySelector('.modal-nav.prev').addEventListener('click', (e) => {\n e.stopPropagation();\n navigateSlide(-1);\n });\n document.querySelector('.modal-nav.next').addEventListener('click', (e) => {\n e.stopPropagation();\n navigateSlide(1);\n });\n\n document.addEventListener('keydown', (e) => {\n const modal = document.getElementById('modal');\n if (!modal.classList.contains('active')) return;\n if (e.key === 'Escape') modal.classList.remove('active');\n if (e.key === 'ArrowLeft') navigateSlide(-1);\n if (e.key === 'ArrowRight') navigateSlide(1);\n });\n </script>\n</body>\n</html>`;\n}\n\n/**\n * Escape special characters in a string for use in a regular expression\n */\nfunction escapeRegExp(str: string): string {\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\n/**\n * Collect slide information from screenshot directory\n */\nexport async function collectSlideInfo(\n dir: string,\n baseName: string,\n format: string\n): Promise<SlideInfo[]> {\n try {\n const files = await readdir(dir);\n const slidePattern = new RegExp(`^${escapeRegExp(baseName)}\\\\.(\\\\d{3})\\\\.${escapeRegExp(format)}$`);\n\n const slides: SlideInfo[] = [];\n for (const file of files) {\n const match = file.match(slidePattern);\n if (match) {\n const index = parseInt(match[1]!, 10);\n slides.push({\n path: join(dir, file),\n title: `Slide ${index}`,\n index,\n });\n }\n }\n\n return slides.sort((a, b) => a.index - b.index);\n } catch {\n return [];\n }\n}\n\n/**\n * Check if marp-cli is available in the system\n * Uses 'marp --version' directly instead of 'npx marp --version'\n * because npx is slow (searches local, global, and npm registry)\n */\nexport async function checkMarpCliAvailable(): Promise<boolean> {\n try {\n execSync('marp --version', { stdio: 'ignore', timeout: 5000 });\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Generate temporary output path for markdown file\n */\nexport function getTempOutputPath(inputPath: string): string {\n const base = basename(inputPath, '.yaml');\n return join(tmpdir(), `slide-gen-preview-${base}-${Date.now()}.md`);\n}\n\n/**\n * Build marp-cli command for preview\n */\nexport function buildMarpCommand(\n markdownPath: string,\n options: PreviewOptions\n): string {\n const parts = ['npx', 'marp', '--preview'];\n\n if (options.port) {\n parts.push('-p', String(options.port));\n }\n\n if (options.watch) {\n parts.push('--watch');\n }\n\n parts.push(markdownPath);\n\n return parts.join(' ');\n}\n\nexport interface StaticServerOptions {\n /** Initial slide number for URL hash */\n initialSlide?: number;\n /** Custom message prefix (default: \"Server\") */\n messagePrefix?: string;\n /** Suppress console output */\n silent?: boolean;\n}\n\n/**\n * Start a simple HTTP server to serve static files\n * Reusable for gallery preview, template preview, etc.\n */\nexport function startStaticServer(\n baseDir: string,\n port: number,\n options: StaticServerOptions = {}\n): Promise<Server> {\n return new Promise((resolve, reject) => {\n const mimeTypes: Record<string, string> = {\n '.html': 'text/html',\n '.png': 'image/png',\n '.jpg': 'image/jpeg',\n '.jpeg': 'image/jpeg',\n '.css': 'text/css',\n '.js': 'application/javascript',\n };\n\n const server = createServer(async (req, res) => {\n try {\n // Parse URL and get pathname only (ignore query strings)\n const urlPath = new URL(req.url || '/', `http://localhost`).pathname;\n const requestedPath = urlPath === '/' ? '/index.html' : urlPath;\n\n // Resolve to absolute path and normalize (handles .. and .)\n const resolvedBaseDir = path.resolve(baseDir);\n const filePath = path.resolve(baseDir, '.' + requestedPath);\n\n // Security: Ensure the resolved path is within baseDir (prevent path traversal)\n if (!filePath.startsWith(resolvedBaseDir + '/') && filePath !== resolvedBaseDir) {\n res.writeHead(403);\n res.end('Forbidden');\n return;\n }\n\n const ext = extname(filePath);\n const contentType = mimeTypes[ext] || 'application/octet-stream';\n\n const data = await readFile(filePath);\n res.writeHead(200, { 'Content-Type': contentType });\n res.end(data);\n } catch {\n res.writeHead(404);\n res.end('Not found');\n }\n });\n\n server.on('error', reject);\n server.listen(port, () => {\n const url = options.initialSlide\n ? `http://localhost:${port}/#slide-${options.initialSlide}`\n : `http://localhost:${port}`;\n if (!options.silent) {\n const prefix = options.messagePrefix ?? 'Server';\n console.log(`${prefix} running at ${chalk.cyan(url)}`);\n }\n resolve(server);\n });\n });\n}\n\n/**\n * Start a simple HTTP server to serve gallery files\n * @deprecated Use startStaticServer instead\n */\nexport function startGalleryServer(\n galleryDir: string,\n port: number,\n initialSlide?: number\n): Promise<Server> {\n return startStaticServer(galleryDir, port, {\n ...(initialSlide !== undefined && { initialSlide }),\n messagePrefix: 'Gallery server',\n });\n}\n\n/**\n * Execute gallery preview mode\n */\nexport async function executeGalleryPreview(\n inputPath: string,\n options: PreviewOptions\n): Promise<PreviewResult> {\n const errors: string[] = [];\n const port = Number(options.port) || 8080;\n const galleryDir = join(tmpdir(), `slide-gen-gallery-${Date.now()}`);\n\n // Validate input file exists\n try {\n await access(inputPath);\n } catch {\n console.error(chalk.red(`Error: File not found: ${inputPath}`));\n errors.push(`File not found: ${inputPath}`);\n process.exitCode = ExitCode.FileReadError;\n return { success: false, errors };\n }\n\n // Check marp-cli availability\n console.log('Checking for Marp CLI...');\n const marpAvailable = await checkMarpCliAvailable();\n if (!marpAvailable) {\n console.error(\n chalk.red(\n 'Error: Marp CLI not found. Install it with: npm install -g @marp-team/marp-cli'\n )\n );\n errors.push('Marp CLI not available');\n process.exitCode = ExitCode.GeneralError;\n return { success: false, errors };\n }\n console.log(chalk.green('✓') + ' Marp CLI found');\n\n // Create gallery directory\n await mkdir(galleryDir, { recursive: true });\n\n // Load configuration\n const configLoader = new ConfigLoader();\n let configPath = options.config;\n\n if (!configPath) {\n configPath = await configLoader.findConfig(dirname(inputPath));\n }\n\n const config = await configLoader.load(configPath);\n\n // Create and initialize pipeline\n console.log('Initializing pipeline...');\n const pipeline = new Pipeline(config);\n\n try {\n await pipeline.initialize();\n } catch (error) {\n const message =\n error instanceof Error ? error.message : 'Unknown initialization error';\n console.error(chalk.red(`Error: Failed to initialize pipeline: ${message}`));\n errors.push(message);\n process.exitCode = ExitCode.ConversionError;\n await rm(galleryDir, { recursive: true, force: true });\n return { success: false, errors };\n }\n\n // Generate markdown\n const tempMdPath = join(galleryDir, 'slides.md');\n console.log(`Converting ${chalk.cyan(inputPath)}...`);\n\n try {\n await pipeline.runWithResult(inputPath, { outputPath: tempMdPath });\n console.log(chalk.green('✓') + ' Conversion complete');\n } catch (error) {\n const message =\n error instanceof PipelineError\n ? `${error.stage}: ${error.message}`\n : error instanceof Error\n ? error.message\n : 'Unknown error';\n console.error(chalk.red(`Error: Conversion failed: ${message}`));\n errors.push(message);\n process.exitCode = ExitCode.ConversionError;\n await rm(galleryDir, { recursive: true, force: true });\n return { success: false, errors };\n }\n\n // Take screenshots\n console.log('Taking screenshots...');\n try {\n execFileSync('npx', ['marp', '--images', 'png', '-o', galleryDir, tempMdPath], {\n stdio: options.verbose ? 'inherit' : 'pipe',\n });\n console.log(chalk.green('✓') + ' Screenshots generated');\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Marp CLI failed';\n console.error(chalk.red(`Error: ${message}`));\n errors.push(message);\n process.exitCode = ExitCode.GeneralError;\n await rm(galleryDir, { recursive: true, force: true });\n return { success: false, errors };\n }\n\n // Collect slide info\n const slides = await collectSlideInfo(galleryDir, 'slides', 'png');\n\n if (slides.length === 0) {\n console.error(chalk.red('Error: No slides found'));\n errors.push('No slides generated');\n process.exitCode = ExitCode.GeneralError;\n await rm(galleryDir, { recursive: true, force: true });\n return { success: false, errors };\n }\n\n // Update paths to be relative for HTTP serving\n const relativeSlides = slides.map((s) => ({\n ...s,\n path: basename(s.path),\n }));\n\n // Generate gallery HTML\n const galleryHtml = generateGalleryHtml(relativeSlides);\n await writeFile(join(galleryDir, 'index.html'), galleryHtml);\n\n // Start gallery server\n console.log(`\\nStarting gallery server on port ${chalk.cyan(port)}...`);\n\n let server: Server;\n try {\n server = await startStaticServer(galleryDir, port, {\n ...(options.slide !== undefined && { initialSlide: options.slide }),\n messagePrefix: 'Gallery server',\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Failed to start server';\n console.error(chalk.red(`Error: ${message}`));\n errors.push(message);\n process.exitCode = ExitCode.GeneralError;\n await rm(galleryDir, { recursive: true, force: true });\n return { success: false, errors };\n }\n\n // Open browser\n const url = options.slide\n ? `http://localhost:${port}/#slide-${options.slide}`\n : `http://localhost:${port}`;\n\n try {\n // Dynamic import for optional 'open' package (ESM)\n // Use variable to prevent TypeScript from checking module existence at compile time\n const moduleName = 'open';\n const openModule = (await import(moduleName)) as { default: (target: string) => Promise<unknown> };\n await openModule.default(url);\n } catch {\n console.log(`Open ${chalk.cyan(url)} in your browser`);\n }\n\n console.log(`\\nShowing ${slides.length} slides in gallery mode`);\n console.log('Press Ctrl+C to stop the server');\n\n // Cleanup on exit\n const cleanup = async () => {\n server.close();\n await rm(galleryDir, { recursive: true, force: true });\n };\n\n if (options.signal) {\n options.signal.addEventListener('abort', cleanup);\n }\n\n const signalHandler = async () => {\n console.log('\\n' + chalk.yellow('Gallery server stopped.'));\n await cleanup();\n process.exit(0);\n };\n\n process.on('SIGINT', signalHandler);\n process.on('SIGTERM', signalHandler);\n\n // Wait for signal\n await new Promise<void>((resolve) => {\n if (options.signal) {\n options.signal.addEventListener('abort', () => resolve());\n }\n server.on('close', () => resolve());\n });\n\n return { success: true, errors };\n}\n\n/**\n * Create the preview command\n */\nexport function createPreviewCommand(): Command {\n return new Command('preview')\n .description('Preview the generated slides in browser (requires Marp CLI)')\n .argument('<input>', 'Input YAML file')\n .option('-p, --port <number>', 'Preview server port', '8080')\n .option('-w, --watch', 'Watch for changes and auto-reload')\n .option('-c, --config <path>', 'Config file path')\n .option('-v, --verbose', 'Verbose output')\n .option('-g, --gallery', 'Show thumbnail gallery')\n .option('-s, --slide <number>', 'Show specific slide', parseInt)\n .action(async (input: string, options: PreviewOptions) => {\n await executePreview(input, options);\n });\n}\n\n/**\n * Execute the preview command\n */\nexport async function executePreview(\n inputPath: string,\n options: PreviewOptions\n): Promise<PreviewResult> {\n // Route to gallery mode if requested\n if (options.gallery) {\n return executeGalleryPreview(inputPath, options);\n }\n\n const errors: string[] = [];\n const verbose = options.verbose ?? false;\n const port = Number(options.port) || 8080;\n\n // Check if immediately aborted (for testing)\n if (options.signal?.aborted) {\n try {\n await access(inputPath);\n } catch {\n errors.push(`File not found: ${inputPath}`);\n return { success: false, errors };\n }\n return { success: true, errors };\n }\n\n // Validate input file exists\n try {\n await access(inputPath);\n } catch {\n console.error(chalk.red(`Error: File not found: ${inputPath}`));\n errors.push(`File not found: ${inputPath}`);\n process.exitCode = ExitCode.FileReadError;\n return { success: false, errors };\n }\n\n // Check marp-cli availability\n console.log('Checking for Marp CLI...');\n const marpAvailable = await checkMarpCliAvailable();\n if (!marpAvailable) {\n console.error(\n chalk.red(\n 'Error: Marp CLI not found. Install it with: npm install -g @marp-team/marp-cli'\n )\n );\n errors.push('Marp CLI not available');\n process.exitCode = ExitCode.GeneralError;\n return { success: false, errors };\n }\n console.log(chalk.green('✓') + ' Marp CLI found');\n\n // Load configuration\n const configLoader = new ConfigLoader();\n let configPath = options.config;\n\n if (!configPath) {\n configPath = await configLoader.findConfig(dirname(inputPath));\n }\n\n const config = await configLoader.load(configPath);\n\n // Create and initialize pipeline\n console.log('Initializing pipeline...');\n const pipeline = new Pipeline(config);\n\n try {\n await pipeline.initialize();\n } catch (error) {\n const message =\n error instanceof Error ? error.message : 'Unknown initialization error';\n console.error(chalk.red(`Error: Failed to initialize pipeline: ${message}`));\n errors.push(message);\n process.exitCode = ExitCode.ConversionError;\n return { success: false, errors };\n }\n\n // Generate initial markdown\n const tempMarkdownPath = getTempOutputPath(inputPath);\n console.log(`Converting ${chalk.cyan(inputPath)}...`);\n\n try {\n await pipeline.runWithResult(inputPath, { outputPath: tempMarkdownPath });\n console.log(chalk.green('✓') + ' Initial conversion complete');\n } catch (error) {\n const message =\n error instanceof PipelineError\n ? `${error.stage}: ${error.message}`\n : error instanceof Error\n ? error.message\n : 'Unknown error';\n console.error(chalk.red(`Error: Conversion failed: ${message}`));\n errors.push(message);\n process.exitCode = ExitCode.ConversionError;\n return { success: false, errors };\n }\n\n // Start marp preview server\n console.log(`\\nStarting preview server on port ${chalk.cyan(port)}...`);\n\n const marpCommand = buildMarpCommand(tempMarkdownPath, {\n ...options,\n port,\n watch: false, // We handle watch ourselves if needed\n });\n\n if (verbose) {\n console.log(`Running: ${marpCommand}`);\n }\n\n const marpProcess = spawn('npx', ['marp', '--preview', '-p', String(port), tempMarkdownPath], {\n stdio: 'inherit',\n shell: true,\n });\n\n let watcher: FSWatcher | null = null;\n let debounceTimer: ReturnType<typeof setTimeout> | null = null;\n\n // Set up file watcher if watch mode enabled\n if (options.watch) {\n console.log(`\\nWatching ${chalk.cyan(inputPath)} for changes...`);\n\n watcher = chokidarWatch(inputPath, {\n persistent: true,\n ignoreInitial: true,\n awaitWriteFinish: {\n stabilityThreshold: 100,\n pollInterval: 50,\n },\n });\n\n watcher.on('change', () => {\n if (debounceTimer) {\n clearTimeout(debounceTimer);\n }\n\n debounceTimer = setTimeout(async () => {\n console.log(`\\n[${new Date().toLocaleTimeString('en-GB')}] File changed, reconverting...`);\n\n try {\n await pipeline.runWithResult(inputPath, { outputPath: tempMarkdownPath });\n console.log(chalk.green('✓') + ' Reconversion complete');\n } catch (error) {\n const message =\n error instanceof PipelineError\n ? `${error.stage}: ${error.message}`\n : error instanceof Error\n ? error.message\n : 'Unknown error';\n console.error(chalk.red(`✗ Reconversion failed: ${message}`));\n }\n }, 300);\n });\n }\n\n // Cleanup function\n const cleanup = async () => {\n if (debounceTimer) {\n clearTimeout(debounceTimer);\n }\n watcher?.close();\n marpProcess.kill();\n\n // Clean up temp file\n try {\n await unlink(tempMarkdownPath);\n } catch {\n // Ignore cleanup errors\n }\n };\n\n // Handle abort signal\n if (options.signal) {\n options.signal.addEventListener('abort', () => {\n cleanup();\n });\n }\n\n // Handle process signals\n const signalHandler = async () => {\n console.log('\\n' + chalk.yellow('Preview stopped.'));\n await cleanup();\n process.exit(0);\n };\n\n process.on('SIGINT', signalHandler);\n process.on('SIGTERM', signalHandler);\n\n // Wait for marp process or abort signal\n await new Promise<void>((resolve) => {\n marpProcess.on('exit', () => {\n cleanup();\n resolve();\n });\n\n if (options.signal) {\n options.signal.addEventListener('abort', () => resolve());\n }\n });\n\n return {\n success: errors.length === 0,\n errors,\n };\n}\n","import { Command } from 'commander';\nimport chalk from 'chalk';\nimport * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport { parse as parseYaml, stringify as stringifyYaml } from 'yaml';\nimport { IconRegistryLoader } from '../../icons/registry.js';\nimport { IconResolver } from '../../icons/resolver.js';\nimport { IconFetcher, isExternalSource } from '../../icons/fetcher.js';\nimport { ConfigLoader } from '../../config/loader.js';\nimport type { IconSource, IconRegistry } from '../../icons/schema.js';\nimport { ExitCode } from './convert.js';\n\ntype OutputFormat = 'table' | 'json' | 'llm';\n\ninterface ListOptions {\n source?: string;\n aliases?: boolean;\n config?: string;\n format?: OutputFormat;\n category?: string;\n showStatus?: boolean;\n}\n\ninterface SearchOptions {\n config?: string;\n format?: OutputFormat;\n}\n\ninterface PreviewOptions {\n format?: 'svg' | 'html';\n size?: string;\n color?: string;\n config?: string;\n}\n\ninterface SearchResult {\n query: string;\n aliases: Array<{ alias: string; target: string }>;\n sources: Array<{ name: string; prefix: string; type: string }>;\n}\n\ninterface AddOptions {\n from?: string;\n search?: boolean;\n saveLocal?: boolean;\n config?: string;\n}\n\ninterface SyncOptions {\n localize?: boolean;\n config?: string;\n}\n\n// Re-export isExternalSource for backward compatibility (used by tests)\nexport { isExternalSource };\n\n/**\n * Extract all icon references from a presentation\n */\nexport function extractIconReferences(presentation: unknown): string[] {\n const icons = new Set<string>();\n\n function extractFromValue(value: unknown): void {\n if (value === null || value === undefined) {\n return;\n }\n\n if (typeof value === 'object') {\n if (Array.isArray(value)) {\n for (const item of value) {\n extractFromValue(item);\n }\n } else {\n const obj = value as Record<string, unknown>;\n // Check for icon property\n if (typeof obj['icon'] === 'string') {\n icons.add(obj['icon']);\n }\n // Recursively check all properties\n for (const key of Object.keys(obj)) {\n extractFromValue(obj[key]);\n }\n }\n }\n }\n\n extractFromValue(presentation);\n return Array.from(icons);\n}\n\n/**\n * Format icon sources for table output\n */\nfunction formatTableSourceList(sources: IconSource[]): string {\n const lines: string[] = ['Icon Sources:', ''];\n\n // Calculate column widths\n const maxNameLen = Math.max(...sources.map((s) => s.name.length), 4);\n const maxPrefixLen = Math.max(...sources.map((s) => s.prefix.length), 6);\n const maxTypeLen = Math.max(...sources.map((s) => s.type.length), 4);\n\n // Header\n const namePad = 'Name'.padEnd(maxNameLen);\n const prefixPad = 'Prefix'.padEnd(maxPrefixLen);\n const typePad = 'Type'.padEnd(maxTypeLen);\n lines.push(` ${namePad} ${prefixPad} ${typePad}`);\n lines.push(` ${'─'.repeat(maxNameLen)} ${'─'.repeat(maxPrefixLen)} ${'─'.repeat(maxTypeLen)}`);\n\n // Data rows\n for (const source of sources) {\n const name = source.name.padEnd(maxNameLen);\n const prefix = source.prefix.padEnd(maxPrefixLen);\n const type = source.type.padEnd(maxTypeLen);\n lines.push(` ${name} ${prefix} ${type}`);\n }\n\n return lines.join('\\n');\n}\n\n/**\n * Format icon sources for JSON output\n */\nfunction formatJsonSourceList(sources: IconSource[]): string {\n const output = sources.map((s) => ({\n name: s.name,\n type: s.type,\n prefix: s.prefix,\n ...(s.url ? { url: s.url } : {}),\n ...(s.path ? { path: s.path } : {}),\n }));\n return JSON.stringify(output, null, 2);\n}\n\n/**\n * Format icon source list in the specified format\n */\nexport function formatIconSourceList(\n sources: IconSource[],\n format: OutputFormat\n): string {\n switch (format) {\n case 'json':\n return formatJsonSourceList(sources);\n case 'table':\n default:\n return formatTableSourceList(sources);\n }\n}\n\n/**\n * Category to alias patterns mapping\n */\nconst CATEGORY_PATTERNS: Record<string, RegExp[]> = {\n medical: [/^(health|hospital|clinic|ambulance|emergency|stethoscope|syringe|vaccine|pill|medicine|doctor|nurse|patient)/i, /^health:/],\n action: [/^(planning|action|analysis|start|stop|pause|save|edit|delete|add|remove|search|refresh|sync|upload|download)/i],\n status: [/^(success|warning|error|info|question|pending|completed|cancelled|approved|rejected)/i],\n navigation: [/^(home|back|forward|up|down|left|right|expand|collapse|menu|close)/i],\n communication: [/^(email|phone|chat|message|notification|feedback|comment)/i],\n business: [/^(workflow|process|cycle|milestone|target|goal|kpi|metric|report|dashboard|chart)/i],\n};\n\n/**\n * Filter aliases by category\n */\nexport function filterAliasesByCategory(\n aliases: Record<string, string>,\n category: string\n): Record<string, string> {\n const patterns = CATEGORY_PATTERNS[category.toLowerCase()];\n\n if (!patterns) {\n // Unknown category, return all aliases\n return aliases;\n }\n\n const filtered: Record<string, string> = {};\n for (const [alias, target] of Object.entries(aliases)) {\n const matchesPattern = patterns.some(pattern =>\n pattern.test(alias) || pattern.test(target)\n );\n if (matchesPattern) {\n filtered[alias] = target;\n }\n }\n\n return filtered;\n}\n\n/**\n * Get icon status (local or external)\n */\nfunction getIconStatus(target: string): 'local' | 'external' {\n const colonIndex = target.indexOf(':');\n if (colonIndex === -1) {\n return 'local';\n }\n const prefix = target.substring(0, colonIndex);\n return isExternalSource(prefix) ? 'external' : 'local';\n}\n\n/**\n * Format aliases with status for table output\n */\nexport function formatAliasesListWithStatus(\n aliases: Record<string, string>,\n format: 'table' | 'json'\n): string {\n const entries = Object.entries(aliases);\n\n if (entries.length === 0) {\n return 'No aliases defined.';\n }\n\n if (format === 'json') {\n const result = entries.map(([alias, target]) => ({\n alias,\n target,\n status: getIconStatus(target),\n }));\n return JSON.stringify(result, null, 2);\n }\n\n const lines: string[] = ['Icon Aliases with Status:', ''];\n\n // Calculate column widths\n const maxAliasLen = Math.max(...entries.map(([a]) => a.length), 5);\n const maxTargetLen = Math.max(...entries.map(([, t]) => t.length), 6);\n\n // Header\n const aliasPad = 'Alias'.padEnd(maxAliasLen);\n const targetPad = 'Target'.padEnd(maxTargetLen);\n lines.push(` ${aliasPad} ${targetPad} Status`);\n lines.push(` ${'─'.repeat(maxAliasLen)} ${'─'.repeat(maxTargetLen)} ${'─'.repeat(10)}`);\n\n // Sort alphabetically\n entries.sort((a, b) => a[0].localeCompare(b[0]));\n\n for (const [alias, target] of entries) {\n const aliasStr = alias.padEnd(maxAliasLen);\n const targetStr = target.padEnd(maxTargetLen);\n const status = getIconStatus(target);\n const statusStr = status === 'local' ? '[local]' : '[external]';\n lines.push(` ${aliasStr} ${targetStr} ${statusStr}`);\n }\n\n return lines.join('\\n');\n}\n\n/**\n * Format aliases for LLM output (YAML format)\n */\nexport function formatAliasesListLLM(aliases: Record<string, string>): string {\n const lines: string[] = [\n '# Icon Aliases',\n '# Use these semantic names instead of raw icon references',\n '',\n 'aliases:',\n ];\n\n // Group by category for better readability\n const entries = Object.entries(aliases).sort((a, b) => a[0].localeCompare(b[0]));\n\n for (const [alias, target] of entries) {\n lines.push(` ${alias}: \"${target}\"`);\n }\n\n return lines.join('\\n');\n}\n\n/**\n * Format aliases for table output\n */\nfunction formatTableAliases(aliases: Record<string, string>): string {\n const entries = Object.entries(aliases);\n\n if (entries.length === 0) {\n return 'No aliases defined.';\n }\n\n const lines: string[] = ['Icon Aliases:', ''];\n\n // Calculate column widths\n const maxAliasLen = Math.max(...entries.map(([a]) => a.length), 5);\n const maxTargetLen = Math.max(...entries.map(([, t]) => t.length), 6);\n\n // Header\n const aliasPad = 'Alias'.padEnd(maxAliasLen);\n const targetPad = 'Target'.padEnd(maxTargetLen);\n lines.push(` ${aliasPad} ${targetPad}`);\n lines.push(` ${'─'.repeat(maxAliasLen)} ${'─'.repeat(maxTargetLen)}`);\n\n // Sort alphabetically\n entries.sort((a, b) => a[0].localeCompare(b[0]));\n\n for (const [alias, target] of entries) {\n const aliasStr = alias.padEnd(maxAliasLen);\n lines.push(` ${aliasStr} ${target}`);\n }\n\n return lines.join('\\n');\n}\n\n/**\n * Format aliases for JSON output\n */\nfunction formatJsonAliases(aliases: Record<string, string>): string {\n return JSON.stringify(aliases, null, 2);\n}\n\n/**\n * Format aliases list in the specified format\n */\nexport function formatAliasesList(\n aliases: Record<string, string>,\n format: OutputFormat\n): string {\n switch (format) {\n case 'json':\n return formatJsonAliases(aliases);\n case 'table':\n default:\n return formatTableAliases(aliases);\n }\n}\n\n/**\n * Format search results for table output\n */\nfunction formatTableSearchResults(results: SearchResult): string {\n const lines: string[] = [`Search results for \"${results.query}\"`, ''];\n\n const hasResults = results.aliases.length > 0 || results.sources.length > 0;\n\n if (!hasResults) {\n lines.push('No results found.');\n return lines.join('\\n');\n }\n\n // Aliases section\n if (results.aliases.length > 0) {\n lines.push('Aliases:');\n for (const { alias, target } of results.aliases) {\n lines.push(` ${alias} → ${target}`);\n }\n lines.push('');\n }\n\n // Sources section\n if (results.sources.length > 0) {\n lines.push('Sources:');\n for (const source of results.sources) {\n lines.push(` ${source.name} (${source.prefix}:) [${source.type}]`);\n }\n }\n\n return lines.join('\\n').trim();\n}\n\n/**\n * Format search results for JSON output\n */\nfunction formatJsonSearchResults(results: SearchResult): string {\n return JSON.stringify(results, null, 2);\n}\n\n/**\n * Format search results in the specified format\n */\nexport function formatSearchResults(\n results: SearchResult,\n format: OutputFormat\n): string {\n switch (format) {\n case 'json':\n return formatJsonSearchResults(results);\n case 'table':\n default:\n return formatTableSearchResults(results);\n }\n}\n\n/**\n * Load icon registry from config\n */\nasync function loadRegistry(configPath?: string): Promise<IconRegistryLoader> {\n const configLoader = new ConfigLoader();\n\n if (!configPath) {\n configPath = await configLoader.findConfig(process.cwd());\n }\n\n const config = await configLoader.load(configPath);\n const registry = new IconRegistryLoader();\n\n if (config.icons?.registry) {\n await registry.load(config.icons.registry);\n }\n\n return registry;\n}\n\n/**\n * Search for icons matching query\n */\nfunction searchIcons(\n registry: IconRegistryLoader,\n query: string\n): SearchResult {\n const lowerQuery = query.toLowerCase();\n\n // Search aliases\n const aliases = Object.entries(registry.getAliases())\n .filter(\n ([alias, target]) =>\n alias.toLowerCase().includes(lowerQuery) ||\n target.toLowerCase().includes(lowerQuery)\n )\n .map(([alias, target]) => ({ alias, target }));\n\n // Search sources\n const sources = registry\n .getSources()\n .filter(\n (source) =>\n source.name.toLowerCase().includes(lowerQuery) ||\n source.prefix.toLowerCase().includes(lowerQuery)\n )\n .map((s) => ({ name: s.name, prefix: s.prefix, type: s.type }));\n\n return { query, aliases, sources };\n}\n\n/**\n * Create the icons list subcommand\n */\nfunction createListCommand(): Command {\n return new Command('list')\n .description('List icon sources and aliases')\n .option('--source <name>', 'Filter by source name')\n .option('--aliases', 'Show only aliases')\n .option('--format <fmt>', 'Output format (table/json/llm)', 'table')\n .option('--category <cat>', 'Filter aliases by category (medical/action/status/navigation/communication/business)')\n .option('--show-status', 'Show local/external status for aliases')\n .option('-c, --config <path>', 'Config file path')\n .action(async (options: ListOptions) => {\n try {\n const registry = await loadRegistry(options.config);\n\n if (!registry.isLoaded()) {\n console.log('No icon registry found.');\n return;\n }\n\n const format = (options.format ?? 'table') as OutputFormat;\n\n if (options.aliases) {\n // Show only aliases\n let aliases = registry.getAliases();\n\n // Filter by category if specified\n if (options.category) {\n aliases = filterAliasesByCategory(aliases, options.category);\n }\n\n // Choose output format\n let output: string;\n if (format === 'llm') {\n output = formatAliasesListLLM(aliases);\n } else if (options.showStatus) {\n output = formatAliasesListWithStatus(aliases, format === 'json' ? 'json' : 'table');\n } else {\n output = formatAliasesList(aliases, format === 'json' ? 'json' : 'table');\n }\n console.log(output);\n return;\n }\n\n if (options.source) {\n // Filter by source\n const sources = registry.getSources().filter(\n (s) => s.name === options.source || s.prefix === options.source\n );\n\n if (sources.length === 0) {\n console.error(chalk.yellow(`No source found matching \"${options.source}\"`));\n return;\n }\n\n const output = formatIconSourceList(sources, format);\n console.log(output);\n return;\n }\n\n // Show all sources\n const sources = registry.getSources();\n const output = formatIconSourceList(sources, format);\n console.log(output);\n } catch (error) {\n console.error(\n chalk.red(`Error: ${error instanceof Error ? error.message : 'Unknown error'}`)\n );\n process.exitCode = ExitCode.GeneralError;\n }\n });\n}\n\n/**\n * Create the icons search subcommand\n */\nfunction createSearchCommand(): Command {\n return new Command('search')\n .description('Search for icons by name or keyword')\n .argument('<query>', 'Search query')\n .option('--format <fmt>', 'Output format (table/json)', 'table')\n .option('-c, --config <path>', 'Config file path')\n .action(async (query: string, options: SearchOptions) => {\n try {\n const registry = await loadRegistry(options.config);\n\n if (!registry.isLoaded()) {\n console.log('No icon registry found.');\n return;\n }\n\n const format = (options.format ?? 'table') as OutputFormat;\n const results = searchIcons(registry, query);\n const output = formatSearchResults(results, format);\n console.log(output);\n } catch (error) {\n console.error(\n chalk.red(`Error: ${error instanceof Error ? error.message : 'Unknown error'}`)\n );\n process.exitCode = ExitCode.GeneralError;\n }\n });\n}\n\n/**\n * Add an alias to the registry file\n */\nexport async function addAliasToRegistry(\n registryPath: string,\n alias: string,\n target: string\n): Promise<void> {\n const content = await fs.readFile(registryPath, 'utf-8');\n const registry = parseYaml(content) as IconRegistry;\n\n // Check if alias already exists\n if (registry.aliases && registry.aliases[alias]) {\n throw new Error(`Alias already exists: ${alias}`);\n }\n\n // Add the new alias\n if (!registry.aliases) {\n registry.aliases = {};\n }\n registry.aliases[alias] = target;\n\n // Write back\n await fs.writeFile(registryPath, stringifyYaml(registry), 'utf-8');\n}\n\n/**\n * Update an existing alias in the registry file (or add if not exists)\n */\nexport async function updateAliasInRegistry(\n registryPath: string,\n alias: string,\n target: string\n): Promise<void> {\n const content = await fs.readFile(registryPath, 'utf-8');\n const registry = parseYaml(content) as IconRegistry;\n\n // Add or update the alias\n if (!registry.aliases) {\n registry.aliases = {};\n }\n registry.aliases[alias] = target;\n\n // Write back\n await fs.writeFile(registryPath, stringifyYaml(registry), 'utf-8');\n}\n\n/**\n * Get registry path from config\n */\nasync function getRegistryPath(configPath?: string): Promise<string> {\n const configLoader = new ConfigLoader();\n\n let resolvedConfigPath = configPath;\n if (!resolvedConfigPath) {\n resolvedConfigPath = await configLoader.findConfig(process.cwd());\n }\n\n if (!resolvedConfigPath) {\n // No config found, use default registry path\n return path.join(process.cwd(), 'icons', 'registry.yaml');\n }\n\n const config = await configLoader.load(resolvedConfigPath);\n\n if (config.icons?.registry) {\n // Make path relative to config file location\n const configDir = path.dirname(resolvedConfigPath);\n return path.resolve(configDir, config.icons.registry);\n }\n\n // Default registry path\n return path.join(process.cwd(), 'icons', 'registry.yaml');\n}\n\n/**\n * Create the icons add subcommand\n */\nfunction createAddCommand(): Command {\n return new Command('add')\n .description('Add an icon alias to registry (fetches and saves locally by default)')\n .argument('<alias>', 'Alias name to add')\n .option('--from <icon>', 'Source icon reference (e.g., health:stethoscope)')\n .option('--search', 'Search for icon interactively')\n .option('--no-save-local', 'Do not save SVG locally (not recommended)')\n .option('-c, --config <path>', 'Config file path')\n .action(async (alias: string, options: AddOptions) => {\n try {\n const registryPath = await getRegistryPath(options.config);\n\n // Check if alias already exists\n const registry = new IconRegistryLoader();\n await registry.load(registryPath);\n\n if (registry.getAliases()[alias]) {\n console.error(chalk.red(`Error: Alias already exists: ${alias}`));\n process.exitCode = ExitCode.GeneralError;\n return;\n }\n\n // Get icon reference\n let iconRef: string;\n if (options.from) {\n iconRef = options.from;\n } else if (options.search) {\n console.error(chalk.yellow('Interactive search not yet implemented. Use --from instead.'));\n process.exitCode = ExitCode.GeneralError;\n return;\n } else {\n console.error(chalk.red('Error: Either --from or --search is required'));\n process.exitCode = ExitCode.GeneralError;\n return;\n }\n\n // Get fetched directory from registry path\n const registryDir = path.dirname(registryPath);\n const fetchedDir = path.join(registryDir, 'fetched');\n\n // Fetch and save\n const fetcher = new IconFetcher({\n fetchedDir,\n saveLocally: options.saveLocal !== false,\n });\n\n const saveLocal = options.saveLocal !== false;\n\n try {\n await fetcher.fetchAndSave(iconRef);\n } catch (error) {\n console.error(chalk.red(`Error fetching icon: ${error instanceof Error ? error.message : 'Unknown error'}`));\n process.exitCode = ExitCode.GeneralError;\n return;\n }\n\n // Determine final reference\n let finalRef: string;\n if (saveLocal) {\n const parsed = fetcher.parseReference(iconRef);\n if (!parsed) {\n console.error(chalk.red(`Invalid icon reference: ${iconRef}`));\n process.exitCode = ExitCode.GeneralError;\n return;\n }\n const setDir = fetcher.getIconifySet(parsed.prefix);\n finalRef = `fetched:${setDir}/${parsed.name}`;\n } else {\n finalRef = iconRef;\n }\n\n // Add to registry\n await addAliasToRegistry(registryPath, alias, finalRef);\n\n if (saveLocal) {\n console.log(chalk.green(`Added alias: ${alias} -> ${finalRef}`));\n console.log(chalk.dim(`SVG saved to: ${fetchedDir}/${fetcher.getIconifySet(fetcher.parseReference(iconRef)!.prefix)}/${fetcher.parseReference(iconRef)!.name}.svg`));\n } else {\n console.log(chalk.yellow(`Added alias: ${alias} -> ${finalRef}`));\n console.log(chalk.yellow('Warning: SVG not saved locally. Project may not be reproducible.'));\n }\n } catch (error) {\n console.error(\n chalk.red(`Error: ${error instanceof Error ? error.message : 'Unknown error'}`)\n );\n process.exitCode = ExitCode.GeneralError;\n }\n });\n}\n\ninterface IconStatus {\n alias: string;\n resolved: string;\n status: 'local' | 'external' | 'missing';\n}\n\n/**\n * Create the icons sync subcommand\n */\nfunction createSyncCommand(): Command {\n return new Command('sync')\n .description('Analyze icon usage and localize external icons')\n .argument('<input>', 'Presentation YAML file')\n .option('--localize', 'Download and save external icons locally')\n .option('-c, --config <path>', 'Config file path')\n .action(async (input: string, options: SyncOptions) => {\n try {\n // Load presentation\n let presentationContent: string;\n try {\n presentationContent = await fs.readFile(input, 'utf-8');\n } catch {\n console.error(chalk.red(`Error: File not found: ${input}`));\n process.exitCode = ExitCode.GeneralError;\n return;\n }\n\n const presentation = parseYaml(presentationContent);\n\n // Load registry\n const registryPath = await getRegistryPath(options.config);\n const registry = new IconRegistryLoader();\n try {\n await registry.load(registryPath);\n } catch {\n console.error(chalk.red('Error: No icon registry found'));\n process.exitCode = ExitCode.GeneralError;\n return;\n }\n\n // Extract icons from presentation\n const usedIcons = extractIconReferences(presentation);\n\n if (usedIcons.length === 0) {\n console.log(chalk.dim('No icons found in presentation.'));\n return;\n }\n\n // Analyze each icon\n const report = {\n local: [] as IconStatus[],\n external: [] as IconStatus[],\n missing: [] as string[],\n };\n\n for (const icon of usedIcons) {\n const resolved = registry.resolveAlias(icon);\n const parsed = registry.parseIconReference(resolved);\n\n if (!parsed) {\n // Not a valid icon reference\n report.missing.push(icon);\n continue;\n }\n\n const source = registry.getSource(parsed.prefix);\n if (!source) {\n report.missing.push(icon);\n continue;\n }\n\n if (isExternalSource(parsed.prefix)) {\n report.external.push({ alias: icon, resolved, status: 'external' });\n } else {\n report.local.push({ alias: icon, resolved, status: 'local' });\n }\n }\n\n // Output report\n console.log(chalk.bold('\\nIcon Sync Report'));\n console.log('─'.repeat(40));\n\n if (report.local.length > 0) {\n console.log(chalk.green(`\\n✓ Local icons (${report.local.length}):`));\n for (const icon of report.local) {\n console.log(` ${icon.alias} -> ${icon.resolved}`);\n }\n }\n\n if (report.external.length > 0) {\n console.log(chalk.yellow(`\\n⚠ External icons (${report.external.length}):`));\n for (const icon of report.external) {\n console.log(` ${icon.alias} -> ${icon.resolved}`);\n }\n }\n\n if (report.missing.length > 0) {\n console.log(chalk.red(`\\n✗ Missing icons (${report.missing.length}):`));\n for (const icon of report.missing) {\n console.log(` ${icon}`);\n }\n }\n\n // Localize external icons if requested\n if (options.localize && report.external.length > 0) {\n console.log(chalk.blue('\\nLocalizing external icons...'));\n\n const registryDir = path.dirname(registryPath);\n const fetchedDir = path.join(registryDir, 'fetched');\n const fetcher = new IconFetcher({ fetchedDir });\n\n for (const icon of report.external) {\n try {\n await fetcher.fetchAndSave(icon.resolved);\n const parsed = registry.parseIconReference(icon.resolved);\n if (parsed) {\n const setDir = fetcher.getIconifySet(parsed.prefix);\n const localRef = `fetched:${setDir}/${parsed.name}`;\n await updateAliasInRegistry(registryPath, icon.alias, localRef);\n console.log(chalk.green(` ✓ ${icon.alias} -> ${localRef}`));\n }\n } catch (error) {\n console.log(chalk.red(` ✗ ${icon.alias}: ${error instanceof Error ? error.message : 'Unknown error'}`));\n }\n }\n\n console.log(chalk.green('\\nDone! External icons have been saved locally.'));\n } else if (report.external.length > 0) {\n console.log(chalk.dim('\\nRun with --localize to save external icons locally.'));\n }\n } catch (error) {\n console.error(\n chalk.red(`Error: ${error instanceof Error ? error.message : 'Unknown error'}`)\n );\n process.exitCode = ExitCode.GeneralError;\n }\n });\n}\n\n/**\n * Create the icons preview subcommand\n */\nfunction createPreviewCommand(): Command {\n return new Command('preview')\n .description('Preview an icon')\n .argument('<name>', 'Icon name or alias')\n .option('--format <fmt>', 'Output format (svg/html)', 'html')\n .option('--size <size>', 'Icon size', '24px')\n .option('--color <color>', 'Icon color', 'currentColor')\n .option('-c, --config <path>', 'Config file path')\n .action(async (name: string, options: PreviewOptions) => {\n try {\n const registry = await loadRegistry(options.config);\n\n if (!registry.isLoaded()) {\n console.error(chalk.red('Error: No icon registry found'));\n process.exitCode = ExitCode.GeneralError;\n return;\n }\n\n const resolver = new IconResolver(registry);\n\n const iconOptions: { size?: string; color?: string } = {};\n if (options.size) {\n iconOptions.size = options.size;\n }\n if (options.color) {\n iconOptions.color = options.color;\n }\n\n const rendered = await resolver.render(name, iconOptions);\n\n if (options.format === 'svg') {\n // Output raw SVG if it's an SVG\n console.log(rendered);\n } else {\n // Wrap in HTML for preview\n const html = `<!DOCTYPE html>\n<html>\n<head>\n <meta charset=\"utf-8\">\n <title>Icon Preview: ${name}</title>\n <link href=\"https://fonts.googleapis.com/icon?family=Material+Icons\" rel=\"stylesheet\">\n <style>\n body {\n display: flex;\n align-items: center;\n justify-content: center;\n min-height: 100vh;\n margin: 0;\n font-family: system-ui, sans-serif;\n background: #f5f5f5;\n }\n .preview {\n padding: 2rem;\n background: white;\n border-radius: 8px;\n box-shadow: 0 2px 8px rgba(0,0,0,0.1);\n text-align: center;\n }\n .icon-container {\n margin-bottom: 1rem;\n }\n .icon-name {\n color: #666;\n font-size: 14px;\n }\n .material-icons {\n font-family: 'Material Icons';\n font-weight: normal;\n font-style: normal;\n display: inline-block;\n line-height: 1;\n text-transform: none;\n letter-spacing: normal;\n word-wrap: normal;\n white-space: nowrap;\n direction: ltr;\n -webkit-font-smoothing: antialiased;\n }\n </style>\n</head>\n<body>\n <div class=\"preview\">\n <div class=\"icon-container\">\n ${rendered}\n </div>\n <div class=\"icon-name\">${name}</div>\n </div>\n</body>\n</html>`;\n console.log(html);\n }\n } catch (error) {\n console.error(\n chalk.red(`Error: ${error instanceof Error ? error.message : 'Unknown error'}`)\n );\n process.exitCode = ExitCode.GeneralError;\n }\n });\n}\n\n/**\n * Create the icons command with subcommands\n */\nexport function createIconsCommand(): Command {\n const cmd = new Command('icons')\n .description('Manage and search icons');\n\n cmd.addCommand(createListCommand());\n cmd.addCommand(createSearchCommand());\n cmd.addCommand(createPreviewCommand());\n cmd.addCommand(createAddCommand());\n cmd.addCommand(createSyncCommand());\n\n return cmd;\n}\n","import * as fs from \"node:fs/promises\";\nimport * as path from \"node:path\";\nimport { stringify as stringifyYaml, parse as parseYaml } from \"yaml\";\n\n/**\n * Options for the IconFetcher\n */\nexport interface FetcherOptions {\n /** Directory to save fetched icons (default: icons/fetched) */\n fetchedDir?: string;\n /** Whether to save icons locally (default: true) */\n saveLocally?: boolean;\n /** Timeout for fetch requests in milliseconds (default: 10000) */\n timeoutMs?: number;\n}\n\n/**\n * Parsed icon reference\n */\nexport interface ParsedReference {\n prefix: string;\n name: string;\n}\n\n/**\n * Source entry in _sources.yaml\n */\ninterface SourceEntry {\n source: string;\n fetched_at: string;\n license: string;\n}\n\n/**\n * Icon source configuration\n */\nexport interface IconSourceConfig {\n /** Iconify set name */\n set: string;\n /** License identifier */\n license: string;\n /** Whether this source requires external fetching */\n external: boolean;\n}\n\n/**\n * Unified icon source definitions\n * Single source of truth for prefix mappings, licenses, and external status\n */\nexport const ICON_SOURCES: Record<string, IconSourceConfig> = {\n health: { set: \"healthicons\", license: \"MIT\", external: true },\n ms: { set: \"material-symbols\", license: \"Apache-2.0\", external: true },\n hero: { set: \"heroicons\", license: \"MIT\", external: true },\n mi: { set: \"material-icons\", license: \"Apache-2.0\", external: false },\n mdi: { set: \"mdi\", license: \"Apache-2.0\", external: true },\n iconify: { set: \"iconify\", license: \"Various\", external: true },\n};\n\n/**\n * Check if a source prefix requires external fetching\n */\nexport function isExternalSource(prefix: string): boolean {\n return ICON_SOURCES[prefix]?.external ?? false;\n}\n\n/**\n * Valid icon name pattern\n * Allows: lowercase letters, numbers, hyphens\n * Must start with a letter or number, cannot end with hyphen\n * Also allows forward slash for subdirectory paths (e.g., healthicons/stethoscope)\n */\nconst VALID_ICON_NAME = /^[a-z0-9][a-z0-9-]*[a-z0-9]$|^[a-z0-9]$/i;\nconst VALID_ICON_NAME_WITH_PATH = /^[a-z0-9][a-z0-9-/]*[a-z0-9]$|^[a-z0-9]$/i;\n\n/**\n * Validate icon name format\n */\nexport function isValidIconName(name: string, allowPath = false): boolean {\n if (!name || name.length > 100) {\n return false;\n }\n // Prevent path traversal\n if (name.includes(\"..\") || name.startsWith(\"/\") || name.endsWith(\"/\")) {\n return false;\n }\n const pattern = allowPath ? VALID_ICON_NAME_WITH_PATH : VALID_ICON_NAME;\n return pattern.test(name);\n}\n\n/**\n * IconFetcher - Fetches icons from external sources and saves them locally\n *\n * Icons are fetched from the Iconify API and saved to the local filesystem\n * for offline use and reproducibility.\n */\nexport class IconFetcher {\n private fetchedDir: string;\n private saveLocally: boolean;\n private timeoutMs: number;\n\n constructor(options: FetcherOptions = {}) {\n this.fetchedDir = options.fetchedDir ?? \"icons/fetched\";\n this.saveLocally = options.saveLocally ?? true;\n this.timeoutMs = options.timeoutMs ?? 10000;\n }\n\n /**\n * Parse an icon reference string (e.g., \"health:stethoscope\")\n * Returns null if the format is invalid or contains unsafe characters\n */\n parseReference(iconRef: string): ParsedReference | null {\n const colonIndex = iconRef.indexOf(\":\");\n if (colonIndex === -1) {\n return null;\n }\n\n const prefix = iconRef.substring(0, colonIndex);\n const name = iconRef.substring(colonIndex + 1);\n\n // Validate prefix (alphanumeric only)\n if (!/^[a-z0-9]+$/i.test(prefix)) {\n return null;\n }\n\n // Validate icon name\n if (!isValidIconName(name)) {\n return null;\n }\n\n return { prefix, name };\n }\n\n /**\n * Get the Iconify set name for a prefix\n */\n getIconifySet(prefix: string): string {\n return ICON_SOURCES[prefix]?.set ?? prefix;\n }\n\n /**\n * Get the local file path for an icon reference\n */\n getLocalPath(iconRef: string): string {\n const parsed = this.parseReference(iconRef);\n if (!parsed) {\n throw new Error(`Invalid icon reference: ${iconRef}`);\n }\n\n const setDir = this.getIconifySet(parsed.prefix);\n return path.join(this.fetchedDir, setDir, `${parsed.name}.svg`);\n }\n\n /**\n * Check if an icon exists locally\n */\n async existsLocally(iconRef: string): Promise<boolean> {\n const localPath = this.getLocalPath(iconRef);\n try {\n await fs.access(localPath);\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * Build the Iconify API URL for an icon\n */\n buildUrl(prefix: string, name: string): string {\n const set = this.getIconifySet(prefix);\n return `https://api.iconify.design/${set}/${name}.svg`;\n }\n\n /**\n * Resolve an icon reference (local first, then fetch)\n */\n async resolve(iconRef: string): Promise<string> {\n // Check if already exists locally\n if (await this.existsLocally(iconRef)) {\n const localPath = this.getLocalPath(iconRef);\n return await fs.readFile(localPath, \"utf-8\");\n }\n\n // Fetch and optionally save\n return await this.fetchAndSave(iconRef);\n }\n\n /**\n * Fetch an icon from external source and save locally\n */\n async fetchAndSave(iconRef: string): Promise<string> {\n const parsed = this.parseReference(iconRef);\n if (!parsed) {\n throw new Error(`Invalid icon reference: ${iconRef}`);\n }\n\n const url = this.buildUrl(parsed.prefix, parsed.name);\n\n // Fetch the icon with timeout\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeoutMs);\n\n let response: Response;\n try {\n response = await fetch(url, { signal: controller.signal });\n } catch (error) {\n if (error instanceof Error && error.name === \"AbortError\") {\n throw new Error(`Fetch timeout: ${iconRef} (exceeded ${this.timeoutMs}ms)`);\n }\n throw error;\n } finally {\n clearTimeout(timeoutId);\n }\n\n if (!response.ok) {\n throw new Error(`Icon not found: ${iconRef} (HTTP ${response.status})`);\n }\n\n const svg = await response.text();\n\n // Save locally if enabled\n if (this.saveLocally) {\n await this.saveLocallyInternal(parsed.prefix, parsed.name, svg, url);\n }\n\n return svg;\n }\n\n /**\n * Save icon to local filesystem\n */\n private async saveLocallyInternal(\n prefix: string,\n name: string,\n svg: string,\n sourceUrl: string\n ): Promise<void> {\n const setDir = this.getIconifySet(prefix);\n const dirPath = path.join(this.fetchedDir, setDir);\n const filePath = path.join(dirPath, `${name}.svg`);\n\n // Create directory\n await fs.mkdir(dirPath, { recursive: true });\n\n // Save SVG\n await fs.writeFile(filePath, svg, \"utf-8\");\n\n // Update _sources.yaml\n await this.updateSourcesYaml(setDir, name, sourceUrl);\n }\n\n /**\n * Update _sources.yaml with source information\n */\n private async updateSourcesYaml(\n setDir: string,\n name: string,\n sourceUrl: string\n ): Promise<void> {\n const sourcesPath = path.join(this.fetchedDir, \"_sources.yaml\");\n let sources: Record<string, SourceEntry> = {};\n\n try {\n const content = await fs.readFile(sourcesPath, \"utf-8\");\n sources = (parseYaml(content) as Record<string, SourceEntry>) ?? {};\n } catch {\n // File doesn't exist, start fresh\n }\n\n const key = `${setDir}/${name}.svg`;\n sources[key] = {\n source: sourceUrl,\n fetched_at: new Date().toISOString(),\n license: this.getLicense(setDir),\n };\n\n // Add header comment\n const header = `# Fetched icon sources\\n# This file tracks where icons were fetched from for traceability\\n\\n`;\n await fs.writeFile(sourcesPath, header + stringifyYaml(sources), \"utf-8\");\n }\n\n /**\n * Get the license for an icon set\n */\n private getLicense(setDir: string): string {\n // Find license by set name\n for (const config of Object.values(ICON_SOURCES)) {\n if (config.set === setDir) {\n return config.license;\n }\n }\n return \"Unknown\";\n }\n}\n","import { Command } from 'commander';\nimport { mkdir, writeFile, access, readdir, cp } from 'fs/promises';\nimport { existsSync } from 'fs';\nimport { execSync } from 'child_process';\nimport { dirname, join, resolve, sep } from 'path';\nimport { fileURLToPath } from 'url';\nimport chalk from 'chalk';\nimport ora from 'ora';\nimport { ExitCode } from './convert.js';\nimport { SourcesManager } from '../../sources/manager.js';\nimport { SourceImporter } from '../../sources/importer.js';\nimport {\n generateSkillMd,\n generateClaudeMd,\n generateAgentsMd,\n generateOpenCodeAgent,\n generateTemplatesRef,\n generateWorkflowsRef,\n generateSlideCreateCommand,\n generateSlideValidateCommand,\n generateSlidePreviewCommand,\n generateSlideScreenshotCommand,\n generateSlideThemeCommand,\n} from '../templates/ai';\n\nexport interface InitOptions {\n template?: string;\n examples?: boolean;\n aiConfig?: boolean;\n sources?: boolean;\n fromDirectory?: string;\n skipMarpInstall?: boolean;\n}\n\n/**\n * Get the package root directory\n * Works for both bundled (dist/cli/index.js) and source (src/cli/commands/init.ts)\n */\nfunction getPackageRoot(): string {\n const __dirname = dirname(fileURLToPath(import.meta.url));\n\n // Check if we're in source (src/) or bundled (dist/)\n // Use path separator agnostic check for Windows compatibility\n if (__dirname.includes(`${sep}src${sep}`) || __dirname.includes('/src/')) {\n // Source: go up from src/cli/commands to package root\n return join(__dirname, '..', '..', '..');\n }\n // Bundled: go up from dist/cli to package root\n return join(__dirname, '..', '..');\n}\n\n/**\n * Create the init command\n */\nexport function createInitCommand(): Command {\n return new Command('init')\n .description('Initialize a new project')\n .argument('[directory]', 'Target directory', '.')\n .option('--template <name>', 'Initial template')\n .option('--no-examples', 'Do not create sample files')\n .option('--no-ai-config', 'Do not create AI assistant config files')\n .option('--no-sources', 'Do not create sources directory')\n .option('--from-directory <path>', 'Import materials from directory')\n .option('--skip-marp-install', 'Skip Marp CLI installation prompt')\n .action(async (directory: string, options: InitOptions) => {\n await executeInit(directory, options);\n });\n}\n\n/**\n * Execute the init command\n */\nexport async function executeInit(\n directory: string,\n options: InitOptions\n): Promise<void> {\n const spinner = ora();\n const targetDir = resolve(directory);\n const includeExamples = options.examples !== false;\n const includeAiConfig = options.aiConfig !== false;\n const includeSources = options.sources !== false;\n\n try {\n spinner.start(`Initializing project in ${targetDir}...`);\n\n // Check if directory exists and has content\n try {\n await access(targetDir);\n const entries = await readdir(targetDir);\n if (entries.length > 0) {\n spinner.info(`Directory ${targetDir} already exists, adding files...`);\n }\n } catch {\n // Directory doesn't exist, will be created\n }\n\n // Create directory structure\n await mkdir(targetDir, { recursive: true });\n await mkdir(join(targetDir, 'themes'), { recursive: true });\n await mkdir(join(targetDir, 'icons', 'custom'), { recursive: true });\n\n // Copy built-in templates and icons registry from package\n const packageRoot = getPackageRoot();\n\n // Copy templates\n const sourceTemplatesDir = join(packageRoot, 'templates');\n const targetTemplatesDir = join(targetDir, 'templates');\n\n try {\n await access(targetTemplatesDir);\n // Templates directory already exists, skip copying\n } catch {\n // Templates directory doesn't exist, copy from package\n await cp(sourceTemplatesDir, targetTemplatesDir, { recursive: true });\n }\n\n // Copy icons registry\n const sourceIconsRegistry = join(packageRoot, 'icons', 'registry.yaml');\n const targetIconsRegistry = join(targetDir, 'icons', 'registry.yaml');\n await copyFileIfNotExists(sourceIconsRegistry, targetIconsRegistry);\n\n // Copy default theme\n const sourceDefaultTheme = join(packageRoot, 'themes', 'default.css');\n const targetDefaultTheme = join(targetDir, 'themes', 'default.css');\n await copyFileIfNotExists(sourceDefaultTheme, targetDefaultTheme);\n\n // Create config.yaml\n const configContent = generateConfigContent();\n await writeFileIfNotExists(join(targetDir, 'config.yaml'), configContent);\n\n // Create themes/custom.css\n const customCssContent = generateCustomCssContent();\n await writeFileIfNotExists(join(targetDir, 'themes', 'custom.css'), customCssContent);\n\n // Create sample files if examples are enabled\n if (includeExamples) {\n const presentationContent = generatePresentationContent(options.template);\n await writeFileIfNotExists(join(targetDir, 'presentation.yaml'), presentationContent);\n }\n\n // Create AI config files\n if (includeAiConfig) {\n await generateAiConfig(targetDir);\n }\n\n // Create sources directory\n let sourcesImported = 0;\n if (includeSources) {\n const sourcesManager = new SourcesManager(targetDir);\n if (!(await sourcesManager.exists())) {\n await sourcesManager.init({\n name: 'Untitled Project',\n setup_pattern: options.fromDirectory ? 'A' : undefined,\n original_source: options.fromDirectory ? resolve(options.fromDirectory) : undefined,\n });\n\n // Import from directory if specified\n if (options.fromDirectory) {\n const importer = new SourceImporter(targetDir, sourcesManager);\n const result = await importer.importDirectory(resolve(options.fromDirectory), {\n recursive: true,\n });\n sourcesImported = result.imported;\n }\n }\n }\n\n spinner.succeed(`Project initialized in ${targetDir}`);\n\n // Print summary\n console.log('');\n console.log(chalk.green('Created files:'));\n console.log(` ${chalk.cyan('config.yaml')} - Project configuration`);\n console.log(` ${chalk.cyan('templates/')} - Slide templates`);\n console.log(` ${chalk.cyan('themes/default.css')} - Default theme`);\n console.log(` ${chalk.cyan('themes/custom.css')} - Custom theme styles`);\n console.log(` ${chalk.cyan('icons/registry.yaml')} - Icon registry`);\n console.log(` ${chalk.cyan('icons/custom/')} - Custom icons directory`);\n if (includeExamples) {\n console.log(` ${chalk.cyan('presentation.yaml')} - Sample presentation`);\n }\n if (includeAiConfig) {\n console.log(` ${chalk.cyan('.skills/')} - AgentSkills configuration`);\n console.log(` ${chalk.cyan('CLAUDE.md')} - Claude Code configuration`);\n console.log(` ${chalk.cyan('AGENTS.md')} - OpenCode configuration`);\n console.log(` ${chalk.cyan('.cursorrules')} - Cursor configuration`);\n console.log(` ${chalk.cyan('.claude/commands/')} - Claude Code slash commands`);\n console.log(` ${chalk.cyan('.opencode/agent/')} - OpenCode agent configuration`);\n }\n if (includeSources) {\n let sourcesMsg = ` ${chalk.cyan('sources/')} - Source materials directory`;\n if (sourcesImported > 0) {\n sourcesMsg += ` (${sourcesImported} files imported)`;\n }\n console.log(sourcesMsg);\n }\n console.log('');\n console.log(chalk.blue('Next steps:'));\n console.log(` 1. Edit ${chalk.yellow('presentation.yaml')} to add your slides`);\n console.log(` 2. Run ${chalk.yellow('slide-gen convert presentation.yaml')} to generate markdown`);\n\n // Show Marp CLI installation info if not skipped\n if (options.skipMarpInstall !== true) {\n showMarpCliInfo(targetDir);\n }\n } catch (error) {\n spinner.fail('Failed to initialize project');\n console.error(\n chalk.red(`Error: ${error instanceof Error ? error.message : 'Unknown error'}`)\n );\n process.exitCode = ExitCode.GeneralError;\n }\n}\n\n/**\n * Write file only if it doesn't exist\n */\nasync function writeFileIfNotExists(filePath: string, content: string): Promise<void> {\n try {\n await access(filePath);\n // File exists, skip\n } catch {\n // File doesn't exist, create it\n await writeFile(filePath, content, 'utf-8');\n }\n}\n\n/**\n * Copy file only if destination doesn't exist\n */\nasync function copyFileIfNotExists(source: string, dest: string): Promise<void> {\n try {\n await access(dest);\n // File exists, skip\n } catch {\n // File doesn't exist, copy from source\n await cp(source, dest);\n }\n}\n\n/**\n * Check if Marp CLI is installed\n * Uses 'marp --version' directly instead of 'npx marp --version'\n * because npx is slow (searches local, global, and npm registry)\n */\nexport function isMarpCliInstalled(): boolean {\n try {\n execSync('marp --version', { stdio: 'pipe', timeout: 5000 });\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Detect package manager from lock files\n */\nexport function detectPackageManager(targetDir?: string): 'pnpm' | 'yarn' | 'npm' {\n const dir = targetDir ?? process.cwd();\n if (existsSync(join(dir, 'pnpm-lock.yaml'))) return 'pnpm';\n if (existsSync(join(dir, 'yarn.lock'))) return 'yarn';\n return 'npm';\n}\n\n/**\n * Show Marp CLI installation information\n */\nfunction showMarpCliInfo(targetDir: string): void {\n if (isMarpCliInstalled()) {\n return;\n }\n\n const pm = detectPackageManager(targetDir);\n const installCmd =\n pm === 'pnpm'\n ? 'pnpm add -D @marp-team/marp-cli'\n : pm === 'yarn'\n ? 'yarn add -D @marp-team/marp-cli'\n : 'npm install -D @marp-team/marp-cli';\n\n console.log('');\n console.log(chalk.yellow('Marp CLI is recommended for full features:'));\n console.log(' - Preview slides in browser');\n console.log(' - Take screenshots for AI review');\n console.log(' - Export to PDF/HTML/PPTX');\n console.log('');\n console.log(chalk.dim('Install with:'));\n console.log(` ${chalk.cyan(installCmd)}`);\n}\n\n/**\n * Generate AI configuration files\n */\nasync function generateAiConfig(targetDir: string): Promise<void> {\n // Create directories\n await mkdir(join(targetDir, '.skills', 'slide-assistant', 'references'), { recursive: true });\n await mkdir(join(targetDir, '.skills', 'slide-assistant', 'scripts'), { recursive: true });\n await mkdir(join(targetDir, '.claude', 'commands'), { recursive: true });\n await mkdir(join(targetDir, '.opencode', 'agent'), { recursive: true });\n\n // Generate AgentSkills (common)\n await writeFileIfNotExists(\n join(targetDir, '.skills', 'slide-assistant', 'SKILL.md'),\n generateSkillMd()\n );\n await writeFileIfNotExists(\n join(targetDir, '.skills', 'slide-assistant', 'references', 'templates.md'),\n generateTemplatesRef()\n );\n await writeFileIfNotExists(\n join(targetDir, '.skills', 'slide-assistant', 'references', 'workflows.md'),\n generateWorkflowsRef()\n );\n\n // Generate Claude Code files\n await writeFileIfNotExists(join(targetDir, 'CLAUDE.md'), generateClaudeMd());\n\n // Generate commands\n const commandGenerators: Record<string, () => string> = {\n 'slide-create': generateSlideCreateCommand,\n 'slide-validate': generateSlideValidateCommand,\n 'slide-preview': generateSlidePreviewCommand,\n 'slide-screenshot': generateSlideScreenshotCommand,\n 'slide-theme': generateSlideThemeCommand,\n };\n for (const [name, generator] of Object.entries(commandGenerators)) {\n await writeFileIfNotExists(\n join(targetDir, '.claude', 'commands', `${name}.md`),\n generator()\n );\n }\n\n // Generate OpenCode files\n await writeFileIfNotExists(join(targetDir, 'AGENTS.md'), generateAgentsMd());\n await writeFileIfNotExists(\n join(targetDir, '.opencode', 'agent', 'slide.md'),\n generateOpenCodeAgent()\n );\n\n // Generate Cursor files (same as AGENTS.md)\n await writeFileIfNotExists(join(targetDir, '.cursorrules'), generateAgentsMd());\n}\n\n/**\n * Generate config.yaml content\n */\nfunction generateConfigContent(): string {\n return `# slide-gen configuration\n# See https://github.com/example/slide-generation for documentation\n\ntemplates:\n # Path to built-in templates (relative to project root)\n builtin: ./templates\n # Path to custom templates (optional)\n # custom: ./my-templates\n\nicons:\n # Path to icon registry file\n registry: ./icons/registry.yaml\n cache:\n enabled: true\n directory: .cache/icons\n ttl: 86400\n\nreferences:\n enabled: true\n connection:\n type: cli\n command: ref\n format:\n locale: ja-JP\n\noutput:\n theme: default\n inlineStyles: false\n`;\n}\n\n/**\n * Generate custom CSS content\n */\nfunction generateCustomCssContent(): string {\n return `/* Custom Marp theme styles */\n/* See https://marpit.marp.app/theme-css for documentation */\n\n/*\nsection {\n background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);\n color: #fff;\n}\n\nh1 {\n color: #fff;\n text-shadow: 2px 2px 4px rgba(0,0,0,0.3);\n}\n*/\n`;\n}\n\n/**\n * Generate sample presentation content\n */\nfunction generatePresentationContent(_template?: string): string {\n const baseContent = `# Sample Presentation\n# Generated by slide-gen init\n\nmeta:\n title: My Presentation\n author: Your Name\n date: \"${new Date().toISOString().split('T')[0]}\"\n theme: default\n\nslides:\n - template: title\n content:\n title: My Presentation\n subtitle: A sample slide deck\n\n - template: bullet-list\n content:\n title: Introduction\n items:\n - Welcome to this presentation!\n - Point one\n - Point two\n - Point three\n\n - template: section\n content:\n title: Section Title\n subtitle: Section description\n\n - template: bullet-list\n content:\n title: Main Content\n items:\n - Here's the main content of your presentation.\n - You can use **markdown** formatting in the body text.\n\n - template: section\n content:\n title: Thank You\n subtitle: Questions?\n`;\n\n return baseContent;\n}\n","import * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport { parse, stringify } from 'yaml';\nimport {\n sourcesYamlSchema,\n type SourcesYaml,\n type SourceEntry,\n type Context,\n type MissingItem,\n type Project,\n} from './schema.js';\n\n/**\n * Manages the sources.yaml file and sources directory structure\n */\nexport class SourcesManager {\n private sourcesDir: string;\n private sourcesYamlPath: string;\n\n /**\n * Standard subdirectories for source materials\n */\n private static readonly SUBDIRECTORIES = [\n 'scenario',\n 'content',\n 'materials',\n 'data',\n 'conversation',\n ];\n\n constructor(projectDir: string) {\n this.sourcesDir = path.join(projectDir, 'sources');\n this.sourcesYamlPath = path.join(this.sourcesDir, 'sources.yaml');\n }\n\n /**\n * Get the sources directory path\n */\n getSourcesDir(): string {\n return this.sourcesDir;\n }\n\n /**\n * Get the sources.yaml file path\n */\n getSourcesYamlPath(): string {\n return this.sourcesYamlPath;\n }\n\n /**\n * Check if sources.yaml exists\n */\n async exists(): Promise<boolean> {\n try {\n await fs.access(this.sourcesYamlPath);\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * Initialize the sources directory and sources.yaml\n */\n async init(project: Partial<Project> & { name: string }): Promise<void> {\n // Create sources directory\n await fs.mkdir(this.sourcesDir, { recursive: true });\n\n // Create subdirectories\n for (const subdir of SourcesManager.SUBDIRECTORIES) {\n await fs.mkdir(path.join(this.sourcesDir, subdir), { recursive: true });\n }\n\n // Get current date in YYYY-MM-DD format\n const today = new Date().toISOString().split('T')[0];\n\n // Create initial sources.yaml\n const data: SourcesYaml = {\n project: {\n name: project.name,\n purpose: project.purpose,\n created: today,\n updated: today,\n setup_pattern: project.setup_pattern,\n original_source: project.original_source,\n },\n };\n\n await this.save(data);\n }\n\n /**\n * Load sources.yaml\n */\n async load(): Promise<SourcesYaml> {\n const content = await fs.readFile(this.sourcesYamlPath, 'utf-8');\n const rawData = parse(content);\n const result = sourcesYamlSchema.safeParse(rawData);\n\n if (!result.success) {\n throw new Error(`Invalid sources.yaml: ${result.error.message}`);\n }\n\n return result.data;\n }\n\n /**\n * Save data to sources.yaml\n */\n async save(data: SourcesYaml): Promise<void> {\n // Update the updated date\n const today = new Date().toISOString().split('T')[0];\n data.project.updated = today;\n\n // Validate before saving\n const result = sourcesYamlSchema.safeParse(data);\n if (!result.success) {\n throw new Error(`Invalid sources.yaml data: ${result.error.message}`);\n }\n\n const content = stringify(data, {\n lineWidth: 0, // Disable line wrapping\n });\n\n await fs.writeFile(this.sourcesYamlPath, content, 'utf-8');\n }\n\n /**\n * Add or update a source entry\n */\n async addSource(entry: SourceEntry): Promise<void> {\n const data = await this.load();\n\n if (!data.sources) {\n data.sources = [];\n }\n\n // Check if entry with same id exists\n const existingIndex = data.sources.findIndex((s) => s.id === entry.id);\n if (existingIndex >= 0) {\n // Replace existing entry\n data.sources[existingIndex] = entry;\n } else {\n // Add new entry\n data.sources.push(entry);\n }\n\n await this.save(data);\n }\n\n /**\n * Remove a source entry by id\n */\n async removeSource(id: string): Promise<void> {\n const data = await this.load();\n\n if (data.sources) {\n data.sources = data.sources.filter((s) => s.id !== id);\n }\n\n await this.save(data);\n }\n\n /**\n * Get a source entry by id\n */\n async getSource(id: string): Promise<SourceEntry | undefined> {\n const data = await this.load();\n return data.sources?.find((s) => s.id === id);\n }\n\n /**\n * Update context (merges with existing)\n */\n async updateContext(context: Partial<Context>): Promise<void> {\n const data = await this.load();\n\n data.context = {\n ...data.context,\n ...context,\n };\n\n await this.save(data);\n }\n\n /**\n * Add a missing item\n */\n async addMissing(item: MissingItem): Promise<void> {\n const data = await this.load();\n\n if (!data.missing) {\n data.missing = [];\n }\n\n // Check if item already exists\n const existingIndex = data.missing.findIndex((m) => m.item === item.item);\n if (existingIndex >= 0) {\n data.missing[existingIndex] = item;\n } else {\n data.missing.push(item);\n }\n\n await this.save(data);\n }\n\n /**\n * Remove a missing item (mark as resolved)\n */\n async resolveMissing(itemName: string): Promise<void> {\n const data = await this.load();\n\n if (data.missing) {\n data.missing = data.missing.filter((m) => m.item !== itemName);\n }\n\n await this.save(data);\n }\n\n /**\n * Get all missing items\n */\n async getMissing(): Promise<MissingItem[]> {\n const data = await this.load();\n return data.missing ?? [];\n }\n\n /**\n * Get all sources of a specific type\n */\n async getSourcesByType(type: SourceEntry['type']): Promise<SourceEntry[]> {\n const data = await this.load();\n return data.sources?.filter((s) => s.type === type) ?? [];\n }\n}\n","import { z } from 'zod';\n\n/**\n * Source type schema\n * Defines the types of source materials that can be tracked\n */\nexport const sourceTypeSchema = z.enum([\n 'scenario', // Scenario/structure files\n 'content', // Content scripts\n 'material', // Reference materials\n 'data', // Data/numbers\n 'conversation', // AI conversation logs\n]);\n\nexport type SourceType = z.infer<typeof sourceTypeSchema>;\n\n/**\n * Source status schema\n * Defines the status of a source material\n */\nexport const sourceStatusSchema = z.enum([\n 'draft', // Work in progress\n 'final', // Finalized\n 'reference', // Reference material (not directly used)\n 'archived', // Archived/historical\n]);\n\nexport type SourceStatus = z.infer<typeof sourceStatusSchema>;\n\n/**\n * Audience schema\n * Describes the target audience for the presentation\n */\nexport const audienceSchema = z.object({\n type: z.string(),\n size: z.string().optional(),\n knowledge_level: z.string().optional(),\n concerns: z.array(z.string()).optional(),\n});\n\nexport type Audience = z.infer<typeof audienceSchema>;\n\n/**\n * Constraints schema\n * Defines constraints for the presentation\n */\nexport const constraintsSchema = z.object({\n duration: z.string().optional(),\n format: z.string().optional(),\n style: z.string().optional(),\n});\n\nexport type Constraints = z.infer<typeof constraintsSchema>;\n\n/**\n * Context schema\n * Contains presentation context information\n */\nexport const contextSchema = z.object({\n objective: z.string().optional(),\n audience: audienceSchema.optional(),\n key_messages: z.array(z.string()).optional(),\n constraints: constraintsSchema.optional(),\n});\n\nexport type Context = z.infer<typeof contextSchema>;\n\n/**\n * Source entry schema\n * Represents a single source material entry\n */\nexport const sourceEntrySchema = z.object({\n id: z.string(),\n type: sourceTypeSchema,\n path: z.string(),\n status: sourceStatusSchema.optional(),\n origin: z.string().optional(),\n description: z.string().optional(),\n notes: z.string().optional(),\n extracted_data: z.array(z.string()).optional(),\n decisions: z.array(z.string()).optional(),\n});\n\nexport type SourceEntry = z.infer<typeof sourceEntrySchema>;\n\n/**\n * Project schema\n * Contains project metadata\n */\nexport const projectSchema = z.object({\n name: z.string(),\n purpose: z.string().optional(),\n created: z.string().optional(),\n updated: z.string().optional(),\n setup_pattern: z.enum(['A', 'B', 'C']).optional(),\n original_source: z.string().optional(),\n});\n\nexport type Project = z.infer<typeof projectSchema>;\n\n/**\n * Dependency schema\n * Tracks which sources a file is derived from\n */\nexport const dependencySchema = z.object({\n derived_from: z.array(z.string()),\n});\n\nexport type Dependency = z.infer<typeof dependencySchema>;\n\n/**\n * Missing item schema\n * Tracks missing information needed for the presentation\n */\nexport const missingItemSchema = z.object({\n item: z.string(),\n needed_for: z.string().optional(),\n status: z.string().optional(),\n notes: z.string().optional(),\n});\n\nexport type MissingItem = z.infer<typeof missingItemSchema>;\n\n/**\n * Sources YAML schema\n * The main schema for sources.yaml file\n */\nexport const sourcesYamlSchema = z.object({\n project: projectSchema,\n context: contextSchema.optional(),\n sources: z.array(sourceEntrySchema).optional(),\n dependencies: z.record(dependencySchema).optional(),\n missing: z.array(missingItemSchema).optional(),\n});\n\nexport type SourcesYaml = z.infer<typeof sourcesYamlSchema>;\n","import * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport { SourceExplorer, type FileClassification } from './explorer.js';\nimport type { SourcesManager } from './manager.js';\nimport type { SourceEntry, SourceType } from './schema.js';\n\n/**\n * Options for importing a file\n */\nexport interface ImportOptions {\n /** Force a specific source type */\n type?: SourceType;\n /** Description for the source entry */\n description?: string;\n /** Copy file (true) or move file (false). Default: true */\n copy?: boolean;\n}\n\n/**\n * Result of importing a file\n */\nexport interface ImportResult {\n /** Relative path from sources directory */\n path: string;\n /** Source type */\n type: SourceType;\n /** Original file path */\n originalPath: string;\n /** Generated source ID */\n id: string;\n}\n\n/**\n * Result of importing a directory\n */\nexport interface DirectoryImportResult {\n /** Number of files imported */\n imported: number;\n /** Number of files skipped */\n skipped: number;\n /** Details of imported files */\n results: ImportResult[];\n}\n\n/**\n * Mapping from classification to target directory and source type\n */\nconst TYPE_MAPPING: Record<\n Exclude<FileClassification, 'unknown' | 'image'>,\n { directory: string; sourceType: SourceType }\n> = {\n scenario: { directory: 'scenario', sourceType: 'scenario' },\n content: { directory: 'content', sourceType: 'content' },\n material: { directory: 'materials', sourceType: 'material' },\n data: { directory: 'data', sourceType: 'data' },\n conversation: { directory: 'conversation', sourceType: 'conversation' },\n};\n\n/**\n * Imports external files into the sources directory\n */\nexport class SourceImporter {\n private sourcesDir: string;\n private explorer: SourceExplorer;\n\n constructor(\n projectDir: string,\n private manager: SourcesManager\n ) {\n this.sourcesDir = path.join(projectDir, 'sources');\n this.explorer = new SourceExplorer();\n }\n\n /**\n * Get the target directory for a source type\n */\n getTargetDirectory(type: SourceType): string {\n return TYPE_MAPPING[type].directory;\n }\n\n /**\n * Import a single file into the sources directory\n */\n async importFile(\n sourcePath: string,\n options: ImportOptions = {}\n ): Promise<ImportResult> {\n const { type, description, copy = true } = options;\n\n const resolvedPath = path.resolve(sourcePath);\n const filename = path.basename(resolvedPath);\n\n // Determine type from options or auto-detect\n let sourceType: SourceType;\n if (type) {\n sourceType = type;\n } else {\n const classification = this.explorer.classifyFile(filename);\n sourceType = this.classificationToSourceType(classification);\n }\n\n // Get target directory\n const targetDir = this.getTargetDirectory(sourceType);\n const targetDirPath = path.join(this.sourcesDir, targetDir);\n\n // Ensure target directory exists\n await fs.mkdir(targetDirPath, { recursive: true });\n\n // Handle filename conflicts\n const targetFilename = await this.getUniqueFilename(targetDirPath, filename);\n const targetPath = path.join(targetDirPath, targetFilename);\n\n // Copy or move file\n if (copy) {\n await fs.copyFile(resolvedPath, targetPath);\n } else {\n await fs.rename(resolvedPath, targetPath);\n }\n\n // Generate source ID from filename\n const id = this.generateSourceId(targetFilename);\n\n // Create relative path for sources.yaml\n const relativePath = path.join(targetDir, targetFilename);\n\n // Create source entry\n const entry: SourceEntry = {\n id,\n type: sourceType,\n path: relativePath,\n origin: resolvedPath,\n description,\n };\n\n // Update sources.yaml\n await this.manager.addSource(entry);\n\n return {\n path: relativePath,\n type: sourceType,\n originalPath: resolvedPath,\n id,\n };\n }\n\n /**\n * Import all files from a directory\n */\n async importDirectory(\n dirPath: string,\n options: { recursive?: boolean } = {}\n ): Promise<DirectoryImportResult> {\n const { recursive = false } = options;\n\n const resolvedPath = path.resolve(dirPath);\n const scanOptions = recursive ? {} : { maxDepth: 0 };\n const files = await this.explorer.scan(resolvedPath, scanOptions);\n\n // Get existing source paths to avoid duplicates\n const data = await this.manager.load();\n const existingOrigins = new Set(\n data.sources?.map((s) => s.origin).filter(Boolean) ?? []\n );\n\n const results: ImportResult[] = [];\n let imported = 0;\n let skipped = 0;\n\n for (const file of files) {\n // Skip images (they go to images/ not sources/)\n if (file.type === 'image') {\n skipped++;\n continue;\n }\n\n // Skip already imported files\n if (existingOrigins.has(file.path)) {\n skipped++;\n continue;\n }\n\n try {\n const result = await this.importFile(file.path);\n results.push(result);\n imported++;\n } catch {\n skipped++;\n }\n }\n\n return {\n imported,\n skipped,\n results,\n };\n }\n\n /**\n * Convert file classification to source type\n */\n private classificationToSourceType(\n classification: FileClassification\n ): SourceType {\n if (classification === 'unknown' || classification === 'image') {\n return 'material'; // Default to material for unknown types\n }\n return classification;\n }\n\n /**\n * Get a unique filename in the target directory\n */\n private async getUniqueFilename(\n targetDir: string,\n filename: string\n ): Promise<string> {\n const targetPath = path.join(targetDir, filename);\n\n try {\n await fs.access(targetPath);\n // File exists, generate unique name\n const ext = path.extname(filename);\n const base = path.basename(filename, ext);\n const timestamp = Date.now();\n return `${base}-${timestamp}${ext}`;\n } catch {\n // File doesn't exist, use original name\n return filename;\n }\n }\n\n /**\n * Generate a source ID from filename\n */\n private generateSourceId(filename: string): string {\n const ext = path.extname(filename);\n const base = path.basename(filename, ext);\n // Convert to kebab-case and remove special characters\n return base\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-|-$/g, '');\n }\n}\n","import * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport type { SourceType } from './schema.js';\n\n/**\n * File type classification result\n */\nexport type FileClassification = SourceType | 'image' | 'unknown';\n\n/**\n * Information about a discovered file\n */\nexport interface FileInfo {\n /** Full path to the file */\n path: string;\n /** File name only */\n name: string;\n /** Classified type */\n type: FileClassification;\n /** File size in bytes */\n size: number;\n /** Relative path from scan root */\n relativePath: string;\n}\n\n/**\n * Summary of files discovered in a directory\n */\nexport interface DirectorySummary {\n /** Scenario/structure files */\n scenarios: FileInfo[];\n /** Content/script files */\n content: FileInfo[];\n /** Reference materials */\n materials: FileInfo[];\n /** Data files */\n data: FileInfo[];\n /** Image files */\n images: FileInfo[];\n /** Unclassified files */\n unknown: FileInfo[];\n /** Total number of files */\n totalFiles: number;\n}\n\n/**\n * Options for scanning directories\n */\nexport interface ScanOptions {\n /** Maximum directory depth (default: unlimited) */\n maxDepth?: number;\n /** Include hidden files (default: false) */\n includeHidden?: boolean;\n /** Maximum file size to read in bytes (default: 10MB) */\n fileSizeLimit?: number;\n}\n\n/**\n * Options for getting file preview\n */\nexport interface PreviewOptions {\n /** Maximum preview length in characters (default: 500) */\n maxLength?: number;\n}\n\n/**\n * Classification patterns for different file types\n */\nconst CLASSIFICATION_PATTERNS: Record<\n FileClassification,\n { namePatterns: RegExp[]; extensionPatterns: RegExp[] }\n> = {\n scenario: {\n namePatterns: [\n /scenario/i,\n /brief/i,\n /要件/i,\n /outline/i,\n /構成/i,\n /structure/i,\n /requirement/i,\n ],\n extensionPatterns: [],\n },\n content: {\n namePatterns: [/draft/i, /content/i, /原稿/i, /script/i],\n extensionPatterns: [],\n },\n data: {\n namePatterns: [/data/i, /statistic/i],\n extensionPatterns: [/\\.xlsx$/i, /\\.csv$/i, /\\.xls$/i],\n },\n material: {\n namePatterns: [/spec/i, /report/i, /manual/i, /guide/i],\n extensionPatterns: [/\\.pdf$/i, /\\.docx?$/i],\n },\n image: {\n namePatterns: [],\n extensionPatterns: [/\\.jpe?g$/i, /\\.png$/i, /\\.svg$/i, /\\.gif$/i, /\\.webp$/i],\n },\n conversation: {\n namePatterns: [],\n extensionPatterns: [],\n },\n unknown: {\n namePatterns: [],\n extensionPatterns: [],\n },\n};\n\n/**\n * Explores directories and classifies source files\n */\nexport class SourceExplorer {\n /**\n * Classify a file by its name/extension\n */\n classifyFile(filename: string): FileClassification {\n // First check name patterns (higher priority)\n const namePatternOrder: FileClassification[] = [\n 'scenario',\n 'content',\n 'data',\n 'material',\n ];\n\n for (const type of namePatternOrder) {\n const patterns = CLASSIFICATION_PATTERNS[type];\n for (const pattern of patterns.namePatterns) {\n if (pattern.test(filename)) {\n return type;\n }\n }\n }\n\n // Then check extension patterns\n const extensionOrder: FileClassification[] = [\n 'image',\n 'data',\n 'material',\n ];\n\n for (const type of extensionOrder) {\n const patterns = CLASSIFICATION_PATTERNS[type];\n for (const pattern of patterns.extensionPatterns) {\n if (pattern.test(filename)) {\n return type;\n }\n }\n }\n\n return 'unknown';\n }\n\n /**\n * Scan a directory and list all files with classification\n */\n async scan(dirPath: string, options: ScanOptions = {}): Promise<FileInfo[]> {\n const { maxDepth, includeHidden = false } = options;\n const resolvedPath = path.resolve(dirPath);\n const files: FileInfo[] = [];\n\n await this.scanRecursive(resolvedPath, resolvedPath, files, {\n currentDepth: 0,\n maxDepth,\n includeHidden,\n });\n\n return files;\n }\n\n /**\n * Internal recursive scan implementation\n */\n private async scanRecursive(\n rootPath: string,\n currentPath: string,\n files: FileInfo[],\n options: {\n currentDepth: number;\n maxDepth: number | undefined;\n includeHidden: boolean;\n }\n ): Promise<void> {\n const { currentDepth, maxDepth, includeHidden } = options;\n\n // Check depth limit\n if (maxDepth !== undefined && currentDepth > maxDepth) {\n return;\n }\n\n const entries = await fs.readdir(currentPath, { withFileTypes: true });\n\n for (const entry of entries) {\n // Skip hidden files/directories if not included\n if (!includeHidden && entry.name.startsWith('.')) {\n continue;\n }\n\n const fullPath = path.join(currentPath, entry.name);\n\n if (entry.isDirectory()) {\n await this.scanRecursive(rootPath, fullPath, files, {\n currentDepth: currentDepth + 1,\n maxDepth,\n includeHidden,\n });\n } else if (entry.isFile()) {\n const stats = await fs.stat(fullPath);\n const relativePath = path.relative(rootPath, fullPath);\n\n files.push({\n path: fullPath,\n name: entry.name,\n type: this.classifyFile(entry.name),\n size: stats.size,\n relativePath,\n });\n }\n }\n }\n\n /**\n * Generate a categorized summary of files in a directory\n */\n async generateSummary(\n dirPath: string,\n options: ScanOptions = {}\n ): Promise<DirectorySummary> {\n const files = await this.scan(dirPath, options);\n\n const summary: DirectorySummary = {\n scenarios: [],\n content: [],\n materials: [],\n data: [],\n images: [],\n unknown: [],\n totalFiles: files.length,\n };\n\n for (const file of files) {\n switch (file.type) {\n case 'scenario':\n summary.scenarios.push(file);\n break;\n case 'content':\n summary.content.push(file);\n break;\n case 'material':\n summary.materials.push(file);\n break;\n case 'data':\n summary.data.push(file);\n break;\n case 'image':\n summary.images.push(file);\n break;\n default:\n summary.unknown.push(file);\n }\n }\n\n return summary;\n }\n\n /**\n * Get a preview of a text file's contents\n */\n async getPreview(\n filePath: string,\n options: PreviewOptions = {}\n ): Promise<string | null> {\n const { maxLength = 500 } = options;\n\n try {\n // Check if it's likely a binary file\n const isBinary = await this.isBinaryFile(filePath);\n if (isBinary) {\n return null;\n }\n\n const content = await fs.readFile(filePath, 'utf-8');\n\n if (content.length <= maxLength) {\n return content;\n }\n\n return content.slice(0, maxLength) + '...';\n } catch {\n return null;\n }\n }\n\n /**\n * Check if a file is likely binary\n */\n private async isBinaryFile(filePath: string): Promise<boolean> {\n const ext = path.extname(filePath).toLowerCase();\n\n // Known text extensions - always treat as text\n const textExtensions = [\n '.md',\n '.txt',\n '.yaml',\n '.yml',\n '.json',\n '.csv',\n '.html',\n '.css',\n '.js',\n '.ts',\n ];\n if (textExtensions.includes(ext)) {\n return false;\n }\n\n // Known binary extensions - always treat as binary\n const binaryExtensions = [\n '.pdf',\n '.xlsx',\n '.xls',\n '.docx',\n '.doc',\n '.pptx',\n '.ppt',\n '.jpg',\n '.jpeg',\n '.png',\n '.gif',\n '.webp',\n '.zip',\n '.tar',\n '.gz',\n ];\n if (binaryExtensions.includes(ext)) {\n return true;\n }\n\n // Check file content for null bytes\n try {\n const stats = await fs.stat(filePath);\n if (stats.size === 0) {\n return false; // Empty files are not binary\n }\n\n const bytesToRead = Math.min(512, stats.size);\n const buffer = Buffer.alloc(bytesToRead);\n const fd = await fs.open(filePath, 'r');\n try {\n const { bytesRead } = await fd.read(buffer, 0, bytesToRead, 0);\n // Check for null bytes (common in binary files)\n for (let i = 0; i < bytesRead; i++) {\n if (buffer[i] === 0) {\n return true;\n }\n }\n } finally {\n await fd.close();\n }\n\n return false;\n } catch {\n return true;\n }\n }\n}\n","/**\n * Generate SKILL.md content for AgentSkills\n */\nexport function generateSkillMd(): string {\n return `---\nname: slide-assistant\ndescription: Assists with slide creation using slide-gen CLI. Responds to requests like \"create slides\", \"show templates\", \"convert manuscript to slides\".\nallowed-tools: Read Write Edit Bash Glob Grep\n---\n\n# Slide Assistant\n\nHelps create Marp slides using the slide-gen CLI tool.\n\n## Capabilities\n\n1. **Project initialization**: \\`slide-gen init\\`\n2. **Template discovery**: \\`slide-gen templates list --format llm\\`\n3. **Slide creation**: Create/edit presentation.yaml\n4. **Validation**: \\`slide-gen validate\\`\n5. **Conversion**: \\`slide-gen convert\\`\n6. **Screenshot**: \\`slide-gen screenshot\\` (for AI review)\n\n## Workflow\n\n### New Project\n\n1. Run \\`slide-gen init <directory>\\` to initialize\n2. Gather requirements from user\n3. Check templates with \\`slide-gen templates list --format llm\\`\n4. Create presentation.yaml\n5. Validate and convert\n\n### Existing Project\n\n1. Read presentation.yaml\n2. Edit according to user request\n3. Validate and convert\n\n## YAML Source Format\n\n\\`\\`\\`yaml\nmeta:\n title: \"Presentation Title\"\n author: \"Author Name\"\n date: \"YYYY-MM-DD\"\n theme: \"default\"\n\nslides:\n - template: title\n content:\n title: \"Main Title\"\n subtitle: \"Subtitle\"\n\n - template: bullet-list\n content:\n title: \"Overview\"\n items:\n - \"Item 1\"\n - \"Item 2\"\n\\`\\`\\`\n\n## Template Examples\n\n### Title Slide\n\\`\\`\\`yaml\n- template: title\n content:\n title: \"Title\"\n subtitle: \"Subtitle\"\n author: \"Author\"\n\\`\\`\\`\n\n### Bullet List\n\\`\\`\\`yaml\n- template: bullet-list\n content:\n title: \"Title\"\n items:\n - \"Item 1\"\n - \"Item 2\"\n\\`\\`\\`\n\n### Cycle Diagram\n\\`\\`\\`yaml\n- template: cycle-diagram\n content:\n title: \"PDCA Cycle\"\n nodes:\n - { label: \"Plan\", icon: \"planning\", color: \"#4CAF50\" }\n - { label: \"Do\", icon: \"action\", color: \"#2196F3\" }\n - { label: \"Check\", icon: \"analysis\", color: \"#FF9800\" }\n - { label: \"Act\", icon: \"improvement\", color: \"#9C27B0\" }\n\\`\\`\\`\n\n## Commands Reference\n\n| Command | Description |\n|---------|-------------|\n| \\`slide-gen convert <input>\\` | Convert YAML to Marp Markdown |\n| \\`slide-gen validate <input>\\` | Validate source file |\n| \\`slide-gen templates list\\` | List templates |\n| \\`slide-gen templates info <name>\\` | Template details |\n| \\`slide-gen icons search <query>\\` | Search icons |\n| \\`slide-gen screenshot <input>\\` | Take screenshots |\n| \\`slide-gen preview <input>\\` | Open preview in browser |\n\n## AI-Optimized Output\n\nUse \\`--format llm\\` for token-efficient output:\n\\`\\`\\`bash\nslide-gen templates list --format llm\nslide-gen templates info <name> --format llm\nslide-gen validate <input> --format llm\n\\`\\`\\`\n\nThe \\`validate --format llm\\` command provides:\n- Error locations with line numbers\n- Fix examples from template definitions\n- Contextual hints for unknown templates/icons\n`;\n}\n","/**\n * Generate CLAUDE.md content for Claude Code\n */\nexport function generateClaudeMd(): string {\n return `# Slide Generation Project\n\nThis project uses slide-gen to create Marp slides from YAML source files.\n\n## Quick Start\n\n\\`\\`\\`bash\n# Validate\nslide-gen validate presentation.yaml\n\n# Convert\nslide-gen convert presentation.yaml -o slides.md\n\n# Preview\nslide-gen preview presentation.yaml\n\\`\\`\\`\n\n## Commands\n\n| Command | Description |\n|---------|-------------|\n| \\`slide-gen convert <input>\\` | Convert YAML to Marp Markdown |\n| \\`slide-gen validate <input>\\` | Validate source file |\n| \\`slide-gen templates list\\` | List available templates |\n| \\`slide-gen templates info <name>\\` | Get template details |\n| \\`slide-gen icons search <query>\\` | Search for icons |\n| \\`slide-gen preview <input>\\` | Preview in browser |\n| \\`slide-gen screenshot <input>\\` | Take screenshots |\n\n## AI-Optimized Output\n\nFor token-efficient output, use \\`--format llm\\`:\n\\`\\`\\`bash\nslide-gen templates list --format llm\nslide-gen templates info bullet-list --format llm\n\\`\\`\\`\n\n## Project Structure\n\n- \\`presentation.yaml\\` - Slide source file\n- \\`config.yaml\\` - Project configuration\n- \\`themes/\\` - Custom themes\n- \\`icons/custom/\\` - Custom icons\n\n## Skills\n\nThis project includes AgentSkills at \\`.skills/slide-assistant/\\`.\nRead \\`.skills/slide-assistant/SKILL.md\\` for detailed instructions.\n\n## Slash Commands\n\n- \\`/slide-create\\` - Create slides from requirements\n- \\`/slide-validate\\` - Validate slide source file\n- \\`/slide-preview\\` - Preview slides in browser\n- \\`/slide-screenshot\\` - Take screenshots for review\n- \\`/slide-theme\\` - Adjust theme and styling\n`;\n}\n","/**\n * Generate AGENTS.md content for OpenCode\n */\nexport function generateAgentsMd(): string {\n return `# Slide Generation Project\n\nThis project uses slide-gen to create Marp slides from YAML source files.\n\n## Quick Start\n\n\\`\\`\\`bash\n# Validate\nslide-gen validate presentation.yaml\n\n# Convert\nslide-gen convert presentation.yaml -o slides.md\n\n# Preview\nslide-gen preview presentation.yaml\n\\`\\`\\`\n\n## Commands\n\n| Command | Description |\n|---------|-------------|\n| \\`slide-gen convert <input>\\` | Convert YAML to Marp Markdown |\n| \\`slide-gen validate <input>\\` | Validate source file |\n| \\`slide-gen templates list\\` | List available templates |\n| \\`slide-gen templates info <name>\\` | Get template details |\n| \\`slide-gen icons search <query>\\` | Search for icons |\n| \\`slide-gen preview <input>\\` | Preview in browser |\n| \\`slide-gen screenshot <input>\\` | Take screenshots |\n\n## AI-Optimized Output\n\nFor token-efficient output, use \\`--format llm\\`:\n\\`\\`\\`bash\nslide-gen templates list --format llm\nslide-gen templates info bullet-list --format llm\n\\`\\`\\`\n\n## Project Structure\n\n- \\`presentation.yaml\\` - Slide source file\n- \\`config.yaml\\` - Project configuration\n- \\`themes/\\` - Custom themes\n- \\`icons/custom/\\` - Custom icons\n\n## Skills\n\nThis project includes AgentSkills at \\`.skills/slide-assistant/\\`.\nRead \\`.skills/slide-assistant/SKILL.md\\` for detailed instructions.\n`;\n}\n","/**\n * Generate .opencode/agent/slide.md content\n */\nexport function generateOpenCodeAgent(): string {\n return `---\ndescription: Slide creation assistant using slide-gen CLI\nmode: subagent\ntools:\n write: allow\n edit: allow\n bash: allow\n read: allow\npermission:\n file_edit: allow\n bash: allow\n---\n\n# Slide Assistant\n\nYou are a slide creation assistant that uses the slide-gen CLI tool.\n\n## Available Commands\n\n| Command | Description |\n|---------|-------------|\n| \\`slide-gen convert <input>\\` | Convert YAML to Marp Markdown |\n| \\`slide-gen validate <input>\\` | Validate source file |\n| \\`slide-gen templates list --format llm\\` | List templates (AI format) |\n| \\`slide-gen icons search <query>\\` | Search icons |\n| \\`slide-gen screenshot <input>\\` | Take screenshots |\n\n## Workflow\n\n1. Understand user requirements\n2. Check available templates\n3. Create/edit presentation.yaml\n4. Validate and fix errors\n5. Convert to Marp Markdown\n6. Take screenshots for review\n\n## YAML Format\n\n\\`\\`\\`yaml\nmeta:\n title: \"Title\"\n author: \"Author\"\n\nslides:\n - template: title\n content:\n title: \"Main Title\"\n\\`\\`\\`\n`;\n}\n","/**\n * Generate references/templates.md content\n * Contains detailed template parameter reference\n */\nexport function generateTemplatesRef(): string {\n return `# Template Reference\n\n## Basic Templates\n\n### title\nFull-screen title slide.\n- \\`title\\`: Main title (required)\n- \\`subtitle\\`: Subtitle (optional)\n- \\`author\\`: Author name (optional)\n\n### content\nGeneral content slide with body text.\n- \\`title\\`: Slide title (required)\n- \\`body\\`: Body text with markdown support (required)\n\n### section\nSection divider slide.\n- \\`title\\`: Section title (required)\n- \\`subtitle\\`: Section description (optional)\n\n### bullet-list\nSlide with bullet points.\n- \\`title\\`: Slide title (required)\n- \\`items\\`: Array of strings (required)\n\n### two-column\nTwo-column layout.\n- \\`title\\`: Slide title (required)\n- \\`left\\`: Left column content (required)\n- \\`right\\`: Right column content (required)\n\n### end\nClosing slide.\n- \\`title\\`: Closing title (required)\n- \\`subtitle\\`: Closing subtitle (optional)\n\n## Diagram Templates\n\n### cycle-diagram\nCircular process diagram (3-6 nodes).\n- \\`title\\`: Slide title (required)\n- \\`nodes\\`: Array of {label, icon?, color?} (required)\n\n### flow-diagram\nLinear flow diagram.\n- \\`title\\`: Slide title (required)\n- \\`steps\\`: Array of {label, icon?, description?} (required)\n\n### comparison\nSide-by-side comparison.\n- \\`title\\`: Slide title (required)\n- \\`items\\`: Array of comparison items (required)\n\n## Data Templates\n\n### table\nData table display.\n- \\`title\\`: Slide title (required)\n- \\`headers\\`: Array of column headers (required)\n- \\`rows\\`: Array of row data arrays (required)\n\n### chart\nChart visualization.\n- \\`title\\`: Slide title (required)\n- \\`type\\`: Chart type (bar, line, pie)\n- \\`data\\`: Chart data\n\n## Image Templates\n\n### image-full\nFull-screen background image.\n- \\`image\\`: Image path (required)\n- \\`title\\`: Overlay title (optional)\n- \\`overlay\\`: none|dark|light|gradient (optional)\n\n### image-text\nImage with text side by side.\n- \\`title\\`: Slide title (required)\n- \\`image\\`: Image path (required)\n- \\`image_position\\`: left|right (optional, default: left)\n- \\`items\\` or \\`text\\`: Content (required)\n\n## Run \\`slide-gen templates list --format llm\\` for full list.\n`;\n}\n","/**\n * Generate references/workflows.md content\n * Contains source collection and image collaboration workflows\n */\nexport function generateWorkflowsRef(): string {\n return `# Workflow Reference\n\n## Source Collection Flow\n\n### Pattern A: Directory Exploration\nWhen user has materials in a directory:\n1. Ask for directory path\n2. Scan with Glob tool\n3. Read and classify files\n4. Summarize and confirm with user\n5. Create sources/sources.yaml\n\n### Pattern B: Supplement Mode\nWhen user has partial materials:\n1. Read provided file/text\n2. Analyze content\n3. Identify missing information\n4. Ask supplementary questions\n5. Create sources/sources.yaml\n\n### Pattern C: Interview Mode\nWhen user has no materials:\n1. Ask basic questions (purpose, audience, duration)\n2. Deep-dive based on purpose\n3. Propose slide structure\n4. Iterate based on feedback\n5. Create sources/sources.yaml\n\n## Slide Creation Flow\n\n### Step 1: Gather Requirements\n- Understand presentation purpose\n- Identify target audience\n- Determine slide count and duration\n\n### Step 2: Template Selection\n- Run \\`slide-gen templates list --format llm\\`\n- Match templates to content types\n- Plan slide sequence\n\n### Step 3: Create Source File\n- Create presentation.yaml\n- Use appropriate templates for each slide\n- Add icons where helpful\n\n### Step 4: Validate\n- Run \\`slide-gen validate presentation.yaml\\`\n- Fix any validation errors\n- Check template parameters\n\n### Step 5: Convert and Review\n- Run \\`slide-gen convert presentation.yaml\\`\n- Use \\`slide-gen screenshot\\` for visual review\n- Iterate based on feedback\n\n## Image Collaboration Flow\n\n### Phase 1: Requirement Derivation\nAnalyze presentation scenario to identify needed images.\n\n### Phase 2: Image Request\nGenerate specific image requests with:\n- Purpose and context\n- Recommended specifications\n- File naming convention\n\n### Phase 3: Verification\nAfter user provides images:\n1. Visual inspection (Read tool)\n2. Check metadata if available\n3. Verify compliance and permissions\n4. Provide feedback\n\n### Phase 4: Iteration\nHandle adjustments (cropping, replacement) as needed.\n`;\n}\n","/**\n * Generate .claude/commands/slide-create.md content\n */\nexport function generateSlideCreateCommand(): string {\n return `Create slides from user requirements.\n\n## Steps\n\n1. Get manuscript/requirements from user\n2. Check templates: \\`slide-gen templates list --format llm\\`\n3. Select appropriate templates\n4. Create or edit presentation.yaml\n5. Validate: \\`slide-gen validate presentation.yaml\\`\n6. Fix any errors\n7. Convert: \\`slide-gen convert presentation.yaml -o slides.md\\`\n8. Report results\n\n## Notes\n\n- Select appropriate template for each slide\n- Search icons if needed: \\`slide-gen icons search\\`\n- Fix all validation errors before conversion\n`;\n}\n","/**\n * Generate .claude/commands/slide-validate.md content\n */\nexport function generateSlideValidateCommand(): string {\n return `Validate slide source file.\n\n## Command\n\n\\`\\`\\`bash\nslide-gen validate $ARGUMENTS\n\\`\\`\\`\n\nIf no argument provided:\n\\`\\`\\`bash\nslide-gen validate presentation.yaml\n\\`\\`\\`\n\n## Options\n\n| Option | Description |\n|--------|-------------|\n| \\`--format text\\` | Human-readable output (default) |\n| \\`--format json\\` | JSON output for programmatic use |\n| \\`--format llm\\` | AI-optimized output with line numbers and fix hints |\n| \\`--strict\\` | Treat warnings as errors |\n| \\`-c, --config <path>\\` | Custom config file path |\n\n## AI-Optimized Validation\n\nUse \\`--format llm\\` for structured error output:\n\n\\`\\`\\`bash\nslide-gen validate presentation.yaml --format llm\n\\`\\`\\`\n\n### Example Output (Error)\n\n\\`\\`\\`\nValidation failed.\n\nError at line 15, Slide 2 (bullet-list):\n Missing required field: items\n\nFix:\n content:\n title: \"Your title\"\n items:\n - \"Item 1\"\n - \"Item 2\"\n\\`\\`\\`\n\n### Example Output (Success)\n\n\\`\\`\\`\nValidation passed. 5 slides validated.\n\\`\\`\\`\n\n### Error Types and Hints\n\n- **unknown_template**: Suggests \\`slide-gen templates list --format llm\\`\n- **unknown_icon**: Suggests \\`slide-gen icons search <query>\\`\n- **missing_field**: Shows fix example from template definition\n- **invalid_type**: Shows expected format from template definition\n`;\n}\n\n","/**\n * Generate .claude/commands/slide-preview.md content\n */\nexport function generateSlidePreviewCommand(): string {\n return `Preview slides in browser.\n\n## Command\n\n\\`\\`\\`bash\nslide-gen preview $ARGUMENTS\n\\`\\`\\`\n\nIf no argument provided:\n\\`\\`\\`bash\nslide-gen preview presentation.yaml\n\\`\\`\\`\n\n## Options\n\n- \\`--gallery\\` or \\`-g\\`: Show thumbnail gallery of all slides\n- \\`--slide <number>\\`: Preview specific slide\n`;\n}\n","/**\n * Generate .claude/commands/slide-screenshot.md content\n */\nexport function generateSlideScreenshotCommand(): string {\n return `Take screenshots of slides for AI review.\n\n## Command\n\n\\`\\`\\`bash\nslide-gen screenshot $ARGUMENTS\n\\`\\`\\`\n\nIf no argument provided:\n\\`\\`\\`bash\nslide-gen screenshot presentation.yaml -o screenshots/\n\\`\\`\\`\n\n## Options\n\n- \\`--slide <number>\\`: Screenshot specific slide only\n- \\`--width <pixels>\\`: Image width (default: 1280)\n- \\`--output <dir>\\`: Output directory\n\n## After Screenshot\n\nRead the screenshot images to review slide content and provide feedback.\n`;\n}\n","/**\n * Generate .claude/commands/slide-theme.md content\n */\nexport function generateSlideThemeCommand(): string {\n return `Adjust slide theme and styling.\n\n## Steps\n\n1. Read current theme settings (themes/custom.css)\n2. Confirm user requirements\n3. Edit CSS\n4. Regenerate: \\`slide-gen convert\\`\n5. Take screenshot: \\`slide-gen screenshot\\`\n6. Review and report to user\n\n## Adjustable Items\n\n- Background color\n- Font family and size\n- Heading styles\n- Color scheme\n- Margins and layout\n`;\n}\n","import { Command } from 'commander';\nimport { access } from 'fs/promises';\nimport { basename, dirname, join } from 'path';\nimport chalk from 'chalk';\nimport { watch as chokidarWatch, FSWatcher } from 'chokidar';\nimport { Pipeline, PipelineError } from '../../core/pipeline';\nimport { ConfigLoader } from '../../config/loader';\nimport { ExitCode } from './convert';\n\nexport interface WatchOptions {\n output?: string;\n config?: string;\n debounce?: number;\n verbose?: boolean;\n signal?: AbortSignal;\n}\n\nexport interface WatchResult {\n success: boolean;\n conversionCount: number;\n errors: string[];\n}\n\n/**\n * State management for watch mode\n */\nexport class WatchState {\n private _isRunning = false;\n private _conversionCount = 0;\n private _lastError: Error | null = null;\n\n get isRunning(): boolean {\n return this._isRunning;\n }\n\n get conversionCount(): number {\n return this._conversionCount;\n }\n\n get lastError(): Error | null {\n return this._lastError;\n }\n\n start(): void {\n this._isRunning = true;\n }\n\n stop(): void {\n this._isRunning = false;\n }\n\n incrementConversion(): void {\n this._conversionCount++;\n }\n\n setError(error: Error): void {\n this._lastError = error;\n }\n\n clearError(): void {\n this._lastError = null;\n }\n}\n\n/**\n * Generate default output path from input path\n */\nexport function getDefaultOutputPath(inputPath: string): string {\n const dir = dirname(inputPath);\n const base = basename(inputPath, '.yaml');\n return join(dir, `${base}.md`);\n}\n\n/**\n * Format timestamp for log output\n */\nfunction formatTime(): string {\n const now = new Date();\n return `[${now.toLocaleTimeString('en-GB')}]`;\n}\n\n/**\n * Create the watch command\n */\nexport function createWatchCommand(): Command {\n return new Command('watch')\n .description('Watch source file and auto-convert on changes')\n .argument('<input>', 'Input YAML file to watch')\n .option('-o, --output <path>', 'Output file path')\n .option('-c, --config <path>', 'Config file path')\n .option('--debounce <ms>', 'Debounce delay in milliseconds', '300')\n .option('-v, --verbose', 'Verbose output')\n .action(async (input: string, options: WatchOptions) => {\n await executeWatch(input, options);\n });\n}\n\n/**\n * Execute a single conversion\n */\nasync function runConversion(\n inputPath: string,\n outputPath: string,\n pipeline: Pipeline,\n verbose: boolean\n): Promise<{ success: boolean; error?: string }> {\n try {\n const result = await pipeline.runWithResult(inputPath, { outputPath });\n\n console.log(\n `${formatTime()} ${chalk.green('✓')} Output: ${chalk.cyan(outputPath)}`\n );\n\n if (verbose) {\n console.log(` Parsed ${result.slideCount} slides`);\n if (result.warnings.length > 0) {\n for (const warning of result.warnings) {\n console.log(chalk.yellow(` ⚠ ${warning}`));\n }\n }\n }\n\n return { success: true };\n } catch (error) {\n const message =\n error instanceof PipelineError\n ? `${error.stage}: ${error.message}`\n : error instanceof Error\n ? error.message\n : 'Unknown error';\n\n console.log(\n `${formatTime()} ${chalk.red('✗')} Conversion failed: ${message}`\n );\n\n return { success: false, error: message };\n }\n}\n\n/**\n * Execute the watch command\n */\nexport async function executeWatch(\n inputPath: string,\n options: WatchOptions\n): Promise<WatchResult> {\n const state = new WatchState();\n const errors: string[] = [];\n const debounceMs = Number(options.debounce) || 300;\n const verbose = options.verbose ?? false;\n\n // Check if immediately aborted (for testing)\n if (options.signal?.aborted) {\n // Validate input file exists\n try {\n await access(inputPath);\n } catch {\n errors.push(`File not found: ${inputPath}`);\n return { success: false, conversionCount: 0, errors };\n }\n return { success: true, conversionCount: 0, errors };\n }\n\n // Validate input file exists\n try {\n await access(inputPath);\n } catch {\n console.error(chalk.red(`Error: File not found: ${inputPath}`));\n errors.push(`File not found: ${inputPath}`);\n process.exitCode = ExitCode.FileReadError;\n return { success: false, conversionCount: 0, errors };\n }\n\n // Determine output path\n const outputPath = options.output ?? getDefaultOutputPath(inputPath);\n\n // Load configuration\n const configLoader = new ConfigLoader();\n let configPath = options.config;\n\n if (!configPath) {\n configPath = await configLoader.findConfig(dirname(inputPath));\n }\n\n const config = await configLoader.load(configPath);\n\n // Create and initialize pipeline\n const pipeline = new Pipeline(config);\n\n try {\n await pipeline.initialize();\n } catch (error) {\n const message =\n error instanceof Error ? error.message : 'Unknown initialization error';\n console.error(chalk.red(`Error: Failed to initialize pipeline: ${message}`));\n errors.push(message);\n process.exitCode = ExitCode.ConversionError;\n return { success: false, conversionCount: 0, errors };\n }\n\n console.log(`Watching ${chalk.cyan(inputPath)}...`);\n console.log(`Output: ${chalk.cyan(outputPath)}`);\n console.log('');\n\n // Initial conversion\n console.log(`${formatTime()} Initial conversion...`);\n const initialResult = await runConversion(inputPath, outputPath, pipeline, verbose);\n if (initialResult.success) {\n state.incrementConversion();\n } else if (initialResult.error) {\n errors.push(initialResult.error);\n }\n\n // Set up file watcher\n let debounceTimer: ReturnType<typeof setTimeout> | null = null;\n let watcher: FSWatcher | null = null;\n\n const handleChange = () => {\n if (debounceTimer) {\n clearTimeout(debounceTimer);\n }\n\n debounceTimer = setTimeout(async () => {\n console.log(`${formatTime()} Changed: ${inputPath}`);\n console.log(`${formatTime()} Converting...`);\n\n const result = await runConversion(inputPath, outputPath, pipeline, verbose);\n if (result.success) {\n state.incrementConversion();\n state.clearError();\n } else if (result.error) {\n errors.push(result.error);\n state.setError(new Error(result.error));\n }\n }, debounceMs);\n };\n\n state.start();\n\n watcher = chokidarWatch(inputPath, {\n persistent: true,\n ignoreInitial: true,\n awaitWriteFinish: {\n stabilityThreshold: 100,\n pollInterval: 50,\n },\n });\n\n watcher.on('change', handleChange);\n\n // Handle abort signal\n const cleanup = () => {\n state.stop();\n if (debounceTimer) {\n clearTimeout(debounceTimer);\n }\n watcher?.close();\n };\n\n if (options.signal) {\n options.signal.addEventListener('abort', cleanup);\n }\n\n // Handle process signals\n const signalHandler = () => {\n console.log('\\n' + chalk.yellow('Watch stopped.'));\n cleanup();\n process.exit(0);\n };\n\n process.on('SIGINT', signalHandler);\n process.on('SIGTERM', signalHandler);\n\n // Keep the process running\n await new Promise<void>((resolve) => {\n if (options.signal) {\n options.signal.addEventListener('abort', () => resolve());\n }\n });\n\n return {\n success: errors.length === 0,\n conversionCount: state.conversionCount,\n errors,\n };\n}\n","import { Command } from \"commander\";\nimport { readFile, stat, mkdir } from \"fs/promises\";\nimport { dirname, basename, join } from \"path\";\nimport chalk from \"chalk\";\nimport { stringify as stringifyYaml } from \"yaml\";\nimport { Parser } from \"../../core/parser\";\nimport {\n ImageValidator,\n ImageStats,\n ImageMetadataLoader,\n ImageProcessor,\n ImageProcessingPipeline,\n type ImageMetadata,\n} from \"../../images\";\nimport { isImageFile } from \"../../images/constants\";\n\n/**\n * Create the images command with subcommands\n */\nexport function createImagesCommand(): Command {\n const cmd = new Command(\"images\").description(\"Manage presentation images\");\n\n cmd.addCommand(createImagesStatusCommand());\n cmd.addCommand(createImagesRequestCommand());\n cmd.addCommand(createImagesProcessCommand());\n\n return cmd;\n}\n\n/**\n * Create the images status subcommand\n */\nfunction createImagesStatusCommand(): Command {\n return new Command(\"status\")\n .description(\"Show image permission status\")\n .argument(\"<input>\", \"Presentation YAML file\")\n .action(async (input: string) => {\n await executeImagesStatus(input);\n });\n}\n\n/**\n * Create the images request subcommand\n */\nfunction createImagesRequestCommand(): Command {\n return new Command(\"request\")\n .description(\"Generate missing image request list\")\n .argument(\"<input>\", \"Presentation YAML file\")\n .option(\"--format <format>\", \"Output format (text|llm)\", \"text\")\n .action(async (input: string, options: { format: string }) => {\n await executeImagesRequest(input, options);\n });\n}\n\n/**\n * Execute images status command\n */\nasync function executeImagesStatus(inputPath: string): Promise<void> {\n try {\n const slides = await loadPresentation(inputPath);\n const baseDir = dirname(inputPath);\n const validator = new ImageValidator(baseDir);\n\n // Extract image references\n const imageRefs = validator.extractImageReferences(slides);\n\n if (imageRefs.length === 0) {\n console.log(chalk.yellow(\"No images found in presentation\"));\n return;\n }\n\n // Get stats\n const stats = await validator.getImageStats(slides);\n\n // Output formatted status\n await outputImageStatus(stats, imageRefs, validator, baseDir);\n } catch (error) {\n const message = error instanceof Error ? error.message : \"Unknown error\";\n console.error(chalk.red(`Error: ${message}`));\n process.exitCode = 1;\n }\n}\n\n/**\n * Image info with metadata for status display\n */\ninterface ImageStatusInfo {\n path: string;\n metadata: ImageMetadata;\n}\n\n/**\n * Output image status in a formatted way with per-image details\n */\nasync function outputImageStatus(\n stats: ImageStats,\n imageRefs: string[],\n _validator: ImageValidator,\n baseDir: string\n): Promise<void> {\n const metadataLoader = new ImageMetadataLoader(baseDir);\n\n // Group images by status\n const approved: ImageStatusInfo[] = [];\n const pending: ImageStatusInfo[] = [];\n const restricted: ImageStatusInfo[] = [];\n const rejected: ImageStatusInfo[] = [];\n const unknown: ImageStatusInfo[] = [];\n\n for (const imagePath of imageRefs) {\n const metadata = await metadataLoader.load(imagePath);\n const info: ImageStatusInfo = { path: imagePath, metadata };\n const status = metadata.permissions?.status;\n\n switch (status) {\n case \"approved\":\n approved.push(info);\n break;\n case \"pending\":\n pending.push(info);\n break;\n case \"restricted\":\n restricted.push(info);\n break;\n case \"rejected\":\n rejected.push(info);\n break;\n default:\n unknown.push(info);\n }\n }\n\n console.log(\"\");\n console.log(chalk.bold(\"Image Permissions Status:\"));\n console.log(\"━\".repeat(50));\n\n // Approved images\n if (approved.length > 0) {\n console.log(\"\");\n console.log(chalk.green(`✓ Approved (${approved.length}):`));\n for (const info of approved) {\n const approver = info.metadata.permissions?.approved_by || \"unknown\";\n const expires = info.metadata.permissions?.expires || \"none\";\n console.log(chalk.green(` - ${info.path} (${approver}, expires: ${expires})`));\n }\n }\n\n // Pending images\n if (pending.length > 0) {\n console.log(\"\");\n console.log(chalk.yellow(`⏳ Pending (${pending.length}):`));\n for (const info of pending) {\n console.log(chalk.yellow(` - ${info.path}`));\n const contact = info.metadata.permissions?.pending_contact;\n if (contact) {\n console.log(chalk.yellow(` Contact: ${contact}`));\n }\n }\n }\n\n // Restricted images\n if (restricted.length > 0) {\n console.log(\"\");\n console.log(chalk.yellow(`⚠ Restricted (${restricted.length}):`));\n for (const info of restricted) {\n console.log(chalk.yellow(` - ${info.path}`));\n const conditions = info.metadata.permissions?.conditions;\n if (conditions && conditions.length > 0) {\n console.log(chalk.yellow(` Conditions: ${conditions.join(\", \")}`));\n }\n }\n }\n\n // Rejected images\n if (rejected.length > 0) {\n console.log(\"\");\n console.log(chalk.red(`✗ Rejected (${rejected.length}):`));\n for (const info of rejected) {\n console.log(chalk.red(` - ${info.path}`));\n }\n }\n\n // Unknown images\n if (unknown.length > 0) {\n console.log(\"\");\n console.log(chalk.gray(`? Unknown (${unknown.length}):`));\n for (const info of unknown) {\n console.log(chalk.gray(` - ${info.path}`));\n }\n }\n\n console.log(\"\");\n console.log(\"━\".repeat(50));\n console.log(\n `Summary: ${stats.approved} approved, ${stats.pending} pending, ${stats.restricted} restricted, ${stats.rejected} rejected`\n );\n}\n\n/**\n * Execute images request command\n */\nasync function executeImagesRequest(\n inputPath: string,\n options: { format: string }\n): Promise<void> {\n try {\n const slides = await loadPresentation(inputPath);\n const baseDir = dirname(inputPath);\n const validator = new ImageValidator(baseDir);\n\n // Get missing images\n const missingImages = await validator.getMissingImages(slides);\n\n if (missingImages.length === 0) {\n console.log(chalk.green(\"No missing images found!\"));\n return;\n }\n\n if (options.format === \"llm\") {\n outputMissingImagesLLM(missingImages, slides);\n } else {\n outputMissingImagesText(missingImages);\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : \"Unknown error\";\n console.error(chalk.red(`Error: ${message}`));\n process.exitCode = 1;\n }\n}\n\n/**\n * Output missing images in text format\n */\nfunction outputMissingImagesText(missingImages: string[]): void {\n console.log(\"\");\n console.log(chalk.bold(\"Missing Images:\"));\n console.log(\"━\".repeat(50));\n console.log(\"\");\n\n for (const imagePath of missingImages) {\n console.log(chalk.red(` ✗ ${imagePath}`));\n }\n\n console.log(\"\");\n console.log(`Total: ${missingImages.length} missing image(s)`);\n console.log(\"\");\n console.log(\n chalk.gray(\"Run 'slide-gen images request --format llm' for AI-friendly output\")\n );\n}\n\n/**\n * Output missing images in LLM-friendly YAML format\n */\nfunction outputMissingImagesLLM(\n missingImages: string[],\n slides: SlideContent[]\n): void {\n // Build context for each missing image\n const imageContextMap = buildImageContext(slides);\n\n const output = {\n missing_images: missingImages.map((imagePath) => ({\n path: imagePath,\n slide: findSlideWithImage(slides, imagePath),\n template: findTemplateForImage(slides, imagePath),\n context: imageContextMap.get(imagePath) || {},\n })),\n };\n\n console.log(stringifyYaml(output));\n}\n\n/**\n * Slide content type\n */\ninterface SlideContent {\n template: string;\n content: Record<string, unknown>;\n}\n\n/**\n * Load and parse presentation file\n */\nasync function loadPresentation(inputPath: string): Promise<SlideContent[]> {\n const content = await readFile(inputPath, \"utf-8\");\n const parser = new Parser();\n const presentation = parser.parse(content);\n\n return presentation.slides.map((slide) => ({\n template: slide.template,\n content: slide.content as Record<string, unknown>,\n }));\n}\n\n/**\n * Build context map for images\n */\nfunction buildImageContext(\n slides: SlideContent[]\n): Map<string, Record<string, unknown>> {\n const contextMap = new Map<string, Record<string, unknown>>();\n\n for (let i = 0; i < slides.length; i++) {\n const slide = slides[i]!;\n const content = slide.content;\n\n // Get title from content\n const title = content[\"title\"] as string | undefined;\n\n // Direct image\n const image = content[\"image\"];\n if (typeof image === \"string\") {\n contextMap.set(image, {\n title: title || `Slide ${i + 1}`,\n usage: getImageUsageDescription(slide.template),\n });\n }\n\n // Before/after\n const before = content[\"before\"] as Record<string, unknown> | undefined;\n const after = content[\"after\"] as Record<string, unknown> | undefined;\n if (before?.[\"image\"]) {\n contextMap.set(before[\"image\"] as string, {\n title: title || `Slide ${i + 1}`,\n usage: \"Before image in comparison\",\n });\n }\n if (after?.[\"image\"]) {\n contextMap.set(after[\"image\"] as string, {\n title: title || `Slide ${i + 1}`,\n usage: \"After image in comparison\",\n });\n }\n\n // Gallery images\n const images = content[\"images\"] as Array<{ src: string }> | undefined;\n if (Array.isArray(images)) {\n for (const img of images) {\n if (img.src) {\n contextMap.set(img.src, {\n title: title || `Slide ${i + 1}`,\n usage: \"Gallery image\",\n });\n }\n }\n }\n }\n\n return contextMap;\n}\n\n/**\n * Get usage description for image template\n */\nfunction getImageUsageDescription(template: string): string {\n switch (template) {\n case \"image-full\":\n return \"Fullscreen background image\";\n case \"image-text\":\n return \"Image alongside text content\";\n case \"image-caption\":\n return \"Image with detailed caption\";\n case \"gallery\":\n return \"Gallery grid image\";\n case \"before-after\":\n return \"Comparison image\";\n default:\n return \"Image in slide\";\n }\n}\n\n/**\n * Find slide number containing an image\n */\nfunction findSlideWithImage(slides: SlideContent[], imagePath: string): number {\n for (let i = 0; i < slides.length; i++) {\n const content = slides[i]!.content;\n\n if (content[\"image\"] === imagePath) return i + 1;\n\n const before = content[\"before\"] as Record<string, unknown> | undefined;\n const after = content[\"after\"] as Record<string, unknown> | undefined;\n if (before?.[\"image\"] === imagePath || after?.[\"image\"] === imagePath) {\n return i + 1;\n }\n\n const images = content[\"images\"] as Array<{ src: string }> | undefined;\n if (images?.some((img) => img.src === imagePath)) {\n return i + 1;\n }\n }\n return 0;\n}\n\n/**\n * Find template for an image\n */\nfunction findTemplateForImage(\n slides: SlideContent[],\n imagePath: string\n): string {\n for (const slide of slides) {\n const content = slide.content;\n\n if (content[\"image\"] === imagePath) return slide.template;\n\n const before = content[\"before\"] as Record<string, unknown> | undefined;\n const after = content[\"after\"] as Record<string, unknown> | undefined;\n if (before?.[\"image\"] === imagePath || after?.[\"image\"] === imagePath) {\n return slide.template;\n }\n\n const images = content[\"images\"] as Array<{ src: string }> | undefined;\n if (images?.some((img) => img.src === imagePath)) {\n return slide.template;\n }\n }\n return \"unknown\";\n}\n\n/**\n * Create the images process subcommand\n */\nfunction createImagesProcessCommand(): Command {\n return new Command(\"process\")\n .description(\"Process images (crop, blur)\")\n .argument(\"<path>\", \"Image file or directory\")\n .option(\"--crop <spec>\", 'Crop specification (e.g., \"right:10,bottom:5\")')\n .option(\"--blur <spec>\", 'Blur region (e.g., \"100,100,50,50\")')\n .option(\"--from-meta\", \"Apply processing from metadata files\")\n .option(\"--output <dir>\", \"Output directory\", \".processed\")\n .action(async (inputPath: string, options: ProcessOptions) => {\n await executeImagesProcess(inputPath, options);\n });\n}\n\n/**\n * Options for images process command\n */\ninterface ProcessOptions {\n crop?: string;\n blur?: string;\n fromMeta?: boolean;\n output: string;\n}\n\n/**\n * Execute images process command\n */\nasync function executeImagesProcess(\n inputPath: string,\n options: ProcessOptions\n): Promise<void> {\n try {\n const pathStat = await stat(inputPath);\n const isDirectory = pathStat.isDirectory();\n\n if (isDirectory) {\n // Process directory\n await processDirectory(inputPath, options);\n } else {\n // Process single file\n await processSingleFile(inputPath, options);\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : \"Unknown error\";\n console.error(chalk.red(`Error: ${message}`));\n process.exitCode = 1;\n }\n}\n\n/**\n * Process all images in a directory\n */\nasync function processDirectory(\n dirPath: string,\n options: ProcessOptions\n): Promise<void> {\n if (options.fromMeta) {\n // Use metadata-based processing\n const outputDir = join(dirPath, options.output);\n const pipeline = new ImageProcessingPipeline(dirPath, { outputDir });\n const result = await pipeline.processDirectory();\n\n console.log(\"\");\n console.log(chalk.bold(\"Image Processing Results:\"));\n console.log(\"━\".repeat(50));\n console.log(`Total images: ${result.totalImages}`);\n console.log(chalk.green(`Processed: ${result.processedImages}`));\n console.log(chalk.gray(`Skipped: ${result.skippedImages} (no processing instructions)`));\n\n if (result.errors.length > 0) {\n console.log(chalk.red(`Errors: ${result.errors.length}`));\n for (const err of result.errors) {\n console.log(chalk.red(` - ${err}`));\n }\n }\n\n console.log(\"\");\n console.log(`${result.processedImages} processed, ${result.skippedImages} skipped`);\n } else {\n console.log(\n chalk.yellow(\n \"Warning: Processing directory requires --from-meta flag to apply metadata instructions\"\n )\n );\n console.log(\n chalk.gray(\"Use --crop or --blur options with a single file, or use --from-meta for directory\")\n );\n }\n}\n\n/**\n * Process a single image file\n */\nasync function processSingleFile(\n filePath: string,\n options: ProcessOptions\n): Promise<void> {\n if (!isImageFile(filePath)) {\n console.error(chalk.red(`Error: ${filePath} is not a supported image file`));\n process.exitCode = 1;\n return;\n }\n\n const processor = new ImageProcessor();\n const dir = dirname(filePath);\n const filename = basename(filePath);\n const outputDir = join(dir, options.output);\n\n // Ensure output directory exists\n await mkdir(outputDir, { recursive: true });\n\n const outputPath = join(outputDir, filename);\n let success = false;\n\n if (options.crop) {\n // Parse crop specification\n const edges = parseCropSpec(options.crop);\n if (!edges) {\n console.error(chalk.red(\"Invalid crop specification. Use format: right:10,bottom:5\"));\n process.exitCode = 1;\n return;\n }\n\n const result = await processor.cropEdges(filePath, edges, outputPath);\n if (!result.success) {\n console.error(chalk.red(`Crop failed: ${result.error}`));\n process.exitCode = 1;\n return;\n }\n success = true;\n console.log(chalk.green(`Processed: ${filename} (cropped to ${result.width}x${result.height})`));\n }\n\n if (options.blur) {\n // Parse blur specification\n const region = parseBlurSpec(options.blur);\n if (!region) {\n console.error(chalk.red(\"Invalid blur specification. Use format: x,y,width,height\"));\n process.exitCode = 1;\n return;\n }\n\n const inputForBlur = success ? outputPath : filePath;\n const result = await processor.blurRegion(inputForBlur, region, outputPath);\n if (!result.success) {\n console.error(chalk.red(`Blur failed: ${result.error}`));\n process.exitCode = 1;\n return;\n }\n success = true;\n console.log(chalk.green(`Processed: ${filename} (blurred region)`));\n }\n\n if (options.fromMeta) {\n // Process from metadata\n const metadataLoader = new ImageMetadataLoader(dir);\n const metadata = await metadataLoader.load(filename);\n\n if (!metadata.processing || metadata.processing.length === 0) {\n console.log(chalk.yellow(`No processing instructions found for ${filename}`));\n return;\n }\n\n const pipeline = new ImageProcessingPipeline(dir, { outputDir });\n const result = await pipeline.processImage(filename);\n\n if (!result.success) {\n console.error(chalk.red(`Processing failed: ${result.error}`));\n process.exitCode = 1;\n return;\n }\n\n success = true;\n console.log(\n chalk.green(`Processed: ${filename} (${result.instructionsApplied} instruction(s))`)\n );\n }\n\n if (!success && !options.crop && !options.blur && !options.fromMeta) {\n console.log(\n chalk.yellow(\"No processing options specified. Use --crop, --blur, or --from-meta\")\n );\n }\n\n if (success) {\n console.log(`Output: ${chalk.cyan(outputPath)}`);\n }\n}\n\n/**\n * Parse crop specification string (e.g., \"right:10,bottom:5\")\n */\nfunction parseCropSpec(spec: string): { left?: number; right?: number; top?: number; bottom?: number } | null {\n const result: { left?: number; right?: number; top?: number; bottom?: number } = {};\n const parts = spec.split(\",\");\n\n for (const part of parts) {\n const [key, value] = part.split(\":\");\n if (!key || !value) return null;\n\n const numValue = parseInt(value, 10);\n if (isNaN(numValue) || numValue < 0 || numValue > 50) return null;\n\n const edge = key.trim().toLowerCase();\n if (edge === \"left\") result.left = numValue;\n else if (edge === \"right\") result.right = numValue;\n else if (edge === \"top\") result.top = numValue;\n else if (edge === \"bottom\") result.bottom = numValue;\n else return null;\n }\n\n return Object.keys(result).length > 0 ? result : null;\n}\n\n/**\n * Parse blur specification string (e.g., \"100,100,50,50\")\n */\nfunction parseBlurSpec(spec: string): { x: number; y: number; width: number; height: number } | null {\n const parts = spec.split(\",\").map((p) => parseInt(p.trim(), 10));\n\n if (parts.length !== 4 || parts.some(isNaN)) {\n return null;\n }\n\n const [x, y, width, height] = parts as [number, number, number, number];\n if (x < 0 || y < 0 || width <= 0 || height <= 0) {\n return null;\n }\n\n return { x, y, width, height };\n}\n","import { Command } from 'commander';\nimport { access, mkdir, readdir, unlink } from 'fs/promises';\nimport { basename, dirname, join } from 'path';\nimport { execSync, execFileSync } from 'child_process';\nimport chalk from 'chalk';\nimport ora from 'ora';\nimport { Pipeline, PipelineError } from '../../core/pipeline';\nimport { ConfigLoader } from '../../config/loader';\nimport { ExitCode } from './convert';\n\nexport interface ScreenshotOptions {\n output?: string;\n slide?: number;\n width?: number;\n format?: 'png' | 'jpeg';\n config?: string;\n verbose?: boolean;\n}\n\nexport interface ScreenshotResult {\n success: boolean;\n errors: string[];\n outputDir?: string;\n files?: string[];\n}\n\nexport interface FilterResult {\n success: boolean;\n keptFile?: string;\n error?: string;\n}\n\n/**\n * Filter generated images to keep only a specific slide\n * Marp generates files like: basename.001.png, basename.002.png, etc.\n */\nexport async function filterToSpecificSlide(\n outputDir: string,\n baseName: string,\n slideNumber: number,\n format: string\n): Promise<FilterResult> {\n const slideStr = slideNumber.toString().padStart(3, '0');\n const targetFileName = `${baseName}.${slideStr}.${format}`;\n const targetPath = join(outputDir, targetFileName);\n\n // Check if the target slide exists\n try {\n await access(targetPath);\n } catch {\n return {\n success: false,\n error: `Slide ${slideNumber} not found (expected: ${targetFileName})`,\n };\n }\n\n // Get all slide files and remove all except the target\n const files = await readdir(outputDir);\n const slideFiles = files.filter(\n (f) => f.startsWith(baseName) && f.endsWith(`.${format}`)\n );\n\n for (const file of slideFiles) {\n if (file !== targetFileName) {\n await unlink(join(outputDir, file));\n }\n }\n\n return {\n success: true,\n keptFile: targetFileName,\n };\n}\n\n/**\n * Check if marp-cli is available in the system\n */\nexport function checkMarpCliAvailable(): boolean {\n try {\n execSync('marp --version', { stdio: 'ignore', timeout: 5000 });\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Build marp-cli command arguments for taking screenshots\n * Returns an array of arguments to be used with execFileSync\n */\nexport function buildMarpCommandArgs(\n markdownPath: string,\n outputDir: string,\n options: ScreenshotOptions\n): string[] {\n const format = options.format || 'png';\n const args = ['marp', '--images', format];\n\n // Calculate image scale if width is different from default\n if (options.width && options.width !== 1280) {\n const scale = options.width / 1280;\n args.push('--image-scale', String(scale));\n }\n\n args.push('-o', outputDir);\n args.push(markdownPath);\n\n return args;\n}\n\n/**\n * Create the screenshot command\n */\nexport function createScreenshotCommand(): Command {\n return new Command('screenshot')\n .description('Take screenshots of slides (requires Marp CLI)')\n .argument('<input>', 'Source YAML file')\n .option('-o, --output <path>', 'Output directory', './screenshots')\n .option('-s, --slide <number>', 'Specific slide number (1-based)', parseInt)\n .option('-w, --width <pixels>', 'Image width', parseInt, 1280)\n .option('-f, --format <fmt>', 'Image format (png/jpeg)', 'png')\n .option('-c, --config <path>', 'Config file path')\n .option('-v, --verbose', 'Verbose output')\n .action(async (input: string, options: ScreenshotOptions) => {\n await executeScreenshot(input, options);\n });\n}\n\n/**\n * Execute the screenshot command\n */\nexport async function executeScreenshot(\n inputPath: string,\n options: ScreenshotOptions\n): Promise<ScreenshotResult> {\n const errors: string[] = [];\n const spinner = options.verbose ? null : ora();\n const outputDir = options.output || './screenshots';\n\n // Validate input file exists\n try {\n await access(inputPath);\n } catch {\n const message = `File not found: ${inputPath}`;\n console.error(chalk.red(`Error: ${message}`));\n errors.push(message);\n process.exitCode = ExitCode.FileReadError;\n return { success: false, errors };\n }\n\n // Validate input file extension\n if (!/\\.ya?ml$/i.test(inputPath)) {\n const message = `Invalid file extension: ${inputPath} (expected .yaml or .yml)`;\n console.error(chalk.red(`Error: ${message}`));\n errors.push(message);\n process.exitCode = ExitCode.FileReadError;\n return { success: false, errors };\n }\n\n // Check marp-cli availability\n spinner?.start('Checking for Marp CLI...');\n if (!checkMarpCliAvailable()) {\n spinner?.fail('Marp CLI not found');\n const message =\n 'Marp CLI not found. Install it with: npm install -g @marp-team/marp-cli';\n console.error(chalk.red(`Error: ${message}`));\n errors.push(message);\n process.exitCode = ExitCode.GeneralError;\n return { success: false, errors };\n }\n spinner?.succeed('Marp CLI found');\n\n // Create output directory\n try {\n await mkdir(outputDir, { recursive: true });\n } catch {\n const message = `Failed to create output directory: ${outputDir}`;\n console.error(chalk.red(`Error: ${message}`));\n errors.push(message);\n process.exitCode = ExitCode.GeneralError;\n return { success: false, errors };\n }\n\n // Load configuration\n spinner?.start('Loading configuration...');\n const configLoader = new ConfigLoader();\n let configPath = options.config;\n\n if (!configPath) {\n configPath = await configLoader.findConfig(dirname(inputPath));\n }\n\n const config = await configLoader.load(configPath);\n spinner?.succeed('Configuration loaded');\n\n // Create and initialize pipeline\n spinner?.start('Initializing pipeline...');\n const pipeline = new Pipeline(config);\n\n try {\n await pipeline.initialize();\n spinner?.succeed('Pipeline initialized');\n } catch (error) {\n spinner?.fail('Failed to initialize pipeline');\n const message =\n error instanceof Error ? error.message : 'Unknown initialization error';\n console.error(chalk.red(`Error: ${message}`));\n errors.push(message);\n process.exitCode = ExitCode.ConversionError;\n return { success: false, errors };\n }\n\n // Generate markdown (supports .yaml, .yml, case-insensitive)\n spinner?.start(`Converting ${inputPath}...`);\n const tempMdPath = inputPath.replace(/\\.ya?ml$/i, '.md');\n\n // Helper function to cleanup temporary markdown file\n const cleanupTempFile = async () => {\n try {\n await unlink(tempMdPath);\n } catch {\n // Ignore cleanup errors\n }\n };\n\n try {\n await pipeline.runWithResult(inputPath, { outputPath: tempMdPath });\n spinner?.succeed('Markdown generated');\n } catch (error) {\n spinner?.fail('Conversion failed');\n const message =\n error instanceof PipelineError\n ? `${error.stage}: ${error.message}`\n : error instanceof Error\n ? error.message\n : 'Unknown error';\n console.error(chalk.red(`Error: ${message}`));\n errors.push(message);\n process.exitCode = ExitCode.ConversionError;\n await cleanupTempFile();\n return { success: false, errors };\n }\n\n // Take screenshots with Marp CLI\n spinner?.start('Taking screenshots...');\n const marpArgs = buildMarpCommandArgs(tempMdPath, outputDir, options);\n\n if (options.verbose) {\n console.log(`Running: npx ${marpArgs.join(' ')}`);\n }\n\n try {\n execFileSync('npx', marpArgs, { stdio: options.verbose ? 'inherit' : 'pipe' });\n spinner?.succeed(`Screenshots saved to ${outputDir}`);\n } catch (error) {\n spinner?.fail('Failed to take screenshots');\n const message =\n error instanceof Error ? error.message : 'Marp CLI failed';\n console.error(chalk.red(`Error: ${message}`));\n errors.push(message);\n process.exitCode = ExitCode.GeneralError;\n await cleanupTempFile();\n return { success: false, errors };\n }\n\n // Filter to specific slide if requested\n if (options.slide !== undefined) {\n spinner?.start(`Filtering to slide ${options.slide}...`);\n const mdBaseName = basename(tempMdPath, '.md');\n const format = options.format || 'png';\n\n const filterResult = await filterToSpecificSlide(\n outputDir,\n mdBaseName,\n options.slide,\n format\n );\n\n if (!filterResult.success) {\n spinner?.fail('Failed to filter slides');\n console.error(chalk.red(`Error: ${filterResult.error}`));\n errors.push(filterResult.error || 'Filter failed');\n process.exitCode = ExitCode.GeneralError;\n await cleanupTempFile();\n return { success: false, errors };\n }\n\n spinner?.succeed(`Kept slide ${options.slide}: ${filterResult.keptFile}`);\n }\n\n // Cleanup temporary markdown file\n await cleanupTempFile();\n\n console.log('');\n console.log(`Output: ${chalk.cyan(outputDir)}`);\n\n return {\n success: true,\n errors,\n outputDir,\n };\n}\n","import { Command } from 'commander';\nimport { access, stat } from 'fs/promises';\nimport { resolve } from 'path';\nimport chalk from 'chalk';\nimport ora from 'ora';\nimport { ExitCode } from './convert.js';\nimport { SourcesManager } from '../../sources/manager.js';\nimport { SourceExplorer } from '../../sources/explorer.js';\nimport { SourceImporter } from '../../sources/importer.js';\nimport type { SourceType } from '../../sources/schema.js';\n\n/**\n * Options for sources init command\n */\nexport interface SourcesInitOptions {\n fromDirectory?: string;\n fromFile?: string;\n name?: string;\n}\n\n/**\n * Options for sources import command\n */\nexport interface SourcesImportOptions {\n recursive?: boolean;\n type?: SourceType;\n description?: string;\n}\n\n/**\n * Options for sources status command\n */\nexport interface SourcesStatusOptions {\n verbose?: boolean;\n}\n\n/**\n * Options for sources sync command\n */\nexport interface SourcesSyncOptions {\n check?: boolean;\n}\n\n/**\n * Result of sources init command\n */\nexport interface SourcesInitResult {\n success: boolean;\n message: string;\n filesImported?: number;\n}\n\n/**\n * Result of sources import command\n */\nexport interface SourcesImportResult {\n success: boolean;\n message: string;\n imported: number;\n skipped: number;\n}\n\n/**\n * Result of sources status command\n */\nexport interface SourcesStatusResult {\n success: boolean;\n output: string;\n}\n\n/**\n * Result of sources sync command\n */\nexport interface SourcesSyncResult {\n success: boolean;\n message: string;\n newFiles: number;\n modifiedFiles: number;\n}\n\n/**\n * Create the sources command with subcommands\n */\nexport function createSourcesCommand(): Command {\n const cmd = new Command('sources').description('Manage source materials');\n\n cmd.addCommand(createSourcesInitCommand());\n cmd.addCommand(createSourcesImportCommand());\n cmd.addCommand(createSourcesStatusCommand());\n cmd.addCommand(createSourcesSyncCommand());\n\n return cmd;\n}\n\n/**\n * Create sources init subcommand\n */\nfunction createSourcesInitCommand(): Command {\n return new Command('init')\n .description('Initialize sources directory')\n .option(\n '--from-directory <path>',\n 'Import from existing directory (Pattern A)'\n )\n .option('--from-file <path>', 'Import from scenario file (Pattern B)')\n .option('--name <name>', 'Project name')\n .action(async (options: SourcesInitOptions) => {\n const result = await executeSourcesInit(process.cwd(), options);\n if (!result.success) {\n process.exit(ExitCode.GeneralError);\n }\n });\n}\n\n/**\n * Create sources import subcommand\n */\nfunction createSourcesImportCommand(): Command {\n return new Command('import')\n .description('Import external files')\n .argument('<path>', 'File or directory to import')\n .option('--recursive', 'Import directory recursively')\n .option('--type <type>', 'Force source type')\n .option('--description <desc>', 'Add description')\n .action(async (path: string, options: SourcesImportOptions) => {\n const result = await executeSourcesImport(process.cwd(), path, options);\n if (!result.success) {\n process.exit(ExitCode.GeneralError);\n }\n });\n}\n\n/**\n * Create sources status subcommand\n */\nfunction createSourcesStatusCommand(): Command {\n return new Command('status')\n .description('Show sources status')\n .option('--verbose', 'Show detailed information')\n .action(async (options: SourcesStatusOptions) => {\n const result = await executeSourcesStatus(process.cwd(), options);\n console.log(result.output);\n if (!result.success) {\n process.exit(ExitCode.GeneralError);\n }\n });\n}\n\n/**\n * Create sources sync subcommand\n */\nfunction createSourcesSyncCommand(): Command {\n return new Command('sync')\n .description('Sync with original directory')\n .option('--check', 'Check for changes only')\n .action(async (options: SourcesSyncOptions) => {\n const result = await executeSourcesSync(process.cwd(), options);\n console.log(result.message);\n if (!result.success) {\n process.exit(ExitCode.GeneralError);\n }\n });\n}\n\n/**\n * Execute sources init command\n */\nexport async function executeSourcesInit(\n projectDir: string,\n options: SourcesInitOptions\n): Promise<SourcesInitResult> {\n const resolvedDir = resolve(projectDir);\n const spinner = ora('Initializing sources...').start();\n\n try {\n const manager = new SourcesManager(resolvedDir);\n\n // Check if already initialized\n if (await manager.exists()) {\n spinner.warn('Sources already initialized');\n return {\n success: true,\n message: 'Sources already initialized',\n };\n }\n\n // Determine project name\n let projectName = options.name ?? 'Untitled Project';\n\n // Determine setup pattern\n let setupPattern: 'A' | 'B' | undefined;\n let originalSource: string | undefined;\n\n if (options.fromDirectory) {\n setupPattern = 'A';\n originalSource = resolve(options.fromDirectory);\n } else if (options.fromFile) {\n setupPattern = 'B';\n originalSource = resolve(options.fromFile);\n }\n\n // Initialize sources\n await manager.init({\n name: projectName,\n setup_pattern: setupPattern,\n original_source: originalSource,\n });\n\n let filesImported = 0;\n\n // Import from directory (Pattern A)\n if (options.fromDirectory) {\n const importer = new SourceImporter(resolvedDir, manager);\n const result = await importer.importDirectory(\n resolve(options.fromDirectory),\n { recursive: true }\n );\n filesImported = result.imported;\n }\n\n // Import from file (Pattern B)\n if (options.fromFile) {\n const importer = new SourceImporter(resolvedDir, manager);\n await importer.importFile(resolve(options.fromFile), {\n type: 'scenario',\n });\n filesImported = 1;\n }\n\n spinner.succeed(\n chalk.green(\n `Sources initialized${filesImported > 0 ? ` (${filesImported} files imported)` : ''}`\n )\n );\n\n return {\n success: true,\n message: 'Sources initialized successfully',\n filesImported,\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n spinner.fail(chalk.red(`Failed to initialize sources: ${message}`));\n return {\n success: false,\n message,\n };\n }\n}\n\n/**\n * Execute sources import command\n */\nexport async function executeSourcesImport(\n projectDir: string,\n sourcePath: string,\n options: SourcesImportOptions\n): Promise<SourcesImportResult> {\n const resolvedDir = resolve(projectDir);\n const resolvedSource = resolve(sourcePath);\n const spinner = ora('Importing files...').start();\n\n try {\n const manager = new SourcesManager(resolvedDir);\n\n // Check if sources is initialized\n if (!(await manager.exists())) {\n spinner.fail(\n chalk.red('Sources not initialized. Run `slide-gen sources init` first.')\n );\n return {\n success: false,\n message: 'Sources not initialized',\n imported: 0,\n skipped: 0,\n };\n }\n\n const importer = new SourceImporter(resolvedDir, manager);\n\n // Check if path is file or directory\n const stats = await stat(resolvedSource);\n\n let imported = 0;\n let skipped = 0;\n\n if (stats.isDirectory()) {\n const importDirOptions = options.recursive ? { recursive: true } : {};\n const result = await importer.importDirectory(\n resolvedSource,\n importDirOptions\n );\n imported = result.imported;\n skipped = result.skipped;\n } else {\n const importFileOptions: { type?: SourceType; description?: string } = {};\n if (options.type) {\n importFileOptions.type = options.type;\n }\n if (options.description) {\n importFileOptions.description = options.description;\n }\n await importer.importFile(resolvedSource, importFileOptions);\n imported = 1;\n }\n\n spinner.succeed(\n chalk.green(`Imported ${imported} file(s)${skipped > 0 ? ` (${skipped} skipped)` : ''}`)\n );\n\n return {\n success: true,\n message: `Imported ${imported} files`,\n imported,\n skipped,\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n spinner.fail(chalk.red(`Failed to import: ${message}`));\n return {\n success: false,\n message,\n imported: 0,\n skipped: 0,\n };\n }\n}\n\n/**\n * Execute sources status command\n */\nexport async function executeSourcesStatus(\n projectDir: string,\n _options: SourcesStatusOptions\n): Promise<SourcesStatusResult> {\n const resolvedDir = resolve(projectDir);\n\n try {\n const manager = new SourcesManager(resolvedDir);\n\n // Check if sources is initialized\n if (!(await manager.exists())) {\n return {\n success: false,\n output: chalk.red(\n 'Sources not initialized. Run `slide-gen sources init` first.'\n ),\n };\n }\n\n const data = await manager.load();\n\n // Build status output\n let output = '';\n\n output += chalk.bold(`Sources Status: ${data.project.name}\\n`);\n output += chalk.gray('━'.repeat(50)) + '\\n\\n';\n\n // Setup pattern\n if (data.project.setup_pattern) {\n output += `Setup: Pattern ${data.project.setup_pattern}`;\n if (data.project.original_source) {\n output += ` (from ${data.project.original_source})`;\n }\n output += '\\n';\n }\n\n // Source counts by type\n const sources = data.sources ?? [];\n const countByType = sources.reduce(\n (acc, s) => {\n acc[s.type] = (acc[s.type] ?? 0) + 1;\n return acc;\n },\n {} as Record<string, number>\n );\n\n output += '\\n';\n output += chalk.cyan('Sources:\\n');\n for (const [type, count] of Object.entries(countByType)) {\n output += ` ${type}: ${count} file(s)\\n`;\n }\n\n // Missing items\n const missing = data.missing ?? [];\n if (missing.length > 0) {\n output += '\\n';\n output += chalk.yellow('Missing:\\n');\n for (const item of missing) {\n output += ` ⚠ ${item.item}`;\n if (item.needed_for) {\n output += ` (needed for ${item.needed_for})`;\n }\n output += '\\n';\n }\n }\n\n // Last updated\n if (data.project.updated) {\n output += '\\n';\n output += chalk.gray(`Last updated: ${data.project.updated}\\n`);\n }\n\n return {\n success: true,\n output,\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return {\n success: false,\n output: chalk.red(`Failed to get status: ${message}`),\n };\n }\n}\n\n/**\n * Execute sources sync command\n */\nexport async function executeSourcesSync(\n projectDir: string,\n options: SourcesSyncOptions\n): Promise<SourcesSyncResult> {\n const resolvedDir = resolve(projectDir);\n\n try {\n const manager = new SourcesManager(resolvedDir);\n\n // Check if sources is initialized\n if (!(await manager.exists())) {\n return {\n success: false,\n message: 'Sources not initialized. Run `slide-gen sources init` first.',\n newFiles: 0,\n modifiedFiles: 0,\n };\n }\n\n const data = await manager.load();\n\n // Check if this was initialized from a directory\n if (!data.project.original_source) {\n return {\n success: true,\n message: 'No original source directory to sync with.',\n newFiles: 0,\n modifiedFiles: 0,\n };\n }\n\n const originalDir = data.project.original_source;\n\n // Check if original directory exists\n try {\n await access(originalDir);\n } catch {\n return {\n success: false,\n message: `Original directory not found: ${originalDir}`,\n newFiles: 0,\n modifiedFiles: 0,\n };\n }\n\n // Scan original directory for changes\n const explorer = new SourceExplorer();\n const currentFiles = await explorer.scan(originalDir);\n\n // Get existing source origins\n const existingOrigins = new Set(\n data.sources?.map((s) => s.origin).filter(Boolean) ?? []\n );\n\n // Count new files\n let newFiles = 0;\n for (const file of currentFiles) {\n if (!existingOrigins.has(file.path)) {\n newFiles++;\n }\n }\n\n if (options.check) {\n if (newFiles === 0) {\n return {\n success: true,\n message: 'No changes detected.',\n newFiles: 0,\n modifiedFiles: 0,\n };\n } else {\n return {\n success: true,\n message: `Found ${newFiles} new file(s). Run without --check to sync.`,\n newFiles,\n modifiedFiles: 0,\n };\n }\n }\n\n // Actually sync (import new files)\n if (newFiles > 0) {\n const importer = new SourceImporter(resolvedDir, manager);\n await importer.importDirectory(originalDir, { recursive: true });\n }\n\n return {\n success: true,\n message:\n newFiles > 0 ? `Synced ${newFiles} new file(s).` : 'No changes to sync.',\n newFiles,\n modifiedFiles: 0,\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return {\n success: false,\n message: `Failed to sync: ${message}`,\n newFiles: 0,\n modifiedFiles: 0,\n };\n }\n}\n"],"mappings":";;;AAEA,SAAS,WAAAA,iBAAe;;;ACFxB,SAAS,SAAS;AAClB,SAAS,SAAS,WAAW,eAAe,OAAO,OAAO,QAAQ,mBAAmB;AACrF,SAAS,gBAAgB;AAGzB,IAAM,yBAAyB,EAAE,OAAO;AAAA,EACtC,SAAS,EAAE,QAAQ,EAAE,QAAQ,IAAI;AAAA,EACjC,OAAO,EAAE,OAAO,EAAE,QAAQ,kBAAkB;AAC9C,CAAC;AAGD,IAAM,aAAa,EAAE,OAAO;AAAA,EAC1B,OAAO,EAAE,OAAO;AAAA,EAChB,QAAQ,EAAE,OAAO,EAAE,SAAS;AAAA,EAC5B,MAAM,EAAE,OAAO,EAAE,SAAS;AAAA,EAC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kB;AAAA,MACrD;AAAA,MACA,eAAe;AAAA,IACjB;AAAA,EACF,SAAS,OAAO;AACd,UAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AACrE,WAAO;AAAA,MACL,SAAS;AAAA,MACT,SAAS,mBAAmB,OAAO;AAAA,MACnC,UAAU;AAAA,MACV,eAAe;AAAA,IACjB;AAAA,EACF;AACF;;;AjD1fA,IAAM,UAAU,IAAIC,UAAQ;AAE5B,QACG,KAAK,WAAW,EAChB,YAAY,0DAA0D,EACtE,QAAQ,OAAO;AAGlB,QAAQ,WAAW,qBAAqB,CAAC;AAGzC,QAAQ,WAAW,sBAAsB,CAAC;AAG1C,QAAQ,WAAW,uBAAuB,CAAC;AAG3C,QAAQ,WAAW,mBAAmB,CAAC;AAGvC,QAAQ,WAAW,kBAAkB,CAAC;AAGtC,QAAQ,WAAW,mBAAmB,CAAC;AAGvC,QAAQ,WAAW,qBAAqB,CAAC;AAGzC,QAAQ,WAAW,oBAAoB,CAAC;AAGxC,QAAQ,WAAW,wBAAwB,CAAC;AAG5C,QAAQ,WAAW,qBAAqB,CAAC;AAEzC,QAAQ,MAAM;","names":["Command","z","z","path","z","fs","parseYaml","z","parseYaml","fs","path","nunjucks","resolve","CITATION_BRACKET_PATTERN","SINGLE_CITATION_PATTERN","access","readFile","basename","dirname","join","parseYaml","readFile","join","parseYaml","z","path","join","readFile","parseYaml","z","z","z","z","fs","path","parseYaml","parseYaml","fs","path","fs","path","dirname","basename","join","readFile","parseYaml","content","access","Command","access","readFile","dirname","chalk","ora","parseYaml","yaml","Command","ora","access","readFile","parseYaml","dirname","chalk","Command","chalk","yaml","mkdir","writeFile","rm","join","basename","tmpdir","execFileSync","Command","access","unlink","readdir","mkdir","writeFile","readFile","basename","dirname","join","extname","path","chalk","readdir","join","basename","resolve","extname","readFile","chalk","join","access","chalk","mkdir","dirname","basename","writeFile","resolve","Command","unlink","Command","chalk","escapeHtml","join","tmpdir","mkdir","rm","writeFile","execFileSync","basename","resolve","Command","chalk","fs","path","parseYaml","stringifyYaml","fs","path","parseYaml","createListCommand","Command","output","sources","chalk","parseYaml","stringifyYaml","createPreviewCommand","Command","mkdir","writeFile","access","readdir","execSync","dirname","join","resolve","chalk","ora","fs","path","parse","stringify","z","parse","stringify","fs","path","fs","path","dirname","join","Command","ora","resolve","access","readdir","mkdir","chalk","writeFile","execSync","Command","access","basename","dirname","join","chalk","chokidarWatch","getDefaultOutputPath","dirname","basename","join","Command","chalk","access","chokidarWatch","resolve","Command","readFile","stat","mkdir","dirname","basename","join","chalk","stringifyYaml","Command","dirname","chalk","stringifyYaml","readFile","stat","join","basename","mkdir","Command","access","mkdir","readdir","unlink","basename","dirname","join","execSync","execFileSync","chalk","ora","join","access","readdir","unlink","checkMarpCliAvailable","execSync","Command","ora","chalk","mkdir","dirname","execFileSync","basename","Command","access","stat","resolve","chalk","ora","Command","path","resolve","ora","chalk","stat","access","Command"]}
1
+ {"version":3,"sources":["../../src/cli/index.ts","../../src/core/parser.ts","../../src/core/transformer.ts","../../src/core/renderer.ts","../../src/core/pipeline.ts","../../src/templates/engine.ts","../../src/templates/loader.ts","../../src/templates/validators.ts","../../src/icons/registry.ts","../../src/icons/schema.ts","../../src/icons/resolver.ts","../../src/references/manager.ts","../../src/references/extractor.ts","../../src/references/formatter.ts","../../src/index.ts","../../src/cli/commands/convert.ts","../../src/config/loader.ts","../../src/config/schema.ts","../../src/images/constants.ts","../../src/images/schema.ts","../../src/images/processing-schema.ts","../../src/images/metadata-loader.ts","../../src/images/validator.ts","../../src/images/processor.ts","../../src/images/processing-pipeline.ts","../../src/cli/commands/validate.ts","../../src/cli/commands/templates.ts","../../src/cli/commands/preview.ts","../../src/cli/utils/marp-runner.ts","../../src/cli/commands/icons.ts","../../src/icons/fetcher.ts","../../src/cli/commands/init.ts","../../src/sources/manager.ts","../../src/sources/schema.ts","../../src/sources/importer.ts","../../src/sources/explorer.ts","../../src/cli/templates/ai/skill-md.ts","../../src/cli/templates/ai/claude-md.ts","../../src/cli/templates/ai/agents-md.ts","../../src/cli/templates/ai/opencode-agent.ts","../../src/cli/templates/ai/references/templates-ref.ts","../../src/cli/templates/ai/references/workflows-ref.ts","../../src/cli/templates/ai/commands/slide-create.ts","../../src/cli/templates/ai/commands/slide-validate.ts","../../src/cli/templates/ai/commands/slide-preview.ts","../../src/cli/templates/ai/commands/slide-screenshot.ts","../../src/cli/templates/ai/commands/slide-theme.ts","../../src/cli/commands/watch.ts","../../src/cli/commands/images.ts","../../src/cli/commands/screenshot.ts","../../src/cli/commands/sources.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport { Command } from 'commander';\nimport { VERSION } from '../index.js';\nimport { createConvertCommand } from './commands/convert.js';\nimport { createValidateCommand } from './commands/validate.js';\nimport { createTemplatesCommand } from './commands/templates.js';\nimport { createIconsCommand } from './commands/icons.js';\nimport { createInitCommand } from './commands/init.js';\nimport { createWatchCommand } from './commands/watch.js';\nimport { createPreviewCommand } from './commands/preview.js';\nimport { createImagesCommand } from './commands/images.js';\nimport { createScreenshotCommand } from './commands/screenshot.js';\nimport { createSourcesCommand } from './commands/sources.js';\n\nconst program = new Command();\n\nprogram\n .name('slide-gen')\n .description('Generate Marp-compatible Markdown from YAML source files')\n .version(VERSION);\n\n// Add convert command\nprogram.addCommand(createConvertCommand());\n\n// Add validate command\nprogram.addCommand(createValidateCommand());\n\n// Add templates command\nprogram.addCommand(createTemplatesCommand());\n\n// Add icons command\nprogram.addCommand(createIconsCommand());\n\n// Add init command\nprogram.addCommand(createInitCommand());\n\n// Add watch command\nprogram.addCommand(createWatchCommand());\n\n// Add preview command\nprogram.addCommand(createPreviewCommand());\n\n// Add images command\nprogram.addCommand(createImagesCommand());\n\n// Add screenshot command\nprogram.addCommand(createScreenshotCommand());\n\n// Add sources command\nprogram.addCommand(createSourcesCommand());\n\nprogram.parse();\n","import { z } from 'zod';\nimport { parse as parseYaml, parseDocument, isSeq, isMap, isNode, LineCounter } from 'yaml';\nimport { readFile } from 'fs/promises';\n\n// References config schema\nconst referencesConfigSchema = z.object({\n enabled: z.boolean().default(true),\n style: z.string().default('author-year-pmid'),\n});\n\n// Meta schema\nconst metaSchema = z.object({\n title: z.string(),\n author: z.string().optional(),\n date: z.string().optional(),\n theme: z.string().default('default'),\n references: referencesConfigSchema.optional(),\n});\n\n// Slide schema\nconst slideSchema = z.object({\n template: z.string(),\n content: z.record(z.unknown()).default({}),\n class: z.string().optional(),\n notes: z.string().optional(),\n raw: z.string().optional(),\n});\n\n// Presentation schema\nexport const presentationSchema = z.object({\n meta: metaSchema,\n slides: z.array(slideSchema).default([]),\n});\n\nexport type PresentationMeta = z.infer<typeof metaSchema>;\nexport type ParsedSlide = z.infer<typeof slideSchema>;\nexport type ParsedPresentation = z.infer<typeof presentationSchema>;\n\nexport interface ParseResultWithLines extends ParsedPresentation {\n slideLines: number[];\n}\n\nexport class ParseError extends Error {\n constructor(\n message: string,\n public details?: unknown\n ) {\n super(message);\n this.name = 'ParseError';\n }\n}\n\nexport class ValidationError extends Error {\n constructor(\n message: string,\n public details?: unknown\n ) {\n super(message);\n this.name = 'ValidationError';\n }\n}\n\nexport class Parser {\n parse(yamlContent: string): ParsedPresentation {\n let rawData: unknown;\n\n try {\n rawData = parseYaml(yamlContent);\n } catch (error) {\n throw new ParseError('Failed to parse YAML', error);\n }\n\n const result = presentationSchema.safeParse(rawData);\n\n if (!result.success) {\n throw new ValidationError(\n 'Schema validation failed',\n result.error.format()\n );\n }\n\n return result.data;\n }\n\n async parseFile(filePath: string): Promise<ParsedPresentation> {\n let content: string;\n\n try {\n content = await readFile(filePath, 'utf-8');\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n throw new ParseError(`File not found: ${filePath}`);\n }\n throw new ParseError(`Failed to read file: ${filePath}`, error);\n }\n\n return this.parse(content);\n }\n\n parseWithLineInfo(yamlContent: string): ParseResultWithLines {\n const lineCounter = new LineCounter();\n const doc = parseDocument(yamlContent, { lineCounter });\n\n // Check for YAML parsing errors\n if (doc.errors && doc.errors.length > 0) {\n throw new ParseError('Failed to parse YAML', doc.errors);\n }\n\n // Extract line numbers for slides\n const slideLines: number[] = [];\n const contents = doc.contents;\n\n if (isMap(contents)) {\n const slidesNode = contents.get('slides', true);\n if (isSeq(slidesNode)) {\n for (const item of slidesNode.items) {\n if (isNode(item) && item.range) {\n const pos = lineCounter.linePos(item.range[0]);\n slideLines.push(pos.line);\n }\n }\n }\n }\n\n // Validate with schema\n const rawData = doc.toJSON();\n const result = presentationSchema.safeParse(rawData);\n\n if (!result.success) {\n throw new ValidationError(\n 'Schema validation failed',\n result.error.format()\n );\n }\n\n return {\n ...result.data,\n slideLines,\n };\n }\n\n async parseFileWithLineInfo(filePath: string): Promise<ParseResultWithLines> {\n let content: string;\n\n try {\n content = await readFile(filePath, 'utf-8');\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n throw new ParseError(`File not found: ${filePath}`);\n }\n throw new ParseError(`Failed to read file: ${filePath}`, error);\n }\n\n return this.parseWithLineInfo(content);\n }\n}\n","import type { TemplateEngine, IconsHelper, RefsHelper } from '../templates/engine';\nimport type { TemplateLoader } from '../templates/loader';\nimport type { IconResolver } from '../icons/resolver';\nimport type { CitationFormatter } from '../references/formatter';\nimport type { ParsedSlide, ParsedPresentation, PresentationMeta } from './parser';\n\n// Placeholder patterns for async resolution\nconst ICON_PLACEHOLDER_PREFIX = '___ICON_PLACEHOLDER_';\nconst ICON_PLACEHOLDER_SUFFIX = '___';\nconst REFS_CITE_PLACEHOLDER_PREFIX = '___REFS_CITE_PLACEHOLDER_';\nconst REFS_CITE_PLACEHOLDER_SUFFIX = '___';\nconst REFS_EXPAND_PLACEHOLDER_PREFIX = '___REFS_EXPAND_PLACEHOLDER_';\nconst REFS_EXPAND_PLACEHOLDER_SUFFIX = '___';\n\n/**\n * Context passed to each slide transformation\n */\nexport interface TransformContext {\n meta: PresentationMeta;\n slideIndex: number;\n totalSlides: number;\n}\n\n/**\n * Error thrown when transformation fails\n */\nexport class TransformError extends Error {\n constructor(\n message: string,\n public slide?: ParsedSlide,\n public details?: unknown\n ) {\n super(message);\n this.name = 'TransformError';\n }\n}\n\n/**\n * Pending async operations collected during template rendering\n */\ninterface PendingOperations {\n icons: Map<string, { name: string; options: Record<string, unknown> | undefined }>;\n cites: Map<string, string>;\n expands: Map<string, string>;\n}\n\n/**\n * Transformer applies templates to slides and generates HTML content\n */\nexport class Transformer {\n constructor(\n private templateEngine: TemplateEngine,\n private templateLoader: TemplateLoader,\n private iconResolver: IconResolver,\n private citationFormatter: CitationFormatter\n ) {}\n\n /**\n * Transform a single slide using its template\n */\n async transform(slide: ParsedSlide, context: TransformContext): Promise<string> {\n // Handle raw template - return raw content directly\n if (slide.template === 'raw') {\n return slide.raw ?? '';\n }\n\n // Get the template definition\n const template = this.templateLoader.get(slide.template);\n if (!template) {\n throw new TransformError(\n `Template \"${slide.template}\" not found`,\n slide\n );\n }\n\n // Validate content against template schema\n const validationResult = this.templateLoader.validateContent(\n slide.template,\n slide.content\n );\n if (!validationResult.valid) {\n throw new TransformError(\n `Slide content validation failed: ${validationResult.errors?.join(', ')}`,\n slide,\n validationResult.errors\n );\n }\n\n // Build template context with helpers that use placeholders\n const pending: PendingOperations = {\n icons: new Map(),\n cites: new Map(),\n expands: new Map(),\n };\n const templateContext = this.buildTemplateContext(slide, context, pending);\n\n // Render the template (synchronous, with placeholders)\n let output = this.templateEngine.render(template.output, templateContext);\n\n // Resolve all async operations and replace placeholders\n output = await this.resolvePlaceholders(output, pending);\n\n // Add CSS class directive if specified\n if (slide.class) {\n output = `<!-- _class: ${slide.class} -->\\n${output}`;\n }\n\n return output.trim();\n }\n\n /**\n * Transform all slides in a presentation\n */\n async transformAll(presentation: ParsedPresentation): Promise<string[]> {\n const results: string[] = [];\n const totalSlides = presentation.slides.length;\n\n for (let i = 0; i < presentation.slides.length; i++) {\n const slide = presentation.slides[i]!;\n const context: TransformContext = {\n meta: presentation.meta,\n slideIndex: i,\n totalSlides,\n };\n\n const transformed = await this.transform(slide, context);\n results.push(transformed);\n }\n\n return results;\n }\n\n /**\n * Build the full template context with helpers that collect async operations\n */\n private buildTemplateContext(\n slide: ParsedSlide,\n context: TransformContext,\n pending: PendingOperations\n ): Record<string, unknown> {\n let iconCounter = 0;\n let citeCounter = 0;\n let expandCounter = 0;\n\n // Create icons helper that returns placeholders\n const icons: IconsHelper = {\n render: (name: string, options?: Record<string, unknown>) => {\n const id = `${iconCounter++}`;\n const placeholder = `${ICON_PLACEHOLDER_PREFIX}${id}${ICON_PLACEHOLDER_SUFFIX}`;\n pending.icons.set(id, { name, options });\n return placeholder;\n },\n };\n\n // Create refs helper that returns placeholders\n const refs: RefsHelper = {\n cite: (id: string) => {\n const counterId = `${citeCounter++}`;\n const placeholder = `${REFS_CITE_PLACEHOLDER_PREFIX}${counterId}${REFS_CITE_PLACEHOLDER_SUFFIX}`;\n pending.cites.set(counterId, id);\n return placeholder;\n },\n expand: (text: string) => {\n const counterId = `${expandCounter++}`;\n const placeholder = `${REFS_EXPAND_PLACEHOLDER_PREFIX}${counterId}${REFS_EXPAND_PLACEHOLDER_SUFFIX}`;\n pending.expands.set(counterId, text);\n return placeholder;\n },\n };\n\n return {\n content: slide.content,\n meta: {\n title: context.meta.title,\n author: context.meta.author,\n theme: context.meta.theme,\n },\n slide: {\n index: context.slideIndex,\n total: context.totalSlides,\n },\n icons,\n refs,\n };\n }\n\n /**\n * Resolve all placeholders by executing async operations\n */\n private async resolvePlaceholders(\n output: string,\n pending: PendingOperations\n ): Promise<string> {\n // Resolve icons\n const iconResults = new Map<string, string>();\n for (const [id, { name, options }] of pending.icons) {\n const rendered = await this.iconResolver.render(\n name,\n options as { size?: string; color?: string; class?: string } | undefined\n );\n iconResults.set(id, rendered);\n }\n\n // Resolve citations\n const citeResults = new Map<string, string>();\n for (const [counterId, id] of pending.cites) {\n const formatted = await this.citationFormatter.formatInline(id);\n citeResults.set(counterId, formatted);\n }\n\n // Resolve citation expansions\n const expandResults = new Map<string, string>();\n for (const [counterId, text] of pending.expands) {\n const expanded = await this.citationFormatter.expandCitations(text);\n expandResults.set(counterId, expanded);\n }\n\n // Replace all placeholders\n let result = output;\n\n for (const [id, rendered] of iconResults) {\n const placeholder = `${ICON_PLACEHOLDER_PREFIX}${id}${ICON_PLACEHOLDER_SUFFIX}`;\n result = result.replace(placeholder, rendered);\n }\n\n for (const [counterId, formatted] of citeResults) {\n const placeholder = `${REFS_CITE_PLACEHOLDER_PREFIX}${counterId}${REFS_CITE_PLACEHOLDER_SUFFIX}`;\n result = result.replace(placeholder, formatted);\n }\n\n for (const [counterId, expanded] of expandResults) {\n const placeholder = `${REFS_EXPAND_PLACEHOLDER_PREFIX}${counterId}${REFS_EXPAND_PLACEHOLDER_SUFFIX}`;\n result = result.replace(placeholder, expanded);\n }\n\n return result;\n }\n}\n","import type { PresentationMeta } from './parser';\n\n/**\n * Options for rendering the final Marp markdown\n */\nexport interface RenderOptions {\n /** Include theme in front matter (default: true) */\n includeTheme?: boolean;\n /** Speaker notes for each slide (indexed by slide position) */\n notes?: (string | undefined)[];\n /** Additional front matter properties */\n additionalFrontMatter?: Record<string, unknown>;\n}\n\n/**\n * Renderer combines transformed slides into Marp-compatible Markdown\n */\nexport class Renderer {\n /**\n * Render slides and metadata into final Marp markdown\n */\n render(\n slides: string[],\n meta: PresentationMeta,\n options?: RenderOptions\n ): string {\n const frontMatter = this.renderFrontMatter(meta, options);\n const slidesContent = this.joinSlides(slides, options?.notes);\n\n if (slides.length === 0) {\n return frontMatter;\n }\n\n return `${frontMatter}\\n\\n${slidesContent}`;\n }\n\n /**\n * Render the YAML front matter block\n */\n private renderFrontMatter(\n meta: PresentationMeta,\n options?: RenderOptions\n ): string {\n const lines: string[] = ['---', 'marp: true'];\n\n // Add title\n lines.push(`title: ${meta.title}`);\n\n // Add author if present\n if (meta.author) {\n lines.push(`author: ${meta.author}`);\n }\n\n // Add date if present\n if (meta.date) {\n lines.push(`date: ${meta.date}`);\n }\n\n // Add theme if enabled (default: true)\n const includeTheme = options?.includeTheme ?? true;\n if (includeTheme && meta.theme) {\n lines.push(`theme: ${meta.theme}`);\n }\n\n // Add additional front matter properties\n if (options?.additionalFrontMatter) {\n for (const [key, value] of Object.entries(options.additionalFrontMatter)) {\n lines.push(`${key}: ${this.formatFrontMatterValue(value)}`);\n }\n }\n\n lines.push('---');\n\n return lines.join('\\n');\n }\n\n /**\n * Format a front matter value for YAML\n */\n private formatFrontMatterValue(value: unknown): string {\n if (typeof value === 'boolean') {\n return value ? 'true' : 'false';\n }\n if (typeof value === 'number') {\n return String(value);\n }\n if (typeof value === 'string') {\n // Quote if contains special characters\n if (/[:#[\\]{}|>]/.test(value)) {\n return `\"${value.replace(/\"/g, '\\\\\"')}\"`;\n }\n return value;\n }\n return String(value);\n }\n\n /**\n * Join slides with Marp slide separator\n */\n private joinSlides(\n slides: string[],\n notes?: (string | undefined)[]\n ): string {\n const parts: string[] = [];\n\n for (let i = 0; i < slides.length; i++) {\n let slideContent = slides[i]!;\n\n // Add speaker notes if present\n const note = notes?.[i];\n if (note && note.trim()) {\n slideContent = `${slideContent}\\n\\n${this.renderSpeakerNotes(note)}`;\n }\n\n parts.push(slideContent);\n }\n\n // Join with Marp slide separator (---)\n return parts.map(slide => `---\\n\\n${slide}`).join('\\n\\n');\n }\n\n /**\n * Render speaker notes as HTML comment\n */\n private renderSpeakerNotes(notes: string): string {\n return `<!--\\n${notes}\\n-->`;\n }\n}\n","import { writeFile } from 'fs/promises';\nimport { Parser, type ParsedPresentation } from './parser';\nimport { Transformer } from './transformer';\nimport { Renderer, type RenderOptions } from './renderer';\nimport { TemplateEngine } from '../templates/engine';\nimport { TemplateLoader } from '../templates/loader';\nimport { IconRegistryLoader } from '../icons/registry';\nimport { IconResolver } from '../icons/resolver';\nimport { ReferenceManager, type CSLItem } from '../references/manager';\nimport { CitationExtractor } from '../references/extractor';\nimport { CitationFormatter } from '../references/formatter';\nimport type { Config } from '../config/schema';\n\n/**\n * Options for the Pipeline\n */\nexport interface PipelineOptions {\n /** Custom config path override */\n configPath?: string;\n /** Output file path (if not specified, returns string only) */\n outputPath?: string;\n /** Enable verbose/progress output */\n verbose?: boolean;\n}\n\n/**\n * Result of a pipeline run\n */\nexport interface PipelineResult {\n /** Generated Marp markdown */\n output: string;\n /** Citation IDs found in the presentation */\n citations: string[];\n /** Warnings generated during processing */\n warnings: string[];\n /** Number of slides processed */\n slideCount: number;\n}\n\n/**\n * Error thrown when pipeline processing fails\n */\nexport class PipelineError extends Error {\n constructor(\n message: string,\n public stage: string,\n public details?: unknown\n ) {\n super(message);\n this.name = 'PipelineError';\n }\n}\n\n/**\n * Pipeline orchestrates the full YAML to Marp markdown conversion\n *\n * Stages:\n * 1. Parse Source - Load and validate YAML\n * 2. Collect Citations - Extract citation IDs from all slides\n * 3. Resolve References - Fetch bibliography data\n * 4. Transform Slides - Apply templates and resolve icons/citations\n * 5. Render Output - Generate final Marp markdown\n */\nexport class Pipeline {\n private parser: Parser;\n private templateEngine: TemplateEngine;\n private templateLoader: TemplateLoader;\n private iconRegistry: IconRegistryLoader;\n private iconResolver: IconResolver;\n private referenceManager: ReferenceManager;\n private citationExtractor: CitationExtractor;\n private citationFormatter: CitationFormatter;\n private transformer: Transformer;\n private renderer: Renderer;\n private warnings: string[] = [];\n\n constructor(private config: Config) {\n // Initialize all components\n this.parser = new Parser();\n this.templateEngine = new TemplateEngine();\n this.templateLoader = new TemplateLoader();\n this.iconRegistry = new IconRegistryLoader();\n this.iconResolver = new IconResolver(this.iconRegistry);\n this.referenceManager = new ReferenceManager(\n config.references.connection.command\n );\n this.citationExtractor = new CitationExtractor();\n this.citationFormatter = new CitationFormatter(\n this.referenceManager,\n {\n author: {\n maxAuthors: config.references.format.maxAuthors,\n etAl: config.references.format.etAl,\n etAlJa: config.references.format.etAlJa,\n },\n inline: {\n authorSep: config.references.format.authorSep,\n identifierSep: config.references.format.identifierSep,\n },\n }\n );\n this.transformer = new Transformer(\n this.templateEngine,\n this.templateLoader,\n this.iconResolver,\n this.citationFormatter\n );\n this.renderer = new Renderer();\n }\n\n /**\n * Run the full conversion pipeline\n */\n async run(inputPath: string, options?: PipelineOptions): Promise<string> {\n this.warnings = [];\n\n try {\n // Stage 1: Parse Source\n const presentation = await this.parseSource(inputPath);\n\n // Stage 2: Collect Citations\n const citationIds = this.collectCitations(presentation);\n\n // Stage 3: Resolve References\n await this.resolveReferences(citationIds);\n\n // Stage 4: Transform Slides\n const transformedSlides = await this.transformSlides(presentation);\n\n // Stage 5: Render Output\n const output = this.render(transformedSlides, presentation);\n\n // Write output file if specified\n if (options?.outputPath) {\n await writeFile(options.outputPath, output, 'utf-8');\n }\n\n return output;\n } catch (error) {\n if (error instanceof PipelineError) {\n throw error;\n }\n throw new PipelineError(\n error instanceof Error ? error.message : 'Unknown error',\n 'unknown',\n error\n );\n }\n }\n\n /**\n * Run the full pipeline with detailed result\n */\n async runWithResult(\n inputPath: string,\n options?: PipelineOptions\n ): Promise<PipelineResult> {\n this.warnings = [];\n\n try {\n // Stage 1: Parse Source\n const presentation = await this.parseSource(inputPath);\n\n // Stage 2: Collect Citations\n const citationIds = this.collectCitations(presentation);\n\n // Stage 3: Resolve References\n await this.resolveReferences(citationIds);\n\n // Stage 4: Transform Slides\n const transformedSlides = await this.transformSlides(presentation);\n\n // Stage 5: Render Output\n const output = this.render(transformedSlides, presentation);\n\n // Write output file if specified\n if (options?.outputPath) {\n await writeFile(options.outputPath, output, 'utf-8');\n }\n\n return {\n output,\n citations: citationIds,\n warnings: this.warnings,\n slideCount: presentation.slides.length,\n };\n } catch (error) {\n if (error instanceof PipelineError) {\n throw error;\n }\n throw new PipelineError(\n error instanceof Error ? error.message : 'Unknown error',\n 'unknown',\n error\n );\n }\n }\n\n /**\n * Initialize the pipeline by loading templates and icon registry\n */\n async initialize(): Promise<void> {\n try {\n // Load built-in templates\n await this.templateLoader.loadBuiltIn(this.config.templates.builtin);\n\n // Load custom templates if specified\n if (this.config.templates.custom) {\n await this.templateLoader.loadCustom(this.config.templates.custom);\n }\n\n // Load icon registry\n await this.iconRegistry.load(this.config.icons.registry);\n } catch (error) {\n throw new PipelineError(\n `Failed to initialize pipeline: ${error instanceof Error ? error.message : 'Unknown error'}`,\n 'initialize',\n error\n );\n }\n }\n\n /**\n * Get collected warnings\n */\n getWarnings(): string[] {\n return [...this.warnings];\n }\n\n // --- Private Stage Methods ---\n\n /**\n * Stage 1: Parse the YAML source file\n */\n private async parseSource(inputPath: string): Promise<ParsedPresentation> {\n try {\n return await this.parser.parseFile(inputPath);\n } catch (error) {\n throw new PipelineError(\n `Failed to parse source file: ${error instanceof Error ? error.message : 'Unknown error'}`,\n 'parse',\n error\n );\n }\n }\n\n /**\n * Stage 2: Collect all citation IDs from the presentation\n */\n private collectCitations(presentation: ParsedPresentation): string[] {\n const citations = this.citationExtractor.extractFromPresentation(presentation);\n return this.citationExtractor.getUniqueIds(citations);\n }\n\n /**\n * Stage 3: Resolve references from the reference manager\n */\n private async resolveReferences(ids: string[]): Promise<Map<string, CSLItem>> {\n if (!this.config.references.enabled || ids.length === 0) {\n return new Map();\n }\n\n try {\n const items = await this.referenceManager.getByIds(ids);\n\n // Warn about missing references\n for (const id of ids) {\n if (!items.has(id)) {\n this.warnings.push(`Reference not found: ${id}`);\n }\n }\n\n return items;\n } catch (error) {\n // Non-fatal: log warning and continue\n this.warnings.push(\n `Failed to resolve references: ${error instanceof Error ? error.message : 'Unknown error'}`\n );\n return new Map();\n }\n }\n\n /**\n * Stage 4: Transform all slides using templates\n */\n private async transformSlides(\n presentation: ParsedPresentation\n ): Promise<string[]> {\n try {\n return await this.transformer.transformAll(presentation);\n } catch (error) {\n throw new PipelineError(\n `Failed to transform slides: ${error instanceof Error ? error.message : 'Unknown error'}`,\n 'transform',\n error\n );\n }\n }\n\n /**\n * Stage 5: Render the final Marp markdown\n */\n private render(\n slides: string[],\n presentation: ParsedPresentation\n ): string {\n try {\n // Collect notes from slides\n const notes = presentation.slides.map((slide) => slide.notes);\n\n const renderOptions: RenderOptions = {\n includeTheme: true,\n notes,\n };\n\n return this.renderer.render(slides, presentation.meta, renderOptions);\n } catch (error) {\n throw new PipelineError(\n `Failed to render output: ${error instanceof Error ? error.message : 'Unknown error'}`,\n 'render',\n error\n );\n }\n }\n}\n","import nunjucks from \"nunjucks\";\n\n/**\n * Icons helper interface for template rendering\n */\nexport interface IconsHelper {\n render: (name: string, options?: Record<string, unknown>) => string;\n}\n\n/**\n * References helper interface for citation handling\n */\nexport interface RefsHelper {\n cite: (id: string) => string;\n expand: (text: string) => string;\n}\n\n/**\n * Slide context passed to templates\n */\nexport interface SlideContext {\n index: number;\n total: number;\n}\n\n/**\n * Meta context for presentation metadata\n */\nexport interface MetaContext {\n title: string;\n author?: string;\n theme: string;\n [key: string]: unknown;\n}\n\n/**\n * Full template context interface\n */\nexport interface TemplateContext {\n content: Record<string, unknown>;\n meta: MetaContext;\n slide: SlideContext;\n icons: IconsHelper;\n refs: RefsHelper;\n [key: string]: unknown;\n}\n\nexport class TemplateEngine {\n private env: nunjucks.Environment;\n\n constructor() {\n this.env = new nunjucks.Environment(null, {\n autoescape: false, // HTML output for Marp\n throwOnUndefined: false,\n });\n this.registerFilters();\n this.registerGlobals();\n }\n\n render(template: string, context: Record<string, unknown>): string {\n return this.env.renderString(template, context);\n }\n\n private registerFilters(): void {\n // Will be extended in later steps\n }\n\n private registerGlobals(): void {\n // Icon helper stub - will be replaced with real implementation\n const icons = {\n render: (name: string, options?: Record<string, unknown>): string => {\n const size = (options?.[\"size\"] as string) ?? \"24px\";\n const color = (options?.[\"color\"] as string) ?? \"currentColor\";\n return `<span class=\"icon icon-${name}\" style=\"font-size: ${size}; color: ${color};\">[${name}]</span>`;\n },\n };\n\n this.env.addGlobal(\"icons\", icons);\n\n // Reference helper stub - will be replaced with real implementation\n const refs = {\n cite: (id: string): string => {\n const cleanId = id.replace(\"@\", \"\");\n return `(${cleanId})`;\n },\n expand: (text: string): string => {\n // Simple stub - replace [@id] with (id)\n return text.replace(/\\[@(\\w+)\\]/g, \"($1)\");\n },\n };\n\n this.env.addGlobal(\"refs\", refs);\n }\n}\n","import { z } from \"zod\";\nimport * as yaml from \"yaml\";\nimport * as fs from \"node:fs/promises\";\nimport * as path from \"node:path\";\nimport {\n validateWithJsonSchema,\n type JsonSchema,\n type ValidationResult,\n} from \"./validators\";\n\n/**\n * JSON Schema-like structure for template content validation\n */\nconst jsonSchemaSchema = z.record(z.unknown());\n\n/**\n * Template definition schema - validates YAML template definition files\n */\nexport const templateDefSchema = z.object({\n name: z.string().min(1, \"Template name is required\"),\n description: z.string(),\n category: z.string(),\n schema: jsonSchemaSchema,\n example: z.record(z.unknown()).optional(),\n output: z.string().min(1, \"Template output is required\"),\n css: z.string().optional(),\n});\n\n/**\n * Template definition type derived from schema\n */\nexport type TemplateDefinition = z.infer<typeof templateDefSchema>;\n\n/**\n * Loads and manages template definitions from YAML files\n */\nexport class TemplateLoader {\n private templates: Map<string, TemplateDefinition>;\n\n constructor() {\n this.templates = new Map();\n }\n\n /**\n * Load a template from a YAML string\n */\n async loadFromString(yamlContent: string): Promise<void> {\n const parsed = yaml.parse(yamlContent);\n const result = templateDefSchema.safeParse(parsed);\n\n if (!result.success) {\n const errors = result.error.errors\n .map(e => `${e.path.join(\".\")}: ${e.message}`)\n .join(\", \");\n throw new Error(`Invalid template definition: ${errors}`);\n }\n\n this.templates.set(result.data.name, result.data);\n }\n\n /**\n * Load a template from a file\n */\n async loadFromFile(filePath: string): Promise<void> {\n const content = await fs.readFile(filePath, \"utf-8\");\n await this.loadFromString(content);\n }\n\n /**\n * Load all templates from a directory (recursively)\n */\n async loadBuiltIn(directory: string): Promise<void> {\n await this.loadDirectory(directory);\n }\n\n /**\n * Load custom templates from a directory (can override built-in)\n */\n async loadCustom(directory: string): Promise<void> {\n await this.loadDirectory(directory);\n }\n\n /**\n * Internal method to load templates from a directory\n */\n private async loadDirectory(directory: string): Promise<void> {\n const entries = await fs.readdir(directory, { withFileTypes: true });\n\n for (const entry of entries) {\n const fullPath = path.join(directory, entry.name);\n\n if (entry.isDirectory()) {\n await this.loadDirectory(fullPath);\n } else if (entry.isFile() && (entry.name.endsWith(\".yaml\") || entry.name.endsWith(\".yml\"))) {\n await this.loadFromFile(fullPath);\n }\n }\n }\n\n /**\n * Get a template by name\n */\n get(name: string): TemplateDefinition | undefined {\n return this.templates.get(name);\n }\n\n /**\n * List all loaded templates\n */\n list(): TemplateDefinition[] {\n return Array.from(this.templates.values());\n }\n\n /**\n * List templates filtered by category\n */\n listByCategory(category: string): TemplateDefinition[] {\n return this.list().filter(t => t.category === category);\n }\n\n /**\n * Validate content against a template's schema\n */\n validateContent(templateName: string, content: unknown): ValidationResult {\n const template = this.get(templateName);\n\n if (!template) {\n return {\n valid: false,\n errors: [`Template \"${templateName}\" not found`],\n };\n }\n\n return validateWithJsonSchema(template.schema as JsonSchema, content);\n }\n}\n\nexport type { ValidationResult };\n","import { z, type ZodTypeAny, type ZodIssue } from \"zod\";\n\n/**\n * JSON Schema type definition (subset used by templates)\n */\nexport interface JsonSchema {\n type?: string;\n required?: string[];\n properties?: Record<string, JsonSchema>;\n items?: JsonSchema;\n minItems?: number;\n maxItems?: number;\n pattern?: string;\n enum?: (string | number | boolean)[];\n default?: unknown;\n description?: string;\n oneOf?: JsonSchema[];\n}\n\n/**\n * Validation result for content against template schema\n */\nexport interface ValidationResult {\n valid: boolean;\n errors: string[];\n}\n\n/**\n * Convert a JSON Schema object to a Zod schema\n *\n * Supports a subset of JSON Schema used by template definitions:\n * - Basic types: string, number, boolean, array, object\n * - Required fields\n * - Nested objects and arrays\n * - Pattern validation for strings\n * - minItems/maxItems for arrays\n */\nexport function jsonSchemaToZod(schema: JsonSchema): ZodTypeAny {\n // Handle oneOf first (union type)\n if (schema.oneOf && schema.oneOf.length > 0) {\n const schemas = schema.oneOf.map((s) => jsonSchemaToZod(s));\n if (schemas.length === 1) {\n return schemas[0]!;\n }\n // z.union requires at least 2 schemas\n return z.union(schemas as [ZodTypeAny, ZodTypeAny, ...ZodTypeAny[]]);\n }\n\n const type = schema.type ?? \"object\";\n\n switch (type) {\n case \"string\": {\n // Handle enum first (enum values are always valid)\n if (schema.enum && schema.enum.length > 0) {\n const enumValues = schema.enum as [string, ...string[]];\n return z.enum(enumValues);\n }\n\n let zodSchema = z.string();\n if (schema.pattern) {\n zodSchema = zodSchema.regex(new RegExp(schema.pattern));\n }\n return zodSchema;\n }\n\n case \"number\":\n return z.number();\n\n case \"integer\":\n return z.number().int();\n\n case \"boolean\":\n return z.boolean();\n\n case \"array\": {\n const itemSchema = schema.items ? jsonSchemaToZod(schema.items) : z.unknown();\n let arraySchema = z.array(itemSchema);\n\n if (schema.minItems !== undefined) {\n arraySchema = arraySchema.min(schema.minItems);\n }\n if (schema.maxItems !== undefined) {\n arraySchema = arraySchema.max(schema.maxItems);\n }\n\n return arraySchema;\n }\n\n case \"object\": {\n if (!schema.properties) {\n return z.record(z.unknown());\n }\n\n const shape: Record<string, ZodTypeAny> = {};\n const required = new Set(schema.required ?? []);\n\n for (const [key, propSchema] of Object.entries(schema.properties)) {\n const propZod = jsonSchemaToZod(propSchema);\n shape[key] = required.has(key) ? propZod : propZod.optional();\n }\n\n return z.object(shape).passthrough();\n }\n\n default:\n return z.unknown();\n }\n}\n\n/**\n * Validate content against a JSON Schema\n */\nexport function validateWithJsonSchema(\n schema: JsonSchema,\n content: unknown\n): ValidationResult {\n const zodSchema = jsonSchemaToZod(schema);\n const result = zodSchema.safeParse(content);\n\n if (result.success) {\n return { valid: true, errors: [] };\n }\n\n const errors = result.error.errors.map((issue: ZodIssue) => {\n const path = issue.path.join(\".\");\n return path ? `${path}: ${issue.message}` : issue.message;\n });\n\n return { valid: false, errors };\n}\n","import * as fs from \"node:fs/promises\";\nimport { parse as parseYaml } from \"yaml\";\nimport {\n iconRegistrySchema,\n type IconRegistry,\n type IconSource,\n type IconDefaults,\n} from \"./schema.js\";\n\n/**\n * Parsed icon reference with prefix and name\n */\nexport interface ParsedIconReference {\n prefix: string;\n name: string;\n}\n\n/**\n * Icon Registry Loader - loads and manages icon registry configuration\n */\nexport class IconRegistryLoader {\n private registry: IconRegistry | null = null;\n private sourcesByPrefix: Map<string, IconSource> = new Map();\n private aliasMap: Map<string, string> = new Map();\n private colorMap: Map<string, string> = new Map();\n\n /**\n * Load registry from YAML file\n */\n async load(configPath: string): Promise<IconRegistry> {\n const content = await fs.readFile(configPath, \"utf-8\");\n const parsed = parseYaml(content);\n const validated = iconRegistrySchema.parse(parsed);\n\n this.registry = validated;\n this.buildMaps();\n\n return validated;\n }\n\n /**\n * Resolve an alias to its icon reference\n * @returns The resolved icon reference or the original name if not an alias\n */\n resolveAlias(nameOrAlias: string): string {\n return this.aliasMap.get(nameOrAlias) ?? nameOrAlias;\n }\n\n /**\n * Get icon source by prefix\n */\n getSource(prefix: string): IconSource | undefined {\n return this.sourcesByPrefix.get(prefix);\n }\n\n /**\n * Parse an icon reference string (e.g., \"mi:home\" or \"iconify:mdi:account\")\n * @returns Parsed reference or null if invalid format\n */\n parseIconReference(reference: string): ParsedIconReference | null {\n const colonIndex = reference.indexOf(\":\");\n if (colonIndex === -1) {\n return null;\n }\n\n const prefix = reference.substring(0, colonIndex);\n const name = reference.substring(colonIndex + 1);\n\n return { prefix, name };\n }\n\n /**\n * Get registry defaults\n */\n getDefaults(): IconDefaults {\n if (!this.registry) {\n return { size: \"24px\", color: \"currentColor\" };\n }\n return this.registry.defaults;\n }\n\n /**\n * Get color by name from color palette\n */\n getColor(name: string): string | undefined {\n return this.colorMap.get(name);\n }\n\n /**\n * Get all sources\n */\n getSources(): IconSource[] {\n return this.registry?.sources ?? [];\n }\n\n /**\n * Get all aliases\n */\n getAliases(): Record<string, string> {\n return this.registry?.aliases ?? {};\n }\n\n /**\n * Check if registry is loaded\n */\n isLoaded(): boolean {\n return this.registry !== null;\n }\n\n /**\n * Build internal lookup maps from registry\n */\n private buildMaps(): void {\n this.sourcesByPrefix.clear();\n this.aliasMap.clear();\n this.colorMap.clear();\n\n if (!this.registry) {\n return;\n }\n\n // Build sources map\n for (const source of this.registry.sources) {\n this.sourcesByPrefix.set(source.prefix, source);\n }\n\n // Build aliases map\n for (const [alias, target] of Object.entries(this.registry.aliases)) {\n this.aliasMap.set(alias, target);\n }\n\n // Build colors map\n if (this.registry.colors) {\n for (const [name, color] of Object.entries(this.registry.colors)) {\n this.colorMap.set(name, color);\n }\n }\n }\n}\n","import { z } from \"zod\";\n\n/**\n * Schema for icon source types\n */\nexport const iconSourceTypeSchema = z.enum([\n \"web-font\",\n \"svg-inline\",\n \"svg-sprite\",\n \"local-svg\",\n]);\n\nexport type IconSourceType = z.infer<typeof iconSourceTypeSchema>;\n\n/**\n * Schema for individual icon source definition\n */\nexport const iconSourceSchema = z.object({\n name: z.string(),\n type: iconSourceTypeSchema,\n prefix: z.string(),\n url: z.string().optional(),\n path: z.string().optional(),\n render: z.string().optional(),\n});\n\nexport type IconSource = z.infer<typeof iconSourceSchema>;\n\n/**\n * Schema for icon defaults\n */\nexport const iconDefaultsSchema = z.object({\n size: z.string().default(\"24px\"),\n color: z.string().default(\"currentColor\"),\n});\n\nexport type IconDefaults = z.infer<typeof iconDefaultsSchema>;\n\n/**\n * Schema for the full icon registry configuration\n */\nexport const iconRegistrySchema = z.object({\n sources: z.array(iconSourceSchema),\n aliases: z.record(z.string()).default({}),\n colors: z.record(z.string()).optional(),\n defaults: iconDefaultsSchema.default({}),\n});\n\nexport type IconRegistry = z.infer<typeof iconRegistrySchema>;\n","import * as fs from \"node:fs/promises\";\nimport * as path from \"node:path\";\nimport nunjucks from \"nunjucks\";\nimport { IconRegistryLoader } from \"./registry.js\";\nimport type { IconSource } from \"./schema.js\";\n\n/**\n * Options for rendering an icon\n */\nexport interface IconOptions {\n size?: string;\n color?: string;\n class?: string;\n}\n\n/**\n * Options for the IconResolver\n */\nexport interface IconResolverOptions {\n /** Use CSS variables for theme colors (e.g., var(--theme-primary)) */\n useThemeVariables?: boolean;\n}\n\n/**\n * Icon Resolver - renders icons from various sources\n */\nexport class IconResolver {\n private nunjucksEnv: nunjucks.Environment;\n private options: IconResolverOptions;\n\n constructor(private registry: IconRegistryLoader, options: IconResolverOptions = {}) {\n this.nunjucksEnv = new nunjucks.Environment(null, {\n autoescape: false,\n });\n this.options = options;\n }\n\n /**\n * Render an icon by name or alias\n */\n async render(nameOrAlias: string, options?: IconOptions): Promise<string> {\n // Resolve alias if needed\n const resolved = this.registry.resolveAlias(nameOrAlias);\n\n // Parse the icon reference\n const parsed = this.registry.parseIconReference(resolved);\n if (!parsed) {\n throw new Error(\n `Invalid icon reference format: \"${resolved}\". Expected format: \"prefix:name\"`\n );\n }\n\n // Get the source for this prefix\n const source = this.registry.getSource(parsed.prefix);\n if (!source) {\n throw new Error(`Unknown icon source prefix: \"${parsed.prefix}\"`);\n }\n\n // Get defaults and merge options\n const defaults = this.registry.getDefaults();\n const mergedOptions: Required<Omit<IconOptions, \"class\">> & Pick<IconOptions, \"class\"> = {\n size: options?.size ?? defaults.size,\n color: this.resolveColor(options?.color) ?? defaults.color,\n ...(options?.class !== undefined ? { class: options.class } : {}),\n };\n\n // Render based on source type\n switch (source.type) {\n case \"web-font\":\n return this.renderWebFont(source, parsed.name, mergedOptions);\n case \"local-svg\":\n return await this.renderLocalSvg(source, parsed.name, mergedOptions);\n case \"svg-inline\":\n return await this.renderSvgInline(source, parsed.name, mergedOptions);\n case \"svg-sprite\":\n return this.renderSvgSprite(source, parsed.name, mergedOptions);\n default:\n throw new Error(`Unsupported icon source type: \"${source.type}\"`);\n }\n }\n\n /**\n * Render a web-font icon\n */\n private renderWebFont(\n source: IconSource,\n name: string,\n options: IconOptions\n ): string {\n const style = this.buildStyle(options);\n const className = this.buildClassName(name, options);\n\n if (source.render) {\n // Use custom render template\n return this.nunjucksEnv.renderString(source.render, {\n name,\n style,\n class: className,\n size: options.size,\n color: options.color,\n });\n }\n\n // Default web-font render\n return `<span class=\"${className}\" style=\"${style}\">${name}</span>`;\n }\n\n /**\n * Render a local SVG icon\n */\n private async renderLocalSvg(\n source: IconSource,\n name: string,\n options: IconOptions\n ): Promise<string> {\n if (!source.path) {\n throw new Error(`Local SVG source \"${source.name}\" has no path defined`);\n }\n\n const svgPath = path.join(source.path, `${name}.svg`);\n\n try {\n const svgContent = await fs.readFile(svgPath, \"utf-8\");\n return this.processSvg(svgContent, name, options);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n throw new Error(`Icon file not found: ${svgPath}`);\n }\n throw error;\n }\n }\n\n /**\n * Render an SVG from external URL (placeholder without cache)\n */\n private async renderSvgInline(\n source: IconSource,\n name: string,\n options: IconOptions\n ): Promise<string> {\n // Without cache implementation, return a placeholder\n // Cache will be integrated in Step 4\n const className = this.buildClassName(name, options);\n const style = this.buildStyle(options);\n\n return `<span class=\"${className}\" style=\"${style}\" data-icon-source=\"${source.name}\" data-icon-name=\"${name}\">[${name}]</span>`;\n }\n\n /**\n * Render an SVG sprite reference\n */\n private renderSvgSprite(\n source: IconSource,\n name: string,\n options: IconOptions\n ): string {\n const className = this.buildClassName(name, options);\n const size = options.size ?? \"24px\";\n const color = options.color ?? \"currentColor\";\n\n const spriteUrl = source.url ?? \"\";\n\n return `<svg class=\"${className}\" width=\"${size}\" height=\"${size}\" fill=\"${color}\">\n <use xlink:href=\"${spriteUrl}#${name}\"/>\n</svg>`;\n }\n\n /**\n * Process SVG content and apply options\n */\n private processSvg(\n svgContent: string,\n name: string,\n options: IconOptions\n ): string {\n const className = this.buildClassName(name, options);\n const size = options.size ?? \"24px\";\n const color = options.color ?? \"currentColor\";\n\n // Parse and modify SVG attributes\n let processed = svgContent.trim();\n\n // Add/replace class attribute\n if (processed.includes(\"class=\")) {\n processed = processed.replace(/class=\"[^\"]*\"/, `class=\"${className}\"`);\n } else {\n processed = processed.replace(\"<svg\", `<svg class=\"${className}\"`);\n }\n\n // Add/replace width and height\n if (processed.includes(\"width=\")) {\n processed = processed.replace(/width=\"[^\"]*\"/, `width=\"${size}\"`);\n } else {\n processed = processed.replace(\"<svg\", `<svg width=\"${size}\"`);\n }\n\n if (processed.includes(\"height=\")) {\n processed = processed.replace(/height=\"[^\"]*\"/, `height=\"${size}\"`);\n } else {\n processed = processed.replace(\"<svg\", `<svg height=\"${size}\"`);\n }\n\n // Replace fill=\"currentColor\" with actual color\n if (color !== \"currentColor\") {\n processed = processed.replace(/fill=\"currentColor\"/g, `fill=\"${color}\"`);\n }\n\n return processed;\n }\n\n /**\n * Build CSS style string\n */\n private buildStyle(options: IconOptions): string {\n const styles: string[] = [];\n\n if (options.size) {\n styles.push(`font-size: ${options.size}`);\n }\n\n if (options.color) {\n styles.push(`color: ${options.color}`);\n }\n\n return styles.join(\"; \");\n }\n\n /**\n * Build class name string\n */\n private buildClassName(name: string, options: IconOptions): string {\n const classes = [\"icon\", `icon-${name}`];\n\n if (options.class) {\n classes.push(options.class);\n }\n\n return classes.join(\" \");\n }\n\n /**\n * Resolve color value, supporting palette names and CSS variables\n */\n private resolveColor(color?: string): string | undefined {\n if (!color) {\n return undefined;\n }\n\n // Check if it's a palette name\n const paletteColor = this.registry.getColor(color);\n if (paletteColor) {\n if (this.options.useThemeVariables) {\n return `var(--theme-${color})`;\n }\n return paletteColor;\n }\n\n // Pass through hex/rgb/other colors\n return color;\n }\n}\n","import { exec } from 'child_process';\n\nexport interface CSLAuthor {\n family: string;\n given?: string;\n}\n\nexport interface CSLItem {\n id: string;\n author?: CSLAuthor[];\n issued?: { 'date-parts': number[][] };\n title?: string;\n DOI?: string;\n PMID?: string;\n 'container-title'?: string;\n volume?: string;\n issue?: string;\n page?: string;\n URL?: string;\n type?: string;\n}\n\nexport class ReferenceManagerError extends Error {\n constructor(\n message: string,\n public cause?: unknown\n ) {\n super(message);\n this.name = 'ReferenceManagerError';\n }\n}\n\n/**\n * Client for reference-manager CLI\n */\nexport class ReferenceManager {\n constructor(private command: string = 'ref') {}\n\n /**\n * Check if reference-manager CLI is available\n */\n async isAvailable(): Promise<boolean> {\n try {\n await this.execCommand(`${this.command} --version`);\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * Get all references from the library\n */\n async getAll(): Promise<CSLItem[]> {\n const result = await this.execCommand(`${this.command} list --format json`);\n return this.parseJSON(result);\n }\n\n /**\n * Get a single reference by ID\n */\n async getById(id: string): Promise<CSLItem | null> {\n const result = await this.execCommand(\n `${this.command} list --id ${id} --format json`\n );\n const items = this.parseJSON(result);\n return items[0] || null;\n }\n\n /**\n * Get multiple references by IDs\n */\n async getByIds(ids: string[]): Promise<Map<string, CSLItem>> {\n if (ids.length === 0) {\n return new Map();\n }\n\n const result = await this.execCommand(`${this.command} list --format json`);\n const allItems = this.parseJSON(result);\n\n const idSet = new Set(ids);\n const map = new Map<string, CSLItem>();\n\n for (const item of allItems) {\n if (idSet.has(item.id)) {\n map.set(item.id, item);\n }\n }\n\n return map;\n }\n\n private execCommand(cmd: string): Promise<string> {\n return new Promise((resolve, reject) => {\n exec(cmd, (error, stdout) => {\n if (error) {\n reject(\n new ReferenceManagerError(`Failed to execute: ${cmd}`, error)\n );\n return;\n }\n resolve(stdout.toString());\n });\n });\n }\n\n private parseJSON(data: string): CSLItem[] {\n try {\n return JSON.parse(data) as CSLItem[];\n } catch (error) {\n throw new ReferenceManagerError(\n 'Failed to parse reference-manager output as JSON',\n error\n );\n }\n }\n}\n","import type { ParsedSlide, ParsedPresentation } from '../core/parser';\n\nexport interface ExtractedCitation {\n id: string;\n locator?: string | undefined;\n position: { start: number; end: number };\n}\n\n// Pattern to match citations like [@id], [@id, p.42], [@id1; @id2]\n// Matches: [@word-chars] or [@word-chars, locator]\nconst SINGLE_CITATION_PATTERN = /@([\\w-]+)(?:,\\s*([^;\\]]+))?/g;\nconst CITATION_BRACKET_PATTERN = /\\[(@[\\w-]+(?:,\\s*[^;\\]]+)?(?:;\\s*@[\\w-]+(?:,\\s*[^;\\]]+)?)*)\\]/g;\n\n// Pattern to extract @id from source field in structured citations\nconst SOURCE_CITATION_PATTERN = /^@([\\w-]+)$/;\n\nexport class CitationExtractor {\n /**\n * Extract citations from a text string\n */\n extract(text: string): ExtractedCitation[] {\n const citations: ExtractedCitation[] = [];\n\n // Find all bracketed citation groups\n let bracketMatch: RegExpExecArray | null;\n CITATION_BRACKET_PATTERN.lastIndex = 0;\n\n while ((bracketMatch = CITATION_BRACKET_PATTERN.exec(text)) !== null) {\n const bracketStart = bracketMatch.index;\n const bracketContent = bracketMatch[1];\n\n // Parse individual citations within the bracket\n SINGLE_CITATION_PATTERN.lastIndex = 0;\n let singleMatch: RegExpExecArray | null;\n\n while ((singleMatch = SINGLE_CITATION_PATTERN.exec(bracketContent!)) !== null) {\n const id = singleMatch[1]!;\n const locator = singleMatch[2]?.trim();\n\n citations.push({\n id,\n locator: locator ?? undefined,\n position: {\n start: bracketStart,\n end: bracketStart + bracketMatch[0].length,\n },\n });\n }\n }\n\n return citations;\n }\n\n /**\n * Extract citations from a slide's content\n */\n extractFromSlide(slide: ParsedSlide): ExtractedCitation[] {\n const allCitations: ExtractedCitation[] = [];\n const seenIds = new Set<string>();\n\n // Extract from content recursively\n const extractFromValue = (value: unknown): void => {\n if (typeof value === 'string') {\n // Check for structured source citation (e.g., source: \"@smith2024\")\n const sourceMatch = SOURCE_CITATION_PATTERN.exec(value);\n if (sourceMatch && sourceMatch[1]) {\n const id = sourceMatch[1];\n if (!seenIds.has(id)) {\n seenIds.add(id);\n allCitations.push({\n id,\n locator: undefined,\n position: { start: 0, end: value.length },\n });\n }\n return;\n }\n\n // Regular citation extraction\n const citations = this.extract(value);\n for (const citation of citations) {\n if (!seenIds.has(citation.id)) {\n seenIds.add(citation.id);\n allCitations.push(citation);\n }\n }\n } else if (Array.isArray(value)) {\n for (const item of value) {\n extractFromValue(item);\n }\n } else if (value && typeof value === 'object') {\n for (const v of Object.values(value)) {\n extractFromValue(v);\n }\n }\n };\n\n // Extract from content\n extractFromValue(slide.content);\n\n // Extract from notes if present\n if (slide.notes) {\n const notesCitations = this.extract(slide.notes);\n for (const citation of notesCitations) {\n if (!seenIds.has(citation.id)) {\n seenIds.add(citation.id);\n allCitations.push(citation);\n }\n }\n }\n\n return allCitations;\n }\n\n /**\n * Extract citations from all slides in a presentation\n */\n extractFromPresentation(presentation: ParsedPresentation): ExtractedCitation[] {\n const allCitations: ExtractedCitation[] = [];\n const seenIds = new Set<string>();\n\n for (const slide of presentation.slides) {\n const slideCitations = this.extractFromSlide(slide);\n for (const citation of slideCitations) {\n if (!seenIds.has(citation.id)) {\n seenIds.add(citation.id);\n allCitations.push(citation);\n }\n }\n }\n\n return allCitations;\n }\n\n /**\n * Get unique citation IDs in order of first appearance\n */\n getUniqueIds(citations: ExtractedCitation[]): string[] {\n const seen = new Set<string>();\n const uniqueIds: string[] = [];\n\n for (const citation of citations) {\n if (!seen.has(citation.id)) {\n seen.add(citation.id);\n uniqueIds.push(citation.id);\n }\n }\n\n return uniqueIds;\n }\n}\n","import type { ReferenceManager, CSLItem, CSLAuthor } from './manager';\n\nexport interface FormatterConfig {\n author?: {\n maxAuthors?: number;\n etAl?: string;\n etAlJa?: string;\n separatorJa?: string;\n };\n inline?: {\n authorSep?: string;\n identifierSep?: string;\n multiSep?: string;\n };\n}\n\nconst DEFAULT_CONFIG: Required<FormatterConfig> = {\n author: {\n maxAuthors: 2,\n etAl: 'et al.',\n etAlJa: 'ほか',\n separatorJa: '・',\n },\n inline: {\n authorSep: ', ',\n identifierSep: '; ',\n multiSep: '), (',\n },\n};\n\n// Pattern to detect Japanese characters\nconst JAPANESE_PATTERN = /[\\u3040-\\u309F\\u30A0-\\u30FF\\u4E00-\\u9FAF]/;\n\n// Citation patterns for expansion\nconst CITATION_BRACKET_PATTERN =\n /\\[(@[\\w-]+(?:,\\s*[^;\\]]+)?(?:;\\s*@[\\w-]+(?:,\\s*[^;\\]]+)?)*)\\]/g;\nconst SINGLE_CITATION_PATTERN = /@([\\w-]+)(?:,\\s*([^;\\]]+))?/g;\n\n/**\n * Formats citations for inline display and bibliography generation\n */\nexport class CitationFormatter {\n private config: Required<FormatterConfig>;\n\n constructor(\n private manager: ReferenceManager,\n config?: FormatterConfig\n ) {\n this.config = {\n author: { ...DEFAULT_CONFIG.author, ...config?.author },\n inline: { ...DEFAULT_CONFIG.inline, ...config?.inline },\n };\n }\n\n /**\n * Format an inline citation\n * e.g., \"(Smith et al., 2024; PMID: 12345678)\"\n */\n async formatInline(id: string): Promise<string> {\n const item = await this.manager.getById(id);\n if (!item) {\n return `[${id}]`;\n }\n\n return this.formatInlineItem(item);\n }\n\n /**\n * Format a full bibliography citation\n */\n async formatFull(id: string): Promise<string> {\n const item = await this.manager.getById(id);\n if (!item) {\n return `[${id}]`;\n }\n\n return this.formatFullItem(item);\n }\n\n /**\n * Expand all citations in text\n * e.g., \"[@smith2024]\" -> \"(Smith et al., 2024; PMID: 12345678)\"\n */\n async expandCitations(text: string): Promise<string> {\n // First, collect all citation IDs\n const ids = new Set<string>();\n CITATION_BRACKET_PATTERN.lastIndex = 0;\n\n let match: RegExpExecArray | null;\n while ((match = CITATION_BRACKET_PATTERN.exec(text)) !== null) {\n const content = match[1];\n SINGLE_CITATION_PATTERN.lastIndex = 0;\n\n let singleMatch: RegExpExecArray | null;\n while ((singleMatch = SINGLE_CITATION_PATTERN.exec(content!)) !== null) {\n ids.add(singleMatch[1]!);\n }\n }\n\n // Fetch all items at once\n const items = await this.manager.getByIds([...ids]);\n\n // Replace citations\n CITATION_BRACKET_PATTERN.lastIndex = 0;\n let result = text;\n\n // Reset and iterate again for replacement\n const matches: Array<{\n start: number;\n end: number;\n replacement: string;\n }> = [];\n\n CITATION_BRACKET_PATTERN.lastIndex = 0;\n while ((match = CITATION_BRACKET_PATTERN.exec(text)) !== null) {\n const content = match[1];\n const replacements: string[] = [];\n\n SINGLE_CITATION_PATTERN.lastIndex = 0;\n let singleMatch: RegExpExecArray | null;\n while ((singleMatch = SINGLE_CITATION_PATTERN.exec(content!)) !== null) {\n const id = singleMatch[1]!;\n const item = items.get(id);\n if (item) {\n replacements.push(this.formatInlineItem(item));\n } else {\n replacements.push(`[${id}]`);\n }\n }\n\n matches.push({\n start: match.index,\n end: match.index + match[0].length,\n replacement: replacements.join(', '),\n });\n }\n\n // Apply replacements from end to start to maintain positions\n for (const m of [...matches].reverse()) {\n result = result.slice(0, m.start) + m.replacement + result.slice(m.end);\n }\n\n return result;\n }\n\n /**\n * Generate bibliography entries\n */\n async generateBibliography(\n ids: string[],\n sort: 'author' | 'year' | 'citation-order' = 'citation-order'\n ): Promise<string[]> {\n if (ids.length === 0) {\n return [];\n }\n\n const items = await this.manager.getByIds(ids);\n let sortedItems: CSLItem[];\n\n if (sort === 'citation-order') {\n // Keep order of ids, filtering out non-existent\n sortedItems = ids\n .map((id) => items.get(id))\n .filter((item): item is CSLItem => item !== undefined);\n } else if (sort === 'author') {\n sortedItems = [...items.values()].sort((a, b) => {\n const authorA = this.getFirstAuthorFamily(a);\n const authorB = this.getFirstAuthorFamily(b);\n return authorA.localeCompare(authorB);\n });\n } else {\n // sort by year\n sortedItems = [...items.values()].sort((a, b) => {\n const yearA = this.getYear(a);\n const yearB = this.getYear(b);\n return yearA - yearB;\n });\n }\n\n return sortedItems.map((item) => this.formatFullItem(item));\n }\n\n private formatInlineItem(item: CSLItem): string {\n const author = this.formatAuthorInline(item.author);\n const year = this.getYear(item);\n const identifier = this.getIdentifier(item);\n\n if (identifier) {\n return `(${author}, ${year}; ${identifier})`;\n }\n return `(${author}, ${year})`;\n }\n\n private formatFullItem(item: CSLItem): string {\n const parts: string[] = [];\n\n // Authors\n const isJapanese = this.isJapaneseAuthors(item.author);\n const authors = this.formatAuthorsFull(item.author, isJapanese);\n parts.push(authors);\n\n // Year\n const year = this.getYear(item);\n parts.push(`(${year}).`);\n\n // Title\n if (item.title) {\n parts.push(`${item.title}.`);\n }\n\n // Container (journal)\n if (item['container-title']) {\n const journal = isJapanese\n ? item['container-title']\n : `*${item['container-title']}*`;\n\n // Volume, issue, pages\n let location = '';\n if (item.volume) {\n location = item.issue\n ? `${item.volume}(${item.issue})`\n : item.volume;\n }\n if (item.page) {\n location = location ? `${location}, ${item.page}` : item.page;\n }\n\n parts.push(location ? `${journal}, ${location}.` : `${journal}.`);\n }\n\n // Identifier\n const identifier = this.getIdentifier(item);\n if (identifier) {\n parts.push(identifier);\n }\n\n return parts.join(' ');\n }\n\n private formatAuthorInline(authors: CSLAuthor[] | undefined): string {\n if (!authors || authors.length === 0) {\n return 'Unknown';\n }\n\n const isJapanese = this.isJapaneseAuthors(authors);\n const { etAl, etAlJa, separatorJa } = this.config.author;\n const firstAuthor = authors[0]!;\n\n if (authors.length === 1) {\n return firstAuthor.family;\n }\n\n if (authors.length === 2) {\n const separator = isJapanese ? separatorJa : ' & ';\n return `${firstAuthor.family}${separator}${authors[1]!.family}`;\n }\n\n // 3+ authors\n const suffix = isJapanese ? etAlJa : ` ${etAl}`;\n return `${firstAuthor.family}${suffix}`;\n }\n\n private formatAuthorsFull(\n authors: CSLAuthor[] | undefined,\n isJapanese: boolean\n ): string {\n if (!authors || authors.length === 0) {\n return 'Unknown';\n }\n\n if (isJapanese) {\n // Japanese: 田中太郎, 山田花子\n return authors.map((a) => `${a.family}${a.given || ''}`).join(', ');\n }\n\n // English: Smith, J., Johnson, A., & Williams, B.\n if (authors.length === 1) {\n const a = authors[0]!;\n const initial = a.given ? `${a.given.charAt(0)}.` : '';\n return `${a.family}, ${initial}`;\n }\n\n const formatted = authors.map((a, i) => {\n const initial = a.given ? `${a.given.charAt(0)}.` : '';\n if (i === authors.length - 1) {\n return `& ${a.family}, ${initial}`;\n }\n return `${a.family}, ${initial}`;\n });\n\n // Join with \", \" for 3+ authors, or \", \" for 2 authors\n return formatted.join(', ').replace(', &', ', &');\n }\n\n private isJapaneseAuthors(authors: CSLAuthor[] | undefined): boolean {\n if (!authors || authors.length === 0) {\n return false;\n }\n // Check first author's family name for Japanese characters\n return JAPANESE_PATTERN.test(authors[0]!.family);\n }\n\n private getFirstAuthorFamily(item: CSLItem): string {\n return item.author?.[0]?.family || '';\n }\n\n private getYear(item: CSLItem): number {\n const dateParts = item.issued?.['date-parts'];\n if (dateParts && dateParts[0] && dateParts[0][0]) {\n return dateParts[0][0];\n }\n return 0;\n }\n\n private getIdentifier(item: CSLItem): string | null {\n if (item.PMID) {\n return `PMID: ${item.PMID}`;\n }\n if (item.DOI) {\n return `DOI: ${item.DOI}`;\n }\n return null;\n }\n}\n","/**\n * slide-generation - A CLI tool to generate Marp-compatible Markdown from YAML source files\n */\n\ndeclare const __VERSION__: string;\nexport const VERSION = __VERSION__;\n\n// Core modules\nexport * from './core';\n// export * from './core/transformer';\n// export * from './core/renderer';\n// export * from './core/pipeline';\n\n// Template system\nexport * from './templates';\n","import { Command } from 'commander';\nimport { access, readFile } from 'fs/promises';\nimport { basename, dirname, join } from 'path';\nimport chalk from 'chalk';\nimport ora from 'ora';\nimport { parse as parseYaml } from 'yaml';\nimport { Pipeline, PipelineError } from '../../core/pipeline';\nimport { ConfigLoader } from '../../config/loader';\nimport { ImageProcessingPipeline } from '../../images';\n\n/**\n * Exit codes for CLI commands\n */\nexport const ExitCode = {\n Success: 0,\n GeneralError: 1,\n ArgumentError: 2,\n FileReadError: 3,\n ValidationError: 4,\n ConversionError: 5,\n ReferenceError: 6,\n} as const;\n\ninterface ConvertOptions {\n output?: string;\n config?: string;\n theme?: string;\n references?: boolean;\n verbose?: boolean;\n processImages?: boolean;\n}\n\n/**\n * Generate default output path from input path\n */\nfunction getDefaultOutputPath(inputPath: string): string {\n const dir = dirname(inputPath);\n const base = basename(inputPath, '.yaml');\n return join(dir, `${base}.md`);\n}\n\n/**\n * Extract unique image directories from presentation\n */\nasync function extractImageDirectories(\n inputPath: string,\n baseDir: string\n): Promise<string[]> {\n const content = await readFile(inputPath, 'utf-8');\n const parsed = parseYaml(content) as {\n slides?: Array<{ content?: Record<string, unknown> }>;\n };\n\n const imageDirs = new Set<string>();\n\n if (!parsed.slides) return [];\n\n for (const slide of parsed.slides) {\n const content = slide.content;\n if (!content) continue;\n\n // Collect image paths from various content fields\n const imagePaths: string[] = [];\n\n if (typeof content['image'] === 'string') {\n imagePaths.push(content['image']);\n }\n\n const before = content['before'] as { image?: string } | undefined;\n const after = content['after'] as { image?: string } | undefined;\n if (before?.image) imagePaths.push(before.image);\n if (after?.image) imagePaths.push(after.image);\n\n const images = content['images'] as Array<{ src?: string }> | undefined;\n if (images) {\n for (const img of images) {\n if (img.src) imagePaths.push(img.src);\n }\n }\n\n // Extract directory for each image path\n for (const imagePath of imagePaths) {\n const dir = dirname(imagePath);\n if (dir && dir !== '.') {\n imageDirs.add(join(baseDir, dir));\n }\n }\n }\n\n return Array.from(imageDirs);\n}\n\n/**\n * Process images based on metadata instructions\n */\nasync function processImages(\n inputPath: string,\n baseDir: string\n): Promise<number> {\n const imageDirs = await extractImageDirectories(inputPath, baseDir);\n let totalProcessed = 0;\n\n for (const imageDir of imageDirs) {\n try {\n await access(imageDir);\n const pipeline = new ImageProcessingPipeline(imageDir);\n const result = await pipeline.processDirectory();\n totalProcessed += result.processedImages;\n } catch {\n // Directory doesn't exist, skip\n }\n }\n\n return totalProcessed;\n}\n\n/**\n * Create the convert command\n */\nexport function createConvertCommand(): Command {\n return new Command('convert')\n .description('Convert YAML source to Marp Markdown')\n .argument('<input>', 'Input YAML file')\n .option('-o, --output <path>', 'Output file path')\n .option('-c, --config <path>', 'Config file path')\n .option('-t, --theme <name>', 'Theme name')\n .option('--no-references', 'Disable reference processing')\n .option('--process-images', 'Apply image processing from metadata')\n .option('-v, --verbose', 'Verbose output')\n .action(async (input: string, options: ConvertOptions) => {\n await executeConvert(input, options);\n });\n}\n\n/**\n * Execute the convert command\n */\nasync function executeConvert(\n inputPath: string,\n options: ConvertOptions\n): Promise<void> {\n const spinner = options.verbose ? null : ora();\n const verbose = options.verbose ?? false;\n\n const updateSpinner = (text: string) => {\n if (spinner) {\n spinner.text = text;\n }\n };\n\n try {\n // Validate input file exists\n spinner?.start(`Reading ${inputPath}...`);\n try {\n await access(inputPath);\n } catch {\n spinner?.fail(`File not found: ${inputPath}`);\n console.error(chalk.red(`Error: Input file not found: ${inputPath}`));\n process.exitCode = ExitCode.FileReadError;\n return;\n }\n\n // Determine output path\n const outputPath = options.output ?? getDefaultOutputPath(inputPath);\n\n // Load configuration\n updateSpinner('Loading configuration...');\n const configLoader = new ConfigLoader();\n let configPath = options.config;\n\n if (!configPath) {\n configPath = await configLoader.findConfig(dirname(inputPath));\n }\n\n const config = await configLoader.load(configPath);\n\n // Override references if specified\n if (options.references === false) {\n config.references.enabled = false;\n }\n\n // Override theme if specified\n if (options.theme) {\n config.output.theme = options.theme;\n }\n\n // Create and initialize pipeline\n updateSpinner('Initializing pipeline...');\n const pipeline = new Pipeline(config);\n\n try {\n await pipeline.initialize();\n } catch (error) {\n spinner?.fail('Failed to initialize pipeline');\n if (error instanceof PipelineError) {\n console.error(chalk.red(`Error: ${error.message}`));\n } else {\n console.error(\n chalk.red(\n `Error: ${error instanceof Error ? error.message : 'Unknown error'}`\n )\n );\n }\n process.exitCode = ExitCode.ConversionError;\n return;\n }\n\n // Process images if requested\n let processedImageCount = 0;\n if (options.processImages) {\n updateSpinner('Processing images...');\n const baseDir = dirname(inputPath);\n processedImageCount = await processImages(inputPath, baseDir);\n }\n\n // Run pipeline\n updateSpinner(`Converting ${inputPath}...`);\n const result = await pipeline.runWithResult(inputPath, { outputPath });\n\n // Success!\n spinner?.succeed(`Converted ${inputPath}`);\n\n // Show stats in verbose mode or after completion\n if (verbose) {\n console.log('');\n console.log(chalk.green(' ✓') + ` Parsed ${result.slideCount} slides`);\n if (result.citations.length > 0) {\n console.log(\n chalk.green(' ✓') + ` Resolved ${result.citations.length} references`\n );\n }\n if (processedImageCount > 0) {\n console.log(\n chalk.green(' ✓') + ` Processed ${processedImageCount} image(s)`\n );\n }\n console.log(chalk.green(' ✓') + ' Generated output');\n }\n\n // Show warnings\n for (const warning of result.warnings) {\n console.log(chalk.yellow(' ⚠') + ` ${warning}`);\n }\n\n // Show output path\n console.log('');\n console.log(`Output: ${chalk.cyan(outputPath)}`);\n } catch (error) {\n spinner?.fail('Conversion failed');\n\n if (error instanceof PipelineError) {\n console.error(chalk.red(`\\nError (${error.stage}): ${error.message}`));\n\n // Set appropriate exit code based on stage\n switch (error.stage) {\n case 'parse':\n process.exitCode = ExitCode.FileReadError;\n break;\n case 'transform':\n process.exitCode = ExitCode.ValidationError;\n break;\n case 'render':\n process.exitCode = ExitCode.ConversionError;\n break;\n default:\n process.exitCode = ExitCode.GeneralError;\n }\n } else {\n console.error(\n chalk.red(\n `\\nError: ${error instanceof Error ? error.message : 'Unknown error'}`\n )\n );\n process.exitCode = ExitCode.GeneralError;\n }\n }\n}\n","import { access, readFile } from 'fs/promises';\nimport { join } from 'path';\nimport { parse as parseYaml } from 'yaml';\nimport { configSchema, type Config } from './schema';\n\nconst CONFIG_NAMES = ['config.yaml', 'slide-gen.yaml'];\n\nexport class ConfigLoader {\n async load(configPath?: string): Promise<Config> {\n const fileConfig = await this.loadFile(configPath);\n return configSchema.parse(fileConfig);\n }\n\n async findConfig(directory: string): Promise<string | undefined> {\n for (const name of CONFIG_NAMES) {\n const path = join(directory, name);\n try {\n await access(path);\n return path;\n } catch {\n // Continue to next\n }\n }\n return undefined;\n }\n\n private async loadFile(configPath?: string): Promise<unknown> {\n if (!configPath) return {};\n\n try {\n const content = await readFile(configPath, 'utf-8');\n return parseYaml(content) ?? {};\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n return {};\n }\n throw error;\n }\n }\n}\n","import { z } from 'zod';\n\nexport const configSchema = z.object({\n templates: z\n .object({\n builtin: z.string().default('./templates'),\n custom: z.string().optional(),\n })\n .default({}),\n\n icons: z\n .object({\n registry: z.string().default('./icons/registry.yaml'),\n cache: z\n .object({\n enabled: z.boolean().default(true),\n directory: z.string().default('.cache/icons'),\n ttl: z.number().default(86400),\n })\n .default({}),\n })\n .default({}),\n\n references: z\n .object({\n enabled: z.boolean().default(true),\n connection: z\n .object({\n type: z.literal('cli').default('cli'),\n command: z.string().default('ref'),\n })\n .default({}),\n format: z\n .object({\n locale: z.string().default('ja-JP'),\n authorSep: z.string().default(', '),\n identifierSep: z.string().default('; '),\n maxAuthors: z.number().default(2),\n etAl: z.string().default('et al.'),\n etAlJa: z.string().default('ほか'),\n })\n .default({}),\n })\n .default({}),\n\n output: z\n .object({\n theme: z.string().default('default'),\n inlineStyles: z.boolean().default(false),\n })\n .default({}),\n});\n\nexport type Config = z.infer<typeof configSchema>;\n","/**\n * Shared constants for image management\n */\n\n/**\n * Supported image file extensions\n */\nexport const IMAGE_EXTENSIONS = new Set([\n \".jpg\",\n \".jpeg\",\n \".png\",\n \".gif\",\n \".webp\",\n \".svg\",\n]);\n\n/**\n * Check if a file is an image file based on its extension\n */\nexport function isImageFile(filename: string): boolean {\n const ext = filename.slice(filename.lastIndexOf(\".\")).toLowerCase();\n return IMAGE_EXTENSIONS.has(ext);\n}\n\n/**\n * Default minimum resolution thresholds for image quality warnings\n */\nexport const DEFAULT_MIN_RESOLUTION = {\n width: 1280,\n height: 720,\n};\n","import { z } from \"zod\";\nimport { imageProcessingArraySchema } from \"./processing-schema\";\n\n/**\n * Permission status for images\n */\nexport const permissionStatusSchema = z.enum([\n \"approved\",\n \"pending\",\n \"restricted\",\n \"rejected\",\n]);\n\nexport type PermissionStatus = z.infer<typeof permissionStatusSchema>;\n\n/**\n * Permission information for images\n */\nexport const permissionsSchema = z.object({\n status: permissionStatusSchema,\n approved_by: z.string().optional(),\n approved_date: z.string().optional(),\n expires: z.string().nullable().optional(),\n conditions: z.array(z.string()).optional(),\n document: z.string().optional(),\n pending_contact: z.string().optional(),\n});\n\nexport type Permissions = z.infer<typeof permissionsSchema>;\n\n/**\n * Credit/attribution information\n */\nexport const creditsSchema = z.object({\n required: z.boolean().optional(),\n text: z.string().optional(),\n});\n\nexport type Credits = z.infer<typeof creditsSchema>;\n\n/**\n * Individual image metadata schema\n * Used for .meta.yaml files attached to individual images\n */\nexport const individualMetadataSchema = z.object({\n // Basic information\n description: z.string().optional(),\n captured_date: z.string().optional(),\n captured_by: z.string().optional(),\n location: z.string().optional(),\n\n // Subject information - can be string or array of strings\n subject: z.union([z.string(), z.array(z.string())]).optional(),\n\n // Permission information\n permissions: permissionsSchema.optional(),\n\n // Usage restrictions\n restrictions: z.array(z.string()).optional(),\n\n // Notes (supplementary information for AI)\n notes: z.string().optional(),\n\n // Credits\n credits: creditsSchema.optional(),\n\n // Tags for search/filtering\n tags: z.array(z.string()).optional(),\n\n // Image processing instructions (crop, blur, etc.)\n processing: imageProcessingArraySchema.optional(),\n});\n\nexport type ImageMetadata = z.infer<typeof individualMetadataSchema>;\n\n/**\n * Directory-level defaults schema\n */\nexport const directoryDefaultsSchema = z.object({\n permissions: permissionsSchema.optional(),\n credits: creditsSchema.optional(),\n tags: z.array(z.string()).optional(),\n});\n\nexport type DirectoryDefaults = z.infer<typeof directoryDefaultsSchema>;\n\n/**\n * Directory metadata entry schema\n * Can be either defaults or individual file metadata\n */\nexport const directoryMetadataEntrySchema = individualMetadataSchema;\n\n/**\n * Directory metadata schema (images.yaml)\n * Contains _defaults for directory-level settings and individual file entries\n * Uses a more permissive record type to allow any entry\n */\nexport const directoryMetadataSchema = z.record(\n z.string(),\n individualMetadataSchema.passthrough()\n);\n\nexport type DirectoryMetadata = z.infer<typeof directoryMetadataSchema>;\n\n/**\n * Merged metadata result (after applying defaults)\n */\nexport interface ResolvedImageMetadata extends ImageMetadata {\n // Path to the image file (relative to project root)\n path?: string;\n // Source of metadata (individual | directory | defaults)\n metadataSource?: \"individual\" | \"directory\" | \"defaults\" | \"none\";\n}\n","import { z } from \"zod\";\n\n/**\n * Edge crop options schema\n * Each edge is a percentage (0-50) to crop from that edge\n */\nexport const edgeCropOptionsSchema = z.object({\n left: z.number().min(0).max(50).optional(),\n right: z.number().min(0).max(50).optional(),\n top: z.number().min(0).max(50).optional(),\n bottom: z.number().min(0).max(50).optional(),\n});\n\nexport type EdgeCropOptions = z.infer<typeof edgeCropOptionsSchema>;\n\n/**\n * Region specification for crop or blur\n */\nexport const regionSchema = z.object({\n x: z.number().min(0),\n y: z.number().min(0),\n width: z.number().positive(),\n height: z.number().positive(),\n});\n\nexport type Region = z.infer<typeof regionSchema>;\n\n/**\n * Crop instruction schema\n * Can specify either edges (percentage) or region (pixels)\n */\nexport const cropInstructionSchema = z.object({\n type: z.literal(\"crop\"),\n edges: edgeCropOptionsSchema.optional(),\n region: regionSchema.optional(),\n});\n\nexport type CropInstruction = z.infer<typeof cropInstructionSchema>;\n\n/**\n * Blur instruction schema\n * Applies blur to a specified region\n */\nexport const blurInstructionSchema = z.object({\n type: z.literal(\"blur\"),\n region: regionSchema,\n radius: z.number().min(1).max(100).optional(),\n});\n\nexport type BlurInstruction = z.infer<typeof blurInstructionSchema>;\n\n/**\n * Combined processing instruction schema (discriminated union)\n */\nexport const imageProcessingSchema = z.discriminatedUnion(\"type\", [\n cropInstructionSchema,\n blurInstructionSchema,\n]);\n\nexport type ImageProcessingInstruction = z.infer<typeof imageProcessingSchema>;\n\n/**\n * Array of processing instructions\n */\nexport const imageProcessingArraySchema = z.array(imageProcessingSchema);\n\nexport type ImageProcessingInstructions = z.infer<\n typeof imageProcessingArraySchema\n>;\n","import * as fs from \"node:fs/promises\";\nimport * as path from \"node:path\";\nimport { parse as parseYaml } from \"yaml\";\nimport {\n individualMetadataSchema,\n directoryMetadataSchema,\n type ImageMetadata,\n type PermissionStatus,\n} from \"./schema\";\nimport { isImageFile } from \"./constants\";\n\n/**\n * Warning info for metadata loading issues\n */\nexport interface MetadataWarning {\n path: string;\n message: string;\n}\n\n/**\n * Collected warnings during metadata loading\n */\nlet metadataWarnings: MetadataWarning[] = [];\n\n/**\n * Get and clear collected warnings\n */\nexport function getAndClearMetadataWarnings(): MetadataWarning[] {\n const warnings = metadataWarnings;\n metadataWarnings = [];\n return warnings;\n}\n\n/**\n * Loader for image metadata files\n * Supports both individual .meta.yaml files and directory-level images.yaml files\n */\nexport class ImageMetadataLoader {\n constructor(private baseDir: string = \".\") {}\n\n /**\n * Load metadata for a specific image file\n * Priority: individual .meta.yaml > directory images.yaml entry > directory _defaults\n */\n async load(imagePath: string): Promise<ImageMetadata> {\n // Try loading individual metadata first\n const individualMetadata = await this.loadIndividualMetadata(imagePath);\n if (individualMetadata !== null) {\n return individualMetadata;\n }\n\n // Fall back to directory metadata\n const directoryMetadata = await this.loadFromDirectoryMetadata(imagePath);\n return directoryMetadata;\n }\n\n /**\n * Load all metadata for images in a directory\n */\n async loadDirectory(dirPath: string): Promise<Map<string, ImageMetadata>> {\n const result = new Map<string, ImageMetadata>();\n const fullDirPath = path.join(this.baseDir, dirPath);\n\n // Check if directory exists\n try {\n await fs.access(fullDirPath);\n } catch {\n return result;\n }\n\n // Get all image files in directory\n const files = await fs.readdir(fullDirPath);\n const imageFiles = files.filter((f) => isImageFile(f));\n\n // Load metadata for each image\n for (const file of imageFiles) {\n const imagePath = path.join(dirPath, file);\n const metadata = await this.load(imagePath);\n result.set(file, metadata);\n }\n\n return result;\n }\n\n /**\n * Check if metadata exists for an image\n */\n async hasMetadata(imagePath: string): Promise<boolean> {\n // Check individual metadata\n const individualPath = this.getIndividualMetadataPath(imagePath);\n try {\n await fs.access(individualPath);\n return true;\n } catch {\n // Continue to check directory metadata\n }\n\n // Check directory metadata\n const dirMetadata = await this.loadDirectoryMetadataFile(imagePath);\n if (dirMetadata === null) {\n return false;\n }\n\n const filename = path.basename(imagePath);\n return filename in dirMetadata && filename !== \"_defaults\";\n }\n\n /**\n * Get the permission status for an image\n */\n async getPermissionStatus(imagePath: string): Promise<PermissionStatus | null> {\n const metadata = await this.load(imagePath);\n return metadata.permissions?.status ?? null;\n }\n\n /**\n * Get the path to individual metadata file\n */\n private getIndividualMetadataPath(imagePath: string): string {\n return path.join(this.baseDir, `${imagePath}.meta.yaml`);\n }\n\n /**\n * Get the path to directory metadata file\n */\n private getDirectoryMetadataPath(imagePath: string): string {\n const dir = path.dirname(imagePath);\n return path.join(this.baseDir, dir, \"images.yaml\");\n }\n\n /**\n * Load individual metadata file (.meta.yaml)\n */\n private async loadIndividualMetadata(\n imagePath: string\n ): Promise<ImageMetadata | null> {\n const metadataPath = this.getIndividualMetadataPath(imagePath);\n\n // Check if file exists first\n try {\n await fs.access(metadataPath);\n } catch {\n // File doesn't exist - this is normal, not a warning\n return null;\n }\n\n // File exists, try to read and parse it\n try {\n const content = await fs.readFile(metadataPath, \"utf-8\");\n const parsed = parseYaml(content);\n const validated = individualMetadataSchema.safeParse(parsed);\n\n if (validated.success) {\n return validated.data;\n }\n // Schema validation failed\n metadataWarnings.push({\n path: metadataPath,\n message: `Invalid metadata schema: ${validated.error.issues.map((i) => i.message).join(\", \")}`,\n });\n return null;\n } catch (error) {\n // YAML parse error or read error\n const message =\n error instanceof Error ? error.message : \"Unknown parse error\";\n metadataWarnings.push({\n path: metadataPath,\n message: `Failed to parse metadata file: ${message}`,\n });\n return null;\n }\n }\n\n /**\n * Load directory metadata file (images.yaml)\n */\n private async loadDirectoryMetadataFile(\n imagePath: string\n ): Promise<Record<string, unknown> | null> {\n const metadataPath = this.getDirectoryMetadataPath(imagePath);\n\n // Check if file exists first\n try {\n await fs.access(metadataPath);\n } catch {\n // File doesn't exist - this is normal, not a warning\n return null;\n }\n\n // File exists, try to read and parse it\n try {\n const content = await fs.readFile(metadataPath, \"utf-8\");\n const parsed = parseYaml(content);\n const validated = directoryMetadataSchema.safeParse(parsed);\n\n if (validated.success) {\n return validated.data;\n }\n // Schema validation failed\n metadataWarnings.push({\n path: metadataPath,\n message: `Invalid metadata schema: ${validated.error.issues.map((i) => i.message).join(\", \")}`,\n });\n return null;\n } catch (error) {\n // YAML parse error or read error\n const message =\n error instanceof Error ? error.message : \"Unknown parse error\";\n metadataWarnings.push({\n path: metadataPath,\n message: `Failed to parse metadata file: ${message}`,\n });\n return null;\n }\n }\n\n /**\n * Load metadata from directory metadata file\n */\n private async loadFromDirectoryMetadata(\n imagePath: string\n ): Promise<ImageMetadata> {\n const dirMetadata = await this.loadDirectoryMetadataFile(imagePath);\n\n if (dirMetadata === null) {\n return {};\n }\n\n const filename = path.basename(imagePath);\n\n // Get defaults\n const defaults = (dirMetadata[\"_defaults\"] ?? {}) as Partial<ImageMetadata>;\n\n // Get file-specific metadata\n const fileMetadata = (dirMetadata[filename] ?? {}) as Partial<ImageMetadata>;\n\n // Merge defaults with file-specific metadata\n // File-specific values override defaults\n return this.mergeMetadata(defaults, fileMetadata);\n }\n\n /**\n * Merge two metadata objects, with override taking precedence\n */\n private mergeMetadata(\n defaults: Partial<ImageMetadata>,\n override: Partial<ImageMetadata>\n ): ImageMetadata {\n const result: ImageMetadata = { ...defaults };\n\n // Override with file-specific values\n for (const key of Object.keys(override) as (keyof ImageMetadata)[]) {\n const overrideValue = override[key];\n if (overrideValue !== undefined) {\n if (\n key === \"permissions\" &&\n typeof overrideValue === \"object\" &&\n typeof defaults.permissions === \"object\"\n ) {\n // Merge permissions objects\n result.permissions = {\n ...defaults.permissions,\n ...overrideValue,\n };\n } else if (\n key === \"credits\" &&\n typeof overrideValue === \"object\" &&\n typeof defaults.credits === \"object\"\n ) {\n // Merge credits objects\n result.credits = {\n ...defaults.credits,\n ...overrideValue,\n };\n } else {\n // Direct override for other fields\n (result as Record<string, unknown>)[key] = overrideValue;\n }\n }\n }\n\n return result;\n }\n}\n","import * as fs from \"node:fs/promises\";\nimport * as path from \"node:path\";\nimport imageSize from \"image-size\";\nimport { ImageMetadataLoader } from \"./metadata-loader\";\nimport { IMAGE_EXTENSIONS, DEFAULT_MIN_RESOLUTION } from \"./constants\";\n\n/**\n * Validation result for a single check\n */\nexport interface ImageValidationResult {\n valid: boolean;\n errors: string[];\n warnings: string[];\n}\n\n/**\n * Image dimensions info\n */\nexport interface ImageDimensions {\n width: number;\n height: number;\n type?: string;\n}\n\n/**\n * Options for presentation validation\n */\nexport interface ValidatePresentationOptions {\n checkImages?: boolean;\n checkResolution?: boolean;\n minResolution?: {\n width: number;\n height: number;\n };\n}\n\n/**\n * Image statistics by permission status\n */\nexport interface ImageStats {\n total: number;\n approved: number;\n pending: number;\n restricted: number;\n rejected: number;\n unknown: number;\n}\n\n/**\n * Slide content type (simplified for validation)\n */\ninterface SlideContent {\n template: string;\n content: Record<string, unknown>;\n}\n\n/**\n * Validator for images referenced in presentations\n */\nexport class ImageValidator {\n private metadataLoader: ImageMetadataLoader;\n\n constructor(private baseDir: string = \".\") {\n this.metadataLoader = new ImageMetadataLoader(baseDir);\n }\n\n /**\n * Validate that an image file exists and is a supported format\n */\n async validateImageExists(imagePath: string): Promise<ImageValidationResult> {\n const errors: string[] = [];\n const warnings: string[] = [];\n\n const fullPath = path.join(this.baseDir, imagePath);\n const ext = path.extname(imagePath).toLowerCase();\n\n // Check file extension\n if (!IMAGE_EXTENSIONS.has(ext)) {\n errors.push(`Unsupported image format: ${imagePath}`);\n return { valid: false, errors, warnings };\n }\n\n // Check file exists\n try {\n await fs.access(fullPath);\n } catch {\n errors.push(`Image not found: ${imagePath}`);\n return { valid: false, errors, warnings };\n }\n\n return { valid: true, errors, warnings };\n }\n\n /**\n * Get image dimensions\n */\n async getImageDimensions(imagePath: string): Promise<ImageDimensions | null> {\n const fullPath = path.join(this.baseDir, imagePath);\n\n try {\n const buffer = await fs.readFile(fullPath);\n const dimensions = imageSize(buffer);\n\n if (dimensions.width && dimensions.height) {\n return {\n width: dimensions.width,\n height: dimensions.height,\n ...(dimensions.type ? { type: dimensions.type } : {}),\n };\n }\n return null;\n } catch {\n return null;\n }\n }\n\n /**\n * Validate image resolution\n */\n async validateImageResolution(\n imagePath: string,\n minResolution: { width: number; height: number } = DEFAULT_MIN_RESOLUTION\n ): Promise<ImageValidationResult> {\n const errors: string[] = [];\n const warnings: string[] = [];\n\n const dimensions = await this.getImageDimensions(imagePath);\n\n if (!dimensions) {\n // Can't read dimensions - not an error, might be SVG or unsupported\n return { valid: true, errors, warnings };\n }\n\n const { width, height, type } = dimensions;\n const typeStr = type ? type.toUpperCase() : \"unknown\";\n\n if (width < minResolution.width || height < minResolution.height) {\n warnings.push(\n `Low resolution: ${imagePath} (${width}x${height}, ${typeStr}) - minimum recommended: ${minResolution.width}x${minResolution.height}`\n );\n }\n\n return { valid: true, errors, warnings };\n }\n\n /**\n * Extract all image references from slide content\n */\n extractImageReferences(slides: SlideContent[]): string[] {\n const images = new Set<string>();\n\n for (const slide of slides) {\n const content = slide.content;\n\n // Direct image field (image-text, image-full, image-caption)\n if (typeof content[\"image\"] === \"string\") {\n images.add(content[\"image\"]);\n }\n\n // Images array (gallery)\n const contentImages = content[\"images\"];\n if (Array.isArray(contentImages)) {\n for (const img of contentImages) {\n if (typeof img === \"object\" && img !== null && \"src\" in img) {\n images.add(img.src as string);\n }\n }\n }\n\n // Before/after images\n const beforeObj = content[\"before\"];\n if (typeof beforeObj === \"object\" && beforeObj !== null) {\n const before = beforeObj as Record<string, unknown>;\n if (typeof before[\"image\"] === \"string\") {\n images.add(before[\"image\"]);\n }\n }\n const afterObj = content[\"after\"];\n if (typeof afterObj === \"object\" && afterObj !== null) {\n const after = afterObj as Record<string, unknown>;\n if (typeof after[\"image\"] === \"string\") {\n images.add(after[\"image\"]);\n }\n }\n }\n\n return Array.from(images);\n }\n\n /**\n * Validate all images in a presentation\n */\n async validatePresentation(\n slides: SlideContent[],\n options: ValidatePresentationOptions = {}\n ): Promise<ImageValidationResult> {\n const {\n checkImages = false,\n checkResolution = false,\n minResolution = DEFAULT_MIN_RESOLUTION,\n } = options;\n const errors: string[] = [];\n const warnings: string[] = [];\n\n const imageRefs = this.extractImageReferences(slides);\n\n for (const imagePath of imageRefs) {\n // Check file exists\n const existsResult = await this.validateImageExists(imagePath);\n errors.push(...existsResult.errors);\n warnings.push(...existsResult.warnings);\n\n if (existsResult.valid) {\n // Check resolution if requested\n if (checkResolution) {\n const resResult = await this.validateImageResolution(\n imagePath,\n minResolution\n );\n warnings.push(...resResult.warnings);\n }\n\n // Check permissions if requested\n if (checkImages) {\n const permResult = await this.validateImagePermissions(imagePath);\n errors.push(...permResult.errors);\n warnings.push(...permResult.warnings);\n }\n }\n }\n\n return {\n valid: errors.length === 0,\n errors,\n warnings,\n };\n }\n\n /**\n * Validate image permissions from metadata\n */\n private async validateImagePermissions(\n imagePath: string\n ): Promise<ImageValidationResult> {\n const errors: string[] = [];\n const warnings: string[] = [];\n\n const status = await this.metadataLoader.getPermissionStatus(imagePath);\n\n if (status === null) {\n // No permission info - not an error by default\n return { valid: true, errors, warnings };\n }\n\n switch (status) {\n case \"approved\":\n // All good\n break;\n case \"pending\":\n warnings.push(`Pending permission: ${imagePath}`);\n break;\n case \"restricted\":\n warnings.push(`Restricted: ${imagePath}`);\n break;\n case \"rejected\":\n errors.push(`Rejected: ${imagePath}`);\n break;\n }\n\n return {\n valid: errors.length === 0,\n errors,\n warnings,\n };\n }\n\n /**\n * Get statistics about images by permission status\n */\n async getImageStats(slides: SlideContent[]): Promise<ImageStats> {\n const imageRefs = this.extractImageReferences(slides);\n\n const stats: ImageStats = {\n total: imageRefs.length,\n approved: 0,\n pending: 0,\n restricted: 0,\n rejected: 0,\n unknown: 0,\n };\n\n for (const imagePath of imageRefs) {\n const status = await this.metadataLoader.getPermissionStatus(imagePath);\n\n if (status === null) {\n stats.unknown++;\n } else {\n switch (status) {\n case \"approved\":\n stats.approved++;\n break;\n case \"pending\":\n stats.pending++;\n break;\n case \"restricted\":\n stats.restricted++;\n break;\n case \"rejected\":\n stats.rejected++;\n break;\n }\n }\n }\n\n return stats;\n }\n\n /**\n * Get list of missing images\n */\n async getMissingImages(slides: SlideContent[]): Promise<string[]> {\n const missing: string[] = [];\n const imageRefs = this.extractImageReferences(slides);\n\n for (const imagePath of imageRefs) {\n const result = await this.validateImageExists(imagePath);\n if (!result.valid) {\n missing.push(imagePath);\n }\n }\n\n return missing;\n }\n}\n","import sharp from \"sharp\";\n\n/**\n * Crop options for extracting a region from an image\n */\nexport interface CropOptions {\n left: number;\n top: number;\n width: number;\n height: number;\n}\n\n/**\n * Edge crop options for cropping percentage from edges\n */\nexport interface EdgeCropOptions {\n left?: number | undefined; // Percentage to crop from left (0-50)\n right?: number | undefined; // Percentage to crop from right (0-50)\n top?: number | undefined; // Percentage to crop from top (0-50)\n bottom?: number | undefined; // Percentage to crop from bottom (0-50)\n}\n\n/**\n * Blur region options\n */\nexport interface BlurRegionOptions {\n x: number;\n y: number;\n width: number;\n height: number;\n radius?: number | undefined; // Default: 10\n}\n\n/**\n * Result of image processing operation\n */\nexport interface ProcessResult {\n success: boolean;\n outputPath?: string;\n width?: number;\n height?: number;\n error?: string;\n}\n\n/**\n * Image metadata\n */\nexport interface ImageMetadataInfo {\n width: number;\n height: number;\n format?: string;\n}\n\n/**\n * Image processor for crop and blur operations\n */\nexport class ImageProcessor {\n private readonly defaultBlurRadius = 10;\n\n /**\n * Crop image with specified region\n */\n async crop(\n inputPath: string,\n options: CropOptions,\n outputPath: string\n ): Promise<ProcessResult> {\n try {\n const metadata = await sharp(inputPath).metadata();\n const imgWidth = metadata.width ?? 0;\n const imgHeight = metadata.height ?? 0;\n\n // Validate crop region\n if (\n options.left + options.width > imgWidth ||\n options.top + options.height > imgHeight\n ) {\n return {\n success: false,\n error: `Crop region exceeds image dimensions (${imgWidth}x${imgHeight})`,\n };\n }\n\n await sharp(inputPath)\n .extract({\n left: options.left,\n top: options.top,\n width: options.width,\n height: options.height,\n })\n .toFile(outputPath);\n\n return {\n success: true,\n outputPath,\n width: options.width,\n height: options.height,\n };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n }\n\n /**\n * Crop percentage from specified edges\n */\n async cropEdges(\n inputPath: string,\n options: EdgeCropOptions,\n outputPath: string\n ): Promise<ProcessResult> {\n try {\n // Validate percentages\n const edges = [\n options.left ?? 0,\n options.right ?? 0,\n options.top ?? 0,\n options.bottom ?? 0,\n ];\n for (const edge of edges) {\n if (edge > 50) {\n return {\n success: false,\n error: \"Edge crop percentage cannot exceed 50%\",\n };\n }\n }\n\n const metadata = await sharp(inputPath).metadata();\n const imgWidth = metadata.width ?? 0;\n const imgHeight = metadata.height ?? 0;\n\n const leftPixels = Math.round(imgWidth * ((options.left ?? 0) / 100));\n const rightPixels = Math.round(imgWidth * ((options.right ?? 0) / 100));\n const topPixels = Math.round(imgHeight * ((options.top ?? 0) / 100));\n const bottomPixels = Math.round(\n imgHeight * ((options.bottom ?? 0) / 100)\n );\n\n const newWidth = imgWidth - leftPixels - rightPixels;\n const newHeight = imgHeight - topPixels - bottomPixels;\n\n await sharp(inputPath)\n .extract({\n left: leftPixels,\n top: topPixels,\n width: newWidth,\n height: newHeight,\n })\n .toFile(outputPath);\n\n return {\n success: true,\n outputPath,\n width: newWidth,\n height: newHeight,\n };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n }\n\n /**\n * Apply blur to specified region\n */\n async blurRegion(\n inputPath: string,\n options: BlurRegionOptions,\n outputPath: string\n ): Promise<ProcessResult> {\n try {\n const metadata = await sharp(inputPath).metadata();\n const imgWidth = metadata.width ?? 0;\n const imgHeight = metadata.height ?? 0;\n\n // Validate region\n if (\n options.x + options.width > imgWidth ||\n options.y + options.height > imgHeight\n ) {\n return {\n success: false,\n error: `Blur region exceeds image dimensions (${imgWidth}x${imgHeight})`,\n };\n }\n\n const radius = options.radius ?? this.defaultBlurRadius;\n\n // Extract the region to blur\n const blurredRegion = await sharp(inputPath)\n .extract({\n left: options.x,\n top: options.y,\n width: options.width,\n height: options.height,\n })\n .blur(radius)\n .toBuffer();\n\n // Composite the blurred region back onto the original image\n await sharp(inputPath)\n .composite([\n {\n input: blurredRegion,\n left: options.x,\n top: options.y,\n },\n ])\n .toFile(outputPath);\n\n return {\n success: true,\n outputPath,\n width: imgWidth,\n height: imgHeight,\n };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n }\n\n /**\n * Get image metadata\n */\n async getMetadata(inputPath: string): Promise<ImageMetadataInfo> {\n const metadata = await sharp(inputPath).metadata();\n return {\n width: metadata.width ?? 0,\n height: metadata.height ?? 0,\n format: metadata.format,\n };\n }\n}\n","import * as fs from \"node:fs/promises\";\nimport * as path from \"node:path\";\nimport { ImageMetadataLoader } from \"./metadata-loader\";\nimport { ImageProcessor } from \"./processor\";\nimport { isImageFile } from \"./constants\";\nimport type { ImageProcessingInstruction } from \"./processing-schema\";\n\n/**\n * Result of processing a single image\n */\nexport interface ProcessImageResult {\n success: boolean;\n originalPath: string;\n processedPath?: string;\n skipped?: boolean;\n instructionsApplied?: number;\n error?: string;\n}\n\n/**\n * Result of processing a directory of images\n */\nexport interface ProcessDirectoryResult {\n totalImages: number;\n processedImages: number;\n skippedImages: number;\n errors: string[];\n imageMap: Map<string, string>; // original -> processed path mapping\n}\n\n/**\n * Options for the processing pipeline\n */\nexport interface ProcessingPipelineOptions {\n outputDir?: string;\n}\n\n/**\n * Pipeline for processing images based on metadata instructions\n */\nexport class ImageProcessingPipeline {\n private metadataLoader: ImageMetadataLoader;\n private processor: ImageProcessor;\n private outputDir: string;\n\n constructor(\n private baseDir: string,\n options?: ProcessingPipelineOptions\n ) {\n this.metadataLoader = new ImageMetadataLoader(baseDir);\n this.processor = new ImageProcessor();\n this.outputDir = options?.outputDir ?? path.join(baseDir, \".processed\");\n }\n\n /**\n * Process a single image based on its metadata instructions\n */\n async processImage(imagePath: string): Promise<ProcessImageResult> {\n const fullPath = path.join(this.baseDir, imagePath);\n const result: ProcessImageResult = {\n success: true,\n originalPath: fullPath,\n };\n\n try {\n // Load metadata\n const metadata = await this.metadataLoader.load(imagePath);\n\n // Check if processing instructions exist\n if (!metadata.processing || metadata.processing.length === 0) {\n result.skipped = true;\n return result;\n }\n\n // Ensure output directory exists\n await fs.mkdir(this.outputDir, { recursive: true });\n\n // Process image with each instruction\n const processedPath = await this.applyInstructions(\n fullPath,\n imagePath,\n metadata.processing\n );\n\n result.processedPath = processedPath;\n result.instructionsApplied = metadata.processing.length;\n return result;\n } catch (error) {\n return {\n success: false,\n originalPath: fullPath,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n }\n\n /**\n * Process all images in a directory\n */\n async processDirectory(): Promise<ProcessDirectoryResult> {\n const result: ProcessDirectoryResult = {\n totalImages: 0,\n processedImages: 0,\n skippedImages: 0,\n errors: [],\n imageMap: new Map(),\n };\n\n try {\n // Get all image files in directory\n const files = await fs.readdir(this.baseDir);\n const imageFiles = files.filter((f) => isImageFile(f));\n result.totalImages = imageFiles.length;\n\n // Process each image\n for (const imageFile of imageFiles) {\n const imageResult = await this.processImage(imageFile);\n\n if (!imageResult.success) {\n result.errors.push(`${imageFile}: ${imageResult.error}`);\n } else if (imageResult.skipped) {\n result.skippedImages++;\n } else if (imageResult.processedPath) {\n result.processedImages++;\n result.imageMap.set(imageResult.originalPath, imageResult.processedPath);\n }\n }\n\n return result;\n } catch (error) {\n result.errors.push(error instanceof Error ? error.message : String(error));\n return result;\n }\n }\n\n /**\n * Apply processing instructions to an image\n */\n private async applyInstructions(\n inputPath: string,\n relativePath: string,\n instructions: ImageProcessingInstruction[]\n ): Promise<string> {\n const outputFilename = path.basename(relativePath);\n const finalOutputPath = path.join(this.outputDir, outputFilename);\n\n // Use two temp files alternately for intermediate processing\n // This ensures input and output are always different files\n const tempPaths = [\n path.join(this.outputDir, `temp_${outputFilename}`),\n path.join(this.outputDir, `temp2_${outputFilename}`),\n ];\n let currentInputPath = inputPath;\n\n for (let i = 0; i < instructions.length; i++) {\n const instruction = instructions[i]!;\n const isLast = i === instructions.length - 1;\n const outputPath = isLast ? finalOutputPath : tempPaths[i % 2]!;\n\n await this.applyInstruction(currentInputPath, outputPath, instruction);\n\n // For next iteration, use the output as input\n if (!isLast) {\n currentInputPath = outputPath;\n }\n }\n\n // Clean up temp files\n try {\n await fs.unlink(path.join(this.outputDir, `temp_${outputFilename}`));\n } catch {\n // Ignore if doesn't exist\n }\n try {\n await fs.unlink(path.join(this.outputDir, `temp2_${outputFilename}`));\n } catch {\n // Ignore if doesn't exist\n }\n\n return finalOutputPath;\n }\n\n /**\n * Apply a single processing instruction\n */\n private async applyInstruction(\n inputPath: string,\n outputPath: string,\n instruction: ImageProcessingInstruction\n ): Promise<void> {\n switch (instruction.type) {\n case \"crop\":\n await this.applyCrop(inputPath, outputPath, instruction);\n break;\n case \"blur\":\n await this.applyBlur(inputPath, outputPath, instruction);\n break;\n }\n }\n\n /**\n * Apply crop instruction\n */\n private async applyCrop(\n inputPath: string,\n outputPath: string,\n instruction: ImageProcessingInstruction & { type: \"crop\" }\n ): Promise<void> {\n if (instruction.edges) {\n const result = await this.processor.cropEdges(\n inputPath,\n instruction.edges,\n outputPath\n );\n if (!result.success) {\n throw new Error(result.error);\n }\n } else if (instruction.region) {\n const result = await this.processor.crop(\n inputPath,\n {\n left: instruction.region.x,\n top: instruction.region.y,\n width: instruction.region.width,\n height: instruction.region.height,\n },\n outputPath\n );\n if (!result.success) {\n throw new Error(result.error);\n }\n }\n }\n\n /**\n * Apply blur instruction\n */\n private async applyBlur(\n inputPath: string,\n outputPath: string,\n instruction: ImageProcessingInstruction & { type: \"blur\" }\n ): Promise<void> {\n const result = await this.processor.blurRegion(\n inputPath,\n {\n x: instruction.region.x,\n y: instruction.region.y,\n width: instruction.region.width,\n height: instruction.region.height,\n radius: instruction.radius,\n },\n outputPath\n );\n if (!result.success) {\n throw new Error(result.error);\n }\n }\n}\n","import { Command } from 'commander';\nimport { access, readFile } from 'fs/promises';\nimport { dirname } from 'path';\nimport chalk from 'chalk';\nimport ora from 'ora';\nimport { parse as parseYaml, stringify as yamlStringify } from 'yaml';\nimport { Parser, ParseError, ValidationError, type ParseResultWithLines } from '../../core/parser';\nimport { TemplateLoader } from '../../templates/loader';\nimport { IconRegistryLoader } from '../../icons/registry';\nimport { ConfigLoader } from '../../config/loader';\nimport { ExitCode } from './convert';\n\n/**\n * Validation result structure\n */\ninterface ValidationResult {\n valid: boolean;\n errors: string[];\n warnings: string[];\n structuredErrors: StructuredValidationError[];\n slideLines: number[];\n stats: {\n yamlSyntax: boolean;\n metaValid: boolean;\n slideCount: number;\n templatesFound: boolean;\n iconsResolved: boolean;\n referencesCount: number;\n };\n}\n\ninterface ValidateOptions {\n config?: string;\n strict?: boolean;\n format?: 'text' | 'json' | 'llm';\n}\n\n/**\n * Structured validation error for LLM-friendly output\n */\nexport interface StructuredValidationError {\n slide: number;\n line?: number;\n template: string;\n field?: string;\n message: string;\n errorType: 'missing_field' | 'invalid_type' | 'unknown_template' | 'unknown_icon' | 'schema_error';\n fixExample?: string;\n}\n\n/**\n * Get contextual hint based on error type\n */\nexport function getHintForErrorType(errorType: string): string | null {\n switch (errorType) {\n case 'unknown_template':\n return 'Run `slide-gen templates list --format llm` to see available templates.';\n case 'unknown_icon':\n return 'Run `slide-gen icons search <query>` to find icons.';\n default:\n return null;\n }\n}\n\n/**\n * Format validation result for LLM consumption\n */\nexport function formatLlmValidationResult(\n errors: StructuredValidationError[],\n slideCount: number\n): string {\n if (errors.length === 0) {\n return `Validation passed. ${slideCount} slides validated.`;\n }\n\n const lines: string[] = ['Validation failed.', ''];\n\n for (let i = 0; i < errors.length; i++) {\n const error = errors[i]!;\n\n // Error header with line number (if available) and template\n const lineInfo = error.line ? `line ${error.line}, ` : '';\n lines.push(`Error at ${lineInfo}Slide ${error.slide} (${error.template}):`);\n lines.push(` ${error.message}`);\n\n // Fix example (if available)\n if (error.fixExample) {\n lines.push('');\n lines.push('Fix:');\n const exampleLines = error.fixExample.split('\\n');\n for (const line of exampleLines) {\n lines.push(` ${line}`);\n }\n }\n\n // Hint based on error type\n const hint = getHintForErrorType(error.errorType);\n if (hint) {\n lines.push('');\n lines.push(`Hint: ${hint}`);\n }\n\n // Separator between errors\n if (i < errors.length - 1) {\n lines.push('');\n lines.push('---');\n lines.push('');\n }\n }\n\n return lines.join('\\n');\n}\n\n/**\n * Format an example object as YAML string with indentation\n */\nfunction formatExampleAsYaml(example: Record<string, unknown>, indent: number): string {\n const yaml = yamlStringify(example, { indent: 2 });\n const spaces = ' '.repeat(indent);\n return yaml\n .split('\\n')\n .filter(line => line.trim() !== '')\n .map(line => spaces + line)\n .join('\\n');\n}\n\n/**\n * Create the validate command\n */\nexport function createValidateCommand(): Command {\n return new Command('validate')\n .description('Validate source file without conversion')\n .argument('<input>', 'Input YAML file')\n .option('-c, --config <path>', 'Config file path')\n .option('--strict', 'Treat warnings as errors')\n .option('--format <fmt>', 'Output format (text/json/llm)', 'text')\n .action(async (input: string, options: ValidateOptions) => {\n await executeValidate(input, options);\n });\n}\n\n/**\n * Execute the validate command\n */\nasync function executeValidate(\n inputPath: string,\n options: ValidateOptions\n): Promise<void> {\n const isJsonFormat = options.format === 'json';\n const isLlmFormat = options.format === 'llm';\n const spinner = (isJsonFormat || isLlmFormat) ? null : ora();\n\n const result: ValidationResult = {\n valid: true,\n errors: [],\n warnings: [],\n structuredErrors: [],\n slideLines: [],\n stats: {\n yamlSyntax: false,\n metaValid: false,\n slideCount: 0,\n templatesFound: false,\n iconsResolved: false,\n referencesCount: 0,\n },\n };\n\n try {\n // Check file exists\n spinner?.start(`Validating ${inputPath}...`);\n try {\n await access(inputPath);\n } catch {\n spinner?.fail(`File not found: ${inputPath}`);\n result.errors.push(`File not found: ${inputPath}`);\n result.valid = false;\n outputResult(result, options);\n process.exitCode = ExitCode.FileReadError;\n return;\n }\n\n // Read file content\n const content = await readFile(inputPath, 'utf-8');\n\n // Step 1: YAML syntax check\n try {\n parseYaml(content);\n result.stats.yamlSyntax = true;\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Unknown error';\n result.errors.push(`YAML syntax error: ${message}`);\n result.valid = false;\n spinner?.fail('YAML syntax invalid');\n outputResult(result, options);\n process.exitCode = ExitCode.ValidationError;\n return;\n }\n\n // Step 2: Schema validation with line info\n const parser = new Parser();\n let presentation: ParseResultWithLines;\n try {\n presentation = parser.parseWithLineInfo(content);\n result.stats.metaValid = true;\n result.stats.slideCount = presentation.slides.length;\n result.slideLines = presentation.slideLines;\n } catch (error) {\n if (error instanceof ParseError) {\n result.errors.push(`Parse error: ${error.message}`);\n } else if (error instanceof ValidationError) {\n result.errors.push(`Schema validation error: ${error.message}`);\n } else {\n const message = error instanceof Error ? error.message : 'Unknown error';\n result.errors.push(`Schema error: ${message}`);\n }\n result.valid = false;\n spinner?.fail('Schema validation failed');\n outputResult(result, options);\n process.exitCode = ExitCode.ValidationError;\n return;\n }\n\n // Load configuration\n const configLoader = new ConfigLoader();\n let configPath = options.config;\n\n if (!configPath) {\n configPath = await configLoader.findConfig(dirname(inputPath));\n }\n\n const config = await configLoader.load(configPath);\n\n // Step 3: Template validation\n const templateLoader = new TemplateLoader();\n try {\n await templateLoader.loadBuiltIn(config.templates.builtin);\n if (config.templates.custom) {\n try {\n await templateLoader.loadCustom(config.templates.custom);\n } catch {\n // Custom templates directory may not exist\n }\n }\n } catch (error) {\n result.warnings.push(\n `Could not load templates: ${error instanceof Error ? error.message : 'Unknown error'}`\n );\n }\n\n // Check all templates exist\n const missingTemplates: string[] = [];\n for (let i = 0; i < presentation.slides.length; i++) {\n const slide = presentation.slides[i]!;\n const slideNumber = i + 1;\n const slideLine = result.slideLines[i];\n const template = templateLoader.get(slide.template);\n\n if (!template) {\n missingTemplates.push(`Slide ${slideNumber}: Template \"${slide.template}\" not found`);\n const structuredError: StructuredValidationError = {\n slide: slideNumber,\n template: slide.template,\n message: `Template \"${slide.template}\" not found`,\n errorType: 'unknown_template',\n };\n if (slideLine !== undefined) {\n structuredError.line = slideLine;\n }\n result.structuredErrors.push(structuredError);\n } else {\n // Validate slide content against template schema\n const validationResult = templateLoader.validateContent(\n slide.template,\n slide.content\n );\n if (!validationResult.valid) {\n for (const err of validationResult.errors) {\n result.errors.push(`Slide ${slideNumber} (${slide.template}): ${err}`);\n\n // Determine error type and extract field from error message\n const isMissingField = err.toLowerCase().includes('required') || err.toLowerCase().includes('missing');\n const isInvalidType = err.toLowerCase().includes('type') || err.toLowerCase().includes('invalid');\n\n // Try to extract field name from error message\n const fieldMatch = err.match(/(?:field|property)\\s+['\"]?(\\w+)['\"]?/i) ||\n err.match(/^(\\w+)\\s+is\\s+required/i);\n const field = fieldMatch?.[1];\n\n // Get fix example from template\n const fixExample = template.example ?\n `content:\\n${formatExampleAsYaml(template.example, 2)}` : undefined;\n\n const structuredError: StructuredValidationError = {\n slide: slideNumber,\n template: slide.template,\n message: err,\n errorType: isMissingField ? 'missing_field' : isInvalidType ? 'invalid_type' : 'schema_error',\n };\n if (slideLine !== undefined) {\n structuredError.line = slideLine;\n }\n if (field !== undefined) {\n structuredError.field = field;\n }\n if (fixExample !== undefined) {\n structuredError.fixExample = fixExample;\n }\n result.structuredErrors.push(structuredError);\n }\n }\n }\n }\n\n if (missingTemplates.length > 0) {\n for (const msg of missingTemplates) {\n result.errors.push(msg);\n }\n result.valid = false;\n } else {\n result.stats.templatesFound = true;\n }\n\n // Step 4: Icon validation (check for icon references in content)\n const iconRegistry = new IconRegistryLoader();\n try {\n await iconRegistry.load(config.icons.registry);\n result.stats.iconsResolved = true;\n } catch (error) {\n result.warnings.push(\n `Could not load icon registry: ${error instanceof Error ? error.message : 'Unknown error'}`\n );\n }\n\n // Check icon references in slide content (simple pattern matching)\n const iconPattern = /icon\\(['\"]([^'\"]+)['\"]\\)/g;\n for (let i = 0; i < presentation.slides.length; i++) {\n const slide = presentation.slides[i]!;\n const slideNumber = i + 1;\n const slideLine = result.slideLines[i];\n const contentStr = JSON.stringify(slide.content);\n for (const match of contentStr.matchAll(iconPattern)) {\n const iconRef = match[1]!;\n // Try to resolve the icon\n const resolved = iconRegistry.resolveAlias(iconRef);\n const parsed = iconRegistry.parseIconReference(resolved);\n if (parsed) {\n const source = iconRegistry.getSource(parsed.prefix);\n if (!source) {\n result.warnings.push(\n `Slide ${slideNumber}: Unknown icon source \"${parsed.prefix}\" in \"${iconRef}\"`\n );\n const structuredError: StructuredValidationError = {\n slide: slideNumber,\n template: slide.template,\n message: `Unknown icon source \"${parsed.prefix}\" in \"${iconRef}\"`,\n errorType: 'unknown_icon',\n };\n if (slideLine !== undefined) {\n structuredError.line = slideLine;\n }\n result.structuredErrors.push(structuredError);\n }\n } else if (!iconRegistry.resolveAlias(iconRef)) {\n result.warnings.push(`Slide ${slideNumber}: Unknown icon \"${iconRef}\"`);\n const structuredError: StructuredValidationError = {\n slide: slideNumber,\n template: slide.template,\n message: `Unknown icon \"${iconRef}\"`,\n errorType: 'unknown_icon',\n };\n if (slideLine !== undefined) {\n structuredError.line = slideLine;\n }\n result.structuredErrors.push(structuredError);\n }\n }\n }\n\n // Step 5: Reference validation\n const citationPattern = /@([a-zA-Z0-9_-]+)/g;\n const references: Set<string> = new Set();\n for (const slide of presentation.slides) {\n const contentStr = JSON.stringify(slide.content);\n for (const match of contentStr.matchAll(citationPattern)) {\n references.add(match[1]!);\n }\n }\n result.stats.referencesCount = references.size;\n\n // Final validation result\n if (result.errors.length > 0) {\n result.valid = false;\n }\n\n // Strict mode: warnings become errors\n if (options.strict && result.warnings.length > 0) {\n result.valid = false;\n result.errors.push(...result.warnings);\n result.warnings = [];\n }\n\n // Output result\n if (result.valid) {\n spinner?.succeed(`Validated ${inputPath}`);\n } else {\n spinner?.fail(`Validation failed for ${inputPath}`);\n }\n\n outputResult(result, options);\n\n if (!result.valid) {\n process.exitCode = ExitCode.ValidationError;\n }\n } catch (error) {\n spinner?.fail('Validation failed');\n result.errors.push(\n `Unexpected error: ${error instanceof Error ? error.message : 'Unknown error'}`\n );\n result.valid = false;\n outputResult(result, options);\n process.exitCode = ExitCode.GeneralError;\n }\n}\n\n/**\n * Output validation result in the specified format\n */\nfunction outputResult(result: ValidationResult, options: ValidateOptions): void {\n if (options.format === 'json') {\n console.log(\n JSON.stringify(\n {\n valid: result.valid,\n errors: result.errors,\n warnings: result.warnings,\n stats: result.stats,\n },\n null,\n 2\n )\n );\n return;\n }\n\n if (options.format === 'llm') {\n // LLM-friendly output format\n const llmOutput = formatLlmValidationResult(\n result.structuredErrors,\n result.stats.slideCount\n );\n console.log(llmOutput);\n return;\n }\n\n // Text format output\n console.log('');\n\n // Stats\n if (result.stats.yamlSyntax) {\n console.log(chalk.green('✓') + ' YAML syntax valid');\n } else {\n console.log(chalk.red('✗') + ' YAML syntax invalid');\n }\n\n if (result.stats.metaValid) {\n console.log(chalk.green('✓') + ' Meta section valid');\n }\n\n if (result.stats.slideCount > 0) {\n console.log(chalk.green('✓') + ` ${result.stats.slideCount} slides validated`);\n }\n\n if (result.stats.templatesFound) {\n console.log(chalk.green('✓') + ' All templates found');\n }\n\n if (result.stats.iconsResolved) {\n console.log(chalk.green('✓') + ' All icons resolved');\n }\n\n if (result.stats.referencesCount > 0) {\n console.log(chalk.green('✓') + ` ${result.stats.referencesCount} references found`);\n }\n\n // Errors\n for (const error of result.errors) {\n console.log(chalk.red('✗') + ` ${error}`);\n }\n\n // Warnings\n for (const warning of result.warnings) {\n console.log(chalk.yellow('⚠') + ` ${warning}`);\n }\n\n // Summary\n console.log('');\n if (result.valid) {\n console.log(chalk.green('Validation passed!'));\n } else {\n const errorCount = result.errors.length;\n const warningCount = result.warnings.length;\n let summary = `Validation failed with ${errorCount} error${errorCount !== 1 ? 's' : ''}`;\n if (warningCount > 0) {\n summary += ` and ${warningCount} warning${warningCount !== 1 ? 's' : ''}`;\n }\n console.log(chalk.red(summary));\n }\n}\n","import { Command } from 'commander';\nimport chalk from 'chalk';\nimport * as yaml from 'yaml';\nimport { mkdir, writeFile, rm } from 'fs/promises';\nimport { join, basename } from 'path';\nimport { tmpdir } from 'os';\nimport type { Server } from 'http';\nimport { TemplateLoader, type TemplateDefinition } from '../../templates';\nimport { ConfigLoader } from '../../config/loader';\nimport { Pipeline, PipelineError } from '../../core/pipeline';\nimport { ExitCode } from './convert';\nimport { collectSlideInfo, startStaticServer, checkMarpCliAvailable } from './preview';\nimport { runMarp } from '../utils/marp-runner';\n\ntype OutputFormat = 'table' | 'json' | 'llm';\ntype InfoFormat = 'text' | 'json' | 'llm';\n\ninterface ListOptions {\n category?: string;\n format?: OutputFormat;\n config?: string;\n}\n\ninterface InfoOptions {\n format?: InfoFormat;\n config?: string;\n}\n\ninterface ExampleOptions {\n config?: string;\n}\n\n/**\n * Format template list for table output\n */\nfunction formatTableList(templates: TemplateDefinition[]): string {\n const byCategory = new Map<string, TemplateDefinition[]>();\n\n for (const template of templates) {\n const cat = template.category;\n if (!byCategory.has(cat)) {\n byCategory.set(cat, []);\n }\n byCategory.get(cat)!.push(template);\n }\n\n const lines: string[] = ['Templates:', ''];\n\n // Sort categories alphabetically\n const sortedCategories = Array.from(byCategory.keys()).sort();\n\n for (const category of sortedCategories) {\n lines.push(`${category}/`);\n const categoryTemplates = byCategory.get(category)!;\n\n // Sort templates by name within category\n categoryTemplates.sort((a, b) => a.name.localeCompare(b.name));\n\n for (const template of categoryTemplates) {\n // Pad name to align descriptions\n const paddedName = template.name.padEnd(16);\n lines.push(` ${paddedName}${template.description}`);\n }\n lines.push('');\n }\n\n return lines.join('\\n');\n}\n\n/**\n * Format template list for JSON output\n */\nfunction formatJsonList(templates: TemplateDefinition[]): string {\n const output = templates.map((t) => ({\n name: t.name,\n description: t.description,\n category: t.category,\n }));\n return JSON.stringify(output, null, 2);\n}\n\n/**\n * Format template list for LLM output\n */\nfunction formatLlmList(templates: TemplateDefinition[]): string {\n const byCategory = new Map<string, TemplateDefinition[]>();\n\n for (const template of templates) {\n const cat = template.category;\n if (!byCategory.has(cat)) {\n byCategory.set(cat, []);\n }\n byCategory.get(cat)!.push(template);\n }\n\n const lines: string[] = [];\n\n // Sort categories alphabetically\n const sortedCategories = Array.from(byCategory.keys()).sort();\n\n for (const category of sortedCategories) {\n lines.push(`[${category}]`);\n const categoryTemplates = byCategory.get(category)!;\n\n // Sort templates by name within category\n categoryTemplates.sort((a, b) => a.name.localeCompare(b.name));\n\n for (const template of categoryTemplates) {\n lines.push(`${template.name}: ${template.description}`);\n }\n lines.push('');\n }\n\n return lines.join('\\n').trim();\n}\n\n/**\n * Format template list in the specified format\n */\nexport function formatTemplateList(\n templates: TemplateDefinition[],\n format: OutputFormat\n): string {\n switch (format) {\n case 'json':\n return formatJsonList(templates);\n case 'llm':\n return formatLlmList(templates);\n case 'table':\n default:\n return formatTableList(templates);\n }\n}\n\n/**\n * Format schema property for text output\n */\nfunction formatSchemaProperty(\n name: string,\n prop: Record<string, unknown>,\n required: boolean,\n indent: string\n): string[] {\n const lines: string[] = [];\n const type = (prop['type'] as string) ?? 'unknown';\n const requiredStr = required ? ', required' : '';\n const description = prop['description'] as string | undefined;\n\n lines.push(`${indent}${name} (${type}${requiredStr})`);\n if (description) {\n lines.push(`${indent} ${description}`);\n }\n\n // Handle nested objects\n if (type === 'object' && prop['properties']) {\n const nestedRequired = (prop['required'] as string[]) ?? [];\n const properties = prop['properties'] as Record<string, Record<string, unknown>>;\n for (const [propName, propDef] of Object.entries(properties)) {\n lines.push(\n ...formatSchemaProperty(propName, propDef, nestedRequired.includes(propName), indent + ' ')\n );\n }\n }\n\n // Handle array items\n if (type === 'array' && prop['items']) {\n const items = prop['items'] as Record<string, unknown>;\n if (items['type'] === 'object' && items['properties']) {\n const itemRequired = (items['required'] as string[]) ?? [];\n const itemProps = items['properties'] as Record<string, Record<string, unknown>>;\n lines.push(`${indent} Items:`);\n for (const [propName, propDef] of Object.entries(itemProps)) {\n lines.push(\n ...formatSchemaProperty(propName, propDef, itemRequired.includes(propName), indent + ' ')\n );\n }\n }\n }\n\n return lines;\n}\n\n/**\n * Format template info for text output\n */\nfunction formatTextInfo(template: TemplateDefinition): string {\n const lines: string[] = [\n `Template: ${template.name}`,\n `Description: ${template.description}`,\n `Category: ${template.category}`,\n '',\n 'Schema:',\n ];\n\n const schema = template.schema as {\n type?: string;\n required?: string[];\n properties?: Record<string, Record<string, unknown>>;\n };\n\n if (schema.properties) {\n const required = schema.required ?? [];\n for (const [name, prop] of Object.entries(schema.properties)) {\n lines.push(...formatSchemaProperty(name, prop, required.includes(name), ' '));\n }\n }\n\n if (template.example) {\n lines.push('', 'Example:');\n const exampleYaml = yaml.stringify(template.example, { indent: 2 });\n lines.push(\n ...exampleYaml\n .split('\\n')\n .filter((l) => l.trim())\n .map((l) => ` ${l}`)\n );\n }\n\n return lines.join('\\n');\n}\n\n/**\n * Format template info for JSON output\n */\nfunction formatJsonInfo(template: TemplateDefinition): string {\n return JSON.stringify(\n {\n name: template.name,\n description: template.description,\n category: template.category,\n schema: template.schema,\n example: template.example,\n },\n null,\n 2\n );\n}\n\n/**\n * Format template info for LLM output\n */\nfunction formatLlmInfo(template: TemplateDefinition): string {\n const lines: string[] = [\n `Template: ${template.name}`,\n `Description: ${template.description}`,\n `Category: ${template.category}`,\n '',\n 'Schema:',\n ];\n\n const schema = template.schema as {\n type?: string;\n required?: string[];\n properties?: Record<string, Record<string, unknown>>;\n };\n\n if (schema.properties) {\n const required = schema.required ?? [];\n for (const [name, prop] of Object.entries(schema.properties)) {\n const type = (prop['type'] as string) ?? 'unknown';\n const reqStr = required.includes(name) ? ', required' : '';\n lines.push(` ${name} (${type}${reqStr})`);\n\n const description = prop['description'] as string | undefined;\n if (description) {\n lines.push(` ${description}`);\n }\n }\n }\n\n if (template.example) {\n lines.push('', 'Example:');\n const exampleYaml = yaml.stringify(\n { template: template.name, content: template.example },\n { indent: 2 }\n );\n lines.push(\n ...exampleYaml\n .split('\\n')\n .filter((l) => l.trim())\n .map((l) => ` ${l}`)\n );\n }\n\n return lines.join('\\n');\n}\n\n/**\n * Format template info in the specified format\n */\nexport function formatTemplateInfo(\n template: TemplateDefinition,\n format: InfoFormat\n): string {\n switch (format) {\n case 'json':\n return formatJsonInfo(template);\n case 'llm':\n return formatLlmInfo(template);\n case 'text':\n default:\n return formatTextInfo(template);\n }\n}\n\n/**\n * Format template example as slide YAML\n */\nexport function formatTemplateExample(template: TemplateDefinition): string {\n const slideYaml = yaml.stringify(\n [{ template: template.name, content: template.example ?? {} }],\n { indent: 2 }\n );\n return slideYaml;\n}\n\n/**\n * Load templates from config\n */\nasync function loadTemplates(configPath?: string): Promise<TemplateLoader> {\n const configLoader = new ConfigLoader();\n\n if (!configPath) {\n configPath = await configLoader.findConfig(process.cwd());\n }\n\n const config = await configLoader.load(configPath);\n const templateLoader = new TemplateLoader();\n\n try {\n await templateLoader.loadBuiltIn(config.templates.builtin);\n } catch {\n // Built-in templates may not exist in some environments\n }\n\n if (config.templates.custom) {\n try {\n await templateLoader.loadCustom(config.templates.custom);\n } catch {\n // Custom templates directory may not exist\n }\n }\n\n return templateLoader;\n}\n\n/**\n * Create the templates list subcommand\n */\nfunction createListCommand(): Command {\n return new Command('list')\n .description('List available templates')\n .option('--category <cat>', 'Filter by category')\n .option('--format <fmt>', 'Output format (table/json/llm)', 'table')\n .option('-c, --config <path>', 'Config file path')\n .action(async (options: ListOptions) => {\n try {\n const templateLoader = await loadTemplates(options.config);\n\n let templates = templateLoader.list();\n\n if (options.category) {\n templates = templateLoader.listByCategory(options.category);\n }\n\n if (templates.length === 0) {\n if (options.format === 'json') {\n console.log('[]');\n } else {\n console.log('No templates found.');\n }\n return;\n }\n\n const format = (options.format ?? 'table') as OutputFormat;\n const output = formatTemplateList(templates, format);\n console.log(output);\n } catch (error) {\n console.error(\n chalk.red(`Error: ${error instanceof Error ? error.message : 'Unknown error'}`)\n );\n process.exitCode = ExitCode.GeneralError;\n }\n });\n}\n\n/**\n * Create the templates info subcommand\n */\nfunction createInfoCommand(): Command {\n return new Command('info')\n .description('Show template details')\n .argument('<name>', 'Template name')\n .option('--format <fmt>', 'Output format (text/json/llm)', 'text')\n .option('-c, --config <path>', 'Config file path')\n .action(async (name: string, options: InfoOptions) => {\n try {\n const templateLoader = await loadTemplates(options.config);\n const template = templateLoader.get(name);\n\n if (!template) {\n console.error(chalk.red(`Error: Template \"${name}\" not found`));\n process.exitCode = ExitCode.GeneralError;\n return;\n }\n\n const format = (options.format ?? 'text') as InfoFormat;\n const output = formatTemplateInfo(template, format);\n console.log(output);\n } catch (error) {\n console.error(\n chalk.red(`Error: ${error instanceof Error ? error.message : 'Unknown error'}`)\n );\n process.exitCode = ExitCode.GeneralError;\n }\n });\n}\n\n/**\n * Create the templates example subcommand\n */\nfunction createExampleCommand(): Command {\n return new Command('example')\n .description('Output example YAML for a template')\n .argument('<name>', 'Template name')\n .option('-c, --config <path>', 'Config file path')\n .action(async (name: string, options: ExampleOptions) => {\n try {\n const templateLoader = await loadTemplates(options.config);\n const template = templateLoader.get(name);\n\n if (!template) {\n console.error(chalk.red(`Error: Template \"${name}\" not found`));\n process.exitCode = ExitCode.GeneralError;\n return;\n }\n\n const output = formatTemplateExample(template);\n console.log(output);\n } catch (error) {\n console.error(\n chalk.red(`Error: ${error instanceof Error ? error.message : 'Unknown error'}`)\n );\n process.exitCode = ExitCode.GeneralError;\n }\n });\n}\n\ninterface PreviewOptions {\n all?: boolean;\n category?: string;\n port?: number;\n config?: string;\n}\n\n/**\n * Create the templates preview subcommand\n */\nfunction createPreviewSubcommand(): Command {\n return new Command('preview')\n .description('Preview template in browser')\n .argument('[name]', 'Template name')\n .option('--all', 'Show all templates')\n .option('--category <cat>', 'Filter by category')\n .option('-p, --port <number>', 'Preview server port', '8080')\n .option('-c, --config <path>', 'Config file path')\n .action(async (name: string | undefined, options: PreviewOptions) => {\n try {\n await executeTemplatePreview(name, options);\n } catch (error) {\n console.error(\n chalk.red(`Error: ${error instanceof Error ? error.message : 'Unknown error'}`)\n );\n process.exitCode = ExitCode.GeneralError;\n }\n });\n}\n\n/**\n * Template preview information with schema details\n */\ninterface TemplatePreviewInfo {\n template: TemplateDefinition;\n imagePath: string;\n}\n\n/**\n * Escape HTML special characters to prevent XSS\n */\nfunction escapeHtml(str: string): string {\n return str\n .replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;')\n .replace(/'/g, '&#39;');\n}\n\n/**\n * Format schema property for HTML display\n */\nfunction formatSchemaPropertyHtml(\n name: string,\n prop: Record<string, unknown>,\n required: boolean\n): string {\n const type = (prop['type'] as string) ?? 'unknown';\n const description = prop['description'] as string | undefined;\n const requiredBadge = required\n ? '<span class=\"badge required\">required</span>'\n : '<span class=\"badge optional\">optional</span>';\n\n return `\n <div class=\"param\">\n <div class=\"param-header\">\n <code class=\"param-name\">${escapeHtml(name)}</code>\n <span class=\"param-type\">${escapeHtml(type)}</span>\n ${requiredBadge}\n </div>\n ${description ? `<div class=\"param-desc\">${escapeHtml(description)}</div>` : ''}\n </div>\n `;\n}\n\n/**\n * Generate HTML for template preview with parameter information\n */\nfunction generateTemplatePreviewHtml(previews: TemplatePreviewInfo[]): string {\n const templateCards = previews\n .map((p) => {\n const schema = p.template.schema as {\n type?: string;\n required?: string[];\n properties?: Record<string, Record<string, unknown>>;\n };\n\n const requiredFields = schema.required ?? [];\n const properties = schema.properties ?? {};\n\n const paramsHtml = Object.entries(properties)\n .map(([name, prop]) =>\n formatSchemaPropertyHtml(name, prop, requiredFields.includes(name))\n )\n .join('');\n\n return `\n <div class=\"template-card\">\n <div class=\"template-preview\">\n <img src=\"${escapeHtml(p.imagePath)}\" alt=\"${escapeHtml(p.template.name)}\" class=\"template-img\" data-template=\"${escapeHtml(p.template.name)}\">\n </div>\n <div class=\"template-info\">\n <h2 class=\"template-name\">${escapeHtml(p.template.name)}</h2>\n <p class=\"template-desc\">${escapeHtml(p.template.description)}</p>\n <div class=\"template-category\">Category: <code>${escapeHtml(p.template.category)}</code></div>\n <div class=\"template-params\">\n <h3>Parameters</h3>\n ${paramsHtml || '<p class=\"no-params\">No parameters</p>'}\n </div>\n </div>\n </div>\n `;\n })\n .join('');\n\n return `<!DOCTYPE html>\n<html>\n<head>\n <title>Template Preview</title>\n <style>\n * { box-sizing: border-box; margin: 0; padding: 0; }\n body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: #f5f5f5; color: #333; }\n h1 { text-align: center; padding: 24px; background: #fff; border-bottom: 1px solid #ddd; }\n .container { max-width: 1200px; margin: 0 auto; padding: 24px; }\n .template-card { display: grid; grid-template-columns: 1fr 1fr; gap: 24px; background: #fff; border-radius: 12px; padding: 24px; margin-bottom: 24px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); }\n .template-preview { display: flex; align-items: center; justify-content: center; }\n .template-img { max-width: 100%; height: auto; border: 1px solid #ddd; border-radius: 8px; cursor: pointer; transition: transform 0.2s; }\n .template-img:hover { transform: scale(1.02); }\n .template-info { padding: 12px 0; }\n .template-name { font-size: 24px; margin-bottom: 8px; color: #1a1a1a; }\n .template-desc { color: #666; margin-bottom: 16px; font-size: 16px; }\n .template-category { margin-bottom: 16px; font-size: 14px; color: #888; }\n .template-category code { background: #e8e8e8; padding: 2px 8px; border-radius: 4px; }\n .template-params h3 { font-size: 16px; margin-bottom: 12px; color: #444; border-bottom: 1px solid #eee; padding-bottom: 8px; }\n .param { margin-bottom: 12px; padding: 8px; background: #fafafa; border-radius: 6px; }\n .param-header { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }\n .param-name { font-size: 14px; font-weight: 600; color: #0066cc; }\n .param-type { font-size: 12px; color: #666; background: #e8e8e8; padding: 2px 6px; border-radius: 4px; }\n .badge { font-size: 11px; padding: 2px 6px; border-radius: 4px; text-transform: uppercase; }\n .badge.required { background: #fee2e2; color: #dc2626; }\n .badge.optional { background: #e0f2fe; color: #0284c7; }\n .param-desc { font-size: 13px; color: #666; margin-top: 4px; padding-left: 4px; }\n .no-params { color: #999; font-style: italic; }\n .modal { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.9); z-index: 1000; align-items: center; justify-content: center; }\n .modal.active { display: flex; }\n .modal img { max-width: 90%; max-height: 90%; object-fit: contain; }\n .modal-close { position: absolute; top: 20px; right: 30px; color: white; font-size: 40px; cursor: pointer; }\n @media (max-width: 768px) {\n .template-card { grid-template-columns: 1fr; }\n }\n </style>\n</head>\n<body>\n <h1>Template Preview</h1>\n <div class=\"container\">\n ${templateCards || '<p>No templates to preview</p>'}\n </div>\n <div class=\"modal\" id=\"modal\">\n <span class=\"modal-close\">&times;</span>\n <img id=\"modal-img\" src=\"\">\n </div>\n <script>\n // Click on image to show modal\n document.querySelectorAll('.template-img').forEach(img => {\n img.addEventListener('click', () => {\n document.getElementById('modal-img').src = img.src;\n document.getElementById('modal').classList.add('active');\n });\n });\n // Close modal\n document.getElementById('modal').addEventListener('click', (e) => {\n if (e.target.classList.contains('modal') || e.target.classList.contains('modal-close')) {\n document.getElementById('modal').classList.remove('active');\n }\n });\n document.addEventListener('keydown', (e) => {\n if (e.key === 'Escape') {\n document.getElementById('modal').classList.remove('active');\n }\n });\n </script>\n</body>\n</html>`;\n}\n\n/**\n * Generate sample YAML for a template\n */\nfunction generateSampleYaml(template: TemplateDefinition): string {\n const slide = {\n template: template.name,\n content: template.example ?? {},\n };\n return yaml.stringify({ slides: [slide] });\n}\n\n/**\n * Execute template preview\n */\nexport async function executeTemplatePreview(\n name: string | undefined,\n options: PreviewOptions\n): Promise<void> {\n // Validate: either name or --all must be specified\n if (!name && !options.all) {\n console.error(chalk.red('Error: Specify a template name or use --all'));\n process.exitCode = ExitCode.GeneralError;\n return;\n }\n\n const port = Number(options.port) || 8080;\n const previewDir = join(tmpdir(), `slide-gen-template-preview-${Date.now()}`);\n\n // Check marp-cli availability\n console.log('Checking for Marp CLI...');\n const marpAvailable = await checkMarpCliAvailable();\n if (!marpAvailable) {\n console.error(\n chalk.red(\n 'Error: Marp CLI not found. Install it with: npm install -g @marp-team/marp-cli'\n )\n );\n process.exitCode = ExitCode.GeneralError;\n return;\n }\n console.log(chalk.green('✓') + ' Marp CLI found');\n\n // Load configuration and templates\n const configLoader = new ConfigLoader();\n let configPath = options.config;\n\n if (!configPath) {\n configPath = await configLoader.findConfig(process.cwd());\n }\n\n const config = await configLoader.load(configPath);\n const templateLoader = await loadTemplates(options.config);\n\n // Get templates to preview\n let templates = templateLoader.list();\n if (name) {\n const template = templateLoader.get(name);\n if (!template) {\n console.error(chalk.red(`Error: Template \"${name}\" not found`));\n process.exitCode = ExitCode.GeneralError;\n return;\n }\n templates = [template];\n } else if (options.category) {\n templates = templateLoader.listByCategory(options.category);\n }\n\n if (templates.length === 0) {\n console.log('No templates found.');\n return;\n }\n\n console.log(`Found ${templates.length} template(s) to preview`);\n\n // Create preview directory\n await mkdir(previewDir, { recursive: true });\n\n // Initialize pipeline\n console.log('Initializing pipeline...');\n const pipeline = new Pipeline(config);\n\n try {\n await pipeline.initialize();\n } catch (error) {\n const message =\n error instanceof Error ? error.message : 'Unknown initialization error';\n console.error(chalk.red(`Error: Failed to initialize pipeline: ${message}`));\n process.exitCode = ExitCode.GeneralError;\n await rm(previewDir, { recursive: true, force: true });\n return;\n }\n\n // Generate screenshots for each template\n const templatePreviews: TemplatePreviewInfo[] = [];\n\n for (const template of templates) {\n console.log(`Processing template: ${chalk.cyan(template.name)}...`);\n\n // Generate sample YAML\n const sampleYaml = generateSampleYaml(template);\n const yamlPath = join(previewDir, `${template.name}.yaml`);\n await writeFile(yamlPath, sampleYaml);\n\n // Convert to markdown\n const mdPath = join(previewDir, `${template.name}.md`);\n try {\n await pipeline.runWithResult(yamlPath, { outputPath: mdPath });\n } catch (error) {\n const message =\n error instanceof PipelineError\n ? `${error.stage}: ${error.message}`\n : error instanceof Error\n ? error.message\n : 'Unknown error';\n console.warn(chalk.yellow(` Warning: Failed to convert ${template.name}: ${message}`));\n continue;\n }\n\n // Generate screenshot\n try {\n runMarp(['--images', 'png', '-o', previewDir, mdPath], {\n projectDir: process.cwd(),\n stdio: 'pipe',\n });\n } catch {\n console.warn(chalk.yellow(` Warning: Failed to generate screenshot for ${template.name}`));\n continue;\n }\n\n // Collect slide info for this template (use first slide as preview)\n const templateSlides = await collectSlideInfo(previewDir, template.name, 'png');\n if (templateSlides.length > 0) {\n templatePreviews.push({\n template,\n imagePath: basename(templateSlides[0]!.path),\n });\n }\n\n console.log(chalk.green(' ✓') + ` ${template.name}`);\n }\n\n if (templatePreviews.length === 0) {\n console.error(chalk.red('Error: No template previews generated'));\n process.exitCode = ExitCode.GeneralError;\n await rm(previewDir, { recursive: true, force: true });\n return;\n }\n\n // Generate template preview HTML with parameter info\n const previewHtml = generateTemplatePreviewHtml(templatePreviews);\n await writeFile(join(previewDir, 'index.html'), previewHtml);\n\n // Start preview server\n console.log(`\\nStarting preview server on port ${chalk.cyan(port)}...`);\n\n let server: Server;\n try {\n server = await startStaticServer(previewDir, port, {\n messagePrefix: 'Template preview server',\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Failed to start server';\n console.error(chalk.red(`Error: ${message}`));\n process.exitCode = ExitCode.GeneralError;\n await rm(previewDir, { recursive: true, force: true });\n return;\n }\n\n // Open browser\n const url = `http://localhost:${port}`;\n try {\n // Dynamic import for optional 'open' package (ESM)\n // Use variable to prevent TypeScript from checking module existence at compile time\n const moduleName = 'open';\n const openModule = (await import(moduleName)) as { default: (target: string) => Promise<unknown> };\n await openModule.default(url);\n } catch {\n console.log(`Open ${chalk.cyan(url)} in your browser`);\n }\n\n console.log(`\\nShowing ${templatePreviews.length} template preview(s)`);\n console.log('Press Ctrl+C to stop the server');\n\n // Cleanup on exit\n const cleanup = async () => {\n server.close();\n await rm(previewDir, { recursive: true, force: true });\n };\n\n const signalHandler = async () => {\n console.log('\\n' + chalk.yellow('Template preview server stopped.'));\n await cleanup();\n process.exit(0);\n };\n\n process.on('SIGINT', signalHandler);\n process.on('SIGTERM', signalHandler);\n\n // Wait for server to close\n await new Promise<void>((resolve) => {\n server.on('close', () => resolve());\n });\n}\n\n/**\n * Create the templates command with subcommands\n */\nexport function createTemplatesCommand(): Command {\n const cmd = new Command('templates')\n .description('Manage and list templates');\n\n cmd.addCommand(createListCommand());\n cmd.addCommand(createInfoCommand());\n cmd.addCommand(createExampleCommand());\n cmd.addCommand(createPreviewSubcommand());\n\n return cmd;\n}\n","import { Command } from 'commander';\nimport { access, unlink, readdir, mkdir, writeFile, readFile, rm } from 'fs/promises';\nimport { basename, dirname, join, extname } from 'path';\nimport * as path from 'path';\nimport { tmpdir } from 'os';\nimport { createServer, Server } from 'http';\nimport chalk from 'chalk';\nimport { watch as chokidarWatch, FSWatcher } from 'chokidar';\nimport { Pipeline, PipelineError } from '../../core/pipeline';\nimport { ConfigLoader } from '../../config/loader';\nimport { ExitCode } from './convert';\nimport { runMarp, spawnMarp, isMarpAvailable } from '../utils/marp-runner';\n\nexport interface PreviewOptions {\n port?: number;\n watch?: boolean;\n config?: string;\n verbose?: boolean;\n signal?: AbortSignal;\n gallery?: boolean;\n slide?: number;\n}\n\nexport interface PreviewResult {\n success: boolean;\n errors: string[];\n}\n\nexport interface SlideInfo {\n path: string;\n title: string;\n index: number;\n}\n\n/**\n * Escape HTML special characters to prevent XSS\n */\nfunction escapeHtml(str: string): string {\n return str\n .replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;')\n .replace(/'/g, '&#39;');\n}\n\n/**\n * Generate HTML for gallery view with slide thumbnails\n */\nexport function generateGalleryHtml(slides: SlideInfo[]): string {\n const slideItems =\n slides.length > 0\n ? slides\n .map(\n (s) => `\n <div class=\"slide\" data-index=\"${s.index}\" data-path=\"${escapeHtml(s.path)}\">\n <img src=\"${escapeHtml(s.path)}\" alt=\"Slide ${s.index}\">\n <div class=\"slide-title\">${escapeHtml(s.title)}</div>\n </div>\n `\n )\n .join('')\n : '<p class=\"no-slides\">No slides available</p>';\n\n return `<!DOCTYPE html>\n<html>\n<head>\n <title>Slide Gallery</title>\n <style>\n * { box-sizing: border-box; margin: 0; padding: 0; }\n body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: #f5f5f5; }\n h1 { text-align: center; padding: 24px; color: #333; }\n .gallery { display: grid; grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); gap: 20px; padding: 20px; max-width: 1400px; margin: 0 auto; }\n .slide { cursor: pointer; border: 1px solid #ddd; border-radius: 8px; overflow: hidden; background: white; transition: transform 0.2s, box-shadow 0.2s; }\n .slide:hover { transform: translateY(-4px); box-shadow: 0 8px 16px rgba(0,0,0,0.1); }\n .slide img { width: 100%; height: auto; display: block; }\n .slide-title { padding: 12px; text-align: center; font-size: 14px; color: #666; border-top: 1px solid #eee; }\n .no-slides { text-align: center; padding: 40px; color: #999; }\n .modal { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.9); z-index: 1000; }\n .modal.active { display: flex; align-items: center; justify-content: center; }\n .modal img { max-width: 90%; max-height: 90%; object-fit: contain; }\n .modal-close { position: absolute; top: 20px; right: 30px; color: white; font-size: 40px; cursor: pointer; }\n .modal-nav { position: absolute; top: 50%; color: white; font-size: 60px; cursor: pointer; user-select: none; }\n .modal-nav.prev { left: 20px; }\n .modal-nav.next { right: 20px; }\n </style>\n</head>\n<body>\n <h1>Slide Gallery</h1>\n <div class=\"gallery\">\n ${slideItems}\n </div>\n <div class=\"modal\" id=\"modal\">\n <span class=\"modal-close\">&times;</span>\n <span class=\"modal-nav prev\">&lt;</span>\n <img id=\"modal-img\" src=\"\">\n <span class=\"modal-nav next\">&gt;</span>\n </div>\n <script>\n const slides = ${JSON.stringify(slides).replace(/<\\//g, '<\\\\/')};\n let currentIndex = 0;\n\n function showSlide(index, path) {\n currentIndex = slides.findIndex(s => s.index === index);\n document.getElementById('modal-img').src = path;\n document.getElementById('modal').classList.add('active');\n }\n\n function hideSlide(event) {\n if (event.target.classList.contains('modal') || event.target.classList.contains('modal-close')) {\n document.getElementById('modal').classList.remove('active');\n }\n }\n\n function navigateSlide(direction) {\n currentIndex = (currentIndex + direction + slides.length) % slides.length;\n const slide = slides[currentIndex];\n document.getElementById('modal-img').src = slide.path;\n }\n\n // Event delegation for slide clicks\n document.querySelector('.gallery').addEventListener('click', (e) => {\n const slideEl = e.target.closest('.slide');\n if (slideEl) {\n const index = parseInt(slideEl.dataset.index, 10);\n const path = slideEl.dataset.path;\n showSlide(index, path);\n }\n });\n\n // Modal event handlers\n document.getElementById('modal').addEventListener('click', hideSlide);\n document.querySelector('.modal-nav.prev').addEventListener('click', (e) => {\n e.stopPropagation();\n navigateSlide(-1);\n });\n document.querySelector('.modal-nav.next').addEventListener('click', (e) => {\n e.stopPropagation();\n navigateSlide(1);\n });\n\n document.addEventListener('keydown', (e) => {\n const modal = document.getElementById('modal');\n if (!modal.classList.contains('active')) return;\n if (e.key === 'Escape') modal.classList.remove('active');\n if (e.key === 'ArrowLeft') navigateSlide(-1);\n if (e.key === 'ArrowRight') navigateSlide(1);\n });\n </script>\n</body>\n</html>`;\n}\n\n/**\n * Escape special characters in a string for use in a regular expression\n */\nfunction escapeRegExp(str: string): string {\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\n/**\n * Collect slide information from screenshot directory\n */\nexport async function collectSlideInfo(\n dir: string,\n baseName: string,\n format: string\n): Promise<SlideInfo[]> {\n try {\n const files = await readdir(dir);\n const slidePattern = new RegExp(`^${escapeRegExp(baseName)}\\\\.(\\\\d{3})\\\\.${escapeRegExp(format)}$`);\n\n const slides: SlideInfo[] = [];\n for (const file of files) {\n const match = file.match(slidePattern);\n if (match) {\n const index = parseInt(match[1]!, 10);\n slides.push({\n path: join(dir, file),\n title: `Slide ${index}`,\n index,\n });\n }\n }\n\n return slides.sort((a, b) => a.index - b.index);\n } catch {\n return [];\n }\n}\n\n/**\n * Check if marp-cli is available in the system (globally or locally)\n * Uses the centralized marp-runner utility\n */\nexport async function checkMarpCliAvailable(projectDir?: string): Promise<boolean> {\n return isMarpAvailable(projectDir);\n}\n\n/**\n * Generate temporary output path for markdown file\n */\nexport function getTempOutputPath(inputPath: string): string {\n const base = basename(inputPath, '.yaml');\n return join(tmpdir(), `slide-gen-preview-${base}-${Date.now()}.md`);\n}\n\n/**\n * Build marp-cli command for preview (for display purposes)\n */\nexport function buildMarpCommand(\n markdownPath: string,\n options: PreviewOptions\n): string {\n const parts = ['marp', '--preview'];\n\n if (options.port) {\n parts.push('-p', String(options.port));\n }\n\n if (options.watch) {\n parts.push('--watch');\n }\n\n parts.push(markdownPath);\n\n return parts.join(' ');\n}\n\nexport interface StaticServerOptions {\n /** Initial slide number for URL hash */\n initialSlide?: number;\n /** Custom message prefix (default: \"Server\") */\n messagePrefix?: string;\n /** Suppress console output */\n silent?: boolean;\n}\n\n/**\n * Start a simple HTTP server to serve static files\n * Reusable for gallery preview, template preview, etc.\n */\nexport function startStaticServer(\n baseDir: string,\n port: number,\n options: StaticServerOptions = {}\n): Promise<Server> {\n return new Promise((resolve, reject) => {\n const mimeTypes: Record<string, string> = {\n '.html': 'text/html',\n '.png': 'image/png',\n '.jpg': 'image/jpeg',\n '.jpeg': 'image/jpeg',\n '.css': 'text/css',\n '.js': 'application/javascript',\n };\n\n const server = createServer(async (req, res) => {\n try {\n // Parse URL and get pathname only (ignore query strings)\n const urlPath = new URL(req.url || '/', `http://localhost`).pathname;\n const requestedPath = urlPath === '/' ? '/index.html' : urlPath;\n\n // Resolve to absolute path and normalize (handles .. and .)\n const resolvedBaseDir = path.resolve(baseDir);\n const filePath = path.resolve(baseDir, '.' + requestedPath);\n\n // Security: Ensure the resolved path is within baseDir (prevent path traversal)\n if (!filePath.startsWith(resolvedBaseDir + '/') && filePath !== resolvedBaseDir) {\n res.writeHead(403);\n res.end('Forbidden');\n return;\n }\n\n const ext = extname(filePath);\n const contentType = mimeTypes[ext] || 'application/octet-stream';\n\n const data = await readFile(filePath);\n res.writeHead(200, { 'Content-Type': contentType });\n res.end(data);\n } catch {\n res.writeHead(404);\n res.end('Not found');\n }\n });\n\n server.on('error', reject);\n server.listen(port, () => {\n const url = options.initialSlide\n ? `http://localhost:${port}/#slide-${options.initialSlide}`\n : `http://localhost:${port}`;\n if (!options.silent) {\n const prefix = options.messagePrefix ?? 'Server';\n console.log(`${prefix} running at ${chalk.cyan(url)}`);\n }\n resolve(server);\n });\n });\n}\n\n/**\n * Start a simple HTTP server to serve gallery files\n * @deprecated Use startStaticServer instead\n */\nexport function startGalleryServer(\n galleryDir: string,\n port: number,\n initialSlide?: number\n): Promise<Server> {\n return startStaticServer(galleryDir, port, {\n ...(initialSlide !== undefined && { initialSlide }),\n messagePrefix: 'Gallery server',\n });\n}\n\n/**\n * Execute gallery preview mode\n */\nexport async function executeGalleryPreview(\n inputPath: string,\n options: PreviewOptions\n): Promise<PreviewResult> {\n const errors: string[] = [];\n const port = Number(options.port) || 8080;\n const galleryDir = join(tmpdir(), `slide-gen-gallery-${Date.now()}`);\n\n // Validate input file exists\n try {\n await access(inputPath);\n } catch {\n console.error(chalk.red(`Error: File not found: ${inputPath}`));\n errors.push(`File not found: ${inputPath}`);\n process.exitCode = ExitCode.FileReadError;\n return { success: false, errors };\n }\n\n // Check marp-cli availability\n console.log('Checking for Marp CLI...');\n const projectDir = dirname(inputPath);\n const marpAvailable = await checkMarpCliAvailable(projectDir);\n if (!marpAvailable) {\n console.error(\n chalk.red(\n 'Error: Marp CLI not found. Install it with: npm install -D @marp-team/marp-cli'\n )\n );\n errors.push('Marp CLI not available');\n process.exitCode = ExitCode.GeneralError;\n return { success: false, errors };\n }\n console.log(chalk.green('✓') + ' Marp CLI found');\n\n // Create gallery directory\n await mkdir(galleryDir, { recursive: true });\n\n // Load configuration\n const configLoader = new ConfigLoader();\n let configPath = options.config;\n\n if (!configPath) {\n configPath = await configLoader.findConfig(dirname(inputPath));\n }\n\n const config = await configLoader.load(configPath);\n\n // Create and initialize pipeline\n console.log('Initializing pipeline...');\n const pipeline = new Pipeline(config);\n\n try {\n await pipeline.initialize();\n } catch (error) {\n const message =\n error instanceof Error ? error.message : 'Unknown initialization error';\n console.error(chalk.red(`Error: Failed to initialize pipeline: ${message}`));\n errors.push(message);\n process.exitCode = ExitCode.ConversionError;\n await rm(galleryDir, { recursive: true, force: true });\n return { success: false, errors };\n }\n\n // Generate markdown\n const tempMdPath = join(galleryDir, 'slides.md');\n console.log(`Converting ${chalk.cyan(inputPath)}...`);\n\n try {\n await pipeline.runWithResult(inputPath, { outputPath: tempMdPath });\n console.log(chalk.green('✓') + ' Conversion complete');\n } catch (error) {\n const message =\n error instanceof PipelineError\n ? `${error.stage}: ${error.message}`\n : error instanceof Error\n ? error.message\n : 'Unknown error';\n console.error(chalk.red(`Error: Conversion failed: ${message}`));\n errors.push(message);\n process.exitCode = ExitCode.ConversionError;\n await rm(galleryDir, { recursive: true, force: true });\n return { success: false, errors };\n }\n\n // Take screenshots\n console.log('Taking screenshots...');\n try {\n runMarp(['--images', 'png', '-o', galleryDir, tempMdPath], {\n projectDir,\n stdio: options.verbose ? 'inherit' : 'pipe',\n });\n console.log(chalk.green('✓') + ' Screenshots generated');\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Marp CLI failed';\n console.error(chalk.red(`Error: ${message}`));\n errors.push(message);\n process.exitCode = ExitCode.GeneralError;\n await rm(galleryDir, { recursive: true, force: true });\n return { success: false, errors };\n }\n\n // Collect slide info\n const slides = await collectSlideInfo(galleryDir, 'slides', 'png');\n\n if (slides.length === 0) {\n console.error(chalk.red('Error: No slides found'));\n errors.push('No slides generated');\n process.exitCode = ExitCode.GeneralError;\n await rm(galleryDir, { recursive: true, force: true });\n return { success: false, errors };\n }\n\n // Update paths to be relative for HTTP serving\n const relativeSlides = slides.map((s) => ({\n ...s,\n path: basename(s.path),\n }));\n\n // Generate gallery HTML\n const galleryHtml = generateGalleryHtml(relativeSlides);\n await writeFile(join(galleryDir, 'index.html'), galleryHtml);\n\n // Start gallery server\n console.log(`\\nStarting gallery server on port ${chalk.cyan(port)}...`);\n\n let server: Server;\n try {\n server = await startStaticServer(galleryDir, port, {\n ...(options.slide !== undefined && { initialSlide: options.slide }),\n messagePrefix: 'Gallery server',\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Failed to start server';\n console.error(chalk.red(`Error: ${message}`));\n errors.push(message);\n process.exitCode = ExitCode.GeneralError;\n await rm(galleryDir, { recursive: true, force: true });\n return { success: false, errors };\n }\n\n // Open browser\n const url = options.slide\n ? `http://localhost:${port}/#slide-${options.slide}`\n : `http://localhost:${port}`;\n\n try {\n // Dynamic import for optional 'open' package (ESM)\n // Use variable to prevent TypeScript from checking module existence at compile time\n const moduleName = 'open';\n const openModule = (await import(moduleName)) as { default: (target: string) => Promise<unknown> };\n await openModule.default(url);\n } catch {\n console.log(`Open ${chalk.cyan(url)} in your browser`);\n }\n\n console.log(`\\nShowing ${slides.length} slides in gallery mode`);\n console.log('Press Ctrl+C to stop the server');\n\n // Cleanup on exit\n const cleanup = async () => {\n server.close();\n await rm(galleryDir, { recursive: true, force: true });\n };\n\n if (options.signal) {\n options.signal.addEventListener('abort', cleanup);\n }\n\n const signalHandler = async () => {\n console.log('\\n' + chalk.yellow('Gallery server stopped.'));\n await cleanup();\n process.exit(0);\n };\n\n process.on('SIGINT', signalHandler);\n process.on('SIGTERM', signalHandler);\n\n // Wait for signal\n await new Promise<void>((resolve) => {\n if (options.signal) {\n options.signal.addEventListener('abort', () => resolve());\n }\n server.on('close', () => resolve());\n });\n\n return { success: true, errors };\n}\n\n/**\n * Create the preview command\n */\nexport function createPreviewCommand(): Command {\n return new Command('preview')\n .description('Preview the generated slides in browser (requires Marp CLI)')\n .argument('<input>', 'Input YAML file')\n .option('-p, --port <number>', 'Preview server port', '8080')\n .option('-w, --watch', 'Watch for changes and auto-reload')\n .option('-c, --config <path>', 'Config file path')\n .option('-v, --verbose', 'Verbose output')\n .option('-g, --gallery', 'Show thumbnail gallery')\n .option('-s, --slide <number>', 'Show specific slide', parseInt)\n .action(async (input: string, options: PreviewOptions) => {\n await executePreview(input, options);\n });\n}\n\n/**\n * Execute the preview command\n */\nexport async function executePreview(\n inputPath: string,\n options: PreviewOptions\n): Promise<PreviewResult> {\n // Route to gallery mode if requested\n if (options.gallery) {\n return executeGalleryPreview(inputPath, options);\n }\n\n const errors: string[] = [];\n const verbose = options.verbose ?? false;\n const port = Number(options.port) || 8080;\n\n // Check if immediately aborted (for testing)\n if (options.signal?.aborted) {\n try {\n await access(inputPath);\n } catch {\n errors.push(`File not found: ${inputPath}`);\n return { success: false, errors };\n }\n return { success: true, errors };\n }\n\n // Validate input file exists\n try {\n await access(inputPath);\n } catch {\n console.error(chalk.red(`Error: File not found: ${inputPath}`));\n errors.push(`File not found: ${inputPath}`);\n process.exitCode = ExitCode.FileReadError;\n return { success: false, errors };\n }\n\n // Check marp-cli availability\n console.log('Checking for Marp CLI...');\n const marpAvailable = await checkMarpCliAvailable(dirname(inputPath));\n if (!marpAvailable) {\n console.error(\n chalk.red(\n 'Error: Marp CLI not found. Install it with: npm install -D @marp-team/marp-cli'\n )\n );\n errors.push('Marp CLI not available');\n process.exitCode = ExitCode.GeneralError;\n return { success: false, errors };\n }\n console.log(chalk.green('✓') + ' Marp CLI found');\n\n // Load configuration\n const configLoader = new ConfigLoader();\n let configPath = options.config;\n\n if (!configPath) {\n configPath = await configLoader.findConfig(dirname(inputPath));\n }\n\n const config = await configLoader.load(configPath);\n\n // Create and initialize pipeline\n console.log('Initializing pipeline...');\n const pipeline = new Pipeline(config);\n\n try {\n await pipeline.initialize();\n } catch (error) {\n const message =\n error instanceof Error ? error.message : 'Unknown initialization error';\n console.error(chalk.red(`Error: Failed to initialize pipeline: ${message}`));\n errors.push(message);\n process.exitCode = ExitCode.ConversionError;\n return { success: false, errors };\n }\n\n // Generate initial markdown\n const tempMarkdownPath = getTempOutputPath(inputPath);\n console.log(`Converting ${chalk.cyan(inputPath)}...`);\n\n try {\n await pipeline.runWithResult(inputPath, { outputPath: tempMarkdownPath });\n console.log(chalk.green('✓') + ' Initial conversion complete');\n } catch (error) {\n const message =\n error instanceof PipelineError\n ? `${error.stage}: ${error.message}`\n : error instanceof Error\n ? error.message\n : 'Unknown error';\n console.error(chalk.red(`Error: Conversion failed: ${message}`));\n errors.push(message);\n process.exitCode = ExitCode.ConversionError;\n return { success: false, errors };\n }\n\n // Start marp preview server\n console.log(`\\nStarting preview server on port ${chalk.cyan(port)}...`);\n\n const marpCommand = buildMarpCommand(tempMarkdownPath, {\n ...options,\n port,\n watch: false, // We handle watch ourselves if needed\n });\n\n if (verbose) {\n console.log(`Running: ${marpCommand}`);\n }\n\n const marpProcess = spawnMarp(['--preview', '-p', String(port), tempMarkdownPath], {\n projectDir: dirname(inputPath),\n stdio: 'inherit',\n });\n\n let watcher: FSWatcher | null = null;\n let debounceTimer: ReturnType<typeof setTimeout> | null = null;\n\n // Set up file watcher if watch mode enabled\n if (options.watch) {\n console.log(`\\nWatching ${chalk.cyan(inputPath)} for changes...`);\n\n watcher = chokidarWatch(inputPath, {\n persistent: true,\n ignoreInitial: true,\n awaitWriteFinish: {\n stabilityThreshold: 100,\n pollInterval: 50,\n },\n });\n\n watcher.on('change', () => {\n if (debounceTimer) {\n clearTimeout(debounceTimer);\n }\n\n debounceTimer = setTimeout(async () => {\n console.log(`\\n[${new Date().toLocaleTimeString('en-GB')}] File changed, reconverting...`);\n\n try {\n await pipeline.runWithResult(inputPath, { outputPath: tempMarkdownPath });\n console.log(chalk.green('✓') + ' Reconversion complete');\n } catch (error) {\n const message =\n error instanceof PipelineError\n ? `${error.stage}: ${error.message}`\n : error instanceof Error\n ? error.message\n : 'Unknown error';\n console.error(chalk.red(`✗ Reconversion failed: ${message}`));\n }\n }, 300);\n });\n }\n\n // Cleanup function\n const cleanup = async () => {\n if (debounceTimer) {\n clearTimeout(debounceTimer);\n }\n watcher?.close();\n marpProcess.kill();\n\n // Clean up temp file\n try {\n await unlink(tempMarkdownPath);\n } catch {\n // Ignore cleanup errors\n }\n };\n\n // Handle abort signal\n if (options.signal) {\n options.signal.addEventListener('abort', () => {\n cleanup();\n });\n }\n\n // Handle process signals\n const signalHandler = async () => {\n console.log('\\n' + chalk.yellow('Preview stopped.'));\n await cleanup();\n process.exit(0);\n };\n\n process.on('SIGINT', signalHandler);\n process.on('SIGTERM', signalHandler);\n\n // Wait for marp process or abort signal\n await new Promise<void>((resolve) => {\n marpProcess.on('exit', () => {\n cleanup();\n resolve();\n });\n\n if (options.signal) {\n options.signal.addEventListener('abort', () => resolve());\n }\n });\n\n return {\n success: errors.length === 0,\n errors,\n };\n}\n","/**\n * Marp CLI runner utilities\n *\n * Provides optimized execution of Marp CLI commands by:\n * 1. Using local node_modules/.bin/marp when available (fastest)\n * 2. Falling back to global marp command\n * 3. Avoiding npx which is slow (especially on Windows CI)\n */\n\nimport { existsSync } from 'fs';\nimport { join } from 'path';\nimport {\n execFileSync,\n spawn,\n ChildProcess,\n SpawnOptions,\n ExecFileSyncOptions,\n} from 'child_process';\n\nexport interface MarpRunOptions extends Omit<ExecFileSyncOptions, 'encoding'> {\n /** Project directory to search for local marp installation */\n projectDir?: string;\n}\n\nexport interface MarpSpawnOptions extends SpawnOptions {\n /** Project directory to search for local marp installation */\n projectDir?: string;\n}\n\n/**\n * Get the marp command path\n * Priority: local install > global install\n *\n * @param projectDir - Directory to search for local marp installation\n * @returns Path to marp command, or null if not found\n */\nexport function getMarpCommand(projectDir?: string): string | null {\n const dir = projectDir ?? process.cwd();\n\n // Check local install first (fastest)\n const localMarp = join(dir, 'node_modules', '.bin', 'marp');\n if (existsSync(localMarp)) {\n return localMarp;\n }\n\n // Check global install\n try {\n execFileSync('marp', ['--version'], { stdio: 'ignore', timeout: 5000 });\n return 'marp';\n } catch {\n return null;\n }\n}\n\n/**\n * Check if Marp CLI is available (locally or globally)\n *\n * @param projectDir - Directory to search for local marp installation\n * @returns true if marp is available\n */\nexport function isMarpAvailable(projectDir?: string): boolean {\n return getMarpCommand(projectDir) !== null;\n}\n\n/**\n * Run marp synchronously\n *\n * @param args - Arguments to pass to marp\n * @param options - Execution options\n * @throws Error if marp is not installed\n */\nexport function runMarp(args: string[], options: MarpRunOptions = {}): void {\n const { projectDir, ...execOptions } = options;\n const marpCmd = getMarpCommand(projectDir);\n\n if (!marpCmd) {\n throw new Error('Marp CLI not found. Install it with: npm install -D @marp-team/marp-cli');\n }\n\n execFileSync(marpCmd, args, execOptions);\n}\n\n/**\n * Run marp synchronously and return output\n *\n * @param args - Arguments to pass to marp\n * @param options - Execution options\n * @returns stdout output as string\n * @throws Error if marp is not installed or command fails\n */\nexport function runMarpWithOutput(args: string[], options: MarpRunOptions = {}): string {\n const { projectDir, ...execOptions } = options;\n const marpCmd = getMarpCommand(projectDir);\n\n if (!marpCmd) {\n throw new Error('Marp CLI not found. Install it with: npm install -D @marp-team/marp-cli');\n }\n\n const result = execFileSync(marpCmd, args, { ...execOptions, encoding: 'utf-8' });\n return result;\n}\n\n/**\n * Spawn marp process (for long-running commands like preview)\n *\n * @param args - Arguments to pass to marp\n * @param options - Spawn options\n * @returns Child process\n * @throws Error if marp is not installed\n */\nexport function spawnMarp(args: string[], options: MarpSpawnOptions = {}): ChildProcess {\n const { projectDir, ...spawnOptions } = options;\n const marpCmd = getMarpCommand(projectDir);\n\n if (!marpCmd) {\n throw new Error('Marp CLI not found. Install it with: npm install -D @marp-team/marp-cli');\n }\n\n return spawn(marpCmd, args, spawnOptions);\n}\n","import { Command } from 'commander';\nimport chalk from 'chalk';\nimport * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport { parse as parseYaml, stringify as stringifyYaml } from 'yaml';\nimport { IconRegistryLoader } from '../../icons/registry.js';\nimport { IconResolver } from '../../icons/resolver.js';\nimport { IconFetcher, isExternalSource } from '../../icons/fetcher.js';\nimport { ConfigLoader } from '../../config/loader.js';\nimport type { IconSource, IconRegistry } from '../../icons/schema.js';\nimport { ExitCode } from './convert.js';\n\ntype OutputFormat = 'table' | 'json' | 'llm';\n\ninterface ListOptions {\n source?: string;\n aliases?: boolean;\n config?: string;\n format?: OutputFormat;\n category?: string;\n showStatus?: boolean;\n}\n\ninterface SearchOptions {\n config?: string;\n format?: OutputFormat;\n}\n\ninterface PreviewOptions {\n format?: 'svg' | 'html';\n size?: string;\n color?: string;\n config?: string;\n}\n\ninterface SearchResult {\n query: string;\n aliases: Array<{ alias: string; target: string }>;\n sources: Array<{ name: string; prefix: string; type: string }>;\n}\n\ninterface AddOptions {\n from?: string;\n search?: boolean;\n saveLocal?: boolean;\n config?: string;\n}\n\ninterface SyncOptions {\n localize?: boolean;\n config?: string;\n}\n\n// Re-export isExternalSource for backward compatibility (used by tests)\nexport { isExternalSource };\n\n/**\n * Extract all icon references from a presentation\n */\nexport function extractIconReferences(presentation: unknown): string[] {\n const icons = new Set<string>();\n\n function extractFromValue(value: unknown): void {\n if (value === null || value === undefined) {\n return;\n }\n\n if (typeof value === 'object') {\n if (Array.isArray(value)) {\n for (const item of value) {\n extractFromValue(item);\n }\n } else {\n const obj = value as Record<string, unknown>;\n // Check for icon property\n if (typeof obj['icon'] === 'string') {\n icons.add(obj['icon']);\n }\n // Recursively check all properties\n for (const key of Object.keys(obj)) {\n extractFromValue(obj[key]);\n }\n }\n }\n }\n\n extractFromValue(presentation);\n return Array.from(icons);\n}\n\n/**\n * Format icon sources for table output\n */\nfunction formatTableSourceList(sources: IconSource[]): string {\n const lines: string[] = ['Icon Sources:', ''];\n\n // Calculate column widths\n const maxNameLen = Math.max(...sources.map((s) => s.name.length), 4);\n const maxPrefixLen = Math.max(...sources.map((s) => s.prefix.length), 6);\n const maxTypeLen = Math.max(...sources.map((s) => s.type.length), 4);\n\n // Header\n const namePad = 'Name'.padEnd(maxNameLen);\n const prefixPad = 'Prefix'.padEnd(maxPrefixLen);\n const typePad = 'Type'.padEnd(maxTypeLen);\n lines.push(` ${namePad} ${prefixPad} ${typePad}`);\n lines.push(` ${'─'.repeat(maxNameLen)} ${'─'.repeat(maxPrefixLen)} ${'─'.repeat(maxTypeLen)}`);\n\n // Data rows\n for (const source of sources) {\n const name = source.name.padEnd(maxNameLen);\n const prefix = source.prefix.padEnd(maxPrefixLen);\n const type = source.type.padEnd(maxTypeLen);\n lines.push(` ${name} ${prefix} ${type}`);\n }\n\n return lines.join('\\n');\n}\n\n/**\n * Format icon sources for JSON output\n */\nfunction formatJsonSourceList(sources: IconSource[]): string {\n const output = sources.map((s) => ({\n name: s.name,\n type: s.type,\n prefix: s.prefix,\n ...(s.url ? { url: s.url } : {}),\n ...(s.path ? { path: s.path } : {}),\n }));\n return JSON.stringify(output, null, 2);\n}\n\n/**\n * Format icon source list in the specified format\n */\nexport function formatIconSourceList(\n sources: IconSource[],\n format: OutputFormat\n): string {\n switch (format) {\n case 'json':\n return formatJsonSourceList(sources);\n case 'table':\n default:\n return formatTableSourceList(sources);\n }\n}\n\n/**\n * Category to alias patterns mapping\n */\nconst CATEGORY_PATTERNS: Record<string, RegExp[]> = {\n medical: [/^(health|hospital|clinic|ambulance|emergency|stethoscope|syringe|vaccine|pill|medicine|doctor|nurse|patient)/i, /^health:/],\n action: [/^(planning|action|analysis|start|stop|pause|save|edit|delete|add|remove|search|refresh|sync|upload|download)/i],\n status: [/^(success|warning|error|info|question|pending|completed|cancelled|approved|rejected)/i],\n navigation: [/^(home|back|forward|up|down|left|right|expand|collapse|menu|close)/i],\n communication: [/^(email|phone|chat|message|notification|feedback|comment)/i],\n business: [/^(workflow|process|cycle|milestone|target|goal|kpi|metric|report|dashboard|chart)/i],\n};\n\n/**\n * Filter aliases by category\n */\nexport function filterAliasesByCategory(\n aliases: Record<string, string>,\n category: string\n): Record<string, string> {\n const patterns = CATEGORY_PATTERNS[category.toLowerCase()];\n\n if (!patterns) {\n // Unknown category, return all aliases\n return aliases;\n }\n\n const filtered: Record<string, string> = {};\n for (const [alias, target] of Object.entries(aliases)) {\n const matchesPattern = patterns.some(pattern =>\n pattern.test(alias) || pattern.test(target)\n );\n if (matchesPattern) {\n filtered[alias] = target;\n }\n }\n\n return filtered;\n}\n\n/**\n * Get icon status (local or external)\n */\nfunction getIconStatus(target: string): 'local' | 'external' {\n const colonIndex = target.indexOf(':');\n if (colonIndex === -1) {\n return 'local';\n }\n const prefix = target.substring(0, colonIndex);\n return isExternalSource(prefix) ? 'external' : 'local';\n}\n\n/**\n * Format aliases with status for table output\n */\nexport function formatAliasesListWithStatus(\n aliases: Record<string, string>,\n format: 'table' | 'json'\n): string {\n const entries = Object.entries(aliases);\n\n if (entries.length === 0) {\n return 'No aliases defined.';\n }\n\n if (format === 'json') {\n const result = entries.map(([alias, target]) => ({\n alias,\n target,\n status: getIconStatus(target),\n }));\n return JSON.stringify(result, null, 2);\n }\n\n const lines: string[] = ['Icon Aliases with Status:', ''];\n\n // Calculate column widths\n const maxAliasLen = Math.max(...entries.map(([a]) => a.length), 5);\n const maxTargetLen = Math.max(...entries.map(([, t]) => t.length), 6);\n\n // Header\n const aliasPad = 'Alias'.padEnd(maxAliasLen);\n const targetPad = 'Target'.padEnd(maxTargetLen);\n lines.push(` ${aliasPad} ${targetPad} Status`);\n lines.push(` ${'─'.repeat(maxAliasLen)} ${'─'.repeat(maxTargetLen)} ${'─'.repeat(10)}`);\n\n // Sort alphabetically\n entries.sort((a, b) => a[0].localeCompare(b[0]));\n\n for (const [alias, target] of entries) {\n const aliasStr = alias.padEnd(maxAliasLen);\n const targetStr = target.padEnd(maxTargetLen);\n const status = getIconStatus(target);\n const statusStr = status === 'local' ? '[local]' : '[external]';\n lines.push(` ${aliasStr} ${targetStr} ${statusStr}`);\n }\n\n return lines.join('\\n');\n}\n\n/**\n * Format aliases for LLM output (YAML format)\n */\nexport function formatAliasesListLLM(aliases: Record<string, string>): string {\n const lines: string[] = [\n '# Icon Aliases',\n '# Use these semantic names instead of raw icon references',\n '',\n 'aliases:',\n ];\n\n // Group by category for better readability\n const entries = Object.entries(aliases).sort((a, b) => a[0].localeCompare(b[0]));\n\n for (const [alias, target] of entries) {\n lines.push(` ${alias}: \"${target}\"`);\n }\n\n return lines.join('\\n');\n}\n\n/**\n * Format aliases for table output\n */\nfunction formatTableAliases(aliases: Record<string, string>): string {\n const entries = Object.entries(aliases);\n\n if (entries.length === 0) {\n return 'No aliases defined.';\n }\n\n const lines: string[] = ['Icon Aliases:', ''];\n\n // Calculate column widths\n const maxAliasLen = Math.max(...entries.map(([a]) => a.length), 5);\n const maxTargetLen = Math.max(...entries.map(([, t]) => t.length), 6);\n\n // Header\n const aliasPad = 'Alias'.padEnd(maxAliasLen);\n const targetPad = 'Target'.padEnd(maxTargetLen);\n lines.push(` ${aliasPad} ${targetPad}`);\n lines.push(` ${'─'.repeat(maxAliasLen)} ${'─'.repeat(maxTargetLen)}`);\n\n // Sort alphabetically\n entries.sort((a, b) => a[0].localeCompare(b[0]));\n\n for (const [alias, target] of entries) {\n const aliasStr = alias.padEnd(maxAliasLen);\n lines.push(` ${aliasStr} ${target}`);\n }\n\n return lines.join('\\n');\n}\n\n/**\n * Format aliases for JSON output\n */\nfunction formatJsonAliases(aliases: Record<string, string>): string {\n return JSON.stringify(aliases, null, 2);\n}\n\n/**\n * Format aliases list in the specified format\n */\nexport function formatAliasesList(\n aliases: Record<string, string>,\n format: OutputFormat\n): string {\n switch (format) {\n case 'json':\n return formatJsonAliases(aliases);\n case 'table':\n default:\n return formatTableAliases(aliases);\n }\n}\n\n/**\n * Format search results for table output\n */\nfunction formatTableSearchResults(results: SearchResult): string {\n const lines: string[] = [`Search results for \"${results.query}\"`, ''];\n\n const hasResults = results.aliases.length > 0 || results.sources.length > 0;\n\n if (!hasResults) {\n lines.push('No results found.');\n return lines.join('\\n');\n }\n\n // Aliases section\n if (results.aliases.length > 0) {\n lines.push('Aliases:');\n for (const { alias, target } of results.aliases) {\n lines.push(` ${alias} → ${target}`);\n }\n lines.push('');\n }\n\n // Sources section\n if (results.sources.length > 0) {\n lines.push('Sources:');\n for (const source of results.sources) {\n lines.push(` ${source.name} (${source.prefix}:) [${source.type}]`);\n }\n }\n\n return lines.join('\\n').trim();\n}\n\n/**\n * Format search results for JSON output\n */\nfunction formatJsonSearchResults(results: SearchResult): string {\n return JSON.stringify(results, null, 2);\n}\n\n/**\n * Format search results in the specified format\n */\nexport function formatSearchResults(\n results: SearchResult,\n format: OutputFormat\n): string {\n switch (format) {\n case 'json':\n return formatJsonSearchResults(results);\n case 'table':\n default:\n return formatTableSearchResults(results);\n }\n}\n\n/**\n * Load icon registry from config\n */\nasync function loadRegistry(configPath?: string): Promise<IconRegistryLoader> {\n const configLoader = new ConfigLoader();\n\n if (!configPath) {\n configPath = await configLoader.findConfig(process.cwd());\n }\n\n const config = await configLoader.load(configPath);\n const registry = new IconRegistryLoader();\n\n if (config.icons?.registry) {\n await registry.load(config.icons.registry);\n }\n\n return registry;\n}\n\n/**\n * Search for icons matching query\n */\nfunction searchIcons(\n registry: IconRegistryLoader,\n query: string\n): SearchResult {\n const lowerQuery = query.toLowerCase();\n\n // Search aliases\n const aliases = Object.entries(registry.getAliases())\n .filter(\n ([alias, target]) =>\n alias.toLowerCase().includes(lowerQuery) ||\n target.toLowerCase().includes(lowerQuery)\n )\n .map(([alias, target]) => ({ alias, target }));\n\n // Search sources\n const sources = registry\n .getSources()\n .filter(\n (source) =>\n source.name.toLowerCase().includes(lowerQuery) ||\n source.prefix.toLowerCase().includes(lowerQuery)\n )\n .map((s) => ({ name: s.name, prefix: s.prefix, type: s.type }));\n\n return { query, aliases, sources };\n}\n\n/**\n * Create the icons list subcommand\n */\nfunction createListCommand(): Command {\n return new Command('list')\n .description('List icon sources and aliases')\n .option('--source <name>', 'Filter by source name')\n .option('--aliases', 'Show only aliases')\n .option('--format <fmt>', 'Output format (table/json/llm)', 'table')\n .option('--category <cat>', 'Filter aliases by category (medical/action/status/navigation/communication/business)')\n .option('--show-status', 'Show local/external status for aliases')\n .option('-c, --config <path>', 'Config file path')\n .action(async (options: ListOptions) => {\n try {\n const registry = await loadRegistry(options.config);\n\n if (!registry.isLoaded()) {\n console.log('No icon registry found.');\n return;\n }\n\n const format = (options.format ?? 'table') as OutputFormat;\n\n if (options.aliases) {\n // Show only aliases\n let aliases = registry.getAliases();\n\n // Filter by category if specified\n if (options.category) {\n aliases = filterAliasesByCategory(aliases, options.category);\n }\n\n // Choose output format\n let output: string;\n if (format === 'llm') {\n output = formatAliasesListLLM(aliases);\n } else if (options.showStatus) {\n output = formatAliasesListWithStatus(aliases, format === 'json' ? 'json' : 'table');\n } else {\n output = formatAliasesList(aliases, format === 'json' ? 'json' : 'table');\n }\n console.log(output);\n return;\n }\n\n if (options.source) {\n // Filter by source\n const sources = registry.getSources().filter(\n (s) => s.name === options.source || s.prefix === options.source\n );\n\n if (sources.length === 0) {\n console.error(chalk.yellow(`No source found matching \"${options.source}\"`));\n return;\n }\n\n const output = formatIconSourceList(sources, format);\n console.log(output);\n return;\n }\n\n // Show all sources\n const sources = registry.getSources();\n const output = formatIconSourceList(sources, format);\n console.log(output);\n } catch (error) {\n console.error(\n chalk.red(`Error: ${error instanceof Error ? error.message : 'Unknown error'}`)\n );\n process.exitCode = ExitCode.GeneralError;\n }\n });\n}\n\n/**\n * Create the icons search subcommand\n */\nfunction createSearchCommand(): Command {\n return new Command('search')\n .description('Search for icons by name or keyword')\n .argument('<query>', 'Search query')\n .option('--format <fmt>', 'Output format (table/json)', 'table')\n .option('-c, --config <path>', 'Config file path')\n .action(async (query: string, options: SearchOptions) => {\n try {\n const registry = await loadRegistry(options.config);\n\n if (!registry.isLoaded()) {\n console.log('No icon registry found.');\n return;\n }\n\n const format = (options.format ?? 'table') as OutputFormat;\n const results = searchIcons(registry, query);\n const output = formatSearchResults(results, format);\n console.log(output);\n } catch (error) {\n console.error(\n chalk.red(`Error: ${error instanceof Error ? error.message : 'Unknown error'}`)\n );\n process.exitCode = ExitCode.GeneralError;\n }\n });\n}\n\n/**\n * Add an alias to the registry file\n */\nexport async function addAliasToRegistry(\n registryPath: string,\n alias: string,\n target: string\n): Promise<void> {\n const content = await fs.readFile(registryPath, 'utf-8');\n const registry = parseYaml(content) as IconRegistry;\n\n // Check if alias already exists\n if (registry.aliases && registry.aliases[alias]) {\n throw new Error(`Alias already exists: ${alias}`);\n }\n\n // Add the new alias\n if (!registry.aliases) {\n registry.aliases = {};\n }\n registry.aliases[alias] = target;\n\n // Write back\n await fs.writeFile(registryPath, stringifyYaml(registry), 'utf-8');\n}\n\n/**\n * Update an existing alias in the registry file (or add if not exists)\n */\nexport async function updateAliasInRegistry(\n registryPath: string,\n alias: string,\n target: string\n): Promise<void> {\n const content = await fs.readFile(registryPath, 'utf-8');\n const registry = parseYaml(content) as IconRegistry;\n\n // Add or update the alias\n if (!registry.aliases) {\n registry.aliases = {};\n }\n registry.aliases[alias] = target;\n\n // Write back\n await fs.writeFile(registryPath, stringifyYaml(registry), 'utf-8');\n}\n\n/**\n * Get registry path from config\n */\nasync function getRegistryPath(configPath?: string): Promise<string> {\n const configLoader = new ConfigLoader();\n\n let resolvedConfigPath = configPath;\n if (!resolvedConfigPath) {\n resolvedConfigPath = await configLoader.findConfig(process.cwd());\n }\n\n if (!resolvedConfigPath) {\n // No config found, use default registry path\n return path.join(process.cwd(), 'icons', 'registry.yaml');\n }\n\n const config = await configLoader.load(resolvedConfigPath);\n\n if (config.icons?.registry) {\n // Make path relative to config file location\n const configDir = path.dirname(resolvedConfigPath);\n return path.resolve(configDir, config.icons.registry);\n }\n\n // Default registry path\n return path.join(process.cwd(), 'icons', 'registry.yaml');\n}\n\n/**\n * Create the icons add subcommand\n */\nfunction createAddCommand(): Command {\n return new Command('add')\n .description('Add an icon alias to registry (fetches and saves locally by default)')\n .argument('<alias>', 'Alias name to add')\n .option('--from <icon>', 'Source icon reference (e.g., health:stethoscope)')\n .option('--search', 'Search for icon interactively')\n .option('--no-save-local', 'Do not save SVG locally (not recommended)')\n .option('-c, --config <path>', 'Config file path')\n .action(async (alias: string, options: AddOptions) => {\n try {\n const registryPath = await getRegistryPath(options.config);\n\n // Check if alias already exists\n const registry = new IconRegistryLoader();\n await registry.load(registryPath);\n\n if (registry.getAliases()[alias]) {\n console.error(chalk.red(`Error: Alias already exists: ${alias}`));\n process.exitCode = ExitCode.GeneralError;\n return;\n }\n\n // Get icon reference\n let iconRef: string;\n if (options.from) {\n iconRef = options.from;\n } else if (options.search) {\n console.error(chalk.yellow('Interactive search not yet implemented. Use --from instead.'));\n process.exitCode = ExitCode.GeneralError;\n return;\n } else {\n console.error(chalk.red('Error: Either --from or --search is required'));\n process.exitCode = ExitCode.GeneralError;\n return;\n }\n\n // Get fetched directory from registry path\n const registryDir = path.dirname(registryPath);\n const fetchedDir = path.join(registryDir, 'fetched');\n\n // Fetch and save\n const fetcher = new IconFetcher({\n fetchedDir,\n saveLocally: options.saveLocal !== false,\n });\n\n const saveLocal = options.saveLocal !== false;\n\n try {\n await fetcher.fetchAndSave(iconRef);\n } catch (error) {\n console.error(chalk.red(`Error fetching icon: ${error instanceof Error ? error.message : 'Unknown error'}`));\n process.exitCode = ExitCode.GeneralError;\n return;\n }\n\n // Determine final reference\n let finalRef: string;\n if (saveLocal) {\n const parsed = fetcher.parseReference(iconRef);\n if (!parsed) {\n console.error(chalk.red(`Invalid icon reference: ${iconRef}`));\n process.exitCode = ExitCode.GeneralError;\n return;\n }\n const setDir = fetcher.getIconifySet(parsed.prefix);\n finalRef = `fetched:${setDir}/${parsed.name}`;\n } else {\n finalRef = iconRef;\n }\n\n // Add to registry\n await addAliasToRegistry(registryPath, alias, finalRef);\n\n if (saveLocal) {\n console.log(chalk.green(`Added alias: ${alias} -> ${finalRef}`));\n console.log(chalk.dim(`SVG saved to: ${fetchedDir}/${fetcher.getIconifySet(fetcher.parseReference(iconRef)!.prefix)}/${fetcher.parseReference(iconRef)!.name}.svg`));\n } else {\n console.log(chalk.yellow(`Added alias: ${alias} -> ${finalRef}`));\n console.log(chalk.yellow('Warning: SVG not saved locally. Project may not be reproducible.'));\n }\n } catch (error) {\n console.error(\n chalk.red(`Error: ${error instanceof Error ? error.message : 'Unknown error'}`)\n );\n process.exitCode = ExitCode.GeneralError;\n }\n });\n}\n\ninterface IconStatus {\n alias: string;\n resolved: string;\n status: 'local' | 'external' | 'missing';\n}\n\n/**\n * Create the icons sync subcommand\n */\nfunction createSyncCommand(): Command {\n return new Command('sync')\n .description('Analyze icon usage and localize external icons')\n .argument('<input>', 'Presentation YAML file')\n .option('--localize', 'Download and save external icons locally')\n .option('-c, --config <path>', 'Config file path')\n .action(async (input: string, options: SyncOptions) => {\n try {\n // Load presentation\n let presentationContent: string;\n try {\n presentationContent = await fs.readFile(input, 'utf-8');\n } catch {\n console.error(chalk.red(`Error: File not found: ${input}`));\n process.exitCode = ExitCode.GeneralError;\n return;\n }\n\n const presentation = parseYaml(presentationContent);\n\n // Load registry\n const registryPath = await getRegistryPath(options.config);\n const registry = new IconRegistryLoader();\n try {\n await registry.load(registryPath);\n } catch {\n console.error(chalk.red('Error: No icon registry found'));\n process.exitCode = ExitCode.GeneralError;\n return;\n }\n\n // Extract icons from presentation\n const usedIcons = extractIconReferences(presentation);\n\n if (usedIcons.length === 0) {\n console.log(chalk.dim('No icons found in presentation.'));\n return;\n }\n\n // Analyze each icon\n const report = {\n local: [] as IconStatus[],\n external: [] as IconStatus[],\n missing: [] as string[],\n };\n\n for (const icon of usedIcons) {\n const resolved = registry.resolveAlias(icon);\n const parsed = registry.parseIconReference(resolved);\n\n if (!parsed) {\n // Not a valid icon reference\n report.missing.push(icon);\n continue;\n }\n\n const source = registry.getSource(parsed.prefix);\n if (!source) {\n report.missing.push(icon);\n continue;\n }\n\n if (isExternalSource(parsed.prefix)) {\n report.external.push({ alias: icon, resolved, status: 'external' });\n } else {\n report.local.push({ alias: icon, resolved, status: 'local' });\n }\n }\n\n // Output report\n console.log(chalk.bold('\\nIcon Sync Report'));\n console.log('─'.repeat(40));\n\n if (report.local.length > 0) {\n console.log(chalk.green(`\\n✓ Local icons (${report.local.length}):`));\n for (const icon of report.local) {\n console.log(` ${icon.alias} -> ${icon.resolved}`);\n }\n }\n\n if (report.external.length > 0) {\n console.log(chalk.yellow(`\\n⚠ External icons (${report.external.length}):`));\n for (const icon of report.external) {\n console.log(` ${icon.alias} -> ${icon.resolved}`);\n }\n }\n\n if (report.missing.length > 0) {\n console.log(chalk.red(`\\n✗ Missing icons (${report.missing.length}):`));\n for (const icon of report.missing) {\n console.log(` ${icon}`);\n }\n }\n\n // Localize external icons if requested\n if (options.localize && report.external.length > 0) {\n console.log(chalk.blue('\\nLocalizing external icons...'));\n\n const registryDir = path.dirname(registryPath);\n const fetchedDir = path.join(registryDir, 'fetched');\n const fetcher = new IconFetcher({ fetchedDir });\n\n for (const icon of report.external) {\n try {\n await fetcher.fetchAndSave(icon.resolved);\n const parsed = registry.parseIconReference(icon.resolved);\n if (parsed) {\n const setDir = fetcher.getIconifySet(parsed.prefix);\n const localRef = `fetched:${setDir}/${parsed.name}`;\n await updateAliasInRegistry(registryPath, icon.alias, localRef);\n console.log(chalk.green(` ✓ ${icon.alias} -> ${localRef}`));\n }\n } catch (error) {\n console.log(chalk.red(` ✗ ${icon.alias}: ${error instanceof Error ? error.message : 'Unknown error'}`));\n }\n }\n\n console.log(chalk.green('\\nDone! External icons have been saved locally.'));\n } else if (report.external.length > 0) {\n console.log(chalk.dim('\\nRun with --localize to save external icons locally.'));\n }\n } catch (error) {\n console.error(\n chalk.red(`Error: ${error instanceof Error ? error.message : 'Unknown error'}`)\n );\n process.exitCode = ExitCode.GeneralError;\n }\n });\n}\n\n/**\n * Create the icons preview subcommand\n */\nfunction createPreviewCommand(): Command {\n return new Command('preview')\n .description('Preview an icon')\n .argument('<name>', 'Icon name or alias')\n .option('--format <fmt>', 'Output format (svg/html)', 'html')\n .option('--size <size>', 'Icon size', '24px')\n .option('--color <color>', 'Icon color', 'currentColor')\n .option('-c, --config <path>', 'Config file path')\n .action(async (name: string, options: PreviewOptions) => {\n try {\n const registry = await loadRegistry(options.config);\n\n if (!registry.isLoaded()) {\n console.error(chalk.red('Error: No icon registry found'));\n process.exitCode = ExitCode.GeneralError;\n return;\n }\n\n const resolver = new IconResolver(registry);\n\n const iconOptions: { size?: string; color?: string } = {};\n if (options.size) {\n iconOptions.size = options.size;\n }\n if (options.color) {\n iconOptions.color = options.color;\n }\n\n const rendered = await resolver.render(name, iconOptions);\n\n if (options.format === 'svg') {\n // Output raw SVG if it's an SVG\n console.log(rendered);\n } else {\n // Wrap in HTML for preview\n const html = `<!DOCTYPE html>\n<html>\n<head>\n <meta charset=\"utf-8\">\n <title>Icon Preview: ${name}</title>\n <link href=\"https://fonts.googleapis.com/icon?family=Material+Icons\" rel=\"stylesheet\">\n <style>\n body {\n display: flex;\n align-items: center;\n justify-content: center;\n min-height: 100vh;\n margin: 0;\n font-family: system-ui, sans-serif;\n background: #f5f5f5;\n }\n .preview {\n padding: 2rem;\n background: white;\n border-radius: 8px;\n box-shadow: 0 2px 8px rgba(0,0,0,0.1);\n text-align: center;\n }\n .icon-container {\n margin-bottom: 1rem;\n }\n .icon-name {\n color: #666;\n font-size: 14px;\n }\n .material-icons {\n font-family: 'Material Icons';\n font-weight: normal;\n font-style: normal;\n display: inline-block;\n line-height: 1;\n text-transform: none;\n letter-spacing: normal;\n word-wrap: normal;\n white-space: nowrap;\n direction: ltr;\n -webkit-font-smoothing: antialiased;\n }\n </style>\n</head>\n<body>\n <div class=\"preview\">\n <div class=\"icon-container\">\n ${rendered}\n </div>\n <div class=\"icon-name\">${name}</div>\n </div>\n</body>\n</html>`;\n console.log(html);\n }\n } catch (error) {\n console.error(\n chalk.red(`Error: ${error instanceof Error ? error.message : 'Unknown error'}`)\n );\n process.exitCode = ExitCode.GeneralError;\n }\n });\n}\n\n/**\n * Create the icons command with subcommands\n */\nexport function createIconsCommand(): Command {\n const cmd = new Command('icons')\n .description('Manage and search icons');\n\n cmd.addCommand(createListCommand());\n cmd.addCommand(createSearchCommand());\n cmd.addCommand(createPreviewCommand());\n cmd.addCommand(createAddCommand());\n cmd.addCommand(createSyncCommand());\n\n return cmd;\n}\n","import * as fs from \"node:fs/promises\";\nimport * as path from \"node:path\";\nimport { stringify as stringifyYaml, parse as parseYaml } from \"yaml\";\n\n/**\n * Options for the IconFetcher\n */\nexport interface FetcherOptions {\n /** Directory to save fetched icons (default: icons/fetched) */\n fetchedDir?: string;\n /** Whether to save icons locally (default: true) */\n saveLocally?: boolean;\n /** Timeout for fetch requests in milliseconds (default: 10000) */\n timeoutMs?: number;\n}\n\n/**\n * Parsed icon reference\n */\nexport interface ParsedReference {\n prefix: string;\n name: string;\n}\n\n/**\n * Source entry in _sources.yaml\n */\ninterface SourceEntry {\n source: string;\n fetched_at: string;\n license: string;\n}\n\n/**\n * Icon source configuration\n */\nexport interface IconSourceConfig {\n /** Iconify set name */\n set: string;\n /** License identifier */\n license: string;\n /** Whether this source requires external fetching */\n external: boolean;\n}\n\n/**\n * Unified icon source definitions\n * Single source of truth for prefix mappings, licenses, and external status\n */\nexport const ICON_SOURCES: Record<string, IconSourceConfig> = {\n health: { set: \"healthicons\", license: \"MIT\", external: true },\n ms: { set: \"material-symbols\", license: \"Apache-2.0\", external: true },\n hero: { set: \"heroicons\", license: \"MIT\", external: true },\n mi: { set: \"material-icons\", license: \"Apache-2.0\", external: false },\n mdi: { set: \"mdi\", license: \"Apache-2.0\", external: true },\n iconify: { set: \"iconify\", license: \"Various\", external: true },\n};\n\n/**\n * Check if a source prefix requires external fetching\n */\nexport function isExternalSource(prefix: string): boolean {\n return ICON_SOURCES[prefix]?.external ?? false;\n}\n\n/**\n * Valid icon name pattern\n * Allows: lowercase letters, numbers, hyphens\n * Must start with a letter or number, cannot end with hyphen\n * Also allows forward slash for subdirectory paths (e.g., healthicons/stethoscope)\n */\nconst VALID_ICON_NAME = /^[a-z0-9][a-z0-9-]*[a-z0-9]$|^[a-z0-9]$/i;\nconst VALID_ICON_NAME_WITH_PATH = /^[a-z0-9][a-z0-9-/]*[a-z0-9]$|^[a-z0-9]$/i;\n\n/**\n * Validate icon name format\n */\nexport function isValidIconName(name: string, allowPath = false): boolean {\n if (!name || name.length > 100) {\n return false;\n }\n // Prevent path traversal\n if (name.includes(\"..\") || name.startsWith(\"/\") || name.endsWith(\"/\")) {\n return false;\n }\n const pattern = allowPath ? VALID_ICON_NAME_WITH_PATH : VALID_ICON_NAME;\n return pattern.test(name);\n}\n\n/**\n * IconFetcher - Fetches icons from external sources and saves them locally\n *\n * Icons are fetched from the Iconify API and saved to the local filesystem\n * for offline use and reproducibility.\n */\nexport class IconFetcher {\n private fetchedDir: string;\n private saveLocally: boolean;\n private timeoutMs: number;\n\n constructor(options: FetcherOptions = {}) {\n this.fetchedDir = options.fetchedDir ?? \"icons/fetched\";\n this.saveLocally = options.saveLocally ?? true;\n this.timeoutMs = options.timeoutMs ?? 10000;\n }\n\n /**\n * Parse an icon reference string (e.g., \"health:stethoscope\")\n * Returns null if the format is invalid or contains unsafe characters\n */\n parseReference(iconRef: string): ParsedReference | null {\n const colonIndex = iconRef.indexOf(\":\");\n if (colonIndex === -1) {\n return null;\n }\n\n const prefix = iconRef.substring(0, colonIndex);\n const name = iconRef.substring(colonIndex + 1);\n\n // Validate prefix (alphanumeric only)\n if (!/^[a-z0-9]+$/i.test(prefix)) {\n return null;\n }\n\n // Validate icon name\n if (!isValidIconName(name)) {\n return null;\n }\n\n return { prefix, name };\n }\n\n /**\n * Get the Iconify set name for a prefix\n */\n getIconifySet(prefix: string): string {\n return ICON_SOURCES[prefix]?.set ?? prefix;\n }\n\n /**\n * Get the local file path for an icon reference\n */\n getLocalPath(iconRef: string): string {\n const parsed = this.parseReference(iconRef);\n if (!parsed) {\n throw new Error(`Invalid icon reference: ${iconRef}`);\n }\n\n const setDir = this.getIconifySet(parsed.prefix);\n return path.join(this.fetchedDir, setDir, `${parsed.name}.svg`);\n }\n\n /**\n * Check if an icon exists locally\n */\n async existsLocally(iconRef: string): Promise<boolean> {\n const localPath = this.getLocalPath(iconRef);\n try {\n await fs.access(localPath);\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * Build the Iconify API URL for an icon\n */\n buildUrl(prefix: string, name: string): string {\n const set = this.getIconifySet(prefix);\n return `https://api.iconify.design/${set}/${name}.svg`;\n }\n\n /**\n * Resolve an icon reference (local first, then fetch)\n */\n async resolve(iconRef: string): Promise<string> {\n // Check if already exists locally\n if (await this.existsLocally(iconRef)) {\n const localPath = this.getLocalPath(iconRef);\n return await fs.readFile(localPath, \"utf-8\");\n }\n\n // Fetch and optionally save\n return await this.fetchAndSave(iconRef);\n }\n\n /**\n * Fetch an icon from external source and save locally\n */\n async fetchAndSave(iconRef: string): Promise<string> {\n const parsed = this.parseReference(iconRef);\n if (!parsed) {\n throw new Error(`Invalid icon reference: ${iconRef}`);\n }\n\n const url = this.buildUrl(parsed.prefix, parsed.name);\n\n // Fetch the icon with timeout\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeoutMs);\n\n let response: Response;\n try {\n response = await fetch(url, { signal: controller.signal });\n } catch (error) {\n if (error instanceof Error && error.name === \"AbortError\") {\n throw new Error(`Fetch timeout: ${iconRef} (exceeded ${this.timeoutMs}ms)`);\n }\n throw error;\n } finally {\n clearTimeout(timeoutId);\n }\n\n if (!response.ok) {\n throw new Error(`Icon not found: ${iconRef} (HTTP ${response.status})`);\n }\n\n const svg = await response.text();\n\n // Save locally if enabled\n if (this.saveLocally) {\n await this.saveLocallyInternal(parsed.prefix, parsed.name, svg, url);\n }\n\n return svg;\n }\n\n /**\n * Save icon to local filesystem\n */\n private async saveLocallyInternal(\n prefix: string,\n name: string,\n svg: string,\n sourceUrl: string\n ): Promise<void> {\n const setDir = this.getIconifySet(prefix);\n const dirPath = path.join(this.fetchedDir, setDir);\n const filePath = path.join(dirPath, `${name}.svg`);\n\n // Create directory\n await fs.mkdir(dirPath, { recursive: true });\n\n // Save SVG\n await fs.writeFile(filePath, svg, \"utf-8\");\n\n // Update _sources.yaml\n await this.updateSourcesYaml(setDir, name, sourceUrl);\n }\n\n /**\n * Update _sources.yaml with source information\n */\n private async updateSourcesYaml(\n setDir: string,\n name: string,\n sourceUrl: string\n ): Promise<void> {\n const sourcesPath = path.join(this.fetchedDir, \"_sources.yaml\");\n let sources: Record<string, SourceEntry> = {};\n\n try {\n const content = await fs.readFile(sourcesPath, \"utf-8\");\n sources = (parseYaml(content) as Record<string, SourceEntry>) ?? {};\n } catch {\n // File doesn't exist, start fresh\n }\n\n const key = `${setDir}/${name}.svg`;\n sources[key] = {\n source: sourceUrl,\n fetched_at: new Date().toISOString(),\n license: this.getLicense(setDir),\n };\n\n // Add header comment\n const header = `# Fetched icon sources\\n# This file tracks where icons were fetched from for traceability\\n\\n`;\n await fs.writeFile(sourcesPath, header + stringifyYaml(sources), \"utf-8\");\n }\n\n /**\n * Get the license for an icon set\n */\n private getLicense(setDir: string): string {\n // Find license by set name\n for (const config of Object.values(ICON_SOURCES)) {\n if (config.set === setDir) {\n return config.license;\n }\n }\n return \"Unknown\";\n }\n}\n","import { Command } from 'commander';\nimport { mkdir, writeFile, access, readdir, cp } from 'fs/promises';\nimport { existsSync } from 'fs';\nimport { execSync, spawnSync } from 'child_process';\nimport { createInterface } from 'readline';\nimport { basename, dirname, join, resolve, sep } from 'path';\nimport { fileURLToPath } from 'url';\nimport chalk from 'chalk';\nimport ora from 'ora';\nimport { ExitCode } from './convert.js';\nimport { SourcesManager } from '../../sources/manager.js';\nimport { SourceImporter } from '../../sources/importer.js';\nimport {\n generateSkillMd,\n generateClaudeMd,\n generateAgentsMd,\n generateOpenCodeAgent,\n generateTemplatesRef,\n generateWorkflowsRef,\n generateSlideCreateCommand,\n generateSlideValidateCommand,\n generateSlidePreviewCommand,\n generateSlideScreenshotCommand,\n generateSlideThemeCommand,\n} from '../templates/ai';\n\nexport interface InitOptions {\n template?: string;\n examples?: boolean;\n aiConfig?: boolean;\n sources?: boolean;\n fromDirectory?: string;\n skipMarpInstall?: boolean;\n}\n\n/**\n * Get the package root directory\n * Works for both bundled (dist/cli/index.js) and source (src/cli/commands/init.ts)\n */\nfunction getPackageRoot(): string {\n const __dirname = dirname(fileURLToPath(import.meta.url));\n\n // Check if we're in source (src/) or bundled (dist/)\n // Use path separator agnostic check for Windows compatibility\n if (__dirname.includes(`${sep}src${sep}`) || __dirname.includes('/src/')) {\n // Source: go up from src/cli/commands to package root\n return join(__dirname, '..', '..', '..');\n }\n // Bundled: go up from dist/cli to package root\n return join(__dirname, '..', '..');\n}\n\n/**\n * Create the init command\n */\nexport function createInitCommand(): Command {\n return new Command('init')\n .description('Initialize a new project')\n .argument('[directory]', 'Target directory', '.')\n .option('--template <name>', 'Initial template')\n .option('--no-examples', 'Do not create sample files')\n .option('--no-ai-config', 'Do not create AI assistant config files')\n .option('--no-sources', 'Do not create sources directory')\n .option('--from-directory <path>', 'Import materials from directory')\n .option('--skip-marp-install', 'Skip Marp CLI installation prompt')\n .action(async (directory: string, options: InitOptions) => {\n await executeInit(directory, options);\n });\n}\n\n/**\n * Execute the init command\n */\nexport async function executeInit(\n directory: string,\n options: InitOptions\n): Promise<void> {\n const spinner = ora();\n const targetDir = resolve(directory);\n const includeExamples = options.examples !== false;\n const includeAiConfig = options.aiConfig !== false;\n const includeSources = options.sources !== false;\n\n try {\n spinner.start(`Initializing project in ${targetDir}...`);\n\n // Check if directory exists and has content\n try {\n await access(targetDir);\n const entries = await readdir(targetDir);\n if (entries.length > 0) {\n spinner.info(`Directory ${targetDir} already exists, adding files...`);\n }\n } catch {\n // Directory doesn't exist, will be created\n }\n\n // Create directory structure\n await mkdir(targetDir, { recursive: true });\n await mkdir(join(targetDir, 'themes'), { recursive: true });\n await mkdir(join(targetDir, 'icons', 'custom'), { recursive: true });\n\n // Copy built-in templates and icons registry from package\n const packageRoot = getPackageRoot();\n\n // Copy templates\n const sourceTemplatesDir = join(packageRoot, 'templates');\n const targetTemplatesDir = join(targetDir, 'templates');\n\n try {\n await access(targetTemplatesDir);\n // Templates directory already exists, skip copying\n } catch {\n // Templates directory doesn't exist, copy from package\n await cp(sourceTemplatesDir, targetTemplatesDir, { recursive: true });\n }\n\n // Copy icons registry\n const sourceIconsRegistry = join(packageRoot, 'icons', 'registry.yaml');\n const targetIconsRegistry = join(targetDir, 'icons', 'registry.yaml');\n await copyFileIfNotExists(sourceIconsRegistry, targetIconsRegistry);\n\n // Copy default theme\n const sourceDefaultTheme = join(packageRoot, 'themes', 'default.css');\n const targetDefaultTheme = join(targetDir, 'themes', 'default.css');\n await copyFileIfNotExists(sourceDefaultTheme, targetDefaultTheme);\n\n // Create config.yaml\n const configContent = generateConfigContent();\n await writeFileIfNotExists(join(targetDir, 'config.yaml'), configContent);\n\n // Create themes/custom.css\n const customCssContent = generateCustomCssContent();\n await writeFileIfNotExists(join(targetDir, 'themes', 'custom.css'), customCssContent);\n\n // Create sample files if examples are enabled\n if (includeExamples) {\n const presentationContent = generatePresentationContent(options.template);\n await writeFileIfNotExists(join(targetDir, 'presentation.yaml'), presentationContent);\n }\n\n // Create AI config files\n if (includeAiConfig) {\n await generateAiConfig(targetDir);\n }\n\n // Create sources directory\n let sourcesImported = 0;\n if (includeSources) {\n const sourcesManager = new SourcesManager(targetDir);\n if (!(await sourcesManager.exists())) {\n await sourcesManager.init({\n name: 'Untitled Project',\n setup_pattern: options.fromDirectory ? 'A' : undefined,\n original_source: options.fromDirectory ? resolve(options.fromDirectory) : undefined,\n });\n\n // Import from directory if specified\n if (options.fromDirectory) {\n const importer = new SourceImporter(targetDir, sourcesManager);\n const result = await importer.importDirectory(resolve(options.fromDirectory), {\n recursive: true,\n });\n sourcesImported = result.imported;\n }\n }\n }\n\n spinner.succeed(`Project initialized in ${targetDir}`);\n\n // Print summary\n console.log('');\n console.log(chalk.green('Created files:'));\n console.log(` ${chalk.cyan('config.yaml')} - Project configuration`);\n console.log(` ${chalk.cyan('templates/')} - Slide templates`);\n console.log(` ${chalk.cyan('themes/default.css')} - Default theme`);\n console.log(` ${chalk.cyan('themes/custom.css')} - Custom theme styles`);\n console.log(` ${chalk.cyan('icons/registry.yaml')} - Icon registry`);\n console.log(` ${chalk.cyan('icons/custom/')} - Custom icons directory`);\n if (includeExamples) {\n console.log(` ${chalk.cyan('presentation.yaml')} - Sample presentation`);\n }\n if (includeAiConfig) {\n console.log(` ${chalk.cyan('.skills/')} - AgentSkills configuration`);\n console.log(` ${chalk.cyan('CLAUDE.md')} - Claude Code configuration`);\n console.log(` ${chalk.cyan('AGENTS.md')} - OpenCode configuration`);\n console.log(` ${chalk.cyan('.cursorrules')} - Cursor configuration`);\n console.log(` ${chalk.cyan('.claude/commands/')} - Claude Code slash commands`);\n console.log(` ${chalk.cyan('.opencode/agent/')} - OpenCode agent configuration`);\n }\n if (includeSources) {\n let sourcesMsg = ` ${chalk.cyan('sources/')} - Source materials directory`;\n if (sourcesImported > 0) {\n sourcesMsg += ` (${sourcesImported} files imported)`;\n }\n console.log(sourcesMsg);\n }\n console.log('');\n console.log(chalk.blue('Next steps:'));\n console.log(` 1. Edit ${chalk.yellow('presentation.yaml')} to add your slides`);\n console.log(` 2. Run ${chalk.yellow('slide-gen convert presentation.yaml')} to generate markdown`);\n\n // Show Marp CLI installation info if not skipped\n if (options.skipMarpInstall !== true) {\n await showMarpCliInfo(targetDir);\n }\n } catch (error) {\n spinner.fail('Failed to initialize project');\n console.error(\n chalk.red(`Error: ${error instanceof Error ? error.message : 'Unknown error'}`)\n );\n process.exitCode = ExitCode.GeneralError;\n }\n}\n\n/**\n * Write file only if it doesn't exist\n */\nasync function writeFileIfNotExists(filePath: string, content: string): Promise<void> {\n try {\n await access(filePath);\n // File exists, skip\n } catch {\n // File doesn't exist, create it\n await writeFile(filePath, content, 'utf-8');\n }\n}\n\n/**\n * Copy file only if destination doesn't exist\n */\nasync function copyFileIfNotExists(source: string, dest: string): Promise<void> {\n try {\n await access(dest);\n // File exists, skip\n } catch {\n // File doesn't exist, copy from source\n await cp(source, dest);\n }\n}\n\n/**\n * Check if Marp CLI is installed globally\n * Uses 'marp --version' directly\n */\nexport function isMarpCliInstalledGlobally(): boolean {\n try {\n execSync('marp --version', { stdio: 'pipe', timeout: 5000 });\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Check if Marp CLI is installed locally in the project\n * Checks node_modules/.bin/marp\n */\nexport function isMarpCliInstalledLocally(targetDir?: string): boolean {\n const dir = targetDir ?? process.cwd();\n const marpBinPath = join(dir, 'node_modules', '.bin', 'marp');\n return existsSync(marpBinPath);\n}\n\n/**\n * Check if Marp CLI is available (either globally or locally)\n * @deprecated Use isMarpCliInstalledGlobally() or isMarpCliInstalledLocally() for specific checks\n */\nexport function isMarpCliInstalled(): boolean {\n return isMarpCliInstalledGlobally();\n}\n\n/**\n * Detect package manager from lock files\n */\nexport function detectPackageManager(targetDir?: string): 'pnpm' | 'yarn' | 'npm' {\n const dir = targetDir ?? process.cwd();\n if (existsSync(join(dir, 'pnpm-lock.yaml'))) return 'pnpm';\n if (existsSync(join(dir, 'yarn.lock'))) return 'yarn';\n return 'npm';\n}\n\n/**\n * Get the install command for Marp CLI based on package manager\n */\nexport function getMarpInstallCommand(pm: 'pnpm' | 'yarn' | 'npm'): string {\n switch (pm) {\n case 'pnpm':\n return 'pnpm add -D @marp-team/marp-cli';\n case 'yarn':\n return 'yarn add -D @marp-team/marp-cli';\n default:\n return 'npm install -D @marp-team/marp-cli';\n }\n}\n\n/**\n * Installation choice for Marp CLI\n */\nexport type MarpInstallChoice = 'global' | 'local' | 'skip';\n\n/**\n * Prompt user for Marp CLI installation choice\n * Returns 'global', 'local', or 'skip'\n */\nexport async function promptMarpInstallChoice(): Promise<MarpInstallChoice> {\n // Check if running in non-interactive mode (CI, piped input, etc.)\n if (!process.stdin.isTTY) {\n return 'skip';\n }\n\n const rl = createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n\n console.log('How would you like to install Marp CLI?');\n console.log(` ${chalk.cyan('1)')} Global install ${chalk.dim('(recommended - works everywhere)')}`);\n console.log(` ${chalk.cyan('2)')} Local install ${chalk.dim('(creates package.json)')}`);\n console.log(` ${chalk.cyan('3)')} Skip ${chalk.dim(\"(I'll install it later)\")}`);\n console.log('');\n\n return new Promise((resolve) => {\n rl.question('Choice [1]: ', (answer) => {\n rl.close();\n const normalized = answer.trim();\n if (normalized === '' || normalized === '1') {\n resolve('global');\n } else if (normalized === '2') {\n resolve('local');\n } else {\n resolve('skip');\n }\n });\n });\n}\n\n/**\n * Install Marp CLI globally\n * Returns true if installation succeeded\n */\nexport function installMarpCliGlobally(): boolean {\n const spinner = ora('Installing Marp CLI globally...').start();\n\n try {\n const result = spawnSync('npm', ['install', '-g', '@marp-team/marp-cli'], {\n stdio: 'pipe',\n shell: true,\n timeout: 120000, // 2 minutes timeout\n });\n\n if (result.status === 0) {\n spinner.succeed('Marp CLI installed globally');\n return true;\n } else {\n const stderr = result.stderr?.toString() || 'Unknown error';\n spinner.fail(`Failed to install Marp CLI: ${stderr}`);\n console.log(chalk.dim('You can install it manually with: npm install -g @marp-team/marp-cli'));\n return false;\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Unknown error';\n spinner.fail(`Failed to install Marp CLI: ${message}`);\n console.log(chalk.dim('You can install it manually with: npm install -g @marp-team/marp-cli'));\n return false;\n }\n}\n\n/**\n * Install Marp CLI locally (creates package.json if needed)\n * Returns true if installation succeeded\n */\nexport async function installMarpCliLocally(targetDir: string): Promise<boolean> {\n const pm = detectPackageManager(targetDir);\n const installCmd = getMarpInstallCommand(pm);\n\n // Create package.json if it doesn't exist\n const packageJsonPath = join(targetDir, 'package.json');\n if (!existsSync(packageJsonPath)) {\n const packageJsonContent = generatePackageJsonContent(targetDir);\n await writeFile(packageJsonPath, packageJsonContent, 'utf-8');\n }\n\n const spinner = ora(`Installing Marp CLI locally with ${pm}...`).start();\n\n try {\n const result = spawnSync(pm, ['add', '-D', '@marp-team/marp-cli'], {\n cwd: targetDir,\n stdio: 'pipe',\n shell: true,\n timeout: 120000, // 2 minutes timeout\n });\n\n if (result.status === 0) {\n spinner.succeed('Marp CLI installed locally');\n return true;\n } else {\n const stderr = result.stderr?.toString() || 'Unknown error';\n spinner.fail(`Failed to install Marp CLI: ${stderr}`);\n console.log(chalk.dim(`You can install it manually with: ${installCmd}`));\n return false;\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Unknown error';\n spinner.fail(`Failed to install Marp CLI: ${message}`);\n console.log(chalk.dim(`You can install it manually with: ${installCmd}`));\n return false;\n }\n}\n\n/**\n * Generate minimal package.json content for the project\n */\nfunction generatePackageJsonContent(targetDir: string): string {\n const projectName = basename(targetDir) || 'my-presentation';\n return JSON.stringify(\n {\n name: projectName,\n version: '1.0.0',\n private: true,\n description: 'Presentation project created with slide-gen',\n scripts: {\n preview: 'slide-gen preview presentation.yaml',\n build: 'slide-gen convert presentation.yaml',\n },\n },\n null,\n 2\n );\n}\n\n/**\n * Show Marp CLI installation information and optionally install\n * Returns true if Marp CLI is available after this function completes\n */\nasync function showMarpCliInfo(targetDir: string): Promise<boolean> {\n // Check if already installed (globally or locally)\n if (isMarpCliInstalledGlobally() || isMarpCliInstalledLocally(targetDir)) {\n console.log('');\n console.log(chalk.green('✓') + ' Marp CLI is available');\n return true;\n }\n\n console.log('');\n console.log(chalk.dim('─'.repeat(45)));\n console.log(chalk.yellow('Marp CLI is recommended for full features:'));\n console.log(' • Preview slides in browser');\n console.log(' • Take screenshots for AI review');\n console.log(' • Export to PDF/HTML/PPTX');\n console.log('');\n console.log(chalk.dim('Marp CLI is not currently installed.'));\n console.log(chalk.dim('─'.repeat(45)));\n console.log('');\n\n // Prompt for installation choice\n const choice = await promptMarpInstallChoice();\n\n switch (choice) {\n case 'global':\n return installMarpCliGlobally();\n case 'local':\n return await installMarpCliLocally(targetDir);\n case 'skip':\n default:\n console.log('');\n console.log(chalk.dim('You can install Marp CLI later with:'));\n console.log(` ${chalk.cyan('npm install -g @marp-team/marp-cli')} ${chalk.dim('(global)')}`);\n console.log(` ${chalk.cyan('npm install -D @marp-team/marp-cli')} ${chalk.dim('(local)')}`);\n return false;\n }\n}\n\n/**\n * Generate AI configuration files\n */\nasync function generateAiConfig(targetDir: string): Promise<void> {\n // Create directories\n await mkdir(join(targetDir, '.skills', 'slide-assistant', 'references'), { recursive: true });\n await mkdir(join(targetDir, '.skills', 'slide-assistant', 'scripts'), { recursive: true });\n await mkdir(join(targetDir, '.claude', 'commands'), { recursive: true });\n await mkdir(join(targetDir, '.opencode', 'agent'), { recursive: true });\n\n // Generate AgentSkills (common)\n await writeFileIfNotExists(\n join(targetDir, '.skills', 'slide-assistant', 'SKILL.md'),\n generateSkillMd()\n );\n await writeFileIfNotExists(\n join(targetDir, '.skills', 'slide-assistant', 'references', 'templates.md'),\n generateTemplatesRef()\n );\n await writeFileIfNotExists(\n join(targetDir, '.skills', 'slide-assistant', 'references', 'workflows.md'),\n generateWorkflowsRef()\n );\n\n // Generate Claude Code files\n await writeFileIfNotExists(join(targetDir, 'CLAUDE.md'), generateClaudeMd());\n\n // Generate commands\n const commandGenerators: Record<string, () => string> = {\n 'slide-create': generateSlideCreateCommand,\n 'slide-validate': generateSlideValidateCommand,\n 'slide-preview': generateSlidePreviewCommand,\n 'slide-screenshot': generateSlideScreenshotCommand,\n 'slide-theme': generateSlideThemeCommand,\n };\n for (const [name, generator] of Object.entries(commandGenerators)) {\n await writeFileIfNotExists(\n join(targetDir, '.claude', 'commands', `${name}.md`),\n generator()\n );\n }\n\n // Generate OpenCode files\n await writeFileIfNotExists(join(targetDir, 'AGENTS.md'), generateAgentsMd());\n await writeFileIfNotExists(\n join(targetDir, '.opencode', 'agent', 'slide.md'),\n generateOpenCodeAgent()\n );\n\n // Generate Cursor files (same as AGENTS.md)\n await writeFileIfNotExists(join(targetDir, '.cursorrules'), generateAgentsMd());\n}\n\n/**\n * Generate config.yaml content\n */\nfunction generateConfigContent(): string {\n return `# slide-gen configuration\n# See https://github.com/example/slide-generation for documentation\n\ntemplates:\n # Path to built-in templates (relative to project root)\n builtin: ./templates\n # Path to custom templates (optional)\n # custom: ./my-templates\n\nicons:\n # Path to icon registry file\n registry: ./icons/registry.yaml\n cache:\n enabled: true\n directory: .cache/icons\n ttl: 86400\n\nreferences:\n enabled: true\n connection:\n type: cli\n command: ref\n format:\n locale: ja-JP\n\noutput:\n theme: default\n inlineStyles: false\n`;\n}\n\n/**\n * Generate custom CSS content\n */\nfunction generateCustomCssContent(): string {\n return `/* Custom Marp theme styles */\n/* See https://marpit.marp.app/theme-css for documentation */\n\n/*\nsection {\n background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);\n color: #fff;\n}\n\nh1 {\n color: #fff;\n text-shadow: 2px 2px 4px rgba(0,0,0,0.3);\n}\n*/\n`;\n}\n\n/**\n * Generate sample presentation content\n */\nfunction generatePresentationContent(_template?: string): string {\n const baseContent = `# Sample Presentation\n# Generated by slide-gen init\n\nmeta:\n title: My Presentation\n author: Your Name\n date: \"${new Date().toISOString().split('T')[0]}\"\n theme: default\n\nslides:\n - template: title\n content:\n title: My Presentation\n subtitle: A sample slide deck\n\n - template: bullet-list\n content:\n title: Introduction\n items:\n - Welcome to this presentation!\n - Point one\n - Point two\n - Point three\n\n - template: section\n content:\n title: Section Title\n subtitle: Section description\n\n - template: bullet-list\n content:\n title: Main Content\n items:\n - Here's the main content of your presentation.\n - You can use **markdown** formatting in the body text.\n\n - template: section\n content:\n title: Thank You\n subtitle: Questions?\n`;\n\n return baseContent;\n}\n","import * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport { parse, stringify } from 'yaml';\nimport {\n sourcesYamlSchema,\n type SourcesYaml,\n type SourceEntry,\n type Context,\n type MissingItem,\n type Project,\n} from './schema.js';\n\n/**\n * Manages the sources.yaml file and sources directory structure\n */\nexport class SourcesManager {\n private sourcesDir: string;\n private sourcesYamlPath: string;\n\n /**\n * Standard subdirectories for source materials\n */\n private static readonly SUBDIRECTORIES = [\n 'scenario',\n 'content',\n 'materials',\n 'data',\n 'conversation',\n ];\n\n constructor(projectDir: string) {\n this.sourcesDir = path.join(projectDir, 'sources');\n this.sourcesYamlPath = path.join(this.sourcesDir, 'sources.yaml');\n }\n\n /**\n * Get the sources directory path\n */\n getSourcesDir(): string {\n return this.sourcesDir;\n }\n\n /**\n * Get the sources.yaml file path\n */\n getSourcesYamlPath(): string {\n return this.sourcesYamlPath;\n }\n\n /**\n * Check if sources.yaml exists\n */\n async exists(): Promise<boolean> {\n try {\n await fs.access(this.sourcesYamlPath);\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * Initialize the sources directory and sources.yaml\n */\n async init(project: Partial<Project> & { name: string }): Promise<void> {\n // Create sources directory\n await fs.mkdir(this.sourcesDir, { recursive: true });\n\n // Create subdirectories\n for (const subdir of SourcesManager.SUBDIRECTORIES) {\n await fs.mkdir(path.join(this.sourcesDir, subdir), { recursive: true });\n }\n\n // Get current date in YYYY-MM-DD format\n const today = new Date().toISOString().split('T')[0];\n\n // Create initial sources.yaml\n const data: SourcesYaml = {\n project: {\n name: project.name,\n purpose: project.purpose,\n created: today,\n updated: today,\n setup_pattern: project.setup_pattern,\n original_source: project.original_source,\n },\n };\n\n await this.save(data);\n }\n\n /**\n * Load sources.yaml\n */\n async load(): Promise<SourcesYaml> {\n const content = await fs.readFile(this.sourcesYamlPath, 'utf-8');\n const rawData = parse(content);\n const result = sourcesYamlSchema.safeParse(rawData);\n\n if (!result.success) {\n throw new Error(`Invalid sources.yaml: ${result.error.message}`);\n }\n\n return result.data;\n }\n\n /**\n * Save data to sources.yaml\n */\n async save(data: SourcesYaml): Promise<void> {\n // Update the updated date\n const today = new Date().toISOString().split('T')[0];\n data.project.updated = today;\n\n // Validate before saving\n const result = sourcesYamlSchema.safeParse(data);\n if (!result.success) {\n throw new Error(`Invalid sources.yaml data: ${result.error.message}`);\n }\n\n const content = stringify(data, {\n lineWidth: 0, // Disable line wrapping\n });\n\n await fs.writeFile(this.sourcesYamlPath, content, 'utf-8');\n }\n\n /**\n * Add or update a source entry\n */\n async addSource(entry: SourceEntry): Promise<void> {\n const data = await this.load();\n\n if (!data.sources) {\n data.sources = [];\n }\n\n // Check if entry with same id exists\n const existingIndex = data.sources.findIndex((s) => s.id === entry.id);\n if (existingIndex >= 0) {\n // Replace existing entry\n data.sources[existingIndex] = entry;\n } else {\n // Add new entry\n data.sources.push(entry);\n }\n\n await this.save(data);\n }\n\n /**\n * Remove a source entry by id\n */\n async removeSource(id: string): Promise<void> {\n const data = await this.load();\n\n if (data.sources) {\n data.sources = data.sources.filter((s) => s.id !== id);\n }\n\n await this.save(data);\n }\n\n /**\n * Get a source entry by id\n */\n async getSource(id: string): Promise<SourceEntry | undefined> {\n const data = await this.load();\n return data.sources?.find((s) => s.id === id);\n }\n\n /**\n * Update context (merges with existing)\n */\n async updateContext(context: Partial<Context>): Promise<void> {\n const data = await this.load();\n\n data.context = {\n ...data.context,\n ...context,\n };\n\n await this.save(data);\n }\n\n /**\n * Add a missing item\n */\n async addMissing(item: MissingItem): Promise<void> {\n const data = await this.load();\n\n if (!data.missing) {\n data.missing = [];\n }\n\n // Check if item already exists\n const existingIndex = data.missing.findIndex((m) => m.item === item.item);\n if (existingIndex >= 0) {\n data.missing[existingIndex] = item;\n } else {\n data.missing.push(item);\n }\n\n await this.save(data);\n }\n\n /**\n * Remove a missing item (mark as resolved)\n */\n async resolveMissing(itemName: string): Promise<void> {\n const data = await this.load();\n\n if (data.missing) {\n data.missing = data.missing.filter((m) => m.item !== itemName);\n }\n\n await this.save(data);\n }\n\n /**\n * Get all missing items\n */\n async getMissing(): Promise<MissingItem[]> {\n const data = await this.load();\n return data.missing ?? [];\n }\n\n /**\n * Get all sources of a specific type\n */\n async getSourcesByType(type: SourceEntry['type']): Promise<SourceEntry[]> {\n const data = await this.load();\n return data.sources?.filter((s) => s.type === type) ?? [];\n }\n}\n","import { z } from 'zod';\n\n/**\n * Source type schema\n * Defines the types of source materials that can be tracked\n */\nexport const sourceTypeSchema = z.enum([\n 'scenario', // Scenario/structure files\n 'content', // Content scripts\n 'material', // Reference materials\n 'data', // Data/numbers\n 'conversation', // AI conversation logs\n]);\n\nexport type SourceType = z.infer<typeof sourceTypeSchema>;\n\n/**\n * Source status schema\n * Defines the status of a source material\n */\nexport const sourceStatusSchema = z.enum([\n 'draft', // Work in progress\n 'final', // Finalized\n 'reference', // Reference material (not directly used)\n 'archived', // Archived/historical\n]);\n\nexport type SourceStatus = z.infer<typeof sourceStatusSchema>;\n\n/**\n * Audience schema\n * Describes the target audience for the presentation\n */\nexport const audienceSchema = z.object({\n type: z.string(),\n size: z.string().optional(),\n knowledge_level: z.string().optional(),\n concerns: z.array(z.string()).optional(),\n});\n\nexport type Audience = z.infer<typeof audienceSchema>;\n\n/**\n * Constraints schema\n * Defines constraints for the presentation\n */\nexport const constraintsSchema = z.object({\n duration: z.string().optional(),\n format: z.string().optional(),\n style: z.string().optional(),\n});\n\nexport type Constraints = z.infer<typeof constraintsSchema>;\n\n/**\n * Context schema\n * Contains presentation context information\n */\nexport const contextSchema = z.object({\n objective: z.string().optional(),\n audience: audienceSchema.optional(),\n key_messages: z.array(z.string()).optional(),\n constraints: constraintsSchema.optional(),\n});\n\nexport type Context = z.infer<typeof contextSchema>;\n\n/**\n * Source entry schema\n * Represents a single source material entry\n */\nexport const sourceEntrySchema = z.object({\n id: z.string(),\n type: sourceTypeSchema,\n path: z.string(),\n status: sourceStatusSchema.optional(),\n origin: z.string().optional(),\n description: z.string().optional(),\n notes: z.string().optional(),\n extracted_data: z.array(z.string()).optional(),\n decisions: z.array(z.string()).optional(),\n});\n\nexport type SourceEntry = z.infer<typeof sourceEntrySchema>;\n\n/**\n * Project schema\n * Contains project metadata\n */\nexport const projectSchema = z.object({\n name: z.string(),\n purpose: z.string().optional(),\n created: z.string().optional(),\n updated: z.string().optional(),\n setup_pattern: z.enum(['A', 'B', 'C']).optional(),\n original_source: z.string().optional(),\n});\n\nexport type Project = z.infer<typeof projectSchema>;\n\n/**\n * Dependency schema\n * Tracks which sources a file is derived from\n */\nexport const dependencySchema = z.object({\n derived_from: z.array(z.string()),\n});\n\nexport type Dependency = z.infer<typeof dependencySchema>;\n\n/**\n * Missing item schema\n * Tracks missing information needed for the presentation\n */\nexport const missingItemSchema = z.object({\n item: z.string(),\n needed_for: z.string().optional(),\n status: z.string().optional(),\n notes: z.string().optional(),\n});\n\nexport type MissingItem = z.infer<typeof missingItemSchema>;\n\n/**\n * Sources YAML schema\n * The main schema for sources.yaml file\n */\nexport const sourcesYamlSchema = z.object({\n project: projectSchema,\n context: contextSchema.optional(),\n sources: z.array(sourceEntrySchema).optional(),\n dependencies: z.record(dependencySchema).optional(),\n missing: z.array(missingItemSchema).optional(),\n});\n\nexport type SourcesYaml = z.infer<typeof sourcesYamlSchema>;\n","import * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport { SourceExplorer, type FileClassification } from './explorer.js';\nimport type { SourcesManager } from './manager.js';\nimport type { SourceEntry, SourceType } from './schema.js';\n\n/**\n * Options for importing a file\n */\nexport interface ImportOptions {\n /** Force a specific source type */\n type?: SourceType;\n /** Description for the source entry */\n description?: string;\n /** Copy file (true) or move file (false). Default: true */\n copy?: boolean;\n}\n\n/**\n * Result of importing a file\n */\nexport interface ImportResult {\n /** Relative path from sources directory */\n path: string;\n /** Source type */\n type: SourceType;\n /** Original file path */\n originalPath: string;\n /** Generated source ID */\n id: string;\n}\n\n/**\n * Result of importing a directory\n */\nexport interface DirectoryImportResult {\n /** Number of files imported */\n imported: number;\n /** Number of files skipped */\n skipped: number;\n /** Details of imported files */\n results: ImportResult[];\n}\n\n/**\n * Mapping from classification to target directory and source type\n */\nconst TYPE_MAPPING: Record<\n Exclude<FileClassification, 'unknown' | 'image'>,\n { directory: string; sourceType: SourceType }\n> = {\n scenario: { directory: 'scenario', sourceType: 'scenario' },\n content: { directory: 'content', sourceType: 'content' },\n material: { directory: 'materials', sourceType: 'material' },\n data: { directory: 'data', sourceType: 'data' },\n conversation: { directory: 'conversation', sourceType: 'conversation' },\n};\n\n/**\n * Imports external files into the sources directory\n */\nexport class SourceImporter {\n private sourcesDir: string;\n private explorer: SourceExplorer;\n\n constructor(\n projectDir: string,\n private manager: SourcesManager\n ) {\n this.sourcesDir = path.join(projectDir, 'sources');\n this.explorer = new SourceExplorer();\n }\n\n /**\n * Get the target directory for a source type\n */\n getTargetDirectory(type: SourceType): string {\n return TYPE_MAPPING[type].directory;\n }\n\n /**\n * Import a single file into the sources directory\n */\n async importFile(\n sourcePath: string,\n options: ImportOptions = {}\n ): Promise<ImportResult> {\n const { type, description, copy = true } = options;\n\n const resolvedPath = path.resolve(sourcePath);\n const filename = path.basename(resolvedPath);\n\n // Determine type from options or auto-detect\n let sourceType: SourceType;\n if (type) {\n sourceType = type;\n } else {\n const classification = this.explorer.classifyFile(filename);\n sourceType = this.classificationToSourceType(classification);\n }\n\n // Get target directory\n const targetDir = this.getTargetDirectory(sourceType);\n const targetDirPath = path.join(this.sourcesDir, targetDir);\n\n // Ensure target directory exists\n await fs.mkdir(targetDirPath, { recursive: true });\n\n // Handle filename conflicts\n const targetFilename = await this.getUniqueFilename(targetDirPath, filename);\n const targetPath = path.join(targetDirPath, targetFilename);\n\n // Copy or move file\n if (copy) {\n await fs.copyFile(resolvedPath, targetPath);\n } else {\n await fs.rename(resolvedPath, targetPath);\n }\n\n // Generate source ID from filename\n const id = this.generateSourceId(targetFilename);\n\n // Create relative path for sources.yaml\n const relativePath = path.join(targetDir, targetFilename);\n\n // Create source entry\n const entry: SourceEntry = {\n id,\n type: sourceType,\n path: relativePath,\n origin: resolvedPath,\n description,\n };\n\n // Update sources.yaml\n await this.manager.addSource(entry);\n\n return {\n path: relativePath,\n type: sourceType,\n originalPath: resolvedPath,\n id,\n };\n }\n\n /**\n * Import all files from a directory\n */\n async importDirectory(\n dirPath: string,\n options: { recursive?: boolean } = {}\n ): Promise<DirectoryImportResult> {\n const { recursive = false } = options;\n\n const resolvedPath = path.resolve(dirPath);\n const scanOptions = recursive ? {} : { maxDepth: 0 };\n const files = await this.explorer.scan(resolvedPath, scanOptions);\n\n // Get existing source paths to avoid duplicates\n const data = await this.manager.load();\n const existingOrigins = new Set(\n data.sources?.map((s) => s.origin).filter(Boolean) ?? []\n );\n\n const results: ImportResult[] = [];\n let imported = 0;\n let skipped = 0;\n\n for (const file of files) {\n // Skip images (they go to images/ not sources/)\n if (file.type === 'image') {\n skipped++;\n continue;\n }\n\n // Skip already imported files\n if (existingOrigins.has(file.path)) {\n skipped++;\n continue;\n }\n\n try {\n const result = await this.importFile(file.path);\n results.push(result);\n imported++;\n } catch {\n skipped++;\n }\n }\n\n return {\n imported,\n skipped,\n results,\n };\n }\n\n /**\n * Convert file classification to source type\n */\n private classificationToSourceType(\n classification: FileClassification\n ): SourceType {\n if (classification === 'unknown' || classification === 'image') {\n return 'material'; // Default to material for unknown types\n }\n return classification;\n }\n\n /**\n * Get a unique filename in the target directory\n */\n private async getUniqueFilename(\n targetDir: string,\n filename: string\n ): Promise<string> {\n const targetPath = path.join(targetDir, filename);\n\n try {\n await fs.access(targetPath);\n // File exists, generate unique name\n const ext = path.extname(filename);\n const base = path.basename(filename, ext);\n const timestamp = Date.now();\n return `${base}-${timestamp}${ext}`;\n } catch {\n // File doesn't exist, use original name\n return filename;\n }\n }\n\n /**\n * Generate a source ID from filename\n */\n private generateSourceId(filename: string): string {\n const ext = path.extname(filename);\n const base = path.basename(filename, ext);\n // Convert to kebab-case and remove special characters\n return base\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-|-$/g, '');\n }\n}\n","import * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport type { SourceType } from './schema.js';\n\n/**\n * File type classification result\n */\nexport type FileClassification = SourceType | 'image' | 'unknown';\n\n/**\n * Information about a discovered file\n */\nexport interface FileInfo {\n /** Full path to the file */\n path: string;\n /** File name only */\n name: string;\n /** Classified type */\n type: FileClassification;\n /** File size in bytes */\n size: number;\n /** Relative path from scan root */\n relativePath: string;\n}\n\n/**\n * Summary of files discovered in a directory\n */\nexport interface DirectorySummary {\n /** Scenario/structure files */\n scenarios: FileInfo[];\n /** Content/script files */\n content: FileInfo[];\n /** Reference materials */\n materials: FileInfo[];\n /** Data files */\n data: FileInfo[];\n /** Image files */\n images: FileInfo[];\n /** Unclassified files */\n unknown: FileInfo[];\n /** Total number of files */\n totalFiles: number;\n}\n\n/**\n * Options for scanning directories\n */\nexport interface ScanOptions {\n /** Maximum directory depth (default: unlimited) */\n maxDepth?: number;\n /** Include hidden files (default: false) */\n includeHidden?: boolean;\n /** Maximum file size to read in bytes (default: 10MB) */\n fileSizeLimit?: number;\n}\n\n/**\n * Options for getting file preview\n */\nexport interface PreviewOptions {\n /** Maximum preview length in characters (default: 500) */\n maxLength?: number;\n}\n\n/**\n * Classification patterns for different file types\n */\nconst CLASSIFICATION_PATTERNS: Record<\n FileClassification,\n { namePatterns: RegExp[]; extensionPatterns: RegExp[] }\n> = {\n scenario: {\n namePatterns: [\n /scenario/i,\n /brief/i,\n /要件/i,\n /outline/i,\n /構成/i,\n /structure/i,\n /requirement/i,\n ],\n extensionPatterns: [],\n },\n content: {\n namePatterns: [/draft/i, /content/i, /原稿/i, /script/i],\n extensionPatterns: [],\n },\n data: {\n namePatterns: [/data/i, /statistic/i],\n extensionPatterns: [/\\.xlsx$/i, /\\.csv$/i, /\\.xls$/i],\n },\n material: {\n namePatterns: [/spec/i, /report/i, /manual/i, /guide/i],\n extensionPatterns: [/\\.pdf$/i, /\\.docx?$/i],\n },\n image: {\n namePatterns: [],\n extensionPatterns: [/\\.jpe?g$/i, /\\.png$/i, /\\.svg$/i, /\\.gif$/i, /\\.webp$/i],\n },\n conversation: {\n namePatterns: [],\n extensionPatterns: [],\n },\n unknown: {\n namePatterns: [],\n extensionPatterns: [],\n },\n};\n\n/**\n * Explores directories and classifies source files\n */\nexport class SourceExplorer {\n /**\n * Classify a file by its name/extension\n */\n classifyFile(filename: string): FileClassification {\n // First check name patterns (higher priority)\n const namePatternOrder: FileClassification[] = [\n 'scenario',\n 'content',\n 'data',\n 'material',\n ];\n\n for (const type of namePatternOrder) {\n const patterns = CLASSIFICATION_PATTERNS[type];\n for (const pattern of patterns.namePatterns) {\n if (pattern.test(filename)) {\n return type;\n }\n }\n }\n\n // Then check extension patterns\n const extensionOrder: FileClassification[] = [\n 'image',\n 'data',\n 'material',\n ];\n\n for (const type of extensionOrder) {\n const patterns = CLASSIFICATION_PATTERNS[type];\n for (const pattern of patterns.extensionPatterns) {\n if (pattern.test(filename)) {\n return type;\n }\n }\n }\n\n return 'unknown';\n }\n\n /**\n * Scan a directory and list all files with classification\n */\n async scan(dirPath: string, options: ScanOptions = {}): Promise<FileInfo[]> {\n const { maxDepth, includeHidden = false } = options;\n const resolvedPath = path.resolve(dirPath);\n const files: FileInfo[] = [];\n\n await this.scanRecursive(resolvedPath, resolvedPath, files, {\n currentDepth: 0,\n maxDepth,\n includeHidden,\n });\n\n return files;\n }\n\n /**\n * Internal recursive scan implementation\n */\n private async scanRecursive(\n rootPath: string,\n currentPath: string,\n files: FileInfo[],\n options: {\n currentDepth: number;\n maxDepth: number | undefined;\n includeHidden: boolean;\n }\n ): Promise<void> {\n const { currentDepth, maxDepth, includeHidden } = options;\n\n // Check depth limit\n if (maxDepth !== undefined && currentDepth > maxDepth) {\n return;\n }\n\n const entries = await fs.readdir(currentPath, { withFileTypes: true });\n\n for (const entry of entries) {\n // Skip hidden files/directories if not included\n if (!includeHidden && entry.name.startsWith('.')) {\n continue;\n }\n\n const fullPath = path.join(currentPath, entry.name);\n\n if (entry.isDirectory()) {\n await this.scanRecursive(rootPath, fullPath, files, {\n currentDepth: currentDepth + 1,\n maxDepth,\n includeHidden,\n });\n } else if (entry.isFile()) {\n const stats = await fs.stat(fullPath);\n const relativePath = path.relative(rootPath, fullPath);\n\n files.push({\n path: fullPath,\n name: entry.name,\n type: this.classifyFile(entry.name),\n size: stats.size,\n relativePath,\n });\n }\n }\n }\n\n /**\n * Generate a categorized summary of files in a directory\n */\n async generateSummary(\n dirPath: string,\n options: ScanOptions = {}\n ): Promise<DirectorySummary> {\n const files = await this.scan(dirPath, options);\n\n const summary: DirectorySummary = {\n scenarios: [],\n content: [],\n materials: [],\n data: [],\n images: [],\n unknown: [],\n totalFiles: files.length,\n };\n\n for (const file of files) {\n switch (file.type) {\n case 'scenario':\n summary.scenarios.push(file);\n break;\n case 'content':\n summary.content.push(file);\n break;\n case 'material':\n summary.materials.push(file);\n break;\n case 'data':\n summary.data.push(file);\n break;\n case 'image':\n summary.images.push(file);\n break;\n default:\n summary.unknown.push(file);\n }\n }\n\n return summary;\n }\n\n /**\n * Get a preview of a text file's contents\n */\n async getPreview(\n filePath: string,\n options: PreviewOptions = {}\n ): Promise<string | null> {\n const { maxLength = 500 } = options;\n\n try {\n // Check if it's likely a binary file\n const isBinary = await this.isBinaryFile(filePath);\n if (isBinary) {\n return null;\n }\n\n const content = await fs.readFile(filePath, 'utf-8');\n\n if (content.length <= maxLength) {\n return content;\n }\n\n return content.slice(0, maxLength) + '...';\n } catch {\n return null;\n }\n }\n\n /**\n * Check if a file is likely binary\n */\n private async isBinaryFile(filePath: string): Promise<boolean> {\n const ext = path.extname(filePath).toLowerCase();\n\n // Known text extensions - always treat as text\n const textExtensions = [\n '.md',\n '.txt',\n '.yaml',\n '.yml',\n '.json',\n '.csv',\n '.html',\n '.css',\n '.js',\n '.ts',\n ];\n if (textExtensions.includes(ext)) {\n return false;\n }\n\n // Known binary extensions - always treat as binary\n const binaryExtensions = [\n '.pdf',\n '.xlsx',\n '.xls',\n '.docx',\n '.doc',\n '.pptx',\n '.ppt',\n '.jpg',\n '.jpeg',\n '.png',\n '.gif',\n '.webp',\n '.zip',\n '.tar',\n '.gz',\n ];\n if (binaryExtensions.includes(ext)) {\n return true;\n }\n\n // Check file content for null bytes\n try {\n const stats = await fs.stat(filePath);\n if (stats.size === 0) {\n return false; // Empty files are not binary\n }\n\n const bytesToRead = Math.min(512, stats.size);\n const buffer = Buffer.alloc(bytesToRead);\n const fd = await fs.open(filePath, 'r');\n try {\n const { bytesRead } = await fd.read(buffer, 0, bytesToRead, 0);\n // Check for null bytes (common in binary files)\n for (let i = 0; i < bytesRead; i++) {\n if (buffer[i] === 0) {\n return true;\n }\n }\n } finally {\n await fd.close();\n }\n\n return false;\n } catch {\n return true;\n }\n }\n}\n","/**\n * Generate SKILL.md content for AgentSkills\n */\nexport function generateSkillMd(): string {\n return `---\nname: slide-assistant\ndescription: Assists with slide creation using slide-gen CLI. Responds to requests like \"create slides\", \"show templates\", \"convert manuscript to slides\".\nallowed-tools: Read Write Edit Bash Glob Grep\n---\n\n# Slide Assistant\n\nHelps create Marp slides using the slide-gen CLI tool.\n\n## Capabilities\n\n1. **Project initialization**: \\`slide-gen init\\`\n2. **Template discovery**: \\`slide-gen templates list --format llm\\`\n3. **Slide creation**: Create/edit presentation.yaml\n4. **Validation**: \\`slide-gen validate\\`\n5. **Conversion**: \\`slide-gen convert\\`\n6. **Screenshot**: \\`slide-gen screenshot\\` (for AI review)\n\n## Workflow\n\n### New Project\n\n1. Run \\`slide-gen init <directory>\\` to initialize\n2. Gather requirements from user\n3. Check templates with \\`slide-gen templates list --format llm\\`\n4. Create presentation.yaml\n5. Validate and convert\n\n### Existing Project\n\n1. Read presentation.yaml\n2. Edit according to user request\n3. Validate and convert\n\n## YAML Source Format\n\n\\`\\`\\`yaml\nmeta:\n title: \"Presentation Title\"\n author: \"Author Name\"\n date: \"YYYY-MM-DD\"\n theme: \"default\"\n\nslides:\n - template: title\n content:\n title: \"Main Title\"\n subtitle: \"Subtitle\"\n\n - template: bullet-list\n content:\n title: \"Overview\"\n items:\n - \"Item 1\"\n - \"Item 2\"\n\\`\\`\\`\n\n## Template Examples\n\n### Title Slide\n\\`\\`\\`yaml\n- template: title\n content:\n title: \"Title\"\n subtitle: \"Subtitle\"\n author: \"Author\"\n\\`\\`\\`\n\n### Bullet List\n\\`\\`\\`yaml\n- template: bullet-list\n content:\n title: \"Title\"\n items:\n - \"Item 1\"\n - \"Item 2\"\n\\`\\`\\`\n\n### Cycle Diagram\n\\`\\`\\`yaml\n- template: cycle-diagram\n content:\n title: \"PDCA Cycle\"\n nodes:\n - { label: \"Plan\", icon: \"planning\", color: \"#4CAF50\" }\n - { label: \"Do\", icon: \"action\", color: \"#2196F3\" }\n - { label: \"Check\", icon: \"analysis\", color: \"#FF9800\" }\n - { label: \"Act\", icon: \"improvement\", color: \"#9C27B0\" }\n\\`\\`\\`\n\n## Commands Reference\n\n| Command | Description |\n|---------|-------------|\n| \\`slide-gen convert <input>\\` | Convert YAML to Marp Markdown |\n| \\`slide-gen validate <input>\\` | Validate source file |\n| \\`slide-gen templates list\\` | List templates |\n| \\`slide-gen templates info <name>\\` | Template details |\n| \\`slide-gen icons search <query>\\` | Search icons |\n| \\`slide-gen screenshot <input>\\` | Take screenshots |\n| \\`slide-gen preview <input>\\` | Open preview in browser |\n\n## AI-Optimized Output\n\nUse \\`--format llm\\` for token-efficient output:\n\\`\\`\\`bash\nslide-gen templates list --format llm\nslide-gen templates info <name> --format llm\nslide-gen validate <input> --format llm\n\\`\\`\\`\n\nThe \\`validate --format llm\\` command provides:\n- Error locations with line numbers\n- Fix examples from template definitions\n- Contextual hints for unknown templates/icons\n`;\n}\n","/**\n * Generate CLAUDE.md content for Claude Code\n */\nexport function generateClaudeMd(): string {\n return `# Slide Generation Project\n\nThis project uses slide-gen to create Marp slides from YAML source files.\n\n## Quick Start\n\n\\`\\`\\`bash\n# Validate\nslide-gen validate presentation.yaml\n\n# Convert\nslide-gen convert presentation.yaml -o slides.md\n\n# Preview\nslide-gen preview presentation.yaml\n\\`\\`\\`\n\n## Commands\n\n| Command | Description |\n|---------|-------------|\n| \\`slide-gen convert <input>\\` | Convert YAML to Marp Markdown |\n| \\`slide-gen validate <input>\\` | Validate source file |\n| \\`slide-gen templates list\\` | List available templates |\n| \\`slide-gen templates info <name>\\` | Get template details |\n| \\`slide-gen icons search <query>\\` | Search for icons |\n| \\`slide-gen preview <input>\\` | Preview in browser |\n| \\`slide-gen screenshot <input>\\` | Take screenshots |\n\n## AI-Optimized Output\n\nFor token-efficient output, use \\`--format llm\\`:\n\\`\\`\\`bash\nslide-gen templates list --format llm\nslide-gen templates info bullet-list --format llm\n\\`\\`\\`\n\n## Project Structure\n\n- \\`presentation.yaml\\` - Slide source file\n- \\`config.yaml\\` - Project configuration\n- \\`themes/\\` - Custom themes\n- \\`icons/custom/\\` - Custom icons\n\n## Skills\n\nThis project includes AgentSkills at \\`.skills/slide-assistant/\\`.\nRead \\`.skills/slide-assistant/SKILL.md\\` for detailed instructions.\n\n## Slash Commands\n\n- \\`/slide-create\\` - Create slides from requirements\n- \\`/slide-validate\\` - Validate slide source file\n- \\`/slide-preview\\` - Preview slides in browser\n- \\`/slide-screenshot\\` - Take screenshots for review\n- \\`/slide-theme\\` - Adjust theme and styling\n`;\n}\n","/**\n * Generate AGENTS.md content for OpenCode\n */\nexport function generateAgentsMd(): string {\n return `# Slide Generation Project\n\nThis project uses slide-gen to create Marp slides from YAML source files.\n\n## Quick Start\n\n\\`\\`\\`bash\n# Validate\nslide-gen validate presentation.yaml\n\n# Convert\nslide-gen convert presentation.yaml -o slides.md\n\n# Preview\nslide-gen preview presentation.yaml\n\\`\\`\\`\n\n## Commands\n\n| Command | Description |\n|---------|-------------|\n| \\`slide-gen convert <input>\\` | Convert YAML to Marp Markdown |\n| \\`slide-gen validate <input>\\` | Validate source file |\n| \\`slide-gen templates list\\` | List available templates |\n| \\`slide-gen templates info <name>\\` | Get template details |\n| \\`slide-gen icons search <query>\\` | Search for icons |\n| \\`slide-gen preview <input>\\` | Preview in browser |\n| \\`slide-gen screenshot <input>\\` | Take screenshots |\n\n## AI-Optimized Output\n\nFor token-efficient output, use \\`--format llm\\`:\n\\`\\`\\`bash\nslide-gen templates list --format llm\nslide-gen templates info bullet-list --format llm\n\\`\\`\\`\n\n## Project Structure\n\n- \\`presentation.yaml\\` - Slide source file\n- \\`config.yaml\\` - Project configuration\n- \\`themes/\\` - Custom themes\n- \\`icons/custom/\\` - Custom icons\n\n## Skills\n\nThis project includes AgentSkills at \\`.skills/slide-assistant/\\`.\nRead \\`.skills/slide-assistant/SKILL.md\\` for detailed instructions.\n`;\n}\n","/**\n * Generate .opencode/agent/slide.md content\n */\nexport function generateOpenCodeAgent(): string {\n return `---\ndescription: Slide creation assistant using slide-gen CLI\nmode: subagent\ntools:\n write: allow\n edit: allow\n bash: allow\n read: allow\npermission:\n file_edit: allow\n bash: allow\n---\n\n# Slide Assistant\n\nYou are a slide creation assistant that uses the slide-gen CLI tool.\n\n## Available Commands\n\n| Command | Description |\n|---------|-------------|\n| \\`slide-gen convert <input>\\` | Convert YAML to Marp Markdown |\n| \\`slide-gen validate <input>\\` | Validate source file |\n| \\`slide-gen templates list --format llm\\` | List templates (AI format) |\n| \\`slide-gen icons search <query>\\` | Search icons |\n| \\`slide-gen screenshot <input>\\` | Take screenshots |\n\n## Workflow\n\n1. Understand user requirements\n2. Check available templates\n3. Create/edit presentation.yaml\n4. Validate and fix errors\n5. Convert to Marp Markdown\n6. Take screenshots for review\n\n## YAML Format\n\n\\`\\`\\`yaml\nmeta:\n title: \"Title\"\n author: \"Author\"\n\nslides:\n - template: title\n content:\n title: \"Main Title\"\n\\`\\`\\`\n`;\n}\n","/**\n * Generate references/templates.md content\n * Contains detailed template parameter reference\n */\nexport function generateTemplatesRef(): string {\n return `# Template Reference\n\n## Basic Templates\n\n### title\nFull-screen title slide.\n- \\`title\\`: Main title (required)\n- \\`subtitle\\`: Subtitle (optional)\n- \\`author\\`: Author name (optional)\n\n### content\nGeneral content slide with body text.\n- \\`title\\`: Slide title (required)\n- \\`body\\`: Body text with markdown support (required)\n\n### section\nSection divider slide.\n- \\`title\\`: Section title (required)\n- \\`subtitle\\`: Section description (optional)\n\n### bullet-list\nSlide with bullet points.\n- \\`title\\`: Slide title (required)\n- \\`items\\`: Array of strings (required)\n\n### two-column\nTwo-column layout.\n- \\`title\\`: Slide title (required)\n- \\`left\\`: Left column content (required)\n- \\`right\\`: Right column content (required)\n\n### end\nClosing slide.\n- \\`title\\`: Closing title (required)\n- \\`subtitle\\`: Closing subtitle (optional)\n\n## Diagram Templates\n\n### cycle-diagram\nCircular process diagram (3-6 nodes).\n- \\`title\\`: Slide title (required)\n- \\`nodes\\`: Array of {label, icon?, color?} (required)\n\n### flow-diagram\nLinear flow diagram.\n- \\`title\\`: Slide title (required)\n- \\`steps\\`: Array of {label, icon?, description?} (required)\n\n### comparison\nSide-by-side comparison.\n- \\`title\\`: Slide title (required)\n- \\`items\\`: Array of comparison items (required)\n\n## Data Templates\n\n### table\nData table display.\n- \\`title\\`: Slide title (required)\n- \\`headers\\`: Array of column headers (required)\n- \\`rows\\`: Array of row data arrays (required)\n\n### chart\nChart visualization.\n- \\`title\\`: Slide title (required)\n- \\`type\\`: Chart type (bar, line, pie)\n- \\`data\\`: Chart data\n\n## Image Templates\n\n### image-full\nFull-screen background image.\n- \\`image\\`: Image path (required)\n- \\`title\\`: Overlay title (optional)\n- \\`overlay\\`: none|dark|light|gradient (optional)\n\n### image-text\nImage with text side by side.\n- \\`title\\`: Slide title (required)\n- \\`image\\`: Image path (required)\n- \\`image_position\\`: left|right (optional, default: left)\n- \\`items\\` or \\`text\\`: Content (required)\n\n## Run \\`slide-gen templates list --format llm\\` for full list.\n`;\n}\n","/**\n * Generate references/workflows.md content\n * Contains source collection and image collaboration workflows\n */\nexport function generateWorkflowsRef(): string {\n return `# Workflow Reference\n\n## Source Collection Flow\n\n### Pattern A: Directory Exploration\nWhen user has materials in a directory:\n1. Ask for directory path\n2. Scan with Glob tool\n3. Read and classify files\n4. Summarize and confirm with user\n5. Create sources/sources.yaml\n\n### Pattern B: Supplement Mode\nWhen user has partial materials:\n1. Read provided file/text\n2. Analyze content\n3. Identify missing information\n4. Ask supplementary questions\n5. Create sources/sources.yaml\n\n### Pattern C: Interview Mode\nWhen user has no materials:\n1. Ask basic questions (purpose, audience, duration)\n2. Deep-dive based on purpose\n3. Propose slide structure\n4. Iterate based on feedback\n5. Create sources/sources.yaml\n\n## Slide Creation Flow\n\n### Step 1: Gather Requirements\n- Understand presentation purpose\n- Identify target audience\n- Determine slide count and duration\n\n### Step 2: Template Selection\n- Run \\`slide-gen templates list --format llm\\`\n- Match templates to content types\n- Plan slide sequence\n\n### Step 3: Create Source File\n- Create presentation.yaml\n- Use appropriate templates for each slide\n- Add icons where helpful\n\n### Step 4: Validate\n- Run \\`slide-gen validate presentation.yaml\\`\n- Fix any validation errors\n- Check template parameters\n\n### Step 5: Convert and Review\n- Run \\`slide-gen convert presentation.yaml\\`\n- Use \\`slide-gen screenshot\\` for visual review\n- Iterate based on feedback\n\n## Image Collaboration Flow\n\n### Phase 1: Requirement Derivation\nAnalyze presentation scenario to identify needed images.\n\n### Phase 2: Image Request\nGenerate specific image requests with:\n- Purpose and context\n- Recommended specifications\n- File naming convention\n\n### Phase 3: Verification\nAfter user provides images:\n1. Visual inspection (Read tool)\n2. Check metadata if available\n3. Verify compliance and permissions\n4. Provide feedback\n\n### Phase 4: Iteration\nHandle adjustments (cropping, replacement) as needed.\n`;\n}\n","/**\n * Generate .claude/commands/slide-create.md content\n */\nexport function generateSlideCreateCommand(): string {\n return `Create slides from user requirements.\n\n## Steps\n\n1. Get manuscript/requirements from user\n2. Check templates: \\`slide-gen templates list --format llm\\`\n3. Select appropriate templates\n4. Create or edit presentation.yaml\n5. Validate: \\`slide-gen validate presentation.yaml\\`\n6. Fix any errors\n7. Convert: \\`slide-gen convert presentation.yaml -o slides.md\\`\n8. Report results\n\n## Notes\n\n- Select appropriate template for each slide\n- Search icons if needed: \\`slide-gen icons search\\`\n- Fix all validation errors before conversion\n`;\n}\n","/**\n * Generate .claude/commands/slide-validate.md content\n */\nexport function generateSlideValidateCommand(): string {\n return `Validate slide source file.\n\n## Command\n\n\\`\\`\\`bash\nslide-gen validate $ARGUMENTS\n\\`\\`\\`\n\nIf no argument provided:\n\\`\\`\\`bash\nslide-gen validate presentation.yaml\n\\`\\`\\`\n\n## Options\n\n| Option | Description |\n|--------|-------------|\n| \\`--format text\\` | Human-readable output (default) |\n| \\`--format json\\` | JSON output for programmatic use |\n| \\`--format llm\\` | AI-optimized output with line numbers and fix hints |\n| \\`--strict\\` | Treat warnings as errors |\n| \\`-c, --config <path>\\` | Custom config file path |\n\n## AI-Optimized Validation\n\nUse \\`--format llm\\` for structured error output:\n\n\\`\\`\\`bash\nslide-gen validate presentation.yaml --format llm\n\\`\\`\\`\n\n### Example Output (Error)\n\n\\`\\`\\`\nValidation failed.\n\nError at line 15, Slide 2 (bullet-list):\n Missing required field: items\n\nFix:\n content:\n title: \"Your title\"\n items:\n - \"Item 1\"\n - \"Item 2\"\n\\`\\`\\`\n\n### Example Output (Success)\n\n\\`\\`\\`\nValidation passed. 5 slides validated.\n\\`\\`\\`\n\n### Error Types and Hints\n\n- **unknown_template**: Suggests \\`slide-gen templates list --format llm\\`\n- **unknown_icon**: Suggests \\`slide-gen icons search <query>\\`\n- **missing_field**: Shows fix example from template definition\n- **invalid_type**: Shows expected format from template definition\n`;\n}\n\n","/**\n * Generate .claude/commands/slide-preview.md content\n */\nexport function generateSlidePreviewCommand(): string {\n return `Preview slides in browser.\n\n## Command\n\n\\`\\`\\`bash\nslide-gen preview $ARGUMENTS\n\\`\\`\\`\n\nIf no argument provided:\n\\`\\`\\`bash\nslide-gen preview presentation.yaml\n\\`\\`\\`\n\n## Options\n\n- \\`--gallery\\` or \\`-g\\`: Show thumbnail gallery of all slides\n- \\`--slide <number>\\`: Preview specific slide\n`;\n}\n","/**\n * Generate .claude/commands/slide-screenshot.md content\n */\nexport function generateSlideScreenshotCommand(): string {\n return `Take screenshots of slides for AI review.\n\n## Command\n\n\\`\\`\\`bash\nslide-gen screenshot $ARGUMENTS\n\\`\\`\\`\n\nIf no argument provided:\n\\`\\`\\`bash\nslide-gen screenshot presentation.yaml -o screenshots/\n\\`\\`\\`\n\n## Options\n\n- \\`--slide <number>\\`: Screenshot specific slide only\n- \\`--width <pixels>\\`: Image width (default: 1280)\n- \\`--output <dir>\\`: Output directory\n\n## After Screenshot\n\nRead the screenshot images to review slide content and provide feedback.\n`;\n}\n","/**\n * Generate .claude/commands/slide-theme.md content\n */\nexport function generateSlideThemeCommand(): string {\n return `Adjust slide theme and styling.\n\n## Steps\n\n1. Read current theme settings (themes/custom.css)\n2. Confirm user requirements\n3. Edit CSS\n4. Regenerate: \\`slide-gen convert\\`\n5. Take screenshot: \\`slide-gen screenshot\\`\n6. Review and report to user\n\n## Adjustable Items\n\n- Background color\n- Font family and size\n- Heading styles\n- Color scheme\n- Margins and layout\n`;\n}\n","import { Command } from 'commander';\nimport { access } from 'fs/promises';\nimport { basename, dirname, join } from 'path';\nimport chalk from 'chalk';\nimport { watch as chokidarWatch, FSWatcher } from 'chokidar';\nimport { Pipeline, PipelineError } from '../../core/pipeline';\nimport { ConfigLoader } from '../../config/loader';\nimport { ExitCode } from './convert';\n\nexport interface WatchOptions {\n output?: string;\n config?: string;\n debounce?: number;\n verbose?: boolean;\n signal?: AbortSignal;\n}\n\nexport interface WatchResult {\n success: boolean;\n conversionCount: number;\n errors: string[];\n}\n\n/**\n * State management for watch mode\n */\nexport class WatchState {\n private _isRunning = false;\n private _conversionCount = 0;\n private _lastError: Error | null = null;\n\n get isRunning(): boolean {\n return this._isRunning;\n }\n\n get conversionCount(): number {\n return this._conversionCount;\n }\n\n get lastError(): Error | null {\n return this._lastError;\n }\n\n start(): void {\n this._isRunning = true;\n }\n\n stop(): void {\n this._isRunning = false;\n }\n\n incrementConversion(): void {\n this._conversionCount++;\n }\n\n setError(error: Error): void {\n this._lastError = error;\n }\n\n clearError(): void {\n this._lastError = null;\n }\n}\n\n/**\n * Generate default output path from input path\n */\nexport function getDefaultOutputPath(inputPath: string): string {\n const dir = dirname(inputPath);\n const base = basename(inputPath, '.yaml');\n return join(dir, `${base}.md`);\n}\n\n/**\n * Format timestamp for log output\n */\nfunction formatTime(): string {\n const now = new Date();\n return `[${now.toLocaleTimeString('en-GB')}]`;\n}\n\n/**\n * Create the watch command\n */\nexport function createWatchCommand(): Command {\n return new Command('watch')\n .description('Watch source file and auto-convert on changes')\n .argument('<input>', 'Input YAML file to watch')\n .option('-o, --output <path>', 'Output file path')\n .option('-c, --config <path>', 'Config file path')\n .option('--debounce <ms>', 'Debounce delay in milliseconds', '300')\n .option('-v, --verbose', 'Verbose output')\n .action(async (input: string, options: WatchOptions) => {\n await executeWatch(input, options);\n });\n}\n\n/**\n * Execute a single conversion\n */\nasync function runConversion(\n inputPath: string,\n outputPath: string,\n pipeline: Pipeline,\n verbose: boolean\n): Promise<{ success: boolean; error?: string }> {\n try {\n const result = await pipeline.runWithResult(inputPath, { outputPath });\n\n console.log(\n `${formatTime()} ${chalk.green('✓')} Output: ${chalk.cyan(outputPath)}`\n );\n\n if (verbose) {\n console.log(` Parsed ${result.slideCount} slides`);\n if (result.warnings.length > 0) {\n for (const warning of result.warnings) {\n console.log(chalk.yellow(` ⚠ ${warning}`));\n }\n }\n }\n\n return { success: true };\n } catch (error) {\n const message =\n error instanceof PipelineError\n ? `${error.stage}: ${error.message}`\n : error instanceof Error\n ? error.message\n : 'Unknown error';\n\n console.log(\n `${formatTime()} ${chalk.red('✗')} Conversion failed: ${message}`\n );\n\n return { success: false, error: message };\n }\n}\n\n/**\n * Execute the watch command\n */\nexport async function executeWatch(\n inputPath: string,\n options: WatchOptions\n): Promise<WatchResult> {\n const state = new WatchState();\n const errors: string[] = [];\n const debounceMs = Number(options.debounce) || 300;\n const verbose = options.verbose ?? false;\n\n // Check if immediately aborted (for testing)\n if (options.signal?.aborted) {\n // Validate input file exists\n try {\n await access(inputPath);\n } catch {\n errors.push(`File not found: ${inputPath}`);\n return { success: false, conversionCount: 0, errors };\n }\n return { success: true, conversionCount: 0, errors };\n }\n\n // Validate input file exists\n try {\n await access(inputPath);\n } catch {\n console.error(chalk.red(`Error: File not found: ${inputPath}`));\n errors.push(`File not found: ${inputPath}`);\n process.exitCode = ExitCode.FileReadError;\n return { success: false, conversionCount: 0, errors };\n }\n\n // Determine output path\n const outputPath = options.output ?? getDefaultOutputPath(inputPath);\n\n // Load configuration\n const configLoader = new ConfigLoader();\n let configPath = options.config;\n\n if (!configPath) {\n configPath = await configLoader.findConfig(dirname(inputPath));\n }\n\n const config = await configLoader.load(configPath);\n\n // Create and initialize pipeline\n const pipeline = new Pipeline(config);\n\n try {\n await pipeline.initialize();\n } catch (error) {\n const message =\n error instanceof Error ? error.message : 'Unknown initialization error';\n console.error(chalk.red(`Error: Failed to initialize pipeline: ${message}`));\n errors.push(message);\n process.exitCode = ExitCode.ConversionError;\n return { success: false, conversionCount: 0, errors };\n }\n\n console.log(`Watching ${chalk.cyan(inputPath)}...`);\n console.log(`Output: ${chalk.cyan(outputPath)}`);\n console.log('');\n\n // Initial conversion\n console.log(`${formatTime()} Initial conversion...`);\n const initialResult = await runConversion(inputPath, outputPath, pipeline, verbose);\n if (initialResult.success) {\n state.incrementConversion();\n } else if (initialResult.error) {\n errors.push(initialResult.error);\n }\n\n // Set up file watcher\n let debounceTimer: ReturnType<typeof setTimeout> | null = null;\n let watcher: FSWatcher | null = null;\n\n const handleChange = () => {\n if (debounceTimer) {\n clearTimeout(debounceTimer);\n }\n\n debounceTimer = setTimeout(async () => {\n console.log(`${formatTime()} Changed: ${inputPath}`);\n console.log(`${formatTime()} Converting...`);\n\n const result = await runConversion(inputPath, outputPath, pipeline, verbose);\n if (result.success) {\n state.incrementConversion();\n state.clearError();\n } else if (result.error) {\n errors.push(result.error);\n state.setError(new Error(result.error));\n }\n }, debounceMs);\n };\n\n state.start();\n\n watcher = chokidarWatch(inputPath, {\n persistent: true,\n ignoreInitial: true,\n awaitWriteFinish: {\n stabilityThreshold: 100,\n pollInterval: 50,\n },\n });\n\n watcher.on('change', handleChange);\n\n // Handle abort signal\n const cleanup = () => {\n state.stop();\n if (debounceTimer) {\n clearTimeout(debounceTimer);\n }\n watcher?.close();\n };\n\n if (options.signal) {\n options.signal.addEventListener('abort', cleanup);\n }\n\n // Handle process signals\n const signalHandler = () => {\n console.log('\\n' + chalk.yellow('Watch stopped.'));\n cleanup();\n process.exit(0);\n };\n\n process.on('SIGINT', signalHandler);\n process.on('SIGTERM', signalHandler);\n\n // Keep the process running\n await new Promise<void>((resolve) => {\n if (options.signal) {\n options.signal.addEventListener('abort', () => resolve());\n }\n });\n\n return {\n success: errors.length === 0,\n conversionCount: state.conversionCount,\n errors,\n };\n}\n","import { Command } from \"commander\";\nimport { readFile, stat, mkdir } from \"fs/promises\";\nimport { dirname, basename, join } from \"path\";\nimport chalk from \"chalk\";\nimport { stringify as stringifyYaml } from \"yaml\";\nimport { Parser } from \"../../core/parser\";\nimport {\n ImageValidator,\n ImageStats,\n ImageMetadataLoader,\n ImageProcessor,\n ImageProcessingPipeline,\n type ImageMetadata,\n} from \"../../images\";\nimport { isImageFile } from \"../../images/constants\";\n\n/**\n * Create the images command with subcommands\n */\nexport function createImagesCommand(): Command {\n const cmd = new Command(\"images\").description(\"Manage presentation images\");\n\n cmd.addCommand(createImagesStatusCommand());\n cmd.addCommand(createImagesRequestCommand());\n cmd.addCommand(createImagesProcessCommand());\n\n return cmd;\n}\n\n/**\n * Create the images status subcommand\n */\nfunction createImagesStatusCommand(): Command {\n return new Command(\"status\")\n .description(\"Show image permission status\")\n .argument(\"<input>\", \"Presentation YAML file\")\n .action(async (input: string) => {\n await executeImagesStatus(input);\n });\n}\n\n/**\n * Create the images request subcommand\n */\nfunction createImagesRequestCommand(): Command {\n return new Command(\"request\")\n .description(\"Generate missing image request list\")\n .argument(\"<input>\", \"Presentation YAML file\")\n .option(\"--format <format>\", \"Output format (text|llm)\", \"text\")\n .action(async (input: string, options: { format: string }) => {\n await executeImagesRequest(input, options);\n });\n}\n\n/**\n * Execute images status command\n */\nasync function executeImagesStatus(inputPath: string): Promise<void> {\n try {\n const slides = await loadPresentation(inputPath);\n const baseDir = dirname(inputPath);\n const validator = new ImageValidator(baseDir);\n\n // Extract image references\n const imageRefs = validator.extractImageReferences(slides);\n\n if (imageRefs.length === 0) {\n console.log(chalk.yellow(\"No images found in presentation\"));\n return;\n }\n\n // Get stats\n const stats = await validator.getImageStats(slides);\n\n // Output formatted status\n await outputImageStatus(stats, imageRefs, validator, baseDir);\n } catch (error) {\n const message = error instanceof Error ? error.message : \"Unknown error\";\n console.error(chalk.red(`Error: ${message}`));\n process.exitCode = 1;\n }\n}\n\n/**\n * Image info with metadata for status display\n */\ninterface ImageStatusInfo {\n path: string;\n metadata: ImageMetadata;\n}\n\n/**\n * Output image status in a formatted way with per-image details\n */\nasync function outputImageStatus(\n stats: ImageStats,\n imageRefs: string[],\n _validator: ImageValidator,\n baseDir: string\n): Promise<void> {\n const metadataLoader = new ImageMetadataLoader(baseDir);\n\n // Group images by status\n const approved: ImageStatusInfo[] = [];\n const pending: ImageStatusInfo[] = [];\n const restricted: ImageStatusInfo[] = [];\n const rejected: ImageStatusInfo[] = [];\n const unknown: ImageStatusInfo[] = [];\n\n for (const imagePath of imageRefs) {\n const metadata = await metadataLoader.load(imagePath);\n const info: ImageStatusInfo = { path: imagePath, metadata };\n const status = metadata.permissions?.status;\n\n switch (status) {\n case \"approved\":\n approved.push(info);\n break;\n case \"pending\":\n pending.push(info);\n break;\n case \"restricted\":\n restricted.push(info);\n break;\n case \"rejected\":\n rejected.push(info);\n break;\n default:\n unknown.push(info);\n }\n }\n\n console.log(\"\");\n console.log(chalk.bold(\"Image Permissions Status:\"));\n console.log(\"━\".repeat(50));\n\n // Approved images\n if (approved.length > 0) {\n console.log(\"\");\n console.log(chalk.green(`✓ Approved (${approved.length}):`));\n for (const info of approved) {\n const approver = info.metadata.permissions?.approved_by || \"unknown\";\n const expires = info.metadata.permissions?.expires || \"none\";\n console.log(chalk.green(` - ${info.path} (${approver}, expires: ${expires})`));\n }\n }\n\n // Pending images\n if (pending.length > 0) {\n console.log(\"\");\n console.log(chalk.yellow(`⏳ Pending (${pending.length}):`));\n for (const info of pending) {\n console.log(chalk.yellow(` - ${info.path}`));\n const contact = info.metadata.permissions?.pending_contact;\n if (contact) {\n console.log(chalk.yellow(` Contact: ${contact}`));\n }\n }\n }\n\n // Restricted images\n if (restricted.length > 0) {\n console.log(\"\");\n console.log(chalk.yellow(`⚠ Restricted (${restricted.length}):`));\n for (const info of restricted) {\n console.log(chalk.yellow(` - ${info.path}`));\n const conditions = info.metadata.permissions?.conditions;\n if (conditions && conditions.length > 0) {\n console.log(chalk.yellow(` Conditions: ${conditions.join(\", \")}`));\n }\n }\n }\n\n // Rejected images\n if (rejected.length > 0) {\n console.log(\"\");\n console.log(chalk.red(`✗ Rejected (${rejected.length}):`));\n for (const info of rejected) {\n console.log(chalk.red(` - ${info.path}`));\n }\n }\n\n // Unknown images\n if (unknown.length > 0) {\n console.log(\"\");\n console.log(chalk.gray(`? Unknown (${unknown.length}):`));\n for (const info of unknown) {\n console.log(chalk.gray(` - ${info.path}`));\n }\n }\n\n console.log(\"\");\n console.log(\"━\".repeat(50));\n console.log(\n `Summary: ${stats.approved} approved, ${stats.pending} pending, ${stats.restricted} restricted, ${stats.rejected} rejected`\n );\n}\n\n/**\n * Execute images request command\n */\nasync function executeImagesRequest(\n inputPath: string,\n options: { format: string }\n): Promise<void> {\n try {\n const slides = await loadPresentation(inputPath);\n const baseDir = dirname(inputPath);\n const validator = new ImageValidator(baseDir);\n\n // Get missing images\n const missingImages = await validator.getMissingImages(slides);\n\n if (missingImages.length === 0) {\n console.log(chalk.green(\"No missing images found!\"));\n return;\n }\n\n if (options.format === \"llm\") {\n outputMissingImagesLLM(missingImages, slides);\n } else {\n outputMissingImagesText(missingImages);\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : \"Unknown error\";\n console.error(chalk.red(`Error: ${message}`));\n process.exitCode = 1;\n }\n}\n\n/**\n * Output missing images in text format\n */\nfunction outputMissingImagesText(missingImages: string[]): void {\n console.log(\"\");\n console.log(chalk.bold(\"Missing Images:\"));\n console.log(\"━\".repeat(50));\n console.log(\"\");\n\n for (const imagePath of missingImages) {\n console.log(chalk.red(` ✗ ${imagePath}`));\n }\n\n console.log(\"\");\n console.log(`Total: ${missingImages.length} missing image(s)`);\n console.log(\"\");\n console.log(\n chalk.gray(\"Run 'slide-gen images request --format llm' for AI-friendly output\")\n );\n}\n\n/**\n * Output missing images in LLM-friendly YAML format\n */\nfunction outputMissingImagesLLM(\n missingImages: string[],\n slides: SlideContent[]\n): void {\n // Build context for each missing image\n const imageContextMap = buildImageContext(slides);\n\n const output = {\n missing_images: missingImages.map((imagePath) => ({\n path: imagePath,\n slide: findSlideWithImage(slides, imagePath),\n template: findTemplateForImage(slides, imagePath),\n context: imageContextMap.get(imagePath) || {},\n })),\n };\n\n console.log(stringifyYaml(output));\n}\n\n/**\n * Slide content type\n */\ninterface SlideContent {\n template: string;\n content: Record<string, unknown>;\n}\n\n/**\n * Load and parse presentation file\n */\nasync function loadPresentation(inputPath: string): Promise<SlideContent[]> {\n const content = await readFile(inputPath, \"utf-8\");\n const parser = new Parser();\n const presentation = parser.parse(content);\n\n return presentation.slides.map((slide) => ({\n template: slide.template,\n content: slide.content as Record<string, unknown>,\n }));\n}\n\n/**\n * Build context map for images\n */\nfunction buildImageContext(\n slides: SlideContent[]\n): Map<string, Record<string, unknown>> {\n const contextMap = new Map<string, Record<string, unknown>>();\n\n for (let i = 0; i < slides.length; i++) {\n const slide = slides[i]!;\n const content = slide.content;\n\n // Get title from content\n const title = content[\"title\"] as string | undefined;\n\n // Direct image\n const image = content[\"image\"];\n if (typeof image === \"string\") {\n contextMap.set(image, {\n title: title || `Slide ${i + 1}`,\n usage: getImageUsageDescription(slide.template),\n });\n }\n\n // Before/after\n const before = content[\"before\"] as Record<string, unknown> | undefined;\n const after = content[\"after\"] as Record<string, unknown> | undefined;\n if (before?.[\"image\"]) {\n contextMap.set(before[\"image\"] as string, {\n title: title || `Slide ${i + 1}`,\n usage: \"Before image in comparison\",\n });\n }\n if (after?.[\"image\"]) {\n contextMap.set(after[\"image\"] as string, {\n title: title || `Slide ${i + 1}`,\n usage: \"After image in comparison\",\n });\n }\n\n // Gallery images\n const images = content[\"images\"] as Array<{ src: string }> | undefined;\n if (Array.isArray(images)) {\n for (const img of images) {\n if (img.src) {\n contextMap.set(img.src, {\n title: title || `Slide ${i + 1}`,\n usage: \"Gallery image\",\n });\n }\n }\n }\n }\n\n return contextMap;\n}\n\n/**\n * Get usage description for image template\n */\nfunction getImageUsageDescription(template: string): string {\n switch (template) {\n case \"image-full\":\n return \"Fullscreen background image\";\n case \"image-text\":\n return \"Image alongside text content\";\n case \"image-caption\":\n return \"Image with detailed caption\";\n case \"gallery\":\n return \"Gallery grid image\";\n case \"before-after\":\n return \"Comparison image\";\n default:\n return \"Image in slide\";\n }\n}\n\n/**\n * Find slide number containing an image\n */\nfunction findSlideWithImage(slides: SlideContent[], imagePath: string): number {\n for (let i = 0; i < slides.length; i++) {\n const content = slides[i]!.content;\n\n if (content[\"image\"] === imagePath) return i + 1;\n\n const before = content[\"before\"] as Record<string, unknown> | undefined;\n const after = content[\"after\"] as Record<string, unknown> | undefined;\n if (before?.[\"image\"] === imagePath || after?.[\"image\"] === imagePath) {\n return i + 1;\n }\n\n const images = content[\"images\"] as Array<{ src: string }> | undefined;\n if (images?.some((img) => img.src === imagePath)) {\n return i + 1;\n }\n }\n return 0;\n}\n\n/**\n * Find template for an image\n */\nfunction findTemplateForImage(\n slides: SlideContent[],\n imagePath: string\n): string {\n for (const slide of slides) {\n const content = slide.content;\n\n if (content[\"image\"] === imagePath) return slide.template;\n\n const before = content[\"before\"] as Record<string, unknown> | undefined;\n const after = content[\"after\"] as Record<string, unknown> | undefined;\n if (before?.[\"image\"] === imagePath || after?.[\"image\"] === imagePath) {\n return slide.template;\n }\n\n const images = content[\"images\"] as Array<{ src: string }> | undefined;\n if (images?.some((img) => img.src === imagePath)) {\n return slide.template;\n }\n }\n return \"unknown\";\n}\n\n/**\n * Create the images process subcommand\n */\nfunction createImagesProcessCommand(): Command {\n return new Command(\"process\")\n .description(\"Process images (crop, blur)\")\n .argument(\"<path>\", \"Image file or directory\")\n .option(\"--crop <spec>\", 'Crop specification (e.g., \"right:10,bottom:5\")')\n .option(\"--blur <spec>\", 'Blur region (e.g., \"100,100,50,50\")')\n .option(\"--from-meta\", \"Apply processing from metadata files\")\n .option(\"--output <dir>\", \"Output directory\", \".processed\")\n .action(async (inputPath: string, options: ProcessOptions) => {\n await executeImagesProcess(inputPath, options);\n });\n}\n\n/**\n * Options for images process command\n */\ninterface ProcessOptions {\n crop?: string;\n blur?: string;\n fromMeta?: boolean;\n output: string;\n}\n\n/**\n * Execute images process command\n */\nasync function executeImagesProcess(\n inputPath: string,\n options: ProcessOptions\n): Promise<void> {\n try {\n const pathStat = await stat(inputPath);\n const isDirectory = pathStat.isDirectory();\n\n if (isDirectory) {\n // Process directory\n await processDirectory(inputPath, options);\n } else {\n // Process single file\n await processSingleFile(inputPath, options);\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : \"Unknown error\";\n console.error(chalk.red(`Error: ${message}`));\n process.exitCode = 1;\n }\n}\n\n/**\n * Process all images in a directory\n */\nasync function processDirectory(\n dirPath: string,\n options: ProcessOptions\n): Promise<void> {\n if (options.fromMeta) {\n // Use metadata-based processing\n const outputDir = join(dirPath, options.output);\n const pipeline = new ImageProcessingPipeline(dirPath, { outputDir });\n const result = await pipeline.processDirectory();\n\n console.log(\"\");\n console.log(chalk.bold(\"Image Processing Results:\"));\n console.log(\"━\".repeat(50));\n console.log(`Total images: ${result.totalImages}`);\n console.log(chalk.green(`Processed: ${result.processedImages}`));\n console.log(chalk.gray(`Skipped: ${result.skippedImages} (no processing instructions)`));\n\n if (result.errors.length > 0) {\n console.log(chalk.red(`Errors: ${result.errors.length}`));\n for (const err of result.errors) {\n console.log(chalk.red(` - ${err}`));\n }\n }\n\n console.log(\"\");\n console.log(`${result.processedImages} processed, ${result.skippedImages} skipped`);\n } else {\n console.log(\n chalk.yellow(\n \"Warning: Processing directory requires --from-meta flag to apply metadata instructions\"\n )\n );\n console.log(\n chalk.gray(\"Use --crop or --blur options with a single file, or use --from-meta for directory\")\n );\n }\n}\n\n/**\n * Process a single image file\n */\nasync function processSingleFile(\n filePath: string,\n options: ProcessOptions\n): Promise<void> {\n if (!isImageFile(filePath)) {\n console.error(chalk.red(`Error: ${filePath} is not a supported image file`));\n process.exitCode = 1;\n return;\n }\n\n const processor = new ImageProcessor();\n const dir = dirname(filePath);\n const filename = basename(filePath);\n const outputDir = join(dir, options.output);\n\n // Ensure output directory exists\n await mkdir(outputDir, { recursive: true });\n\n const outputPath = join(outputDir, filename);\n let success = false;\n\n if (options.crop) {\n // Parse crop specification\n const edges = parseCropSpec(options.crop);\n if (!edges) {\n console.error(chalk.red(\"Invalid crop specification. Use format: right:10,bottom:5\"));\n process.exitCode = 1;\n return;\n }\n\n const result = await processor.cropEdges(filePath, edges, outputPath);\n if (!result.success) {\n console.error(chalk.red(`Crop failed: ${result.error}`));\n process.exitCode = 1;\n return;\n }\n success = true;\n console.log(chalk.green(`Processed: ${filename} (cropped to ${result.width}x${result.height})`));\n }\n\n if (options.blur) {\n // Parse blur specification\n const region = parseBlurSpec(options.blur);\n if (!region) {\n console.error(chalk.red(\"Invalid blur specification. Use format: x,y,width,height\"));\n process.exitCode = 1;\n return;\n }\n\n const inputForBlur = success ? outputPath : filePath;\n const result = await processor.blurRegion(inputForBlur, region, outputPath);\n if (!result.success) {\n console.error(chalk.red(`Blur failed: ${result.error}`));\n process.exitCode = 1;\n return;\n }\n success = true;\n console.log(chalk.green(`Processed: ${filename} (blurred region)`));\n }\n\n if (options.fromMeta) {\n // Process from metadata\n const metadataLoader = new ImageMetadataLoader(dir);\n const metadata = await metadataLoader.load(filename);\n\n if (!metadata.processing || metadata.processing.length === 0) {\n console.log(chalk.yellow(`No processing instructions found for ${filename}`));\n return;\n }\n\n const pipeline = new ImageProcessingPipeline(dir, { outputDir });\n const result = await pipeline.processImage(filename);\n\n if (!result.success) {\n console.error(chalk.red(`Processing failed: ${result.error}`));\n process.exitCode = 1;\n return;\n }\n\n success = true;\n console.log(\n chalk.green(`Processed: ${filename} (${result.instructionsApplied} instruction(s))`)\n );\n }\n\n if (!success && !options.crop && !options.blur && !options.fromMeta) {\n console.log(\n chalk.yellow(\"No processing options specified. Use --crop, --blur, or --from-meta\")\n );\n }\n\n if (success) {\n console.log(`Output: ${chalk.cyan(outputPath)}`);\n }\n}\n\n/**\n * Parse crop specification string (e.g., \"right:10,bottom:5\")\n */\nfunction parseCropSpec(spec: string): { left?: number; right?: number; top?: number; bottom?: number } | null {\n const result: { left?: number; right?: number; top?: number; bottom?: number } = {};\n const parts = spec.split(\",\");\n\n for (const part of parts) {\n const [key, value] = part.split(\":\");\n if (!key || !value) return null;\n\n const numValue = parseInt(value, 10);\n if (isNaN(numValue) || numValue < 0 || numValue > 50) return null;\n\n const edge = key.trim().toLowerCase();\n if (edge === \"left\") result.left = numValue;\n else if (edge === \"right\") result.right = numValue;\n else if (edge === \"top\") result.top = numValue;\n else if (edge === \"bottom\") result.bottom = numValue;\n else return null;\n }\n\n return Object.keys(result).length > 0 ? result : null;\n}\n\n/**\n * Parse blur specification string (e.g., \"100,100,50,50\")\n */\nfunction parseBlurSpec(spec: string): { x: number; y: number; width: number; height: number } | null {\n const parts = spec.split(\",\").map((p) => parseInt(p.trim(), 10));\n\n if (parts.length !== 4 || parts.some(isNaN)) {\n return null;\n }\n\n const [x, y, width, height] = parts as [number, number, number, number];\n if (x < 0 || y < 0 || width <= 0 || height <= 0) {\n return null;\n }\n\n return { x, y, width, height };\n}\n","import { Command } from 'commander';\nimport { access, mkdir, readdir, unlink } from 'fs/promises';\nimport { basename, dirname, join } from 'path';\nimport chalk from 'chalk';\nimport ora from 'ora';\nimport { Pipeline, PipelineError } from '../../core/pipeline';\nimport { ConfigLoader } from '../../config/loader';\nimport { ExitCode } from './convert';\nimport { runMarp, isMarpAvailable } from '../utils/marp-runner';\n\nexport interface ScreenshotOptions {\n output?: string;\n slide?: number;\n width?: number;\n format?: 'png' | 'jpeg';\n config?: string;\n verbose?: boolean;\n}\n\nexport interface ScreenshotResult {\n success: boolean;\n errors: string[];\n outputDir?: string;\n files?: string[];\n}\n\nexport interface FilterResult {\n success: boolean;\n keptFile?: string;\n error?: string;\n}\n\n/**\n * Filter generated images to keep only a specific slide\n * Marp generates files like: basename.001.png, basename.002.png, etc.\n */\nexport async function filterToSpecificSlide(\n outputDir: string,\n baseName: string,\n slideNumber: number,\n format: string\n): Promise<FilterResult> {\n const slideStr = slideNumber.toString().padStart(3, '0');\n const targetFileName = `${baseName}.${slideStr}.${format}`;\n const targetPath = join(outputDir, targetFileName);\n\n // Check if the target slide exists\n try {\n await access(targetPath);\n } catch {\n return {\n success: false,\n error: `Slide ${slideNumber} not found (expected: ${targetFileName})`,\n };\n }\n\n // Get all slide files and remove all except the target\n const files = await readdir(outputDir);\n const slideFiles = files.filter(\n (f) => f.startsWith(baseName) && f.endsWith(`.${format}`)\n );\n\n for (const file of slideFiles) {\n if (file !== targetFileName) {\n await unlink(join(outputDir, file));\n }\n }\n\n return {\n success: true,\n keptFile: targetFileName,\n };\n}\n\n/**\n * Check if marp-cli is available in the system (globally or locally)\n * Uses the centralized marp-runner utility\n */\nexport function checkMarpCliAvailable(projectDir?: string): boolean {\n return isMarpAvailable(projectDir);\n}\n\n/**\n * Build marp-cli command arguments for taking screenshots\n * Returns an array of arguments (without the 'marp' command itself)\n */\nexport function buildMarpCommandArgs(\n markdownPath: string,\n outputDir: string,\n options: ScreenshotOptions\n): string[] {\n const format = options.format || 'png';\n const args = ['--images', format];\n\n // Calculate image scale if width is different from default\n if (options.width && options.width !== 1280) {\n const scale = options.width / 1280;\n args.push('--image-scale', String(scale));\n }\n\n args.push('-o', outputDir);\n args.push(markdownPath);\n\n return args;\n}\n\n/**\n * Create the screenshot command\n */\nexport function createScreenshotCommand(): Command {\n return new Command('screenshot')\n .description('Take screenshots of slides (requires Marp CLI)')\n .argument('<input>', 'Source YAML file')\n .option('-o, --output <path>', 'Output directory', './screenshots')\n .option('-s, --slide <number>', 'Specific slide number (1-based)', parseInt)\n .option('-w, --width <pixels>', 'Image width', parseInt, 1280)\n .option('-f, --format <fmt>', 'Image format (png/jpeg)', 'png')\n .option('-c, --config <path>', 'Config file path')\n .option('-v, --verbose', 'Verbose output')\n .action(async (input: string, options: ScreenshotOptions) => {\n await executeScreenshot(input, options);\n });\n}\n\n/**\n * Execute the screenshot command\n */\nexport async function executeScreenshot(\n inputPath: string,\n options: ScreenshotOptions\n): Promise<ScreenshotResult> {\n const errors: string[] = [];\n const spinner = options.verbose ? null : ora();\n const outputDir = options.output || './screenshots';\n\n // Validate input file exists\n try {\n await access(inputPath);\n } catch {\n const message = `File not found: ${inputPath}`;\n console.error(chalk.red(`Error: ${message}`));\n errors.push(message);\n process.exitCode = ExitCode.FileReadError;\n return { success: false, errors };\n }\n\n // Validate input file extension\n if (!/\\.ya?ml$/i.test(inputPath)) {\n const message = `Invalid file extension: ${inputPath} (expected .yaml or .yml)`;\n console.error(chalk.red(`Error: ${message}`));\n errors.push(message);\n process.exitCode = ExitCode.FileReadError;\n return { success: false, errors };\n }\n\n // Check marp-cli availability\n spinner?.start('Checking for Marp CLI...');\n if (!checkMarpCliAvailable(dirname(inputPath))) {\n spinner?.fail('Marp CLI not found');\n const message =\n 'Marp CLI not found. Install it with: npm install -D @marp-team/marp-cli';\n console.error(chalk.red(`Error: ${message}`));\n errors.push(message);\n process.exitCode = ExitCode.GeneralError;\n return { success: false, errors };\n }\n spinner?.succeed('Marp CLI found');\n\n // Create output directory\n try {\n await mkdir(outputDir, { recursive: true });\n } catch {\n const message = `Failed to create output directory: ${outputDir}`;\n console.error(chalk.red(`Error: ${message}`));\n errors.push(message);\n process.exitCode = ExitCode.GeneralError;\n return { success: false, errors };\n }\n\n // Load configuration\n spinner?.start('Loading configuration...');\n const configLoader = new ConfigLoader();\n let configPath = options.config;\n\n if (!configPath) {\n configPath = await configLoader.findConfig(dirname(inputPath));\n }\n\n const config = await configLoader.load(configPath);\n spinner?.succeed('Configuration loaded');\n\n // Create and initialize pipeline\n spinner?.start('Initializing pipeline...');\n const pipeline = new Pipeline(config);\n\n try {\n await pipeline.initialize();\n spinner?.succeed('Pipeline initialized');\n } catch (error) {\n spinner?.fail('Failed to initialize pipeline');\n const message =\n error instanceof Error ? error.message : 'Unknown initialization error';\n console.error(chalk.red(`Error: ${message}`));\n errors.push(message);\n process.exitCode = ExitCode.ConversionError;\n return { success: false, errors };\n }\n\n // Generate markdown (supports .yaml, .yml, case-insensitive)\n spinner?.start(`Converting ${inputPath}...`);\n const tempMdPath = inputPath.replace(/\\.ya?ml$/i, '.md');\n\n // Helper function to cleanup temporary markdown file\n const cleanupTempFile = async () => {\n try {\n await unlink(tempMdPath);\n } catch {\n // Ignore cleanup errors\n }\n };\n\n try {\n await pipeline.runWithResult(inputPath, { outputPath: tempMdPath });\n spinner?.succeed('Markdown generated');\n } catch (error) {\n spinner?.fail('Conversion failed');\n const message =\n error instanceof PipelineError\n ? `${error.stage}: ${error.message}`\n : error instanceof Error\n ? error.message\n : 'Unknown error';\n console.error(chalk.red(`Error: ${message}`));\n errors.push(message);\n process.exitCode = ExitCode.ConversionError;\n await cleanupTempFile();\n return { success: false, errors };\n }\n\n // Take screenshots with Marp CLI\n spinner?.start('Taking screenshots...');\n const marpArgs = buildMarpCommandArgs(tempMdPath, outputDir, options);\n\n if (options.verbose) {\n console.log(`Running: marp ${marpArgs.join(' ')}`);\n }\n\n try {\n runMarp(marpArgs, {\n projectDir: dirname(inputPath),\n stdio: options.verbose ? 'inherit' : 'pipe',\n });\n spinner?.succeed(`Screenshots saved to ${outputDir}`);\n } catch (error) {\n spinner?.fail('Failed to take screenshots');\n const message =\n error instanceof Error ? error.message : 'Marp CLI failed';\n console.error(chalk.red(`Error: ${message}`));\n errors.push(message);\n process.exitCode = ExitCode.GeneralError;\n await cleanupTempFile();\n return { success: false, errors };\n }\n\n // Filter to specific slide if requested\n if (options.slide !== undefined) {\n spinner?.start(`Filtering to slide ${options.slide}...`);\n const mdBaseName = basename(tempMdPath, '.md');\n const format = options.format || 'png';\n\n const filterResult = await filterToSpecificSlide(\n outputDir,\n mdBaseName,\n options.slide,\n format\n );\n\n if (!filterResult.success) {\n spinner?.fail('Failed to filter slides');\n console.error(chalk.red(`Error: ${filterResult.error}`));\n errors.push(filterResult.error || 'Filter failed');\n process.exitCode = ExitCode.GeneralError;\n await cleanupTempFile();\n return { success: false, errors };\n }\n\n spinner?.succeed(`Kept slide ${options.slide}: ${filterResult.keptFile}`);\n }\n\n // Cleanup temporary markdown file\n await cleanupTempFile();\n\n console.log('');\n console.log(`Output: ${chalk.cyan(outputDir)}`);\n\n return {\n success: true,\n errors,\n outputDir,\n };\n}\n","import { Command } from 'commander';\nimport { access, stat } from 'fs/promises';\nimport { resolve } from 'path';\nimport chalk from 'chalk';\nimport ora from 'ora';\nimport { ExitCode } from './convert.js';\nimport { SourcesManager } from '../../sources/manager.js';\nimport { SourceExplorer } from '../../sources/explorer.js';\nimport { SourceImporter } from '../../sources/importer.js';\nimport type { SourceType } from '../../sources/schema.js';\n\n/**\n * Options for sources init command\n */\nexport interface SourcesInitOptions {\n fromDirectory?: string;\n fromFile?: string;\n name?: string;\n}\n\n/**\n * Options for sources import command\n */\nexport interface SourcesImportOptions {\n recursive?: boolean;\n type?: SourceType;\n description?: string;\n}\n\n/**\n * Options for sources status command\n */\nexport interface SourcesStatusOptions {\n verbose?: boolean;\n}\n\n/**\n * Options for sources sync command\n */\nexport interface SourcesSyncOptions {\n check?: boolean;\n}\n\n/**\n * Result of sources init command\n */\nexport interface SourcesInitResult {\n success: boolean;\n message: string;\n filesImported?: number;\n}\n\n/**\n * Result of sources import command\n */\nexport interface SourcesImportResult {\n success: boolean;\n message: string;\n imported: number;\n skipped: number;\n}\n\n/**\n * Result of sources status command\n */\nexport interface SourcesStatusResult {\n success: boolean;\n output: string;\n}\n\n/**\n * Result of sources sync command\n */\nexport interface SourcesSyncResult {\n success: boolean;\n message: string;\n newFiles: number;\n modifiedFiles: number;\n}\n\n/**\n * Create the sources command with subcommands\n */\nexport function createSourcesCommand(): Command {\n const cmd = new Command('sources').description('Manage source materials');\n\n cmd.addCommand(createSourcesInitCommand());\n cmd.addCommand(createSourcesImportCommand());\n cmd.addCommand(createSourcesStatusCommand());\n cmd.addCommand(createSourcesSyncCommand());\n\n return cmd;\n}\n\n/**\n * Create sources init subcommand\n */\nfunction createSourcesInitCommand(): Command {\n return new Command('init')\n .description('Initialize sources directory')\n .option(\n '--from-directory <path>',\n 'Import from existing directory (Pattern A)'\n )\n .option('--from-file <path>', 'Import from scenario file (Pattern B)')\n .option('--name <name>', 'Project name')\n .action(async (options: SourcesInitOptions) => {\n const result = await executeSourcesInit(process.cwd(), options);\n if (!result.success) {\n process.exit(ExitCode.GeneralError);\n }\n });\n}\n\n/**\n * Create sources import subcommand\n */\nfunction createSourcesImportCommand(): Command {\n return new Command('import')\n .description('Import external files')\n .argument('<path>', 'File or directory to import')\n .option('--recursive', 'Import directory recursively')\n .option('--type <type>', 'Force source type')\n .option('--description <desc>', 'Add description')\n .action(async (path: string, options: SourcesImportOptions) => {\n const result = await executeSourcesImport(process.cwd(), path, options);\n if (!result.success) {\n process.exit(ExitCode.GeneralError);\n }\n });\n}\n\n/**\n * Create sources status subcommand\n */\nfunction createSourcesStatusCommand(): Command {\n return new Command('status')\n .description('Show sources status')\n .option('--verbose', 'Show detailed information')\n .action(async (options: SourcesStatusOptions) => {\n const result = await executeSourcesStatus(process.cwd(), options);\n console.log(result.output);\n if (!result.success) {\n process.exit(ExitCode.GeneralError);\n }\n });\n}\n\n/**\n * Create sources sync subcommand\n */\nfunction createSourcesSyncCommand(): Command {\n return new Command('sync')\n .description('Sync with original directory')\n .option('--check', 'Check for changes only')\n .action(async (options: SourcesSyncOptions) => {\n const result = await executeSourcesSync(process.cwd(), options);\n console.log(result.message);\n if (!result.success) {\n process.exit(ExitCode.GeneralError);\n }\n });\n}\n\n/**\n * Execute sources init command\n */\nexport async function executeSourcesInit(\n projectDir: string,\n options: SourcesInitOptions\n): Promise<SourcesInitResult> {\n const resolvedDir = resolve(projectDir);\n const spinner = ora('Initializing sources...').start();\n\n try {\n const manager = new SourcesManager(resolvedDir);\n\n // Check if already initialized\n if (await manager.exists()) {\n spinner.warn('Sources already initialized');\n return {\n success: true,\n message: 'Sources already initialized',\n };\n }\n\n // Determine project name\n let projectName = options.name ?? 'Untitled Project';\n\n // Determine setup pattern\n let setupPattern: 'A' | 'B' | undefined;\n let originalSource: string | undefined;\n\n if (options.fromDirectory) {\n setupPattern = 'A';\n originalSource = resolve(options.fromDirectory);\n } else if (options.fromFile) {\n setupPattern = 'B';\n originalSource = resolve(options.fromFile);\n }\n\n // Initialize sources\n await manager.init({\n name: projectName,\n setup_pattern: setupPattern,\n original_source: originalSource,\n });\n\n let filesImported = 0;\n\n // Import from directory (Pattern A)\n if (options.fromDirectory) {\n const importer = new SourceImporter(resolvedDir, manager);\n const result = await importer.importDirectory(\n resolve(options.fromDirectory),\n { recursive: true }\n );\n filesImported = result.imported;\n }\n\n // Import from file (Pattern B)\n if (options.fromFile) {\n const importer = new SourceImporter(resolvedDir, manager);\n await importer.importFile(resolve(options.fromFile), {\n type: 'scenario',\n });\n filesImported = 1;\n }\n\n spinner.succeed(\n chalk.green(\n `Sources initialized${filesImported > 0 ? ` (${filesImported} files imported)` : ''}`\n )\n );\n\n return {\n success: true,\n message: 'Sources initialized successfully',\n filesImported,\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n spinner.fail(chalk.red(`Failed to initialize sources: ${message}`));\n return {\n success: false,\n message,\n };\n }\n}\n\n/**\n * Execute sources import command\n */\nexport async function executeSourcesImport(\n projectDir: string,\n sourcePath: string,\n options: SourcesImportOptions\n): Promise<SourcesImportResult> {\n const resolvedDir = resolve(projectDir);\n const resolvedSource = resolve(sourcePath);\n const spinner = ora('Importing files...').start();\n\n try {\n const manager = new SourcesManager(resolvedDir);\n\n // Check if sources is initialized\n if (!(await manager.exists())) {\n spinner.fail(\n chalk.red('Sources not initialized. Run `slide-gen sources init` first.')\n );\n return {\n success: false,\n message: 'Sources not initialized',\n imported: 0,\n skipped: 0,\n };\n }\n\n const importer = new SourceImporter(resolvedDir, manager);\n\n // Check if path is file or directory\n const stats = await stat(resolvedSource);\n\n let imported = 0;\n let skipped = 0;\n\n if (stats.isDirectory()) {\n const importDirOptions = options.recursive ? { recursive: true } : {};\n const result = await importer.importDirectory(\n resolvedSource,\n importDirOptions\n );\n imported = result.imported;\n skipped = result.skipped;\n } else {\n const importFileOptions: { type?: SourceType; description?: string } = {};\n if (options.type) {\n importFileOptions.type = options.type;\n }\n if (options.description) {\n importFileOptions.description = options.description;\n }\n await importer.importFile(resolvedSource, importFileOptions);\n imported = 1;\n }\n\n spinner.succeed(\n chalk.green(`Imported ${imported} file(s)${skipped > 0 ? ` (${skipped} skipped)` : ''}`)\n );\n\n return {\n success: true,\n message: `Imported ${imported} files`,\n imported,\n skipped,\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n spinner.fail(chalk.red(`Failed to import: ${message}`));\n return {\n success: false,\n message,\n imported: 0,\n skipped: 0,\n };\n }\n}\n\n/**\n * Execute sources status command\n */\nexport async function executeSourcesStatus(\n projectDir: string,\n _options: SourcesStatusOptions\n): Promise<SourcesStatusResult> {\n const resolvedDir = resolve(projectDir);\n\n try {\n const manager = new SourcesManager(resolvedDir);\n\n // Check if sources is initialized\n if (!(await manager.exists())) {\n return {\n success: false,\n output: chalk.red(\n 'Sources not initialized. Run `slide-gen sources init` first.'\n ),\n };\n }\n\n const data = await manager.load();\n\n // Build status output\n let output = '';\n\n output += chalk.bold(`Sources Status: ${data.project.name}\\n`);\n output += chalk.gray('━'.repeat(50)) + '\\n\\n';\n\n // Setup pattern\n if (data.project.setup_pattern) {\n output += `Setup: Pattern ${data.project.setup_pattern}`;\n if (data.project.original_source) {\n output += ` (from ${data.project.original_source})`;\n }\n output += '\\n';\n }\n\n // Source counts by type\n const sources = data.sources ?? [];\n const countByType = sources.reduce(\n (acc, s) => {\n acc[s.type] = (acc[s.type] ?? 0) + 1;\n return acc;\n },\n {} as Record<string, number>\n );\n\n output += '\\n';\n output += chalk.cyan('Sources:\\n');\n for (const [type, count] of Object.entries(countByType)) {\n output += ` ${type}: ${count} file(s)\\n`;\n }\n\n // Missing items\n const missing = data.missing ?? [];\n if (missing.length > 0) {\n output += '\\n';\n output += chalk.yellow('Missing:\\n');\n for (const item of missing) {\n output += ` ⚠ ${item.item}`;\n if (item.needed_for) {\n output += ` (needed for ${item.needed_for})`;\n }\n output += '\\n';\n }\n }\n\n // Last updated\n if (data.project.updated) {\n output += '\\n';\n output += chalk.gray(`Last updated: ${data.project.updated}\\n`);\n }\n\n return {\n success: true,\n output,\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return {\n success: false,\n output: chalk.red(`Failed to get status: ${message}`),\n };\n }\n}\n\n/**\n * Execute sources sync command\n */\nexport async function executeSourcesSync(\n projectDir: string,\n options: SourcesSyncOptions\n): Promise<SourcesSyncResult> {\n const resolvedDir = resolve(projectDir);\n\n try {\n const manager = new SourcesManager(resolvedDir);\n\n // Check if sources is initialized\n if (!(await manager.exists())) {\n return {\n success: false,\n message: 'Sources not initialized. Run `slide-gen sources init` first.',\n newFiles: 0,\n modifiedFiles: 0,\n };\n }\n\n const data = await manager.load();\n\n // Check if this was initialized from a directory\n if (!data.project.original_source) {\n return {\n success: true,\n message: 'No original source directory to sync with.',\n newFiles: 0,\n modifiedFiles: 0,\n };\n }\n\n const originalDir = data.project.original_source;\n\n // Check if original directory exists\n try {\n await access(originalDir);\n } catch {\n return {\n success: false,\n message: `Original directory not found: ${originalDir}`,\n newFiles: 0,\n modifiedFiles: 0,\n };\n }\n\n // Scan original directory for changes\n const explorer = new SourceExplorer();\n const currentFiles = await explorer.scan(originalDir);\n\n // Get existing source origins\n const existingOrigins = new Set(\n data.sources?.map((s) => s.origin).filter(Boolean) ?? []\n );\n\n // Count new files\n let newFiles = 0;\n for (const file of currentFiles) {\n if (!existingOrigins.has(file.path)) {\n newFiles++;\n }\n }\n\n if (options.check) {\n if (newFiles === 0) {\n return {\n success: true,\n message: 'No changes detected.',\n newFiles: 0,\n modifiedFiles: 0,\n };\n } else {\n return {\n success: true,\n message: `Found ${newFiles} new file(s). Run without --check to sync.`,\n newFiles,\n modifiedFiles: 0,\n };\n }\n }\n\n // Actually sync (import new files)\n if (newFiles > 0) {\n const importer = new SourceImporter(resolvedDir, manager);\n await importer.importDirectory(originalDir, { recursive: true });\n }\n\n return {\n success: true,\n message:\n newFiles > 0 ? `Synced ${newFiles} new file(s).` : 'No changes to sync.',\n newFiles,\n modifiedFiles: 0,\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return {\n success: false,\n message: `Failed to sync: ${message}`,\n newFiles: 0,\n modifiedFiles: 0,\n };\n }\n}\n"],"mappings":";;;AAEA,SAAS,WAAAA,iBAAe;;;ACFxB,SAAS,SAAS;AAClB,SAAS,SAAS,WAAW,eAAe,OAAO,OAAO,QAAQ,mBAAmB;AACr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C,UAAQ;AAE5B,QACG,KAAK,WAAW,EAChB,YAAY,0DAA0D,EACtE,QAAQ,OAAO;AAGlB,QAAQ,WAAW,qBAAqB,CAAC;AAGzC,QAAQ,WAAW,sBAAsB,CAAC;AAG1C,QAAQ,WAAW,uBAAuB,CAAC;AAG3C,QAAQ,WAAW,mBAAmB,CAAC;AAGvC,QAAQ,WAAW,kBAAkB,CAAC;AAGtC,QAAQ,WAAW,mBAAmB,CAAC;AAGvC,QAAQ,WAAW,qBAAqB,CAAC;AAGzC,QAAQ,WAAW,oBAAoB,CAAC;AAGxC,QAAQ,WAAW,wBAAwB,CAAC;AAG5C,QAAQ,WAAW,qBAAqB,CAAC;AAEzC,QAAQ,MAAM;","names":["Command","z","z","path","z","fs","parseYaml","z","parseYaml","fs","path","nunjucks","resolve","CITATION_BRACKET_PATTERN","SINGLE_CITATION_PATTERN","access","readFile","basename","dirname","join","parseYaml","readFile","join","parseYaml","z","path","join","readFile","parseYaml","z","z","z","z","fs","path","parseYaml","parseYaml","fs","path","fs","path","dirname","basename","join","readFile","parseYaml","content","access","Command","access","readFile","dirname","chalk","ora","parseYaml","yaml","Command","ora","access","readFile","parseYaml","dirname","chalk","Command","chalk","yaml","mkdir","writeFile","rm","join","basename","tmpdir","Command","access","unlink","readdir","mkdir","writeFile","readFile","basename","dirname","join","extname","path","chalk","join","readdir","join","basename","resolve","extname","readFile","chalk","join","access","chalk","dirname","mkdir","basename","writeFile","resolve","Command","unlink","Command","chalk","escapeHtml","join","tmpdir","mkdir","rm","writeFile","basename","resolve","Command","chalk","fs","path","parseYaml","stringifyYaml","fs","path","parseYaml","createListCommand","Command","output","sources","chalk","parseYaml","stringifyYaml","createPreviewCommand","Command","mkdir","writeFile","access","readdir","existsSync","basename","dirname","join","resolve","chalk","ora","fs","path","parse","stringify","z","parse","stringify","fs","path","fs","path","dirname","join","Command","ora","resolve","access","readdir","mkdir","chalk","writeFile","existsSync","existsSync","join","chalk","resolve","ora","writeFile","basename","mkdir","Command","access","basename","dirname","join","chalk","chokidarWatch","getDefaultOutputPath","dirname","basename","join","Command","chalk","access","chokidarWatch","resolve","Command","readFile","stat","mkdir","dirname","basename","join","chalk","stringifyYaml","Command","dirname","chalk","stringifyYaml","readFile","stat","join","basename","mkdir","Command","access","mkdir","readdir","unlink","basename","dirname","join","chalk","ora","join","access","readdir","unlink","checkMarpCliAvailable","Command","ora","chalk","dirname","mkdir","basename","Command","access","stat","resolve","chalk","ora","Command","path","resolve","ora","chalk","stat","access","Command"]}