Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
feat(mcp-host): lay out PPTX slides from measured text
marcotebf7ce2747da61
diff --git a/mcp-host/src/workflow/pptxCharts.ts b/mcp-host/src/workflow/pptxCharts.tsnew file mode 100644index 000000000..d8f4b47b0--- /dev/null+++ b/mcp-host/src/workflow/pptxCharts.ts@@ -0,0 +1,268 @@+/**+ * Native (editable) PowerPoint charts for clerum__generate_pptx.+ *+ * The data goes through the same normalizer as clerum__generate_chart, because+ * PowerPoint drops chart-cache values written as text such as "1,200".+ */+import { ChartDataError, normalizeChartData } from './chartData'+import { PPTX_FONT_FACE } from './pptxText'++/** Types drawn as native charts; the stacked ones are bar and area charts with stacked grouping. */+export const NATIVE_CHART_TYPES = [+ 'line',+ 'bar',+ 'horizontalBar',+ 'pie',+ 'doughnut',+ 'area',+ 'stackedBar',+ 'stackedArea',+] as const++export type NativeChartType = (typeof NATIVE_CHART_TYPES)[number]++const SLICE_TYPES = new Set<NativeChartType>(['pie', 'doughnut'])++/** Series longer than this get no value labels; they would overlap. */+const MAX_LABELLED_POINTS = 12++export interface NativeChart {+ type: NativeChartType+ labels: string[]+ series: Array<{ name: string; values: Array<number | null> }>+}++export class ChartSpecError extends Error {}++function isRecord(v: unknown): v is Record<string, unknown> {+ return v !== null && typeof v === 'object' && !Array.isArray(v)+}++/**+ * The native chart `raw` describes, or undefined when it carries no data at+ * all. Throws ChartSpecError, naming the field under `where`, for a type+ * PowerPoint cannot draw natively or data no chart can be drawn from.+ */+export function readNativeChart(+ raw: Record<string, unknown>,+ where: string,+ warnings: string[]+): NativeChart | undefined {+ const nested = isRecord(raw.data) ? raw.data : undefined+ // Labels and datasets are each read where they were given, nested or at the top.+ const labelsFrom = nested?.labels !== undefined ? nested : raw+ const datasetsFrom = nested?.datasets !== undefined ? nested : raw+ if (datasetsFrom.datasets === undefined && labelsFrom.labels === undefined) return undefined++ let type: NativeChartType+ if (raw.type === undefined || raw.type === null || raw.type === '') {+ type = 'bar'+ warnings.push(`${where}.type was missing, so a bar chart was drawn; set type to choose one.`)+ } else if ((NATIVE_CHART_TYPES as readonly unknown[]).includes(raw.type)) {+ type = raw.type as NativeChartType+ } else {+ throw new ChartSpecError(+ `${where}.type ${JSON.stringify(raw.type)} has no native PowerPoint chart. Use one of ` ++ `${NATIVE_CHART_TYPES.join(', ')}; for any other type, draw it with ` ++ `clerum__generate_chart and pass the file name it returns as ${where}.path.`+ )+ }++ const baseOf = (from: Record<string, unknown>) => (from === nested ? `${where}.data` : where)+ const base = baseOf(datasetsFrom)+ // Template charts leave the nested form out of the schema, so its labels are checked here.+ if (nested) checkNestedLabels(nested, `${where}.data`)+ const rewrite = (message: string) =>+ message+ .replace(/\bdata\.labels\b/g, `${baseOf(labelsFrom)}.labels`)+ .replace(/\bdata\.datasets\b/g, `${base}.datasets`)+ .replace(/`data`/g, `\`${base}\``)+ let normalized+ try {+ normalized = normalizeChartData(+ { labels: labelsFrom.labels, datasets: datasetsFrom.datasets },+ { chartType: type }+ )+ } catch (err) {+ if (err instanceof ChartDataError) throw new ChartSpecError(rewrite(err.message))+ throw err+ }+ for (const w of normalized.warnings) {+ const text = rewrite(w)+ warnings.push(text.includes(where) ? text : `${where}: ${text}`)+ }++ const unnamed = normalized.datasets.filter(d => !d.label).length+ if (unnamed > 0 && normalized.datasets.length > 1) {+ warnings.push(+ `${base}.datasets: ${unnamed} series had no label, so the legend numbers them; give each a label.`+ )+ }+ let series = normalized.datasets.map((d, i) => ({+ name: boundLabel(d.label || `#${i + 1}`, MAX_SERIES_NAME),+ values: d.data as Array<number | null>,+ }))+ if (SLICE_TYPES.has(type) && series.length > 1) {+ warnings.push(+ `${where}: a ${type} chart draws one series, so only "${series[0].name}" was drawn and ` ++ `${series.length - 1} more were left out. Use a bar or line chart to compare series.`+ )+ series = series.slice(0, 1)+ }+ const labels = (normalized.labels ?? []).map(l => boundLabel(l, MAX_CATEGORY_LABEL))+ return { type, labels, series }+}++function checkNestedLabels(data: Record<string, unknown>, base: string): void {+ if (Array.isArray(data.labels)) {+ data.labels.forEach((label, i) => {+ if (typeof label !== 'string' && typeof label !== 'number') {+ throw new ChartSpecError(`${base}.labels[${i}] must be text or a number.`)+ }+ })+ }+ if (Array.isArray(data.datasets)) {+ data.datasets.forEach((ds, i) => {+ if (isRecord(ds) && ds.label !== undefined && typeof ds.label !== 'string') {+ throw new ChartSpecError(`${base}.datasets[${i}].label must be text.`)+ }+ })+ }+}++/** Axis and legend text longer than this crowds the plot out of the chart area. */+const MAX_CATEGORY_LABEL = 80+const MAX_SERIES_NAME = 100++function boundLabel(text: string, max: number): string {+ const chars = Array.from(text)+ return chars.length > max ? `${chars.slice(0, max - 1).join('')}…` : text+}++export interface NativeChartStyle {+ /** Shown above the plot; omitted when it would repeat the slide title. */+ title?: string+ colors: string[]+ textColor: string+ mutedColor: string+}++/**+ * Values below 1000 in General, which prints each with the decimals it has,+ * and larger ones grouped: "1,200", "5,000,000" and "980.5" in one series.+ * "#,##0.##" would print the integers as "1,200.".+ */+const GROUPED_OR_GENERAL = '[>=1000]#,##0;[<=-1000]-#,##0;General'++/** Decimal places `v` carries, ignoring binary noise such as 0.1 + 0.2. */+function decimals(v: number): number {+ const text = String(Number(v.toPrecision(12)))+ if (text.includes('e')) return 0+ return text.includes('.') ? text.length - text.indexOf('.') - 1 : 0+}++/** Excel number formats for the value labels and the value axis. */+function valueFormats(values: number[]): { label: string; axis: string } {+ const fractional = values.filter(v => !Number.isInteger(v))+ let label = '#,##0'+ if (fractional.some(v => Math.abs(v) >= 1000)) {+ // Grouping and General cannot be combined, so every label gets the same decimals.+ const places = Math.min(Math.max(...fractional.map(decimals), 1), 2)+ label = `#,##0.${'0'.repeat(places)}`+ } else if (fractional.length > 0) {+ label = GROUPED_OR_GENERAL+ }+ // PowerPoint picks fractional axis steps for small ranges, which an integer+ // format would print as repeated labels; grouping only matters for large values.+ const axis = values.some(v => Math.abs(v) >= 1000) ? '#,##0' : 'General'+ return { label, axis }+}++/** Arguments for pptxgenjs `slide.addChart(type, data, options)`. */+export function nativeChartArgs(+ chart: NativeChart,+ style: NativeChartStyle,+ pptx: any+): { type: string; data: unknown[]; options: Record<string, unknown> } {+ const c = pptx.charts ?? {}+ const type =+ chart.type === 'line'+ ? (c.LINE ?? 'line')+ : chart.type === 'area' || chart.type === 'stackedArea'+ ? (c.AREA ?? 'area')+ : chart.type === 'pie'+ ? (c.PIE ?? 'pie')+ : chart.type === 'doughnut'+ ? (c.DOUGHNUT ?? 'doughnut')+ : (c.BAR ?? 'bar')+ const slices = SLICE_TYPES.has(chart.type)+ const stacked = chart.type === 'stackedBar' || chart.type === 'stackedArea'+ const barLike = ['bar', 'horizontalBar', 'stackedBar'].includes(chart.type)+ const labelled =+ !slices &&+ (barLike || chart.type === 'line') &&+ chart.series.every(s => s.values.length <= MAX_LABELLED_POINTS)+ const values = chart.series.flatMap(s => s.values).filter((v): v is number => v !== null)+ const format = valueFormats(values)+ const options: Record<string, unknown> = {+ barDir: chart.type === 'horizontalBar' ? 'bar' : 'col',+ // pptxgenjs colors each bar of a lone series differently when given+ // several colors, which reads as a legend that is not there.+ chartColors: barLike && chart.series.length === 1 ? style.colors.slice(0, 1) : style.colors,+ showTitle: Boolean(style.title),+ title: style.title ?? '',+ titleColor: style.textColor,+ titleFontFace: PPTX_FONT_FACE,+ titleFontSize: 16,+ // A single-series bar or line needs no key; a pie always does, because+ // its categories appear nowhere else.+ showLegend: slices || chart.series.length > 1,+ legendPos: slices ? 'r' : 'b',+ legendColor: style.textColor,+ legendFontFace: PPTX_FONT_FACE,+ legendFontSize: 12,+ catAxisLabelColor: style.mutedColor,+ catAxisLabelFontFace: PPTX_FONT_FACE,+ valAxisLabelColor: style.mutedColor,+ valAxisLabelFontFace: PPTX_FONT_FACE,+ valAxisLabelFormatCode: format.axis,+ dataLabelFontFace: PPTX_FONT_FACE,+ dataLabelFontSize: 11,+ dataLabelColor: style.textColor,+ }+ if (stacked) options.barGrouping = 'stacked'+ if (!slices) {+ // A missing value is a gap in the line, not a straight segment drawn across it.+ options.displayBlanksAs = 'gap'+ }+ if (chart.type !== 'line' && !slices) {+ // A bar or area is read by its length, so the value axis starts at zero, as+ // clerum__generate_chart draws it; PowerPoint would otherwise start near the+ // smallest value. An all-zero chart keeps an automatic maximum.+ if (values.every(v => v >= 0)) options.valAxisMinVal = 0+ else if (values.every(v => v <= 0)) options.valAxisMaxVal = 0+ }+ if (chart.type === 'horizontalBar') {+ // The first category on top, as a ranked list reads, with the value axis+ // and its labels kept at the bottom and the category names on the left.+ options.catAxisOrientation = 'maxMin'+ options.catAxisCrossesAt = 'max'+ options.valAxisLabelPos = 'nextTo'+ options.catAxisLabelPos = 'low'+ }+ if (slices) {+ options.showPercent = true+ options.showValue = false+ // Outside the slice, where the text color reads against the background;+ // a doughnut has no such position, so its labels are white on the ring.+ if (chart.type === 'pie') options.dataLabelPosition = 'outEnd'+ else options.dataLabelColor = 'FFFFFF'+ } else if (labelled) {+ options.showValue = true+ options.dataLabelFormatCode = format.label+ if (barLike && !stacked) options.dataLabelPosition = 'outEnd'+ if (chart.type === 'line') options.dataLabelPosition = 't'+ }+ const data = chart.series.map(s => ({ name: s.name, labels: chart.labels, values: s.values }))+ return { type, data, options }+}diff --git a/mcp-host/src/workflow/pptxDeck.ts b/mcp-host/src/workflow/pptxDeck.tsnew file mode 100644index 000000000..588a5309c--- /dev/null+++ b/mcp-host/src/workflow/pptxDeck.ts@@ -0,0 +1,1447 @@+/**+ * Builds the .pptx for clerum__generate_pptx with pptxgenjs.+ *+ * Coordinates are inches. Arguments are read by pptxInput (and pptxTemplates),+ * then every slide is laid out from measured text before anything is drawn:+ * lists and tables that do not fit continue on further slides, titles and+ * values shrink to fit their boxes, and pictures keep their proportions.+ */+import JSZip from 'jszip'+import { bidiLanguage, documentEastAsianScript, isRtlText, scriptSegments } from './docxScript'+import { fitImageSize } from './embeddedImages'+import { nativeChartArgs } from './pptxCharts'+import {+ type PptxColumn,+ PptxInputError,+ type PptxKpi,+ type PptxPicture,+ type PptxSlide,+ type ReadContext,+ fieldPath,+ isRecord,+ readPicture,+ readSlides,+ readText,+} from './pptxInput'+import { type TableLayout, layoutTable } from './pptxTables'+import { PPTX_TEMPLATES, type PptxTemplate, buildTemplateSlides } from './pptxTemplates'+import {+ PPTX_FONT_FACE,+ TEXT_INSET_X,+ TEXT_INSET_Y,+ fitText,+ lineHeightIn,+ scriptOptions,+ textBlockHeight,+ textWidth,+ truncateToLines,+ wrapLines,+} from './pptxText'++const PptxGenJS = require('pptxgenjs')++interface PptxPalette {+ primary: string+ primaryDark: string+ text: string+ muted: string+ border: string+ accent: string+ surface: string+ background: string+ statusGreen: string+ statusYellow: string+ statusRed: string+}++export const PPTX_PALETTES: Record<string, PptxPalette> = {+ default: {+ primary: '#0f172a',+ primaryDark: '#020617',+ text: '#0f172a',+ muted: '#475569',+ border: '#cbd5e1',+ accent: '#3b82f6',+ surface: '#f1f5f9',+ background: '#ffffff',+ statusGreen: '#16a34a',+ statusYellow: '#ca8a04',+ statusRed: '#dc2626',+ },+ corporate: {+ primary: '#1e3a8a',+ primaryDark: '#1e293b',+ text: '#1e293b',+ muted: '#475569',+ border: '#cbd5e1',+ accent: '#0891b2',+ surface: '#e0f2fe',+ background: '#ffffff',+ statusGreen: '#059669',+ statusYellow: '#ca8a04',+ statusRed: '#b91c1c',+ },+ warm: {+ primary: '#b45309',+ primaryDark: '#78350f',+ text: '#2f2823',+ muted: '#66584c',+ border: '#d6d2cc',+ accent: '#0d9488',+ surface: '#f7f7f5',+ background: '#fefdfb',+ statusGreen: '#65a30d',+ statusYellow: '#ca8a04',+ statusRed: '#9f1239',+ },+ alert: {+ primary: '#9f1239',+ primaryDark: '#4c0519',+ text: '#1f2937',+ muted: '#4b5563',+ border: '#fecaca',+ accent: '#dc2626',+ surface: '#fee2e2',+ background: '#ffffff',+ statusGreen: '#16a34a',+ statusYellow: '#ca8a04',+ statusRed: '#dc2626',+ },+}++/** Series colors after the palette's own, so a chart of many slices does not repeat one. */+const EXTRA_SERIES_COLORS = ['#7c3aed', '#0d9488', '#ea580c', '#db2777']++export const PPTX_ASPECT_RATIOS: Record<string, { name: string; width: number; height: number }> = {+ wide: { name: 'LAYOUT_WIDE', width: 13.333, height: 7.5 },+ '16x9': { name: 'LAYOUT_16x9', width: 10, height: 5.625 },+ '16x10': { name: 'LAYOUT_16x10', width: 10, height: 6.25 },+ '4x3': { name: 'LAYOUT_4x3', width: 10, height: 7.5 },+}++/** pptxgenjs takes bare uppercase hex. */+function hex(c: string): string {+ return c.replace(/^#/, '').toUpperCase()+}++/** Indent pptxgenjs gives a bulleted paragraph, in inches. */+const BULLET_INDENT = 27 / 72+// U+2022, not U+25CF: PowerPoint sets the ambiguous-width U+25CF in the East Asian face of+// a CJK-tagged paragraph, where the dot is larger than on the Latin lines around it.+const BULLET = { code: '2022' }+/** Space after each bullet, in points. */+const BULLET_SPACE_AFTER = 8+const KPIS_PER_SLIDE = 8+/** One or two cards stretched across a wide slide leave their figures lost in the card. */+const MAX_CARD_WIDTH = 4.5++interface Box {+ x: number+ y: number+ w: number+ h: number+}++interface Frame {+ width: number+ height: number+ wide: boolean+ marginX: number+ titleY: number+ footerY: number+ /** Lowest point body content may reach. */+ bodyBottom: number+}++function frameFor(width: number, height: number): Frame {+ const footerY = height - 0.45+ return {+ width,+ height,+ wide: width > 12,+ marginX: width <= 10 ? 0.4 : 0.5,+ titleY: 0.4,+ footerY,+ bodyBottom: footerY - 0.2,+ }+}++interface TitleBlock {+ text: string+ size: number+ h: number+}++/** A slide title that fits in two lines (three at the smallest size) and the height it takes. */+function layoutTitle(title: string, frame: Frame, field: string, warnings: string[]): TitleBlock {+ const sizes = frame.wide ? [28, 24, 20, 18] : [22, 20, 18, 16]+ const w = frame.width - frame.marginX * 2+ let fit = fitText([title], { w, h: Infinity }, sizes, { bold: true, maxLines: 2 })+ let text = title+ if (!fit.fits) {+ const size = sizes[sizes.length - 1]+ text = truncateToLines(title, size, w - TEXT_INSET_X, 3, true)+ if (text !== title) {+ warnings.push(`${field} is too long for a slide title and was shortened.`)+ }+ fit = fitText([text], { w, h: Infinity }, [size], { bold: true })+ }+ return { text, size: fit.size, h: Math.max(0.7, fit.height) }+}++function bodyBox(frame: Frame, title: TitleBlock | undefined): Box {+ const y = title ? Math.max(1.3, frame.titleY + title.h + 0.2) : 1.3+ return {+ x: frame.marginX,+ y,+ w: frame.width - frame.marginX * 2,+ h: frame.bodyBottom - y,+ }+}++/** One slide as it will be drawn, after lists and tables are split into pages. */+interface PlannedSlide {+ spec: PptxSlide+ title?: TitleBlock+ body: Box+ bullets?: { items: string[]; size: number }+ table?: { layout: TableLayout; page: number }+ kpis?: PptxKpi[]+}++interface ListPlan {+ pages: string[][]+ size: number+}++/** Height of one bullet; a line break in it starts a line under the same bullet. */+function bulletHeight(item: string, size: number, width: number): number {+ return textBlockHeight([item], size, width, { paraSpaceAfter: BULLET_SPACE_AFTER })+}++/**+ * Bullets for boxes of `box`: all on one slide at the largest size that fits,+ * otherwise over the fewest slides the smallest size allows, at the largest+ * size that still needs no more slides than that.+ */+function planBullets(+ items: string[],+ box: Box,+ frame: Frame,+ where: string,+ warnings: string[]+): ListPlan {+ const sizes = frame.wide ? [18, 16, 14, 12] : [14, 13, 12, 11]+ const width = box.w - TEXT_INSET_X - BULLET_INDENT+ const room = box.h - TEXT_INSET_Y+ const paginate = (size: number) => {+ const pages: string[][] = []+ let page: string[] = []+ let used = 0+ let cut = 0+ for (let item of items) {+ let h = bulletHeight(item, size, width)+ if (h > room) {+ const lines = Math.max(+ Math.floor((room - BULLET_SPACE_AFTER / 72) / lineHeightIn(size, item)),+ 1+ )+ item = truncateToLines(item, size, width, lines)+ h = bulletHeight(item, size, width)+ cut+++ }+ if (page.length > 0 && used + h > room + 1e-9) {+ pages.push(page)+ page = []+ used = 0+ }+ page.push(item)+ used += h+ }+ if (page.length > 0) pages.push(page)+ return { pages, cut }+ }+ const smallest = sizes[sizes.length - 1]+ const fewest = paginate(smallest).pages.length+ let chosen = { ...paginate(smallest), size: smallest }+ for (const size of sizes) {+ const attempt = paginate(size)+ if (attempt.pages.length <= fewest) {+ chosen = { ...attempt, size }+ break+ }+ }+ if (chosen.cut > 0) {+ warnings.push(+ `${where}: ${chosen.cut} bullet(s) were longer than a whole slide and were shortened.`+ )+ }+ return { pages: chosen.pages, size: chosen.size }+}++function pageTitle(title: string | undefined, page: number, pages: number): string | undefined {+ if (pages <= 1) return title+ return `${title ?? ''} (${page}/${pages})`.trim()+}++/**+ * Split a slide whose content needs more than one slide. Titles of the parts+ * are numbered "(1/3)", which reads the same in any language.+ */+function planSlide(spec: PptxSlide, frame: Frame, warnings: string[]): PlannedSlide[] {+ const titled = spec.layout !== 'cover' && spec.layout !== 'section' && spec.layout !== 'quote'+ const titleFor = (text: string | undefined) =>+ titled && text ? layoutTitle(text, frame, fieldPath(spec, 'title'), warnings) : undefined++ if (spec.layout === 'title-bullets' && spec.bullets) {+ let title = titleFor(spec.title)+ let body = bodyBox(frame, title)+ let list = planBullets(spec.bullets, body, frame, fieldPath(spec, 'bullets'), [])+ if (list.pages.length > 1) {+ // The numbered title can take another line, so the split is redone under it.+ title = titleFor(pageTitle(spec.title, list.pages.length, list.pages.length))+ body = bodyBox(frame, title)+ }+ list = planBullets(spec.bullets, body, frame, fieldPath(spec, 'bullets'), warnings)+ const n = list.pages.length+ if (n > 1) {+ warnings.push(+ `${fieldPath(spec, 'bullets')}: the ${spec.bullets.length} bullets did not fit on one slide, so they ` ++ `continue on ${n - 1} more slide(s).`+ )+ }+ return list.pages.map((items, i) => ({+ spec,+ title: titleFor(pageTitle(spec.title, i + 1, n)),+ body,+ bullets: { items, size: list.size },+ }))+ }++ if (spec.layout === 'title-table' && spec.table) {+ let title = titleFor(spec.title)+ let body = bodyBox(frame, title)+ let layout = layoutTable(spec.table, body, frame.wide, fieldPath(spec, 'table'), [])+ if (layout.pages.length > 1) {+ title = titleFor(pageTitle(spec.title, layout.pages.length, layout.pages.length))+ body = bodyBox(frame, title)+ }+ layout = layoutTable(spec.table, body, frame.wide, fieldPath(spec, 'table'), warnings)+ const n = layout.pages.length+ return layout.pages.map((_, i) => ({+ spec,+ title: titleFor(pageTitle(spec.title, i + 1, n)),+ body,+ table: { layout, page: i },+ }))+ }++ if (spec.layout === 'kpis' && spec.kpis) {+ const n = Math.ceil(spec.kpis.length / KPIS_PER_SLIDE)+ if (n > 1) {+ warnings.push(+ `${fieldPath(spec, 'kpis')}: ${spec.kpis.length} KPI cards are more than the ${KPIS_PER_SLIDE} a ` ++ `slide holds, so they continue on ${n - 1} more slide(s).`+ )+ }+ // Spread evenly, so nine cards become five and four rather than eight and one.+ const perSlide = Math.ceil(spec.kpis.length / n)+ return Array.from({ length: n }, (_, i) => {+ const title = titleFor(pageTitle(spec.title, i + 1, n))+ return {+ spec,+ title,+ body: bodyBox(frame, title),+ kpis: spec.kpis!.slice(i * perSlide, (i + 1) * perSlide),+ }+ })+ }++ const title = titleFor(spec.title)+ return [{ spec, title, body: bodyBox(frame, title) }]+}++type Slide = any++interface DrawContext {+ frame: Frame+ palette: PptxPalette+ pptx: any+ warnings: string[]+ logo?: PptxPicture+}++/** The language of each slide's text of Han characters alone: the deck's. */+const hanLanguage = new WeakMap<Slide, string>()++/** Every string in the slides, to find the deck's East Asian language from. */+function deckText(specs: PptxSlide[]): string {+ const out: string[] = []+ const pending: unknown[] = [specs]+ while (pending.length > 0) {+ const value = pending.pop()+ if (typeof value === 'string') out.push(value)+ else if (Array.isArray(value)) for (const item of value) pending.push(item)+ else if (isRecord(value) && !ArrayBuffer.isView(value)) pending.push(...Object.values(value))+ }+ return out.join('\n')+}++/**+ * Language and direction for a run of `text` on `slide`. A right-to-left+ * paragraph is right-aligned unless it was centred.+ */+function runOptions(slide: Slide, text: string, align?: unknown): Record<string, unknown> {+ const script = scriptOptions(text, hanLanguage.get(slide))+ const out: Record<string, unknown> = {}+ if (script.lang) out.lang = script.lang+ if (script.rtlMode) {+ out.rtlMode = true+ if (!align || align === 'left') out.align = 'right'+ }+ return out+}++/**+ * Arabic-script text. It is never set italic: PowerPoint takes an italic Arabic+ * run from Arial Italic, which has no Arabic glyphs, and prints unrelated Latin+ * letters. Letter spacing pulls its joined letters apart, so the section+ * eyebrow leaves it unspaced.+ */+const ARABIC_SCRIPT = /\p{Script=Arabic}/u+const RTL_LETTER = /[\p{Script=Arabic}\p{Script=Hebrew}]/u++type TextRun = { text: string; options: Record<string, unknown> }++/**+ * `text` as runs of one direction each, tagged with their own language:+ * PowerPoint orders a run by its language, so Latin words in a run tagged+ * Arabic print in reverse. `paragraph` (alignment, direction) goes on every+ * run, since pptxgenjs starts a new paragraph where the alignment changes.+ */+function directionRuns(text: string, paragraph: Record<string, unknown>): TextRun[] {+ return scriptSegments(text, isRtlText(text)).map(segment => ({+ text: segment.text,+ options: { ...paragraph, lang: segment.rtl ? bidiLanguage(segment.text) : 'en-US' },+ }))+}++/** Paragraph options without the language, which directionRuns sets per run. */+function paragraphOptions(slide: Slide, text: string, align?: unknown): Record<string, unknown> {+ const { lang: _lang, ...paragraph } = runOptions(slide, text, align)+ return align && !paragraph.align ? { align, ...paragraph } : paragraph+}++function addText(slide: Slide, text: string, box: Box, options: Record<string, unknown>): void {+ const upright = ARABIC_SCRIPT.test(text) ? { italic: false } : {}+ if (!RTL_LETTER.test(text)) {+ slide.addText(text, {+ ...box,+ ...options,+ ...upright,+ ...runOptions(slide, text, options.align),+ })+ return+ }+ const paragraph = paragraphOptions(slide, text, options.align)+ slide.addText(directionRuns(text, paragraph), { ...box, ...options, ...upright, ...paragraph })+}++/**+ * Paragraphs of a bulleted list; each carries its own language and direction.+ * A line break in an item is a soft break, so its lines stay under one bullet.+ */+function bulletRuns(slide: Slide, items: string[]): TextRun[] {+ // breakLine keeps one paragraph per item: pptxgenjs merges consecutive runs+ // into one paragraph whenever an alignment is set, as it is for RTL items.+ return items.flatMap(text => {+ const runs = text.split('\n').flatMap((line, i) => {+ const lineRuns = RTL_LETTER.test(text)+ ? directionRuns(line, paragraphOptions(slide, text))+ : [{ text: line, options: runOptions(slide, text) }]+ if (i > 0) lineRuns[0].options.softBreakBefore = true+ return lineRuns+ })+ runs[0].options.bullet = BULLET+ runs[runs.length - 1].options.breakLine = true+ return runs+ })+}++/**+ * A picture drawn to fill its space is shown at most this much larger than its+ * pixels at 96 dpi, or it blurs.+ */+const MAX_UPSCALE = 2+const PIXELS_PER_INCH = 96++/** Where a small picture is reported, and whether its field takes a width. */+interface PictureReport {+ where: string+ sized: boolean+ warnings: string[]+}++/**+ * Box for `image` inside `area`, at the image's own proportions. Without a+ * requested size it fills the area, up to MAX_UPSCALE times its own size.+ */+function placePicture(+ picture: { image: PptxPicture['image']; width?: number; height?: number },+ area: Box,+ align: 'center' | 'top-left' = 'center',+ report?: PictureReport+): Box {+ // fitImageSize rounds to whole units; thousandths of an inch keep the ratio exact enough.+ const unit = 1000+ const { width, height, image } = picture+ let requested: { width?: number; height?: number } = {+ width: area.w * unit,+ height: area.h * unit,+ }+ if (width || height) {+ requested = { width: width && width * unit, height: height && height * unit }+ } else {+ // Sharpness depends on the pixels stored, not on the density the file declares.+ const { pixels } = image+ const most = {+ w: (pixels.width / PIXELS_PER_INCH) * MAX_UPSCALE,+ h: (pixels.height / PIXELS_PER_INCH) * MAX_UPSCALE,+ }+ if (most.w < area.w && most.h < area.h) {+ requested = { width: most.w * unit, height: most.h * unit }+ report?.warnings.push(+ `${report.where}: the image is ${pixels.width}×${pixels.height} pixels, so it is shown at ` ++ `${most.w.toFixed(1)}×${most.h.toFixed(1)} in rather than blurred to fill its space. ` ++ `Send a larger image${report.sized ? ', or set width to enlarge it anyway' : ''}.`+ )+ }+ }+ const size = fitImageSize(+ { width: image.width, height: image.height },+ { width: area.w * unit, height: area.h * unit },+ requested+ )+ const w = size.width / unit+ const h = size.height / unit+ return align === 'top-left'+ ? { x: area.x, y: area.y, w, h }+ : { x: area.x + (area.w - w) / 2, y: area.y + (area.h - h) / 2, w, h }+}++function addPicture(slide: Slide, image: PptxPicture['image'], box: Box, altText = ''): void {+ slide.addImage({+ data: `image/${image.format};base64,${image.data.toString('base64')}`,+ ...box,+ altText,+ })+}++/** Fit `text` to `box` at one of `sizes`; if it cannot fit, shorten it at the smallest. */+function fitOrShorten(+ text: string,+ box: { w: number; h: number },+ sizes: number[],+ what: string,+ warnings: string[],+ style: { bold?: boolean } = {}+): { text: string; size: number; height: number } {+ const fit = fitText([text], box, sizes, style)+ if (fit.fits) return { text, size: fit.size, height: fit.height }+ const size = sizes[sizes.length - 1]+ const lines = Math.max(Math.floor((box.h - TEXT_INSET_Y) / lineHeightIn(size, text)), 1)+ const short = truncateToLines(text, size, box.w - TEXT_INSET_X, lines, style.bold)+ warnings.push(`${what} is too long for its space on the slide and was shortened.`)+ return {+ text: short,+ size,+ height: fitText([short], { w: box.w, h: Infinity }, [size], style).height,+ }+}++function drawTitle(slide: Slide, title: TitleBlock, ctx: DrawContext): void {+ const { frame, palette } = ctx+ addText(+ slide,+ title.text,+ { x: frame.marginX, y: frame.titleY, w: frame.width - frame.marginX * 2, h: title.h },+ { fontSize: title.size, bold: true, color: hex(palette.primary) }+ )+ slide.addShape(ctx.pptx.shapes?.RECTANGLE ?? 'rect', {+ x: frame.marginX,+ y: frame.titleY + title.h + 0.05,+ w: 1.0,+ h: 0.04,+ fill: { color: hex(palette.accent) },+ line: { color: hex(palette.accent) },+ })+}++function statusColor(status: PptxSlide['status'], palette: PptxPalette): string | undefined {+ if (status === 'green') return palette.statusGreen+ if (status === 'yellow') return palette.statusYellow+ if (status === 'red') return palette.statusRed+ return undefined+}++function drawCover(slide: Slide, spec: PptxSlide, ctx: DrawContext): void {+ const { frame, palette, warnings } = ctx+ const band = statusColor(spec.status, palette)+ if (band) {+ slide.addShape(ctx.pptx.shapes?.RECTANGLE ?? 'rect', {+ x: 0,+ y: 0,+ w: frame.width,+ h: 0.18,+ fill: { color: hex(band) },+ line: { color: hex(band) },+ })+ }+ if (ctx.logo) {+ addPicture(+ slide,+ ctx.logo.image,+ placePicture(ctx.logo, { x: 0.5, y: 0.5, w: 1.5, h: 0.5 }, 'top-left')+ )+ }+ const w = frame.width - 1+ const bottom = frame.height - 0.8+ const titleSizes = frame.wide ? [44, 40, 36, 32, 28] : [36, 32, 28, 24]+ let titleFit = fitText([spec.title ?? ''], { w, h: Infinity }, titleSizes, {+ bold: true,+ maxLines: 3,+ })+ let title = spec.title ?? ''+ if (!titleFit.fits) {+ const size = titleSizes[titleSizes.length - 1]+ title = truncateToLines(title, size, w - TEXT_INSET_X, 4, true)+ if (title !== spec.title)+ warnings.push(`${fieldPath(spec, 'title')} is too long for the cover and was shortened.`)+ titleFit = fitText([title], { w, h: Infinity }, [size], { bold: true })+ }+ const subSizes = frame.wide ? [20, 18, 16, 14] : [16, 14, 12]+ let subtitle = spec.subtitle+ let subFit = subtitle+ ? fitText([subtitle], { w, h: Infinity }, subSizes, { maxLines: 3 })+ : undefined+ const stack = () => titleFit.height + (subFit ? 0.1 + subFit.height : 0)+ let top = frame.height * 0.35+ if (top + stack() > bottom) top = Math.max(1.15, bottom - stack())+ if (subtitle && subFit && top + stack() > bottom) {+ const room = bottom - top - titleFit.height - 0.1+ const fitted = fitOrShorten(+ subtitle,+ { w, h: room },+ subSizes,+ fieldPath(spec, 'subtitle'),+ warnings+ )+ subtitle = fitted.text+ subFit = { size: fitted.size, height: fitted.height, fits: true }+ }+ addText(+ slide,+ title,+ { x: 0.5, y: top, w, h: titleFit.height },+ { fontSize: titleFit.size, bold: true, color: hex(palette.primary) }+ )+ if (subtitle && subFit) {+ addText(+ slide,+ subtitle,+ { x: 0.5, y: top + titleFit.height + 0.1, w, h: subFit.height },+ { fontSize: subFit.size, italic: true, color: hex(palette.muted), valign: 'top' }+ )+ }+ const dateStr = new Date().toLocaleDateString('en-US', {+ year: 'numeric',+ month: 'long',+ day: 'numeric',+ })+ addText(+ slide,+ dateStr,+ { x: 0.5, y: frame.height - 0.7, w, h: 0.3 },+ { fontSize: 11, color: hex(palette.muted) }+ )+}++function drawSection(slide: Slide, spec: PptxSlide, ctx: DrawContext): void {+ const { frame, palette, warnings } = ctx+ slide.addShape(ctx.pptx.shapes?.RECTANGLE ?? 'rect', {+ x: 0,+ y: 0,+ w: frame.width,+ h: frame.height,+ fill: { color: hex(palette.surface) },+ line: { color: hex(palette.surface) },+ })+ const w = frame.width - 1+ const bottom = frame.footerY - 0.1+ // The letter spacing (in points a character) is not in the measurement, so it comes off the width.+ const spacing = spec.eyebrow && !ARABIC_SCRIPT.test(spec.eyebrow) ? 4 : 0+ const eyebrow = spec.eyebrow+ ? truncateToLines(+ spec.eyebrow.toUpperCase(),+ 14,+ w - TEXT_INSET_X - (Array.from(spec.eyebrow).length * spacing) / 72,+ 1,+ true+ )+ : undefined+ if (eyebrow && spec.eyebrow && eyebrow !== spec.eyebrow.toUpperCase()) {+ warnings.push(`${fieldPath(spec, 'eyebrow')} is too long for one line and was shortened.`)+ }+ const eyebrowH = eyebrow ? 0.45 : 0+ const titleSizes = frame.wide ? [48, 40, 36, 32] : [40, 36, 32, 28]+ let title = spec.title ?? ''+ let titleFit = fitText([title], { w, h: Infinity }, titleSizes, { bold: true, maxLines: 2 })+ if (!titleFit.fits) {+ const size = titleSizes[titleSizes.length - 1]+ title = truncateToLines(title, size, w - TEXT_INSET_X, 3, true)+ if (title !== spec.title)+ warnings.push(+ `${fieldPath(spec, 'title')} is too long for a section slide and was shortened.`+ )+ titleFit = fitText([title], { w, h: Infinity }, [size], { bold: true })+ }+ const subSizes = [18, 16, 14, 12]+ let subtitle = spec.subtitle+ let subFit = subtitle+ ? fitText([subtitle], { w, h: Infinity }, subSizes, { maxLines: 4 })+ : undefined+ const stack = () => eyebrowH + titleFit.height + (subFit ? 0.1 + subFit.height : 0)+ let top = frame.height * 0.38+ if (top + stack() > bottom) top = Math.max(0.4, bottom - stack())+ if (subtitle && subFit && top + stack() > bottom) {+ const room = bottom - top - eyebrowH - titleFit.height - 0.1+ const fitted = fitOrShorten(+ subtitle,+ { w, h: room },+ subSizes,+ fieldPath(spec, 'subtitle'),+ warnings+ )+ subtitle = fitted.text+ subFit = { size: fitted.size, height: fitted.height, fits: true }+ }+ if (eyebrow) {+ addText(+ slide,+ eyebrow,+ { x: 0.5, y: top, w, h: eyebrowH },+ { fontSize: 14, bold: true, color: hex(palette.accent), charSpacing: spacing }+ )+ }+ addText(+ slide,+ title,+ { x: 0.5, y: top + eyebrowH, w, h: titleFit.height },+ { fontSize: titleFit.size, bold: true, color: hex(palette.primary) }+ )+ if (subtitle && subFit) {+ addText(+ slide,+ subtitle,+ { x: 0.5, y: top + eyebrowH + titleFit.height + 0.1, w, h: subFit.height },+ { fontSize: subFit.size, italic: true, color: hex(palette.muted), valign: 'top' }+ )+ }+}++function drawBullets(slide: Slide, planned: PlannedSlide, ctx: DrawContext): void {+ const list = planned.bullets!+ slide.addText(bulletRuns(slide, list.items), {+ ...planned.body,+ fontSize: list.size,+ color: hex(ctx.palette.text),+ paraSpaceAfter: BULLET_SPACE_AFTER,+ valign: 'top',+ })+}++interface Caption {+ text: string+ size: number+ h: number+}++function captionFor(+ text: string | undefined,+ width: number,+ what: string,+ ctx: DrawContext+): Caption | undefined {+ if (!text) return undefined+ const sizes = [11, 10, 9]+ const fit = fitText([text], { w: width, h: Infinity }, sizes, { maxLines: 3 })+ if (fit.fits) return { text, size: fit.size, h: fit.height }+ const short = truncateToLines(text, 9, width - TEXT_INSET_X, 3)+ ctx.warnings.push(`${what} is longer than three lines under the picture and was shortened.`)+ return { text: short, size: 9, h: fitText([short], { w: width, h: Infinity }, [9]).height }+}++function drawCaption(+ slide: Slide,+ caption: Caption,+ x: number,+ y: number,+ w: number,+ ctx: DrawContext+): void {+ addText(+ slide,+ caption.text,+ { x, y, w, h: caption.h },+ {+ fontSize: caption.size,+ italic: true,+ color: hex(ctx.palette.muted),+ align: 'center',+ valign: 'top',+ }+ )+}++function sameText(a: string | undefined, b: string | undefined): boolean {+ return (a ?? '').trim().toLowerCase() === (b ?? '').trim().toLowerCase()+}++function drawChart(slide: Slide, planned: PlannedSlide, ctx: DrawContext): void {+ const { spec, body } = planned+ const chart = spec.chart!+ const caption = captionFor(chart.caption, body.w, `${fieldPath(spec, 'chart')}.caption`, ctx)+ const area = { ...body, h: body.h - (caption ? caption.h + 0.05 : 0) }+ let bottom = area.y + area.h+ if (chart.picture) {+ const box = placePicture({ image: chart.picture }, area, 'center', {+ where: `${fieldPath(spec, 'chart')}.path`,+ sized: false,+ warnings: ctx.warnings,+ })+ addPicture(slide, chart.picture, box, chart.caption ?? chart.title ?? '')+ bottom = box.y + box.h+ } else if (chart.native) {+ const p = ctx.palette+ const { type, data, options } = nativeChartArgs(+ chart.native,+ {+ // The slide already shows the title a template takes from the chart.+ title: chart.title && !sameText(chart.title, spec.title) ? chart.title : undefined,+ colors: [+ p.primary,+ p.accent,+ p.statusGreen,+ p.statusYellow,+ p.statusRed,+ p.muted,+ ...EXTRA_SERIES_COLORS,+ ].map(hex),+ textColor: hex(p.text),+ mutedColor: hex(p.muted),+ },+ ctx.pptx+ )+ slide.addChart(type, data, { ...area, ...options })+ }+ if (caption) drawCaption(slide, caption, body.x, bottom + 0.05, body.w, ctx)+}++function drawTable(slide: Slide, planned: PlannedSlide, ctx: DrawContext): void {+ const { layout, page } = planned.table!+ const { rows, rowHeights } = layout.pages[page]+ const p = ctx.palette+ const data = rows.map((row, r) =>+ row.map(text => ({+ text: RTL_LETTER.test(text)+ ? directionRuns(text, paragraphOptions(slide, text, 'left'))+ : text,+ options: {+ ...(r === 0+ ? { bold: true, color: 'FFFFFF', fill: { color: hex(p.primary) } }+ : {+ color: hex(p.text),+ fill: r % 2 === 0 ? { color: hex(p.surface) } : undefined,+ }),+ align: 'left',+ valign: 'top',+ ...runOptions(slide, text, 'left'),+ },+ }))+ )+ slide.addTable(data, {+ x: planned.body.x,+ y: planned.body.y,+ w: layout.columnWidths.reduce((a, b) => a + b, 0),+ colW: layout.columnWidths,+ rowH: rowHeights,+ fontSize: layout.fontSize,+ border: { type: 'solid', pt: 0.5, color: hex(p.border) },+ autoPage: false,+ })+}++/** Label and value sizes shared by every card on a slide, so no figure looks more important. */+interface CardType {+ labelSize: number+ /** Room above the value, the same on every card so the values line up. */+ labelHeight: number+ valueSize: number+}++const LABEL_SIZES = [11, 10, 9]+const LABEL_MAX_HEIGHT = 0.6++/** Width of the text in a card, inside its 0.2in padding. */+function cardTextWidth(cardW: number): number {+ return cardW - 0.4+}++function cardType(cards: PptxKpi[], cardW: number, columns: number, people: boolean): CardType {+ const w = cardTextWidth(cardW)+ const labels = people ? [] : cards.flatMap(c => (c.label ? [c.label] : []))+ const labelSize =+ LABEL_SIZES.find(size =>+ labels.every(l => fitText([l], { w, h: LABEL_MAX_HEIGHT }, [size], { bold: true }).fits)+ ) ?? LABEL_SIZES[LABEL_SIZES.length - 1]+ const labelHeight = Math.max(+ 0,+ ...labels.map(l =>+ Math.min(+ fitText([l], { w, h: Infinity }, [labelSize], { bold: true }).height,+ LABEL_MAX_HEIGHT+ )+ )+ )+ const valueSizes = people+ ? columns >= 3+ ? [20, 18, 16, 14, 12]+ : [24, 20, 18, 16, 14, 12]+ : columns >= 3+ ? [24, 22, 20, 18, 16, 14, 12]+ : [32, 28, 24, 20, 18, 16, 14, 12]+ // The largest size at which every value fits on one line; a value too long+ // even at the smallest wraps there.+ const inner = w - TEXT_INSET_X+ const valueSize =+ valueSizes.find(size => cards.every(c => textWidth(c.value, size, true) <= inner)) ??+ valueSizes[valueSizes.length - 1]+ return { labelSize, labelHeight, valueSize }+}++function drawCard(+ slide: Slide,+ card: PptxKpi,+ box: Box,+ type: CardType,+ people: boolean,+ ctx: DrawContext+): void {+ const p = ctx.palette+ slide.addShape(ctx.pptx.shapes?.ROUNDED_RECTANGLE ?? 'roundRect', {+ ...box,+ fill: { color: hex(p.surface) },+ line: { color: hex(p.border), width: 0.5 },+ rectRadius: 0.05,+ })+ const x = box.x + 0.2+ const w = cardTextWidth(box.w)+ const inner = w - TEXT_INSET_X+ let y = box.y + 0.15+ if (card.label && !people) {+ const label = fitOrShorten(+ card.label,+ { w, h: LABEL_MAX_HEIGHT },+ [type.labelSize],+ `${card.where}.label`,+ ctx.warnings,+ { bold: true }+ )+ addText(+ slide,+ label.text,+ { x, y, w, h: label.height },+ {+ fontSize: label.size,+ color: hex(p.muted),+ bold: true,+ }+ )+ }+ y += type.labelHeight+ let bottom = box.y + box.h - 0.1+ const glyph = card.deltaDirection === 'up' ? '▲ ' : card.deltaDirection === 'down' ? '▼ ' : '— '+ const delta = card.delta+ ? fitOrShorten(+ `${glyph}${card.delta}`,+ { w, h: 0.55 },+ [11, 10, 9],+ `${card.where}.delta`,+ ctx.warnings+ )+ : undefined+ if (delta) bottom -= delta.height+ const size = type.valueSize+ if (textWidth(card.value, size, true) <= inner) {+ const h = lineHeightIn(size, card.value) + TEXT_INSET_Y+ addText(+ slide,+ card.value,+ { x, y, w, h },+ {+ fontSize: size,+ bold: true,+ color: hex(p.primary),+ wrap: false,+ }+ )+ y += h+ } else {+ // A value that wraps keeps the size of the other cards' values and stops above the delta.+ const value = fitOrShorten(+ card.value,+ { w, h: bottom - y },+ [size],+ `${card.where}.value`,+ ctx.warnings,+ { bold: true }+ )+ addText(+ slide,+ value.text,+ { x, y, w, h: value.height },+ { fontSize: size, bold: true, color: hex(p.primary) }+ )+ y += value.height+ }+ if (delta) {+ const color =+ card.deltaDirection === 'up'+ ? p.statusGreen+ : card.deltaDirection === 'down'+ ? p.statusRed+ : p.muted+ addText(+ slide,+ delta.text,+ { x, y: bottom, w, h: delta.height },+ { fontSize: delta.size, color: hex(color) }+ )+ }+ if (card.note) {+ const room = bottom - y+ if (room > TEXT_INSET_Y + 0.1) {+ const note = fitOrShorten(+ card.note,+ { w, h: room },+ people ? [14, 12, 11, 10] : [12, 11, 10, 9],+ card.notePath ?? `${card.where}.note`,+ ctx.warnings+ )+ addText(+ slide,+ note.text,+ { x, y, w, h: note.height },+ {+ fontSize: note.size,+ color: hex(people ? p.muted : p.text),+ valign: 'top',+ }+ )+ } else {+ ctx.warnings.push(+ `${card.notePath ?? card.where}: the card has no room left for this text, which was left out.`+ )+ }+ }+}++function drawKpis(slide: Slide, planned: PlannedSlide, ctx: DrawContext): void {+ const cards = planned.kpis!+ const body = planned.body+ // One row up to four cards, then two rows with the longer one first:+ // five cards are three and two, not four and one.+ const rows = cards.length <= 4 ? 1 : 2+ const cols = Math.ceil(cards.length / rows)+ const gap = 0.2+ const people = planned.spec.kpiStyle === 'people'+ const cellW = Math.min((body.w - gap * (cols - 1)) / cols, MAX_CARD_WIDTH)+ const tallest = cards.some(c => c.note) && !people ? 3.2 : 2.0+ const cellH = Math.min((body.h - gap * (rows - 1)) / rows, tallest)+ const type = cardType(cards, cellW, cols, people)+ cards.forEach((card, i) => {+ const row = Math.floor(i / cols)+ const inRow = Math.min(cols, cards.length - row * cols)+ // Each row is centred, so a shorter last row sits under the middle of the first.+ const left = body.x + (body.w - (cellW * inRow + gap * (inRow - 1))) / 2+ const box = {+ x: left + (i % cols) * (cellW + gap),+ y: body.y + row * (cellH + gap),+ w: cellW,+ h: cellH,+ }+ drawCard(slide, card, box, type, people, ctx)+ })+}++function drawColumn(+ slide: Slide,+ col: PptxColumn,+ area: Box,+ where: string,+ ctx: DrawContext+): void {+ const color = hex(ctx.palette.text)+ const sizes = [14, 13, 12, 11]+ if (col.bullets) {+ const columnStyle = { paraSpaceAfter: 6, indent: BULLET_INDENT }+ const bullets = col.bullets+ const fitFirst = (count: number) => fitText(bullets.slice(0, count), area, sizes, columnStyle)+ let items = bullets+ let fit = fitFirst(items.length)+ if (!fit.fits && items.length > 1) {+ // Fewer bullets never need more room, so the most that fit is found by halving.+ let lo = 1+ let hi = items.length - 1+ while (lo < hi) {+ const mid = Math.ceil((lo + hi) / 2)+ if (fitFirst(mid).fits) lo = mid+ else hi = mid - 1+ }+ items = items.slice(0, lo)+ fit = fitFirst(lo)+ }+ if (!fit.fits) {+ const size = sizes[sizes.length - 1]+ const width = area.w - TEXT_INSET_X - BULLET_INDENT+ const lines = Math.max(+ Math.floor((area.h - TEXT_INSET_Y - 6 / 72) / lineHeightIn(size, items[0])),+ 1+ )+ items = [truncateToLines(items[0], size, width, lines)]+ fit = { size, height: area.h, fits: true }+ ctx.warnings.push(+ `${where}.bullets[0] is too long for the column and was shortened; shorten it, or ` ++ 'give it a title-bullets slide, which has the whole slide width.'+ )+ }+ const dropped = col.bullets.length - items.length+ if (dropped > 0) {+ ctx.warnings.push(+ `${where}.bullets: the last ${dropped} of ${col.bullets.length} bullets did not fit in ` ++ 'the column and were left out; move them to another slide, or use a title-bullets ' ++ 'slide, which continues on more slides.'+ )+ }+ slide.addText(bulletRuns(slide, items), {+ ...area,+ fontSize: fit.size,+ color,+ paraSpaceAfter: 6,+ valign: 'top',+ })+ } else if (col.text) {+ const text = fitOrShorten(col.text, area, sizes, `${where}.text`, ctx.warnings)+ addText(slide, text.text, area, {+ fontSize: text.size,+ color,+ paraSpaceAfter: 6,+ valign: 'top',+ })+ } else if (col.picture) {+ const caption = captionFor(col.picture.caption, area.w, `${where}.image.caption`, ctx)+ const box = placePicture(+ col.picture,+ { ...area, h: area.h - (caption ? caption.h + 0.05 : 0) },+ 'center',+ { where: `${where}.image`, sized: true, warnings: ctx.warnings }+ )+ addPicture(slide, col.picture.image, box, col.picture.caption ?? '')+ if (caption) drawCaption(slide, caption, area.x, box.y + box.h + 0.05, area.w, ctx)+ }+}++function drawTwoColumn(slide: Slide, planned: PlannedSlide, ctx: DrawContext): void {+ const { body, spec } = planned+ const gap = 0.4+ const colW = (body.w - gap) / 2+ drawColumn(slide, spec.columns!.left, { ...body, w: colW }, `${spec.where}.columns.left`, ctx)+ drawColumn(+ slide,+ spec.columns!.right,+ { ...body, x: body.x + colW + gap, w: colW },+ `${spec.where}.columns.right`,+ ctx+ )+}++function drawImage(slide: Slide, planned: PlannedSlide, ctx: DrawContext): void {+ const { body, spec } = planned+ const picture = spec.picture+ if (!picture) return+ const caption = captionFor(picture.caption, body.w, `${fieldPath(spec, 'image')}.caption`, ctx)+ const box = placePicture(+ picture,+ { ...body, h: body.h - (caption ? caption.h + 0.05 : 0) },+ 'center',+ { where: fieldPath(spec, 'image'), sized: true, warnings: ctx.warnings }+ )+ addPicture(slide, picture.image, box, picture.caption ?? '')+ if (caption) drawCaption(slide, caption, body.x, box.y + box.h + 0.05, body.w, ctx)+}++function drawQuote(slide: Slide, spec: PptxSlide, ctx: DrawContext): void {+ const { frame, palette } = ctx+ const quote = spec.quote!+ addText(+ slide,+ '“',+ { x: frame.marginX, y: frame.height * 0.18, w: 2, h: 2 },+ { fontSize: frame.wide ? 120 : 90, color: hex(palette.accent), bold: true }+ )+ const box = {+ x: frame.marginX + 1.0,+ y: frame.height * 0.32,+ w: frame.width - frame.marginX * 2 - 1.0,+ h: frame.height * 0.44,+ }+ const sizes = frame.wide ? [28, 24, 20, 18, 16] : [22, 20, 18, 16, 14]+ const text = fitOrShorten(+ quote.text,+ box,+ sizes,+ `${fieldPath(spec, 'quote')}.text`,+ ctx.warnings+ )+ addText(slide, text.text, box, {+ fontSize: text.size,+ italic: true,+ color: hex(palette.text),+ valign: 'top',+ })+ if (quote.attribution) {+ const full = `— ${quote.attribution}`+ const line = truncateToLines(full, 14, box.w - TEXT_INSET_X, 1, true)+ if (line !== full) {+ ctx.warnings.push(+ `${fieldPath(spec, 'quote')}.attribution is too long for one line and was shortened.`+ )+ }+ addText(+ slide,+ line,+ { x: box.x, y: frame.height * 0.78, w: box.w, h: 0.5 },+ { fontSize: 14, bold: true, color: hex(palette.muted) }+ )+ }+}++function drawFooter(+ slide: Slide,+ left: string | undefined,+ page: number,+ total: number,+ ctx: DrawContext+): void {+ const { frame, palette } = ctx+ const muted = hex(palette.muted)+ if (left) {+ addText(+ slide,+ left,+ { x: frame.marginX, y: frame.footerY, w: frame.width / 2, h: 0.3 },+ { fontSize: 9, color: muted, align: 'left' }+ )+ }+ slide.addText(`${page} / ${total}`, {+ x: frame.width - frame.marginX - 1.0,+ y: frame.footerY,+ w: 1.0,+ h: 0.3,+ fontSize: 9,+ color: muted,+ align: 'right',+ })+}++function drawSlide(slide: Slide, planned: PlannedSlide, ctx: DrawContext): void {+ const { spec } = planned+ if (planned.title) drawTitle(slide, planned.title, ctx)+ switch (spec.layout) {+ case 'cover':+ return drawCover(slide, spec, ctx)+ case 'section':+ return drawSection(slide, spec, ctx)+ case 'title-bullets':+ return drawBullets(slide, planned, ctx)+ case 'title-chart':+ return drawChart(slide, planned, ctx)+ case 'title-table':+ return drawTable(slide, planned, ctx)+ case 'kpis':+ return drawKpis(slide, planned, ctx)+ case 'two-column':+ return drawTwoColumn(slide, planned, ctx)+ case 'image':+ return drawImage(slide, planned, ctx)+ case 'quote':+ return drawQuote(slide, spec, ctx)+ }+}++function pick<T>(+ table: Record<string, T>,+ value: unknown,+ fallback: string,+ field: string,+ warnings: string[]+): T {+ if (value === undefined || value === null || value === '') return table[fallback]+ if (typeof value === 'string' && table[value]) return table[value]+ warnings.push(+ `${field} ${JSON.stringify(value)} is not one of ${Object.keys(table).join(', ')}; ` ++ `"${fallback}" was used.`+ )+ return table[fallback]+}++/** The slides `args` describe, from a template's data or from slides[]. */+function readDeck(args: Record<string, unknown>, ctx: ReadContext): PptxSlide[] {+ const template = args.template ?? 'custom'+ if (template === 'custom') {+ if (args.slides === undefined && args.data !== undefined) {+ throw new PptxInputError(+ `data is only read with a template: set template to one of ${PPTX_TEMPLATES.join(', ')}, ` ++ 'or send the slides in slides[].'+ )+ }+ if (args.data !== undefined) {+ ctx.warnings.push(+ `data was ignored: it is only read when template is one of ${PPTX_TEMPLATES.join(', ')}.`+ )+ }+ return readSlides(args.slides, ctx)+ }+ if (!(PPTX_TEMPLATES as readonly unknown[]).includes(template)) {+ throw new PptxInputError(+ `template ${JSON.stringify(template)} is not a template. Use one of ` ++ `${PPTX_TEMPLATES.join(', ')} with data, or custom with slides[].`+ )+ }+ const slides = buildTemplateSlides(template as PptxTemplate, args.data, ctx)+ if (args.slides !== undefined) {+ ctx.warnings.push(+ `slides was left out: template "${String(template)}" builds the slides from data. Leave ` ++ 'template out to send your own slides.'+ )+ }+ return slides+}++/**+ * Build the deck `args` describe. Returns the file contents and the number of+ * slides; anything repaired or left out is added to `warnings`. Throws+ * PptxInputError, naming the field, for arguments no deck can be built from.+ */+export async function buildPptxDeck(+ args: Record<string, unknown>,+ outputDir: string,+ warnings: string[]+): Promise<{ buffer: Buffer; slides: number }> {+ const ctx: ReadContext = { outputDir, warnings }+ const specs = readDeck(args, ctx)+ const palette = pick(PPTX_PALETTES, args.palette, 'default', 'palette', warnings)+ const aspect = pick(PPTX_ASPECT_RATIOS, args.aspectRatio, 'wide', 'aspectRatio', warnings)+ if (args.branding !== undefined && args.branding !== null && !isRecord(args.branding)) {+ throw new PptxInputError(+ 'branding must be an object with companyName, logoPath and footerText.'+ )+ }+ const branding = isRecord(args.branding) ? args.branding : {}+ const companyName = readText(branding.companyName, 'branding.companyName', 200, ctx)+ const footerText = readText(branding.footerText, 'branding.footerText', 200, ctx)+ const logo =+ branding.logoPath !== undefined && branding.logoPath !== null && branding.logoPath !== ''+ ? readPicture(branding.logoPath, 'branding.logoPath', ctx)+ : undefined++ const pptx = new PptxGenJS()+ pptx.layout = aspect.name+ // The family is set on the theme, never on a run: pptxgenjs writes a run's+ // face as its East Asian face too, and Arial has no CJK, so PowerPoint would+ // pick CJK glyphs one by one from fallback fonts. Left to the theme, it uses+ // the face for each run's language tag instead.+ pptx.theme = { headFontFace: PPTX_FONT_FACE, bodyFontFace: PPTX_FONT_FACE }+ // Always assign every metadata field (even when empty). pptxgenjs otherwise+ // fills `dc:subject` / `dc:creator` with its own default strings, which would+ // surface as an unintentional brand mark in the deliverable.+ pptx.title = readText(args.title, 'title', 200, ctx) ?? ''+ pptx.subject = readText(args.subject, 'subject', 200, ctx) ?? ''+ pptx.author = readText(args.author, 'author', 200, ctx) ?? ''+ // pptxgenjs writes the company into docProps/app.xml without escaping it,+ // where an unescaped "&" or "<" makes the whole file unreadable.+ pptx.company = (companyName ?? '').replace(+ /[&<>"']/g,+ ch => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[ch]!+ )++ const frame = frameFor(aspect.width, aspect.height)+ const planned = specs.flatMap(spec => planSlide(spec, frame, warnings))+ const drawCtx: DrawContext = { frame, palette, pptx, warnings, logo }++ let footer = [companyName, footerText].filter(Boolean).join(' · ') || undefined+ if (footer && wrapLines(footer, 9, frame.width / 2 - TEXT_INSET_X).length > 1) {+ footer = truncateToLines(footer, 9, frame.width / 2 - TEXT_INSET_X, 1)+ warnings.push(+ 'branding: the company name and footer text are too long for one footer line and were shortened.'+ )+ }++ const han = documentEastAsianScript(deckText(specs))?.lang+ planned.forEach((plan, i) => {+ const slide = pptx.addSlide()+ if (han) hanLanguage.set(slide, han)+ slide.background = { color: hex(palette.background) }+ drawSlide(slide, plan, drawCtx)+ if (plan.spec.notes && planned[i - 1]?.spec !== plan.spec) slide.addNotes(plan.spec.notes)+ // The cover carries its own date instead of the footer.+ if (plan.spec.layout !== 'cover') drawFooter(slide, footer, i + 1, planned.length, drawCtx)+ })++ // A title shortened on a slide split into parts is reported once, not per part.+ const unique = [...new Set(warnings)]+ warnings.splice(0, warnings.length, ...unique)++ const buffer = (await pptx.write({ outputType: 'nodebuffer' })) as Buffer+ return { buffer: await withOnePropertiesPerParagraph(buffer), slides: planned.length }+}++const SLIDE_PART = /^ppt\/slides\/slide\d+\.xml$/+const PARAGRAPH = /<a:p>([\s\S]*?)<\/a:p>/g+const PARAGRAPH_PROPERTIES = /<a:pPr\b[^>]*?(?:\/>|>[\s\S]*?<\/a:pPr>)/g++/**+ * pptxgenjs writes paragraph properties before every run of a paragraph, where+ * a paragraph may have them once, before its first run. The first set is the+ * paragraph's own (its bullet, alignment and direction), so the rest go.+ */+async function withOnePropertiesPerParagraph(buffer: Buffer): Promise<Buffer> {+ const zip = await JSZip.loadAsync(buffer)+ let changed = false+ for (const name of Object.keys(zip.files).filter(n => SLIDE_PART.test(n))) {+ const xml = await zip.file(name)!.async('string')+ const fixed = xml.replace(PARAGRAPH, (_p, inner: string) => {+ let seen = false+ const once = inner.replace(PARAGRAPH_PROPERTIES, props =>+ seen ? '' : ((seen = true), props)+ )+ return `<a:p>${once}</a:p>`+ })+ if (fixed !== xml) {+ zip.file(name, fixed)+ changed = true+ }+ }+ // Stored, as pptxgenjs writes the package, so the pictures are not compressed again.+ return changed ? zip.generateAsync({ type: 'nodebuffer', compression: 'STORE' }) : buffer+}diff --git a/mcp-host/src/workflow/pptxInput.ts b/mcp-host/src/workflow/pptxInput.tsnew file mode 100644index 000000000..8affa9f3f--- /dev/null+++ b/mcp-host/src/workflow/pptxInput.ts@@ -0,0 +1,529 @@+/**+ * Reading clerum__generate_pptx arguments into slide specs.+ *+ * Everything the renderer draws passes through here first, so a malformed+ * argument becomes a message naming the field and the fix rather than a+ * JavaScript TypeError, a slide with an error printed on it, or an empty slide+ * reported as success. Repairs that keep the content (rows sent as records,+ * text over its length limit) are made here and reported as warnings.+ */+import { type EmbeddableImage, loadEmbeddableImage } from './embeddedImages'+import { ChartSpecError, type NativeChart, readNativeChart } from './pptxCharts'+import { headerText, normalizeTableRows } from './tableRows'++/** An argument the deck cannot be built from; the message names the field. */+export class PptxInputError extends Error {}++export const SLIDE_LAYOUTS = [+ 'cover',+ 'section',+ 'title-bullets',+ 'title-chart',+ 'title-table',+ 'kpis',+ 'two-column',+ 'image',+ 'quote',+] as const++export type SlideLayout = (typeof SLIDE_LAYOUTS)[number]++export const STATUSES = ['green', 'yellow', 'red'] as const+export type Status = (typeof STATUSES)[number]++const DELTA_DIRECTIONS = ['up', 'down', 'neutral'] as const++/** Longest text each field keeps, so a runaway model cannot bloat the archive. */+export const TEXT_LIMITS = {+ title: 200,+ eyebrow: 100,+ subtitle: 400,+ bullet: 1000,+ header: 200,+ cell: 500,+ label: 120,+ value: 80,+ delta: 80,+ note: 1000,+ caption: 400,+ quote: 2000,+ attribution: 200,+ narrative: 4000,+ notes: 8000,+}++export interface PptxKpi {+ /** Argument path of the card, for messages. */+ where: string+ /** Argument path of `note`, when it is not `${where}.note`. */+ notePath?: string+ label?: string+ value: string+ delta?: string+ deltaDirection?: (typeof DELTA_DIRECTIONS)[number]+ /** A longer explanation under the value. */+ note?: string+}++export interface PptxTable {+ headers: string[]+ rows: string[][]+}++export interface PptxPicture {+ image: EmbeddableImage+ caption?: string+ /** Requested size in inches; the other side follows the image's proportions. */+ width?: number+ height?: number+}++export interface PptxChart {+ title?: string+ caption?: string+ picture?: EmbeddableImage+ native?: NativeChart+}++export interface PptxColumn {+ bullets?: string[]+ text?: string+ picture?: PptxPicture+}++export interface PptxSlide {+ layout: SlideLayout+ /** Where the slide came from, as the model wrote it: "slides[2]", or "data" for a template. */+ where: string+ title?: string+ eyebrow?: string+ subtitle?: string+ status?: Status+ bullets?: string[]+ table?: PptxTable+ kpis?: PptxKpi[]+ /** People cards: the name large, the role under it. */+ kpiStyle?: 'people'+ chart?: PptxChart+ picture?: PptxPicture+ quote?: { text: string; attribution?: string }+ columns?: { left: PptxColumn; right: PptxColumn }+ notes?: string+ /** Argument paths of fields that did not come from `${where}.<field>`, for messages. */+ paths?: Record<string, string>+}++/** Argument path of one of a slide's fields, as messages name it. */+export function fieldPath(slide: PptxSlide, field: string): string {+ return slide.paths?.[field] ?? `${slide.where}.${field}`+}++export interface ReadContext {+ outputDir: string+ warnings: string[]+}++export function isRecord(value: unknown): value is Record<string, unknown> {+ return value !== null && typeof value === 'object' && !Array.isArray(value)+}++function describe(value: unknown): string {+ if (value === null) return 'null'+ if (Array.isArray(value)) return 'a list'+ return typeof value === 'object' ? 'an object' : `a ${typeof value}`+}++/** `text` shortened to `max` characters at a word, ending in an ellipsis. */+export function shorten(text: string, max: number): string {+ const chars = Array.from(text)+ if (chars.length <= max) return text+ let kept = chars.slice(0, max - 1).join('')+ const space = kept.lastIndexOf(' ')+ if (space > kept.length * 0.8) kept = kept.slice(0, space)+ return `${kept.trimEnd()}…`+}++/** Optional text. Numbers and booleans are written as they print. */+export function readText(+ value: unknown,+ where: string,+ max: number,+ ctx: ReadContext+): string | undefined {+ if (value === undefined || value === null) return undefined+ const raw = typeof value === 'number' || typeof value === 'boolean' ? String(value) : value+ if (typeof raw !== 'string') {+ throw new PptxInputError(`${where} must be text; received ${describe(value)}.`)+ }+ const text = raw.trim()+ if (!text) return undefined+ if (Array.from(text).length > max) {+ ctx.warnings.push(`${where} is longer than ${max} characters and was shortened.`)+ return shorten(text, max)+ }+ return text+}++/** A Markdown list marker, which the slide's own bullet would print twice. */+const LIST_MARKER = /^[-*+•]\s+/++/** A list of text items. One string is read as one item per line. */+export function readStringList(+ value: unknown,+ where: string,+ max: number,+ ctx: ReadContext+): string[] | undefined {+ if (value === undefined || value === null) return undefined+ let items: Array<string | undefined>+ if (typeof value === 'string') {+ items = value.split('\n').map((line, i) => readText(line, `${where} line ${i + 1}`, max, ctx))+ } else if (Array.isArray(value)) {+ items = value.map((item, i) => readText(item, `${where}[${i}]`, max, ctx))+ } else {+ throw new PptxInputError(`${where} must be a list of text items; received ${describe(value)}.`)+ }+ return items.map(item => item?.replace(LIST_MARKER, '')).filter((item): item is string => !!item)+}++export function readEnum<T extends string>(+ value: unknown,+ where: string,+ allowed: readonly T[]+): T | undefined {+ if (value === undefined || value === null || value === '') return undefined+ if (!(allowed as readonly unknown[]).includes(value)) {+ throw new PptxInputError(+ `${where} must be one of ${allowed.join(', ')}; received ${JSON.stringify(value)}.`+ )+ }+ return value as T+}++function requireList(value: unknown, where: string): unknown[] {+ if (!Array.isArray(value)) {+ throw new PptxInputError(`${where} must be a list; received ${describe(value)}.`)+ }+ return value+}++export function readKpis(value: unknown, where: string, ctx: ReadContext): PptxKpi[] {+ return requireList(value, where).map((item, i) => {+ const at = `${where}[${i}]`+ if (!isRecord(item)) {+ throw new PptxInputError(+ `${at} must be an object such as {"label": "Revenue", "value": "$1.2M"}; received ${describe(item)}.`+ )+ }+ const value = readText(item.value, `${at}.value`, TEXT_LIMITS.value, ctx)+ if (value === undefined) {+ throw new PptxInputError(+ `${at}.value is missing: give the figure to show, e.g. "$1.2M" or 48.`+ )+ }+ const kpi: PptxKpi = { where: at, value }+ kpi.label = readText(item.label, `${at}.label`, TEXT_LIMITS.label, ctx)+ kpi.delta = readText(item.delta, `${at}.delta`, TEXT_LIMITS.delta, ctx)+ kpi.deltaDirection = readEnum(item.deltaDirection, `${at}.deltaDirection`, DELTA_DIRECTIONS)+ return kpi+ })+}++function cellText(value: unknown, where: string, ctx: ReadContext): string {+ if (value === undefined || value === null) return ''+ if (typeof value === 'object') {+ throw new PptxInputError(`${where} is ${describe(value)}; a cell holds text or a number.`)+ }+ return readText(value, where, TEXT_LIMITS.cell, ctx) ?? ''+}++export function readTable(value: unknown, where: string, ctx: ReadContext): PptxTable {+ if (!isRecord(value)) {+ throw new PptxInputError(+ `${where} must be an object with headers and rows; received ${describe(value)}.`+ )+ }+ if (!Array.isArray(value.headers) || value.headers.length === 0) {+ throw new PptxInputError(`${where}.headers must list the column headings, left to right.`)+ }+ const headers = value.headers.map(+ (h, i) => readText(headerText(h), `${where}.headers[${i}]`, TEXT_LIMITS.header, ctx) ?? ''+ )+ if (value.rows !== undefined && !Array.isArray(value.rows)) {+ throw new PptxInputError(+ `${where}.rows must be a list of rows, each a list of cells in header order.`+ )+ }+ const rows = normalizeTableRows(value.rows, value.headers, where, ctx.warnings)+ let cut = 0+ const cells = rows.map((row, r) => {+ if (row.length > headers.length) cut+++ return headers.map((_, c) => cellText(row[c], `${where}.rows[${r}][${c}]`, ctx))+ })+ if (cut > 0) {+ ctx.warnings.push(+ `${where}: ${cut} row(s) had more cells than the ${headers.length} headers; the extra cells were left out.`+ )+ }+ if (cells.length === 0) {+ ctx.warnings.push(+ `${where} has no rows, so the table shows only its headings; add rows, or leave the ` ++ 'slide out.'+ )+ }+ return { headers, rows: cells }+}++/**+ * Load an image argument. A missing or unreadable file is a warning and+ * returns undefined; a path escaping the output folder fails the call, as it+ * does in every generator.+ */+export function readPicture(+ value: unknown,+ where: string,+ ctx: ReadContext+): PptxPicture | undefined {+ if (value !== undefined && typeof value !== 'string' && !isRecord(value)) {+ throw new PptxInputError(+ `${where} must be a file name such as 'sales.png' or {"path": "sales.png"}; received ${describe(value)}.`+ )+ }+ const pathField = typeof value === 'string' ? where : `${where}.path`+ const local: string[] = []+ let image: EmbeddableImage | undefined+ try {+ image = loadEmbeddableImage(value, ctx.outputDir, local, pathField)+ } catch (err) {+ const message = err instanceof Error ? err.message : String(err)+ throw new PptxInputError(+ `${pathField}: ${message}. Pass the file name in the output folder, as ` ++ "clerum__generate_chart returns it (e.g. 'sales.png')."+ )+ }+ for (const w of local) ctx.warnings.push(w.startsWith(pathField) ? w : `${pathField}: ${w}`)+ if (!image) {+ if (isRecord(value) && typeof value.caption === 'string' && value.caption.trim()) {+ ctx.warnings.push(`${where}.caption was left out with the image it describes.`)+ }+ return undefined+ }+ const picture: PptxPicture = { image }+ if (isRecord(value)) {+ picture.caption = readText(value.caption, `${where}.caption`, TEXT_LIMITS.caption, ctx)+ for (const side of ['width', 'height'] as const) {+ const n = value[side]+ if (n === undefined || n === null) continue+ if (typeof n !== 'number' || !Number.isFinite(n) || n <= 0) {+ throw new PptxInputError(`${where}.${side} must be a positive number of inches.`)+ }+ picture[side] = n+ }+ }+ return picture+}++export function readChart(value: unknown, where: string, ctx: ReadContext): PptxChart {+ if (!isRecord(value)) {+ throw new PptxInputError(+ `${where} must be an object: {"path": "sales.png"} for a chart image from ` ++ 'clerum__generate_chart, or {"type", "labels", "datasets"} for a native chart.'+ )+ }+ const chart: PptxChart = {+ title: readText(value.title, `${where}.title`, TEXT_LIMITS.title, ctx),+ caption: readText(value.caption, `${where}.caption`, TEXT_LIMITS.caption, ctx),+ }+ try {+ chart.native = readNativeChart(value, where, ctx.warnings)+ } catch (err) {+ if (err instanceof ChartSpecError) throw new PptxInputError(err.message)+ throw err+ }+ if (value.path !== undefined && value.path !== null && value.path !== '') {+ chart.picture = readPicture(value.path, `${where}.path`, ctx)?.image+ if (chart.picture) chart.native = undefined+ else if (chart.native) {+ ctx.warnings.push(+ `${where}: the image could not be used, so the chart was drawn from its data.`+ )+ }+ } else if (!chart.native) {+ throw new PptxInputError(+ `${where} has nothing to draw: pass path with the file name clerum__generate_chart ` ++ 'returned, or type, labels and datasets for a native chart.'+ )+ }+ return chart+}++function readColumn(value: unknown, where: string, ctx: ReadContext): PptxColumn {+ if (!isRecord(value)) {+ throw new PptxInputError(+ `${where} must be an object such as {"type": "bullets", "bullets": ["..."]}.`+ )+ }+ const type =+ value.type ??+ (value.bullets !== undefined ? 'bullets' : value.image !== undefined ? 'image' : 'narrative')+ if (type === 'bullets') {+ const bullets = readStringList(value.bullets, `${where}.bullets`, TEXT_LIMITS.bullet, ctx)+ if (!bullets?.length) throw new PptxInputError(`${where}.bullets needs at least one bullet.`)+ return { bullets }+ }+ if (type === 'narrative') {+ const text = readText(value.text, `${where}.text`, TEXT_LIMITS.narrative, ctx)+ if (!text) throw new PptxInputError(`${where}.text is missing for a narrative column.`)+ return { text }+ }+ if (type === 'image') {+ if (value.image === undefined) {+ throw new PptxInputError(`${where}.image is missing for an image column.`)+ }+ return { picture: readPicture(value.image, `${where}.image`, ctx) }+ }+ throw new PptxInputError(+ `${where}.type must be one of bullets, narrative, image; received ${JSON.stringify(type)}.`+ )+}++/** What each layout draws. Anything else on the slide is reported as left out. */+const LAYOUT_FIELDS: Record<SlideLayout, string[]> = {+ cover: ['title', 'subtitle', 'status'],+ section: ['title', 'eyebrow', 'subtitle'],+ 'title-bullets': ['title', 'bullets'],+ 'title-chart': ['title', 'chart'],+ 'title-table': ['title', 'table'],+ kpis: ['title', 'kpis'],+ 'two-column': ['title', 'columns'],+ image: ['title', 'image'],+ quote: ['quote'],+}++/** The layout for the content a slide carries, to suggest when it names another. */+const CONTENT_LAYOUT: Record<string, SlideLayout> = {+ bullets: 'title-bullets',+ chart: 'title-chart',+ table: 'title-table',+ kpis: 'kpis',+ columns: 'two-column',+ image: 'image',+ quote: 'quote',+}++function missing(where: string, layout: SlideLayout, field: string, shape: string): never {+ throw new PptxInputError(+ `${where} uses layout "${layout}" but has no ${field}; add ${field}: ${shape}, or pick the ` ++ 'layout that matches what the slide carries.'+ )+}++function readSlide(raw: unknown, index: number, ctx: ReadContext): PptxSlide {+ const where = `slides[${index}]`+ if (!isRecord(raw)) {+ throw new PptxInputError(`${where} must be an object with a layout; received ${describe(raw)}.`)+ }+ if (!(SLIDE_LAYOUTS as readonly unknown[]).includes(raw.layout)) {+ const hint = Object.keys(CONTENT_LAYOUT).find(k => raw[k] !== undefined)+ throw new PptxInputError(+ `${where}.layout ${JSON.stringify(raw.layout)} is not a layout. Use one of ` ++ `${SLIDE_LAYOUTS.join(', ')}` ++ (hint ? `; a slide with ${hint} uses "${CONTENT_LAYOUT[hint]}".` : '.')+ )+ }+ const layout = raw.layout as SlideLayout+ const slide: PptxSlide = {+ layout,+ where,+ title: readText(raw.title, `${where}.title`, TEXT_LIMITS.title, ctx),+ notes: readText(raw.notes, `${where}.notes`, TEXT_LIMITS.notes, ctx),+ }+ const used = LAYOUT_FIELDS[layout]+ if (used.includes('eyebrow')) {+ slide.eyebrow = readText(raw.eyebrow, `${where}.eyebrow`, TEXT_LIMITS.eyebrow, ctx)+ }+ if (used.includes('subtitle')) {+ slide.subtitle = readText(raw.subtitle, `${where}.subtitle`, TEXT_LIMITS.subtitle, ctx)+ }+ if (used.includes('status')) slide.status = readEnum(raw.status, `${where}.status`, STATUSES)++ switch (layout) {+ case 'cover':+ case 'section':+ if (!slide.title) missing(where, layout, 'title', '"..."')+ break+ case 'title-bullets':+ slide.bullets = readStringList(raw.bullets, `${where}.bullets`, TEXT_LIMITS.bullet, ctx)+ if (!slide.bullets?.length) missing(where, layout, 'bullets', '["...", "..."]')+ break+ case 'title-chart':+ if (raw.chart === undefined) missing(where, layout, 'chart', '{"path": "sales.png"}')+ slide.chart = readChart(raw.chart, `${where}.chart`, ctx)+ break+ case 'title-table':+ if (raw.table === undefined)+ missing(where, layout, 'table', '{"headers": [...], "rows": [[...]]}')+ slide.table = readTable(raw.table, `${where}.table`, ctx)+ break+ case 'kpis':+ if (raw.kpis === undefined)+ missing(where, layout, 'kpis', '[{"label": "...", "value": "..."}]')+ slide.kpis = readKpis(raw.kpis, `${where}.kpis`, ctx)+ if (slide.kpis.length === 0)+ missing(where, layout, 'kpis', '[{"label": "...", "value": "..."}]')+ break+ case 'two-column': {+ const cols = raw.columns+ if (!isRecord(cols) || cols.left === undefined || cols.right === undefined) {+ missing(where, layout, 'columns', '{"left": {...}, "right": {...}}')+ }+ slide.columns = {+ left: readColumn(cols.left, `${where}.columns.left`, ctx),+ right: readColumn(cols.right, `${where}.columns.right`, ctx),+ }+ break+ }+ case 'image':+ if (raw.image === undefined) missing(where, layout, 'image', '{"path": "photo.png"}')+ slide.picture = readPicture(raw.image, `${where}.image`, ctx)+ break+ case 'quote': {+ const q = typeof raw.quote === 'string' ? { text: raw.quote } : raw.quote+ const text = isRecord(q)+ ? readText(q.text, `${where}.quote.text`, TEXT_LIMITS.quote, ctx)+ : undefined+ if (!isRecord(q) || !text) missing(where, layout, 'quote', '{"text": "..."}')+ slide.quote = {+ text,+ attribution: readText(+ q.attribution,+ `${where}.quote.attribution`,+ TEXT_LIMITS.attribution,+ ctx+ ),+ }+ break+ }+ }++ const ignored = ['title', 'eyebrow', 'subtitle', 'status', ...Object.keys(CONTENT_LAYOUT)].filter(+ k => !used.includes(k) && raw[k] !== undefined && raw[k] !== null && raw[k] !== ''+ )+ if (ignored.length > 0) {+ ctx.warnings.push(+ `${where}: ${ignored.join(', ')} ${ignored.length > 1 ? 'are' : 'is'} not shown on a "${layout}" ` ++ 'slide and was left out; put it on a slide whose layout draws it.'+ )+ }+ return slide+}++export function readSlides(value: unknown, ctx: ReadContext): PptxSlide[] {+ if (!Array.isArray(value) || value.length === 0) {+ throw new PptxInputError(+ 'slides must be a non-empty list of slides, each with a layout, or pass template and data ' ++ 'to have the slides built for you.'+ )+ }+ return value.map((raw, i) => readSlide(raw, i, ctx))+}diff --git a/mcp-host/src/workflow/pptxTables.ts b/mcp-host/src/workflow/pptxTables.tsnew file mode 100644index 000000000..6669cdf57--- /dev/null+++ b/mcp-host/src/workflow/pptxTables.ts@@ -0,0 +1,154 @@+/**+ * Table layout for clerum__generate_pptx.+ *+ * A PowerPoint table grows downward past the slide instead of continuing on+ * another one, and pptxgenjs's own paging does not know how tall wrapped rows+ * are. Rows are measured here and split across slides that repeat the header,+ * with column widths following the content instead of an even split.+ */+import type { PptxTable } from './pptxInput'+import { lineHeightIn, textWidth, truncateToLines, wrapLines } from './pptxText'++/** pptxgenjs's default cell margins, top+bottom and left+right, in inches. */+const CELL_PAD_Y = 0.1+const CELL_PAD_X = 0.2++const EMU = 914400++/** A column never gets narrower than this, even when others need the room. */+const MIN_COLUMN = 0.6++export interface TablePage {+ rows: string[][]+ /** Row heights in inches, header first. */+ rowHeights: number[]+}++export interface TableLayout {+ fontSize: number+ columnWidths: number[]+ pages: TablePage[]+}++/** Body text size for a table of `columns` columns on a slide of this width class. */+export function tableFontSize(columns: number, wide: boolean): number {+ const base = wide ? 12 : 10+ return Math.max(base - (columns >= 7 ? 2 : columns >= 5 ? 1 : 0), 8)+}++/**+ * Widths proportional to how much text each column holds. A column's single+ * longest word sets its floor, so words break inside a cell only when the+ * table cannot be made to fit otherwise.+ */+function columnWidths(table: PptxTable, width: number, size: number): number[] {+ const n = table.headers.length+ const natural: number[] = []+ const floor: number[] = []+ for (let c = 0; c < n; c++) {+ const cells = [table.headers[c], ...table.rows.map(r => r[c])]+ let longestLine = 0+ let longestWord = 0+ cells.forEach((cell, i) => {+ const bold = i === 0+ longestLine = Math.max(longestLine, textWidth(cell, size, bold))+ for (const word of cell.split(/\s+/)) {+ longestWord = Math.max(longestWord, textWidth(word, size, bold))+ }+ })+ natural.push(Math.min(longestLine, width * 0.6) + CELL_PAD_X)+ floor.push(Math.max(Math.min(longestWord, width * 0.3) + CELL_PAD_X, MIN_COLUMN))+ }+ const naturalSum = natural.reduce((a, b) => a + b, 0)+ if (naturalSum <= width) return natural.map(w => (w * width) / naturalSum)+ const floorSum = floor.reduce((a, b) => a + b, 0)+ if (floorSum >= width) return floor.map(w => (w * width) / floorSum)+ const slack = natural.map((w, c) => Math.max(w - floor[c], 0))+ const slackSum = slack.reduce((a, b) => a + b, 0)+ return floor.map((w, c) => w + (slack[c] * (width - floorSum)) / (slackSum || 1))+}++function rowHeight(cells: string[], widths: number[], size: number, bold: boolean): number {+ let tallest = 0+ cells.forEach((cell, c) => {+ const lines = wrapLines(cell, size, widths[c] - CELL_PAD_X, bold).length+ tallest = Math.max(tallest, lines * lineHeightIn(size, cell))+ })+ return tallest + CELL_PAD_Y+}++/** Rounded up to the EMU, so the height written is never below the height measured. */+function ceilEmu(inches: number): number {+ return Math.ceil(inches * EMU) / EMU+}++/**+ * Lay `table` out in a box `box.w` wide, splitting its rows over as many+ * pages of height `box.h` as it needs. A row taller than a page on its own is+ * cut to fit and reported in `warnings`.+ */+export function layoutTable(+ table: PptxTable,+ box: { w: number; h: number },+ wide: boolean,+ where: string,+ warnings: string[]+): TableLayout {+ const fontSize = tableFontSize(table.headers.length, wide)+ // Measured at the width that will be written, so rounding to EMU cannot add a line.+ const widths = columnWidths(table, box.w, fontSize).map(w => Math.floor(w * EMU) / EMU)+ const headerHeight = ceilEmu(rowHeight(table.headers, widths, fontSize, true))+ const room = box.h - headerHeight+ let cut = 0+ const rows = table.rows.map(original => {+ let row = original+ let height = rowHeight(row, widths, fontSize, false)+ if (height > room) {+ cut+++ row = row.map((cell, c) => {+ const maxLines = Math.max(Math.floor((room - CELL_PAD_Y) / lineHeightIn(fontSize, cell)), 1)+ return truncateToLines(cell, fontSize, widths[c] - CELL_PAD_X, maxLines)+ })+ height = rowHeight(row, widths, fontSize, false)+ }+ return { cells: row, height: ceilEmu(height) }+ })+ const paginate = (maxRows: number): TablePage[] => {+ const out: TablePage[] = []+ let current: TablePage = { rows: [table.headers], rowHeights: [headerHeight] }+ let used = 0+ for (const row of rows) {+ const full = used + row.height > room + 1e-9 || current.rows.length - 1 >= maxRows+ if (full && current.rows.length > 1) {+ out.push(current)+ current = { rows: [table.headers], rowHeights: [headerHeight] }+ used = 0+ }+ current.rows.push(row.cells)+ current.rowHeights.push(row.height)+ used += row.height+ }+ out.push(current)+ return out+ }+ let pages = paginate(Infinity)+ if (pages.length > 1) {+ // The same number of slides with the rows spread evenly, so the last one+ // does not carry a single orphaned row.+ const even = paginate(Math.ceil(rows.length / pages.length))+ if (even.length === pages.length) pages = even+ }+ if (cut > 0) {+ warnings.push(+ `${where}: ${cut} row(s) held more text than fits on a slide and were shortened; ` ++ 'split long cells into more rows.'+ )+ }+ if (pages.length > 1) {+ warnings.push(+ `${where}: ${table.rows.length} rows did not fit on one slide, so the table continues on ` ++ `${pages.length - 1} more slide(s) with the header repeated.`+ )+ }+ return { fontSize, columnWidths: widths, pages }+}diff --git a/mcp-host/src/workflow/pptxTemplates.ts b/mcp-host/src/workflow/pptxTemplates.tsnew file mode 100644index 000000000..8f61d9750--- /dev/null+++ b/mcp-host/src/workflow/pptxTemplates.ts@@ -0,0 +1,452 @@+/**+ * The preset decks of clerum__generate_pptx, built from a template's `data`.+ *+ * Each template reads a fixed set of fields, declared in the tool schema and+ * checked here, so a field name the model guessed wrong is reported by name.+ */+import {+ PptxInputError,+ type PptxKpi,+ type PptxSlide,+ type ReadContext,+ STATUSES,+ TEXT_LIMITS,+ isRecord,+ readChart,+ readEnum,+ readKpis,+ readStringList,+ readTable,+ readText,+} from './pptxInput'++export const PPTX_TEMPLATES = [+ 'executive-brief',+ 'quarterly-review',+ 'incident-review',+ 'pitch-deck',+] as const++export type PptxTemplate = (typeof PPTX_TEMPLATES)[number]++/** The fields each template reads; a required one missing fails the call. */+export const PPTX_TEMPLATE_FIELDS: Record<+ PptxTemplate,+ { required: string[]; optional: string[] }+> = {+ 'executive-brief': {+ required: ['title'],+ optional: ['subtitle', 'status', 'kpis', 'charts', 'takeaways', 'nextSteps'],+ },+ 'quarterly-review': {+ required: ['title', 'period'],+ optional: [+ 'status',+ 'highlights',+ 'kpis',+ 'revenueChart',+ 'breakdownChart',+ 'metricsTable',+ 'outlook',+ ],+ },+ 'incident-review': {+ required: ['title', 'severity', 'summary'],+ optional: ['date', 'timelineTable', 'impact', 'rootCause', 'remediation', 'lessons'],+ },+ 'pitch-deck': {+ required: ['company', 'tagline', 'problem', 'solution'],+ optional: ['marketSize', 'tractionChart', 'team', 'ask'],+ },+}++export const SEVERITIES = ['low', 'medium', 'high', 'critical'] as const++function fieldList(template: PptxTemplate): string {+ const { required, optional } = PPTX_TEMPLATE_FIELDS[template]+ return [...required.map(f => `${f} (required)`), ...optional].join(', ')+}++function camelCase(key: string): string {+ return key.replace(/[_\-\s]+([a-zA-Z0-9])/g, (_, c: string) => c.toUpperCase())+}++/** The name `key` of `data` is read under, when it is another field's spelling. */+function renamedField(key: string, data: Record<string, unknown>, known: Set<string>) {+ if (known.has(key)) return undefined+ const camel = camelCase(key)+ return known.has(camel) && !(camel in data) ? camel : undefined+}++/** `data` keyed by the template's field names, with the keys it cannot place. */+function placeFields(+ template: PptxTemplate,+ data: Record<string, unknown>,+ ctx: ReadContext+): { fields: Record<string, unknown>; unknown: string[] } {+ const { required, optional } = PPTX_TEMPLATE_FIELDS[template]+ const known = new Set([...required, ...optional])+ const fields: Record<string, unknown> = {}+ const unknown: string[] = []+ for (const [key, value] of Object.entries(data)) {+ if (known.has(key)) {+ fields[key] = value+ continue+ }+ const camel = renamedField(key, data, known)+ if (camel !== undefined) {+ fields[camel] = value+ ctx.warnings.push(`data.${key} was read as data.${camel}.`)+ continue+ }+ unknown.push(key)+ }+ return { fields, unknown }+}++function requiredText(+ fields: Record<string, unknown>,+ name: string,+ template: PptxTemplate,+ max: number,+ ctx: ReadContext+): string {+ const text = readText(fields[name], `data.${name}`, max, ctx)+ if (!text) {+ throw new PptxInputError(+ `template "${template}" needs data.${name}. Its fields are: ${fieldList(template)}.`+ )+ }+ return text+}++function kpiSlides(kpis: PptxKpi[], title: string): PptxSlide[] {+ return kpis.length > 0+ ? [{ layout: 'kpis', where: 'data', paths: { kpis: 'data.kpis' }, title, kpis }]+ : []+}++function listSlide(+ fields: Record<string, unknown>,+ name: string,+ title: string,+ ctx: ReadContext+): PptxSlide[] {+ const bullets = readStringList(fields[name], `data.${name}`, TEXT_LIMITS.bullet, ctx)+ return bullets?.length+ ? [+ {+ layout: 'title-bullets',+ where: 'data',+ paths: { bullets: `data.${name}` },+ title,+ bullets,+ },+ ]+ : []+}++function chartSlide(+ fields: Record<string, unknown>,+ name: string,+ fallbackTitle: string,+ ctx: ReadContext+): PptxSlide[] {+ if (fields[name] === undefined || fields[name] === null) return []+ const chart = readChart(fields[name], `data.${name}`, ctx)+ return [+ {+ layout: 'title-chart',+ where: 'data',+ paths: { chart: `data.${name}`, title: `data.${name}.title` },+ title: chart.title ?? fallbackTitle,+ chart,+ },+ ]+}++function executiveBrief(f: Record<string, unknown>, ctx: ReadContext): PptxSlide[] {+ const t: PptxTemplate = 'executive-brief'+ const slides: PptxSlide[] = [+ {+ layout: 'cover',+ where: 'data',+ title: requiredText(f, 'title', t, TEXT_LIMITS.title, ctx),+ subtitle: readText(f.subtitle, 'data.subtitle', TEXT_LIMITS.subtitle, ctx),+ status: readEnum(f.status, 'data.status', STATUSES),+ },+ ]+ if (f.kpis !== undefined)+ slides.push(...kpiSlides(readKpis(f.kpis, 'data.kpis', ctx), 'Key Metrics'))+ if (f.charts !== undefined && f.charts !== null) {+ if (!Array.isArray(f.charts)) {+ throw new PptxInputError('data.charts must be a list of charts.')+ }+ f.charts.forEach((raw, i) => {+ const chart = readChart(raw, `data.charts[${i}]`, ctx)+ slides.push({+ layout: 'title-chart',+ where: 'data',+ paths: { chart: `data.charts[${i}]`, title: `data.charts[${i}].title` },+ title: chart.title ?? 'Chart',+ chart,+ })+ })+ }+ slides.push(...listSlide(f, 'takeaways', 'Key Takeaways', ctx))+ slides.push(...listSlide(f, 'nextSteps', 'Next Steps', ctx))+ return slides+}++function quarterlyReview(f: Record<string, unknown>, ctx: ReadContext): PptxSlide[] {+ const t: PptxTemplate = 'quarterly-review'+ const title = requiredText(f, 'title', t, TEXT_LIMITS.title, ctx)+ const period = requiredText(f, 'period', t, TEXT_LIMITS.eyebrow, ctx)+ const slides: PptxSlide[] = [+ {+ layout: 'cover',+ where: 'data',+ paths: { subtitle: 'data.period' },+ title,+ subtitle: period,+ status: readEnum(f.status, 'data.status', STATUSES),+ },+ ]+ slides.push(...listSlide(f, 'highlights', `${period} Highlights`, ctx))+ if (f.kpis !== undefined)+ slides.push(...kpiSlides(readKpis(f.kpis, 'data.kpis', ctx), 'Quarterly KPIs'))+ slides.push(...chartSlide(f, 'revenueChart', 'Revenue Trend', ctx))+ slides.push(...chartSlide(f, 'breakdownChart', 'Revenue Breakdown', ctx))+ if (f.metricsTable !== undefined && f.metricsTable !== null) {+ slides.push({+ layout: 'title-table',+ where: 'data',+ paths: { table: 'data.metricsTable' },+ title: 'Metrics Snapshot',+ table: readTable(f.metricsTable, 'data.metricsTable', ctx),+ })+ }+ const outlook = listSlide(f, 'outlook', 'Next Quarter Priorities', ctx)+ if (outlook.length > 0) {+ slides.push({+ layout: 'section',+ where: 'data',+ eyebrow: 'Looking ahead',+ title: 'Outlook',+ })+ slides.push(...outlook)+ }+ return slides+}++function incidentReview(f: Record<string, unknown>, ctx: ReadContext): PptxSlide[] {+ const t: PptxTemplate = 'incident-review'+ const title = requiredText(f, 'title', t, TEXT_LIMITS.title, ctx)+ const severity = readEnum(f.severity, 'data.severity', SEVERITIES)+ if (!severity) {+ throw new PptxInputError(+ `template "${t}" needs data.severity, one of ${SEVERITIES.join(', ')}. ` ++ `Its fields are: ${fieldList(t)}.`+ )+ }+ const summary = requiredText(f, 'summary', t, TEXT_LIMITS.bullet, ctx)+ const date = readText(f.date, 'data.date', TEXT_LIMITS.eyebrow, ctx)+ const slides: PptxSlide[] = [+ {+ layout: 'cover',+ where: 'data',+ paths: { subtitle: 'data.date' },+ title,+ subtitle: [severity.toUpperCase(), date].filter(Boolean).join(' · '),+ status:+ severity === 'critical' || severity === 'high'+ ? 'red'+ : severity === 'medium'+ ? 'yellow'+ : 'green',+ },+ {+ layout: 'title-bullets',+ where: 'data',+ paths: { bullets: 'data.summary' },+ title: 'Summary',+ bullets: [summary],+ },+ ]+ if (f.timelineTable !== undefined && f.timelineTable !== null) {+ slides.push({+ layout: 'title-table',+ where: 'data',+ paths: { table: 'data.timelineTable' },+ title: 'Timeline',+ table: readTable(f.timelineTable, 'data.timelineTable', ctx),+ })+ }+ slides.push(...listSlide(f, 'impact', 'Impact', ctx))+ const rootCause = readText(f.rootCause, 'data.rootCause', TEXT_LIMITS.bullet, ctx)+ if (rootCause) {+ slides.push({+ layout: 'title-bullets',+ where: 'data',+ paths: { bullets: 'data.rootCause' },+ title: 'Root Cause',+ bullets: [rootCause],+ })+ }+ slides.push(...listSlide(f, 'remediation', 'Remediation', ctx))+ slides.push(...listSlide(f, 'lessons', 'Lessons Learned', ctx))+ return slides+}++/** A money amount: text as written, or a number grouped in thousands ("12,000,000,000"). */+function readAmount(value: unknown, where: string, ctx: ReadContext): string | undefined {+ if (typeof value === 'number' && Number.isFinite(value)) {+ return value.toLocaleString('en-US', { maximumFractionDigits: 2 })+ }+ return readText(value, where, TEXT_LIMITS.value, ctx)+}++function pitchDeck(f: Record<string, unknown>, ctx: ReadContext): PptxSlide[] {+ const t: PptxTemplate = 'pitch-deck'+ const slides: PptxSlide[] = [+ {+ layout: 'cover',+ where: 'data',+ paths: { title: 'data.company', subtitle: 'data.tagline' },+ title: requiredText(f, 'company', t, TEXT_LIMITS.title, ctx),+ subtitle: requiredText(f, 'tagline', t, TEXT_LIMITS.subtitle, ctx),+ },+ {+ layout: 'section',+ where: 'data',+ paths: { subtitle: 'data.problem' },+ eyebrow: 'The pain',+ title: 'Problem',+ subtitle: requiredText(f, 'problem', t, TEXT_LIMITS.subtitle, ctx),+ },+ {+ layout: 'section',+ where: 'data',+ paths: { subtitle: 'data.solution' },+ eyebrow: 'Our approach',+ title: 'Solution',+ subtitle: requiredText(f, 'solution', t, TEXT_LIMITS.subtitle, ctx),+ },+ ]+ if (f.marketSize !== undefined && f.marketSize !== null) {+ const m = f.marketSize+ const value = isRecord(m) ? readAmount(m.value, 'data.marketSize.value', ctx) : undefined+ if (!isRecord(m) || !value) {+ throw new PptxInputError(+ 'data.marketSize must be an object with value (e.g. "$12B" or 12000000000) and an ' ++ 'optional description.'+ )+ }+ slides.push({+ layout: 'kpis',+ where: 'data',+ title: 'Market Size',+ kpis: [+ {+ where: 'data.marketSize',+ notePath: 'data.marketSize.description',+ label: 'TAM',+ value,+ note: readText(m.description, 'data.marketSize.description', TEXT_LIMITS.note, ctx),+ },+ ],+ })+ }+ slides.push(...chartSlide(f, 'tractionChart', 'Traction', ctx))+ if (f.team !== undefined && f.team !== null) {+ if (!Array.isArray(f.team))+ throw new PptxInputError('data.team must be a list of {name, role}.')+ const people = f.team.map((p, i) => {+ const at = `data.team[${i}]`+ if (!isRecord(p)) throw new PptxInputError(`${at} must be an object with name and role.`)+ // Workflows written against the KPI-card shape send {label: name, value: role}.+ const name = readText(p.name ?? p.label, `${at}.name`, TEXT_LIMITS.value, ctx)+ if (!name) throw new PptxInputError(`${at}.name is missing.`)+ return {+ where: at,+ notePath: `${at}.role`,+ value: name,+ note: readText(p.role ?? p.value, `${at}.role`, TEXT_LIMITS.label, ctx),+ }+ })+ if (people.length > 0) {+ slides.push({+ layout: 'kpis',+ where: 'data',+ title: 'Team',+ kpis: people,+ kpiStyle: 'people',+ })+ }+ }+ if (f.ask !== undefined && f.ask !== null) {+ const a = f.ask+ const amount = isRecord(a) ? readAmount(a.amount, 'data.ask.amount', ctx) : undefined+ if (!isRecord(a) || !amount) {+ throw new PptxInputError(+ 'data.ask must be an object with amount (e.g. "$5M" or 5000000) and useOfFunds.'+ )+ }+ const uses = readStringList(a.useOfFunds, 'data.ask.useOfFunds', TEXT_LIMITS.bullet, ctx)+ slides.push(+ uses?.length+ ? {+ layout: 'title-bullets',+ where: 'data',+ paths: { bullets: 'data.ask.useOfFunds', title: 'data.ask.amount' },+ title: `The Ask · ${amount}`,+ bullets: uses,+ }+ : {+ layout: 'section',+ where: 'data',+ paths: { title: 'data.ask.amount' },+ eyebrow: 'The Ask',+ title: amount,+ }+ )+ }+ return slides+}++const BUILDERS: Record<+ PptxTemplate,+ (f: Record<string, unknown>, ctx: ReadContext) => PptxSlide[]+> = {+ 'executive-brief': executiveBrief,+ 'quarterly-review': quarterlyReview,+ 'incident-review': incidentReview,+ 'pitch-deck': pitchDeck,+}++/** The slides a template builds from `data`. Throws PptxInputError naming the field to fix. */+export function buildTemplateSlides(+ template: PptxTemplate,+ data: unknown,+ ctx: ReadContext+): PptxSlide[] {+ if (!isRecord(data)) {+ throw new PptxInputError(+ `template "${template}" requires data, an object with these fields: ` ++ `${fieldList(template)}.`+ )+ }+ const { fields, unknown } = placeFields(template, data, ctx)+ const slides = BUILDERS[template](fields, ctx)+ if (unknown.length > 0) {+ const names = unknown.map(k => `data.${k}`).join(', ')+ const message =+ `${names} ${unknown.length > 1 ? 'are not fields' : 'is not a field'} of the ` ++ `"${template}" template. Its fields are: ${fieldList(template)}.`+ if (slides.length <= 1) {+ throw new PptxInputError(`${message} As sent, the deck would hold only its cover.`)+ }+ ctx.warnings.push(`${message} ${unknown.length > 1 ? 'They were' : 'It was'} left out.`)+ }+ return slides+}diff --git a/mcp-host/src/workflow/pptxText.ts b/mcp-host/src/workflow/pptxText.tsnew file mode 100644index 000000000..37740cd05--- /dev/null+++ b/mcp-host/src/workflow/pptxText.ts@@ -0,0 +1,249 @@+/**+ * Text measurement for the PPTX generator. PowerPoint neither shrinks text to+ * fit on open or export (`normAutofit` is ignored) nor carries a table onto+ * another slide, so the generator lays text out itself. It measures with the+ * Roboto faces fonts.ts registers, within a few percent of Arial, the deck font.+ */+import { type SKRSContext2D, createCanvas } from '@napi-rs/canvas'+import { CHART_FONT_FAMILY, ensureFontsReady } from './fonts'++/** The one family the deck uses, for slides and charts alike. */+export const PPTX_FONT_FACE = 'Arial'++/**+ * Arial against the bundled faces, measured on English and Spanish text:+ * regular runs up to 3% wider than Roboto, bold up to 8% wider than the Roboto+ * Medium registered as bold. Rounded up so an estimate errs toward fitting.+ */+const REGULAR_WIDTH_FACTOR = 1.05+const BOLD_WIDTH_FACTOR = 1.1++/** Single spacing, in ems. The CJK faces PowerPoint substitutes set taller lines. */+const LINE_HEIGHT = 1.2+const WIDE_LINE_HEIGHT = 1.35++/** Default text-box insets PowerPoint applies: 0.1in left and right, 0.05in top and bottom. */+export const TEXT_INSET_X = 0.2+export const TEXT_INSET_Y = 0.1++/**+ * CJK characters, counted one em wide: every CJK face sets them so, and the+ * runtime image may have no CJK face to measure them with.+ */+const WIDE_CHAR =+ /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\u3000-\u303F\uFF01-\uFF60\uFFE0-\uFFE6]/u++/** Runs of spaces, single CJK characters, and words: the points where a line may break. */+const BREAK_TOKENS = new RegExp(+ `\\s+|${WIDE_CHAR.source}|[^\\s]+?(?=\\s|${WIDE_CHAR.source}|$)`,+ 'gu'+)++let context: SKRSContext2D | undefined++function canvasContext(): SKRSContext2D {+ if (!context) {+ ensureFontsReady()+ context = createCanvas(4, 4).getContext('2d')+ }+ return context+}++const widthCache = new Map<string, number>()++/** Width of `text` in ems of the deck font. */+function widthEm(text: string, bold: boolean): number {+ const key = `${bold ? 'b' : 'r'}${text}`+ const cached = widthCache.get(key)+ if (cached !== undefined) return cached+ const ctx = canvasContext()+ ctx.font = `100px "${bold ? `${CHART_FONT_FAMILY} Bold` : CHART_FONT_FAMILY}"`+ let wide = 0+ let narrow = ''+ for (const ch of text) {+ if (WIDE_CHAR.test(ch)) wide+++ else narrow += ch+ }+ const measured = narrow ? ctx.measureText(narrow).width / 100 : 0+ const em = measured * (bold ? BOLD_WIDTH_FACTOR : REGULAR_WIDTH_FACTOR) + wide+ if (widthCache.size > 20_000) widthCache.clear()+ widthCache.set(key, em)+ return em+}++export interface TextStyle {+ bold?: boolean+ /** Space after each paragraph, in points. */+ paraSpaceAfter?: number+}++/** Width of `text` set on one line, in inches. */+export function textWidth(text: string, sizePt: number, bold = false): number {+ return (widthEm(text, bold) * sizePt) / 72+}++/**+ * The lines PowerPoint breaks `text` into in a box `widthIn` wide: at spaces,+ * between CJK characters, and inside a word only when the word alone is wider+ * than the line. A line is measured as its tokens added up, which leaves out+ * the kerning between them (about 1% wider at most, so it errs toward fitting)+ * and measures each token once, so long lists take linear time.+ */+export function wrapLines(text: string, sizePt: number, widthIn: number, bold = false): string[] {+ const max = Math.max(widthIn, 0.1)+ const width = (s: string) => textWidth(s, sizePt, bold)+ const out: string[] = []+ for (const hard of text.split('\n')) {+ const tokens = hard.match(BREAK_TOKENS) ?? []+ let line = ''+ let used = 0+ for (const token of tokens) {+ const w = width(token)+ if (/^\s+$/.test(token)) {+ if (line) {+ line += token+ used += w+ }+ continue+ }+ if (used + w <= max) {+ line += token+ used += w+ continue+ }+ if (line.trim()) out.push(line.trimEnd())+ line = ''+ used = 0+ if (w <= max) {+ line = token+ used = w+ continue+ }+ for (const ch of token) {+ const c = width(ch)+ if (line && used + c > max) {+ out.push(line)+ line = ''+ used = 0+ }+ line += ch+ used += c+ }+ }+ out.push(line.trimEnd())+ }+ return out+}++export function lineHeightIn(sizePt: number, text: string): number {+ return ((WIDE_CHAR.test(text) ? WIDE_LINE_HEIGHT : LINE_HEIGHT) * sizePt) / 72+}++/** Height, in inches, of `paragraphs` set in a box `widthIn` wide, without the box insets. */+export function textBlockHeight(+ paragraphs: string[],+ sizePt: number,+ widthIn: number,+ style: TextStyle = {}+): number {+ let total = 0+ for (const p of paragraphs) {+ total += paragraphHeight(p, wrapLines(p, sizePt, widthIn, style.bold).length, sizePt, style)+ }+ return total+}++function paragraphHeight(text: string, lines: number, sizePt: number, style: TextStyle): number {+ return lines * lineHeightIn(sizePt, text) + (style.paraSpaceAfter ?? 0) / 72+}++export interface FittedText {+ size: number+ /** Height of the text including the box insets, in inches. */+ height: number+ fits: boolean+}++/**+ * The largest of `sizes` at which `paragraphs` fit a box, or the smallest size+ * with `fits: false`. `maxLines` caps the lines of each paragraph.+ */+export function fitText(+ paragraphs: string[],+ box: { w: number; h: number },+ sizes: number[],+ style: TextStyle & { maxLines?: number; indent?: number } = {}+): FittedText {+ const width = box.w - TEXT_INSET_X - (style.indent ?? 0)+ let last: FittedText = { size: sizes[sizes.length - 1], height: Infinity, fits: false }+ for (const size of sizes) {+ let height = TEXT_INSET_Y+ let lines = 0+ for (const p of paragraphs) {+ const n = wrapLines(p, size, width, style.bold).length+ height += paragraphHeight(p, n, size, style)+ lines = Math.max(lines, n)+ }+ const fits = height <= box.h + 1e-6 && (!style.maxLines || lines <= style.maxLines)+ last = { size, height, fits }+ if (fits) return last+ }+ return last+}++/**+ * `text` cut at a word so it takes at most `maxLines` lines, ending in an+ * ellipsis. Returns the text unchanged when it already fits.+ */+export function truncateToLines(+ text: string,+ sizePt: number,+ widthIn: number,+ maxLines: number,+ bold = false+): string {+ if (wrapLines(text, sizePt, widthIn, bold).length <= maxLines) return text+ const chars = Array.from(text)+ const fits = (n: number) =>+ wrapLines(`${chars.slice(0, n).join('').trimEnd()}…`, sizePt, widthIn, bold).length <= maxLines+ let lo = 0+ let hi = chars.length+ while (lo < hi) {+ const mid = Math.ceil((lo + hi) / 2)+ if (fits(mid)) lo = mid+ else hi = mid - 1+ }+ let kept = chars.slice(0, lo).join('')+ const space = kept.lastIndexOf(' ')+ if (space > kept.length * 0.6) kept = kept.slice(0, space)+ return `${kept.trimEnd()}…`+}++export interface ScriptOptions {+ lang?: string+ rtlMode?: boolean+}++const RTL_SCRIPT = /[\p{Script=Arabic}\p{Script=Hebrew}]/u++/**+ * Language and direction for `text`. Untagged runs are en-US, and PowerPoint+ * then mixes CJK glyphs from several fallback fonts; without `rtl` an Arabic+ * paragraph runs left to right. Direction follows the first letter, as bidi does.+ * Han characters alone may be Chinese, Japanese or Korean, so they take `hanLang`,+ * the deck's language.+ */+export function scriptOptions(text: string, hanLang = 'zh-CN'): ScriptOptions {+ let lang: string | undefined+ if (/[\p{Script=Hiragana}\p{Script=Katakana}]/u.test(text)) lang = 'ja-JP'+ else if (/\p{Script=Hangul}/u.test(text)) lang = 'ko-KR'+ else if (/\p{Script=Han}/u.test(text)) lang = hanLang+ else if (/\p{Script=Arabic}/u.test(text)) lang = 'ar-SA'+ else if (/\p{Script=Hebrew}/u.test(text)) lang = 'he-IL'+ const firstLetter = /\p{L}/u.exec(text)?.[0]+ const rtl = firstLetter !== undefined && RTL_SCRIPT.test(firstLetter)+ const out: ScriptOptions = {}+ if (lang) out.lang = lang+ if (rtl) out.rtlMode = true+ return out+}