Bento, the office suite that fits in a file
TypeScript mit-licenseofficeoffice-365office-suiteoffice-toolsoffice365open-sourcepowerpointself-hostedsingle-page-appslidesslideshareslideshowslideshow-galleryslideshow-makerslideshows
convert: a first-party pptx importer in the kernel (#351)
nyblnet2df2b9d4ac0a
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 360c787c..e598f17a 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -653,6 +653,16 @@ jobs:# the ciphertext is the leak the password exists to prevent.run: node scripts/test-dash-preview.ts+ - name: convert engine rigs+ # The pptx importer's resolver is where real decks' fidelity lives --+ # 91% of colour and 71% of run properties are indirect, and every hop+ # fails silently (a backwards clrMap still renders, just dark-on-dark).+ # Seven rigs, 378 checks, negative controls proven against mutated+ # implementations; load.ts is the gate that matters: every emitted+ # document must pass the REAL slides parseDoc with zero validateDoc+ # errors.+ run: node scripts/test-convert.ts+- name: bento/dash zip# Verified against real unzip implementations, not only our own reader:# a reader and a writer that share a bug agree with each other perfectly.diff --git a/dash/src/zip.ts b/dash/src/zip.tsindex cedfa33d..6dc2ae6c 100644--- a/dash/src/zip.ts+++ b/dash/src/zip.ts@@ -1,346 +1,7 @@// SPDX-License-Identifier: MIT// Copyright (c) 2026 The Bento authors-// A minimal ZIP reader and writer — the container .xlsx is made of.-//-// WHY THIS EXISTS RATHER THAN A DEPENDENCY. The shell ships as one-// self-contained HTML file and the whole app is ~98 KB compressed. JSZip is-// ~100 KB and SheetJS is larger than the entire product, so either one doubles-// the file every user downloads in order to open a format most of them will-// never touch. What .xlsx actually needs from ZIP is a fraction of the spec: a-// few dozen small parts, DEFLATE or stored, no encryption, no spanning, no-// streaming producer. That fraction is this file, and the browser already-// carries the expensive half — `DecompressionStream`/`CompressionStream`-// ('deflate-raw') are the same primitives the compressed-shell loader boots on,-// so the baseline is established and costs us nothing.-//-// THE READER TRUSTS THE CENTRAL DIRECTORY, NOT THE LOCAL HEADERS, and that is-// the single decision that makes a hand-written reader survive real files.-// A writer that does not know a part's size in advance (every streaming-// producer — which is most server-side xlsx generators) sets general-purpose-// bit 3, writes zeroes for crc/sizes in the local header, and appends a data-// DESCRIPTOR after the compressed bytes. Reading sizes from the local header-// then yields zero, and the naive fix — scanning forward for the next signature-// — collides with compressed data that happens to contain those four bytes.-// The central directory always has the true sizes. The local header is read for-// exactly one thing: its name and extra-field lengths, which give the offset-// where the data begins, and which may legitimately DIFFER from the central-// copy's (Excel itself writes a Zip64 extra field in one and not the other).-//-// WHAT IS DELIBERATELY NOT HERE: encryption (an encrypted xlsx must be refused,-// loudly, not half-read), multi-disk archives (a floppy-era feature), ZIP64-// WRITING (we would have to be emitting >4 GB from a browser tab, which the-// document budget rules out long before), and CP437 filename decoding — every-// part name inside an OPC package is ASCII by specification, so UTF-8 decodes-// it correctly whether or not the flag bit is set.--/** Thrown for a container that is not a ZIP, or is one we refuse to guess at. */-export class ZipError extends Error {- constructor(message: string) { super(message); this.name = 'ZipError' }-}--const SIG_LOCAL = 0x04034b50-const SIG_CD = 0x02014b50-const SIG_EOCD = 0x06054b50-const SIG_EOCD64 = 0x06064b50-const SIG_EOCD64_LOC = 0x07064b50--const enc = new TextEncoder()-const dec = new TextDecoder()--// --- CRC-32 ------------------------------------------------------------------// Built once, on first use. A ZIP whose CRCs are wrong is a ZIP that `unzip -t`-// rejects and Excel calls corrupt, and there is no way to notice by eye — which-// is exactly why the reader verifies them too (see `readZip`).--let CRC_TABLE: Uint32Array | null = null--function crcTable(): Uint32Array {- if (CRC_TABLE) return CRC_TABLE- const t = new Uint32Array(256)- for (let n = 0; n < 256; n++) {- let c = n- for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1- t[n] = c >>> 0- }- CRC_TABLE = t- return t-}--/** The ZIP/PNG CRC-32 of a byte range. Exported because the rig checks it- * against a known vector — a self-consistent wrong CRC would be invisible. */-export function crc32(b: Uint8Array): number {- const t = crcTable()- let c = 0xffffffff- for (let i = 0; i < b.length; i++) c = t[(c ^ b[i]) & 0xff] ^ (c >>> 8)- return (c ^ 0xffffffff) >>> 0-}--// --- DEFLATE, through the platform ---------------------------------------------const hasCompression = (): boolean => typeof CompressionStream !== 'undefined'--async function through(b: Uint8Array, s: ReadableWritablePair<Uint8Array, Uint8Array>): Promise<Uint8Array> {- // A Blob is the shortest route from bytes to a ReadableStream that works- // identically in a browser and in node's rigs; `Response.arrayBuffer` is the- // shortest route back. Neither allocates more than one extra copy.- const out = new Blob([b as BlobPart]).stream().pipeThrough(s as ReadableWritablePair<BufferSource, BufferSource>)- return new Uint8Array(await new Response(out as BodyInit).arrayBuffer())-}--const inflateRaw = (b: Uint8Array): Promise<Uint8Array> =>- through(b, new DecompressionStream('deflate-raw') as unknown as ReadableWritablePair<Uint8Array, Uint8Array>)--const deflateRaw = (b: Uint8Array): Promise<Uint8Array> =>- through(b, new CompressionStream('deflate-raw') as unknown as ReadableWritablePair<Uint8Array, Uint8Array>)--// --- Reading -------------------------------------------------------------------export interface ZipEntry {- name: string- data: Uint8Array-}--/**- * Every part of a ZIP archive, by name.- *- * A Map rather than an object because part names are attacker-adjacent data:- * `__proto__` is a perfectly legal ZIP entry name, and an object keyed by it is- * a prototype-pollution hole in a file format people will open from email.- */-export type ZipParts = Map<string, Uint8Array>--const u16 = (v: DataView, at: number): number => v.getUint16(at, true)-const u32 = (v: DataView, at: number): number => v.getUint32(at, true)-/** 64-bit little-endian as a JS number. Exact below 2^53, which every real- * archive is; beyond it we would already have failed on allocation. */-const u64 = (v: DataView, at: number): number =>- v.getUint32(at, true) + v.getUint32(at + 4, true) * 0x100000000--/** Locate the end-of-central-directory record, searching back over the- * (almost always empty) archive comment. */-function findEocd(v: DataView, len: number): number {- const min = Math.max(0, len - 22 - 0xffff)- for (let i = len - 22; i >= min; i--) if (u32(v, i) === SIG_EOCD) return i- throw new ZipError('this file does not end in a ZIP central directory — it is not an .xlsx')-}--/**- * Read an archive into its parts.- *- * CRCs ARE VERIFIED. It costs one extra pass over data we have just inflated- * anyway, and it converts the entire class of "the file was truncated by a mail- * gateway / a partial download / a bad USB stick" from *silently short data*- * into a refusal. Silently short data in a spreadsheet importer means a column- * that stops early and a total that is wrong by exactly the missing rows, and- * nothing on screen says so.- */-export async function readZip(bytes: Uint8Array): Promise<ZipParts> {- if (bytes.length < 22) throw new ZipError('this file is too small to be a ZIP archive')- const v = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)- const eocd = findEocd(v, bytes.length)-- let count = u16(v, eocd + 10)- let cdOffset = u32(v, eocd + 16)-- // ZIP64 — reading only. Both markers must be honoured: an archive with more- // than 65535 parts saturates the count, one over 4 GB saturates the offset,- // and Excel writes ZIP64 for either. Missing this reads the central directory- // from offset 0xFFFFFFFF, i.e. off the end, and the file "is not a ZIP".- if (count === 0xffff || cdOffset === 0xffffffff) {- const loc = eocd - 20- if (loc < 0 || u32(v, loc) !== SIG_EOCD64_LOC) {- throw new ZipError('this archive claims ZIP64 sizes but carries no ZIP64 locator')- }- const at = u64(v, loc + 8)- if (u32(v, at) !== SIG_EOCD64) throw new ZipError('the ZIP64 central directory record is missing')- count = u64(v, at + 32)- cdOffset = u64(v, at + 48)- }-- const parts: ZipParts = new Map()- let p = cdOffset- for (let i = 0; i < count; i++) {- if (u32(v, p) !== SIG_CD) throw new ZipError('the ZIP central directory is damaged')- const flags = u16(v, p + 8)- const method = u16(v, p + 10)- const crc = u32(v, p + 16)- let csize = u32(v, p + 20)- let usize = u32(v, p + 24)- const nameLen = u16(v, p + 28)- const extraLen = u16(v, p + 30)- const commentLen = u16(v, p + 32)- let local = u32(v, p + 42)- const name = dec.decode(bytes.subarray(p + 46, p + 46 + nameLen))-- // Bit 0 is the 1989 password scheme; bit 6 is AES. Either way the bytes are- // not the bytes, and half-reading them would produce garbage that looks- // like a parse failure rather than a locked file.- if (flags & 1) throw new ZipError(`"${name}" is encrypted — dash cannot open a password-protected workbook`)-- // The ZIP64 extra field replaces exactly the fields that saturated, in a- // fixed order, and ONLY those. Reading it positionally without checking- // which ones saturated is the classic way to shift every value by 8 bytes.- if (usize === 0xffffffff || csize === 0xffffffff || local === 0xffffffff) {- let e = p + 46 + nameLen- const end = e + extraLen- while (e + 4 <= end) {- const id = u16(v, e)- const size = u16(v, e + 2)- if (id === 0x0001) {- let q = e + 4- if (usize === 0xffffffff) { usize = u64(v, q); q += 8 }- if (csize === 0xffffffff) { csize = u64(v, q); q += 8 }- if (local === 0xffffffff) { local = u64(v, q) }- break- }- e += 4 + size- }- }-- if (u32(v, local) !== SIG_LOCAL) throw new ZipError(`"${name}" does not start with a ZIP local header`)- // The LOCAL header's own name/extra lengths, never the central copy's:- // Excel writes a ZIP64 extra field into one and not the other, and using- // the wrong pair starts the data a few bytes early. The symptom is an- // inflate error on a file every other tool opens.- const dataAt = local + 30 + u16(v, local + 26) + u16(v, local + 28)- const raw = bytes.subarray(dataAt, dataAt + csize)-- let data: Uint8Array- if (method === 0) data = raw- else if (method === 8) {- // DecompressionStream rejects with a bare TypeError whose message is- // often EMPTY, which is how a damaged file first showed up here: the- // caller saw an unnamed exception from somewhere inside a stream and had- // nothing to tell the user. Every failure this file can produce has to- // arrive as a ZipError naming the part, or the refusal is not a refusal.- try {- data = await inflateRaw(raw)- } catch {- throw new ZipError(`"${name}" could not be decompressed — the file is damaged or truncated`)- }- } else throw new ZipError(`"${name}" uses compression method ${method}, which dash does not implement`)-- if (data.length !== usize) {- throw new ZipError(`"${name}" unpacked to ${data.length} bytes but the directory says ${usize} — the file is truncated or damaged`)- }- if (crc32(data) !== crc) {- throw new ZipError(`"${name}" failed its checksum — the file is damaged, and reading it anyway would give you data that is wrong without looking wrong`)- }- parts.set(name, data)- p += 46 + nameLen + extraLen + commentLen- }- return parts-}--// --- Writing --------------------------------------------------------------------export interface WriteOpts {- /** Timestamp stamped into every entry. Fixed by default, so two exports of- * one workbook are byte-identical and a diff means a real change. */- at?: Date- /** Skip DEFLATE. Only for the rig and for a browser without CompressionStream. */- store?: boolean-}--/** DOS date/time. 1980-01-01 is the epoch of the field and the safe default —- * an all-zero date is out of range and makes some tools print a warning. */-function dosStamp(d: Date | undefined): { time: number; date: number } {- if (!d) return { time: 0, date: 33 } // 1980-01-01 00:00- const y = Math.max(1980, d.getFullYear())- return {- time: (d.getHours() << 11) | (d.getMinutes() << 5) | (d.getSeconds() >> 1),- date: ((y - 1980) << 9) | ((d.getMonth() + 1) << 5) | d.getDate(),- }-}--/**- * Build a ZIP archive.- *- * Entries are written in the order given, which for OPC matters more than it- * looks: `[Content_Types].xml` must be the FIRST part, because a consumer is- * entitled to stream the package and it cannot type any part until it has read- * it. Excel tolerates it elsewhere; other readers have not always.- *- * DEFLATE is skipped when it does not pay (tiny parts, and anything that grew),- * and the whole archive falls back to STORED where `CompressionStream` is- * missing. A stored ZIP is a completely valid ZIP — just bigger — so an old- * browser exports a working file instead of an error.- */-export async function writeZip(entries: ZipEntry[], opts: WriteOpts = {}): Promise<Uint8Array> {- const { time, date } = dosStamp(opts.at)- const store = opts.store || !hasCompression()- const locals: Uint8Array[] = []- const central: Uint8Array[] = []- let offset = 0- let cdSize = 0-- for (const e of entries) {- const name = enc.encode(e.name)- const usize = e.data.length- const crc = crc32(e.data)- let method = 0- let body = e.data- if (!store && usize > 64) {- const z = await deflateRaw(e.data)- // A part that got BIGGER (already-compressed media, tiny XML) is stored.- if (z.length < usize) { method = 8; body = z }- }-- const lh = new Uint8Array(30 + name.length)- const lv = new DataView(lh.buffer)- lv.setUint32(0, SIG_LOCAL, true)- lv.setUint16(4, 20, true) // version needed: 2.0 = DEFLATE- lv.setUint16(6, 0x800, true) // bit 11: the name is UTF-8- lv.setUint16(8, method, true)- lv.setUint16(10, time, true)- lv.setUint16(12, date, true)- lv.setUint32(14, crc, true)- lv.setUint32(18, body.length, true)- lv.setUint32(22, usize, true)- lv.setUint16(26, name.length, true)- lv.setUint16(28, 0, true)- lh.set(name, 30)-- const ch = new Uint8Array(46 + name.length)- const cv = new DataView(ch.buffer)- cv.setUint32(0, SIG_CD, true)- cv.setUint16(4, 20, true) // version made by- cv.setUint16(6, 20, true)- cv.setUint16(8, 0x800, true)- cv.setUint16(10, method, true)- cv.setUint16(12, time, true)- cv.setUint16(14, date, true)- cv.setUint32(16, crc, true)- cv.setUint32(20, body.length, true)- cv.setUint32(24, usize, true)- cv.setUint16(28, name.length, true)- cv.setUint32(42, offset, true)- ch.set(name, 46)-- locals.push(lh, body)- central.push(ch)- offset += lh.length + body.length- cdSize += ch.length- }-- const eocd = new Uint8Array(22)- const ev = new DataView(eocd.buffer)- ev.setUint32(0, SIG_EOCD, true)- ev.setUint16(8, entries.length, true)- ev.setUint16(10, entries.length, true)- ev.setUint32(12, cdSize, true)- ev.setUint32(16, offset, true)-- return concat([...locals, ...central, eocd])-}--export function concat(chunks: Uint8Array[]): Uint8Array {- let n = 0- for (const c of chunks) n += c.length- const out = new Uint8Array(n)- let at = 0- for (const c of chunks) { out.set(c, at); at += c.length }- return out-}--export const _internals = { findEocd, dosStamp, inflateRaw, deflateRaw }+// Facade: the ZIP reader/writer lives in the shared kernel now+// (kernel/src/convert/zip.ts) — it is the container .xlsx, .pptx and .docx all+// share, and the convert engine is its second consumer. Same pattern as+// slides/src/charts.ts over kernel/src/charts.ts; call sites are unchanged.+export * from '../../kernel/src/convert/zip.ts'diff --git a/kernel/src/convert/inherit.ts b/kernel/src/convert/inherit.tsnew file mode 100644index 00000000..1baf55fc--- /dev/null+++ b/kernel/src/convert/inherit.ts@@ -0,0 +1,383 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+//+// The placeholder / inheritance resolver — the reason converted shapes have+// frames and text has sizes at all.+//+// The census is blunt about where the values live: ~513 shapes carry no+// geometry element, 100+ carry no a:xfrm, and 10,503 a:defRPr against 4,200+// a:rPr means 71% of run properties are inherited defaults. A converter that+// reads slide XML alone emits unstyled text at 0,0 and it looks like a+// rendering bug, not a missing resolver. Everything here walks the+// slide → layout placeholder → master placeholder chain (plus the master's+// p:txStyles tables for text), and every resolved value records which level+// supplied it, because each hop fails SILENTLY — a wrong match still renders,+// just wrong.+//+// MATCHING IS IDX-FIRST, AND ABSENT idx MEANS "0". The trap: slide-level+// placeholders in real decks carry NO type="title" — the census's p:ph@type+// table has no title row at all. A slide title is written `<p:ph/>`; the type+// lives on the LAYOUT's `<p:ph type="title"/>`. Both sides' idx defaults to 0,+// so idx pairing finds the title; a type-only matcher normalizes the bare+// slide ph to 'body' and grabs the layout's body box instead. Type matching is+// only the fallback for when no candidate shares the idx (a slide ph copied+// against a re-numbered layout).++import { kid, kids, attr, intAttr, NS } from './xml.ts'+import type { XElem } from './xml.ts'+import type { InheritCtx } from './types.ts'+import type { Provenance } from './report.ts'++// --- the chain ---------------------------------------------------------------++export interface ChainLink {+ el: XElem+ from: Provenance+ ph?: XElem+}++/** The shape's p:ph, wherever its nv*Pr flavour keeps it (sp, pic, frame). */+function phOf(shape: XElem): XElem | undefined {+ for (const c of kids(shape)) {+ const nv = kid(c, NS.p, 'nvPr')+ if (nv) return kid(nv, NS.p, 'ph')+ }+ return undefined+}++/** Report `where` for one shape: its cNvPr name when it has one. */+function whereOf(shape: XElem): string {+ for (const c of kids(shape)) {+ const cnv = kid(c, NS.p, 'cNvPr')+ if (cnv) {+ const name = attr(cnv, 'name')+ return name ? `sp "${name}"` : `sp ${attr(cnv, 'id') ?? '?'}`+ }+ }+ return 'sp'+}++/** 'body' and absent type are one thing; ctrTitle pairs with title. */+const normType = (t: string | undefined): string =>+ t === undefined || t === 'body' ? 'body' : t === 'ctrTitle' ? 'title' : t++const effIdx = (ph: XElem): string => attr(ph, 'idx') ?? '0'++/** Every placeholder-bearing shape in a layout/master tree, document order.+ * A hand walker rather than three descendants() calls so mixed sp/pic+ * candidates keep their order — first-match must mean first-in-document. */+function phCandidates(root: XElem): Array<{ el: XElem; ph: XElem }> {+ const out: Array<{ el: XElem; ph: XElem }> = []+ const walk = (e: XElem) => {+ for (const c of e.children) {+ if (typeof c === 'string') continue+ if (c.ns === NS.p && (c.local === 'sp' || c.local === 'pic' || c.local === 'graphicFrame')) {+ const ph = phOf(c)+ if (ph) out.push({ el: c, ph })+ }+ walk(c)+ }+ }+ walk(root)+ return out+}++function matchPh(root: XElem, want: XElem): { el: XElem; ph: XElem } | undefined {+ const cands = phCandidates(root)+ const idx = effIdx(want)+ for (const c of cands) if (effIdx(c.ph) === idx) return c+ const t = normType(attr(want, 'type'))+ for (const c of cands) if (normType(attr(c.ph, 'type')) === t) return c+ return undefined+}++/**+ * The chain with provenance labels: the shape itself, then the layout's+ * matching placeholder, then the master's. The master hop matches against the+ * LAYOUT's ph when one was found — that is where the type actually lives —+ * falling back to the slide's own ph when the layout is silent.+ */+export function labeledChain(sp: XElem, ctx: InheritCtx): ChainLink[] {+ const own = phOf(sp)+ const out: ChainLink[] = [own ? { el: sp, from: 'own', ph: own } : { el: sp, from: 'own' }]+ if (!own) return out+ let want = own+ if (ctx.layout) {+ const m = matchPh(ctx.layout, want)+ if (m) {+ out.push({ el: m.el, from: 'layout', ph: m.ph })+ want = m.ph+ }+ }+ if (ctx.master) {+ const m = matchPh(ctx.master, want)+ if (m) out.push({ el: m.el, from: 'master', ph: m.ph })+ }+ return out+}++/** The chain as bare elements — shape, layout match, master match. */+export function placeholderChain(sp: XElem, ctx: InheritCtx): XElem[] {+ return labeledChain(sp, ctx).map((l) => l.el)+}++/**+ * The placeholder type callers should reason with (and pass to textDefaults):+ * first explicit type along the chain — a bare slide ph inherits 'title' from+ * the layout side. '' = not a placeholder; typeless everywhere = 'body'.+ */+export function effectivePhType(sp: XElem, ctx: InheritCtx): string {+ const chain = labeledChain(sp, ctx)+ if (!chain[0].ph) return ''+ for (const link of chain) {+ const t = link.ph ? attr(link.ph, 'type') : undefined+ if (t) return t+ }+ return 'body'+}++// --- frame -------------------------------------------------------------------++export interface ResolvedFrame {+ x: number+ y: number+ w: number+ h: number+ /** degrees (xfrm rot is 60,000ths of a degree) */+ rotation: number+ flipH: boolean+ flipV: boolean+ from: Provenance+}++const flag = (v: string | undefined): boolean => v === '1' || v === 'true'++/** sp/pic keep xfrm under p:spPr; graphicFrame carries a bare p:xfrm. */+function xfrmOf(el: XElem): XElem | undefined {+ const spPr = kid(el, NS.p, 'spPr')+ if (spPr) {+ const x = kid(spPr, NS.a, 'xfrm')+ if (x) return x+ }+ return kid(el, NS.p, 'xfrm')+}++/**+ * The shape's frame in EMU (callers divide by EMU_PER_PX), from the first+ * chain level carrying a COMPLETE a:xfrm — off and ext both; a partial xfrm+ * pins nothing and mixing halves from two levels would fabricate a box no+ * file specifies. rot/flip ride with the winning xfrm for the same reason.+ * No xfrm anywhere is reported and returned as a zero frame, never invented.+ */+export function resolveFrame(sp: XElem, ctx: InheritCtx): ResolvedFrame {+ for (const link of labeledChain(sp, ctx)) {+ const x = xfrmOf(link.el)+ if (!x) continue+ const off = kid(x, NS.a, 'off')+ const ext = kid(x, NS.a, 'ext')+ if (!off || !ext) continue+ ctx.report.trace('frame', link.from)+ return {+ x: intAttr(off, 'x'),+ y: intAttr(off, 'y'),+ w: intAttr(ext, 'cx'),+ h: intAttr(ext, 'cy'),+ rotation: intAttr(x, 'rot') / 60000,+ flipH: flag(attr(x, 'flipH')),+ flipV: flag(attr(x, 'flipV')),+ from: link.from,+ }+ }+ ctx.report.add('dropped', 'frame-missing', whereOf(sp),+ 'no a:xfrm on the shape, its layout placeholder or its master placeholder — emitted at 0,0 with zero size')+ ctx.report.trace('frame', 'default')+ return { x: 0, y: 0, w: 0, h: 0, rotation: 0, flipH: false, flipV: false, from: 'default' }+}++// --- text defaults -----------------------------------------------------------++export interface TextBullet {+ kind: 'none' | 'char' | 'autoNum'+ char?: string+ /** buFont typeface — read only from the SAME source as its buChar */+ font?: string+ /** buAutoNum numbering scheme, e.g. 'arabicPeriod' */+ scheme?: string+}++export interface TextDefaults {+ /** points (a:defRPr sz is centipoints: sz="1800" = 18pt) */+ fontSize: number+ bold: boolean+ /** typeface name, +mj-lt/+mn-lt already resolved through the theme */+ font: string+ /** the colour element (a:srgbClr/a:schemeClr/…) for theme.resolveColor */+ color?: XElem+ align: 'left' | 'center' | 'right'+ /** set when algn was something bento cannot say (just/dist) — align above+ * is the left approximation, and the caller should report this */+ alignRaw?: string+ /** multiplier (a:lnSpc spcPct val="100000" = 1.0; spcPts converts via fontSize) */+ lineHeight: number+ /** presence only — bento has no paragraph spacing, callers report the drop */+ hasSpcBef: boolean+ hasSpcAft: boolean+ bullet: TextBullet+}++function lstStyleOf(shape: XElem): XElem | undefined {+ const tb = kid(shape, NS.p, 'txBody')+ return tb ? kid(tb, NS.a, 'lstStyle') : undefined+}++/**+ * Resolved paragraph + run defaults for one indent level (0-based here;+ * lvl1pPr..lvl9pPr in the XML). Sources, nearest first: the shape's own+ * lstStyle → layout placeholder lstStyle → master placeholder lstStyle →+ * master p:txStyles (titleStyle for title/ctrTitle, bodyStyle for+ * body/subTitle, otherStyle else — pass phType from effectivePhType) → hard+ * defaults (18pt, minor font, left; colour stays undefined for the caller's+ * default ink). Each property takes the FIRST source that speaks; levels+ * never borrow from other levels.+ *+ * THE PRECEDENCE TRAP, guarded by the rig: bullets resolve as one unit. A+ * buNone at a nearer level is a declaration that SILENCES an inherited+ * buChar — the first source carrying ANY of buNone/buAutoNum/buChar wins+ * whole, and buFont is only ever read beside its own buChar. A per-property+ * merge would resurrect the master's bullet under a shape that turned+ * bullets off (the census carries 4,542 a:buNone doing exactly that).+ */+export function textDefaults(sp: XElem, ctx: InheritCtx, level: number, phType: string): TextDefaults {+ const lvlName = `lvl${Math.min(Math.max(level, 0), 8) + 1}pPr`+ const srcs: Array<{ pPr: XElem; from: Provenance }> = []+ for (const link of labeledChain(sp, ctx)) {+ const style = lstStyleOf(link.el)+ const p = style ? kid(style, NS.a, lvlName) : undefined+ if (p) srcs.push({ pPr: p, from: link.from })+ }+ if (ctx.master) {+ const table = phType === 'title' || phType === 'ctrTitle' ? 'titleStyle'+ : phType === 'body' || phType === 'subTitle' ? 'bodyStyle' : 'otherStyle'+ const styles = kid(ctx.master, NS.p, 'txStyles')+ const tbl = styles ? kid(styles, NS.p, table) : undefined+ const p = tbl ? kid(tbl, NS.a, lvlName) : undefined+ if (p) srcs.push({ pPr: p, from: 'master' })+ }++ const first = <T>(get: (pPr: XElem) => T | undefined): { v: T; from: Provenance } | undefined => {+ for (const s of srcs) {+ const v = get(s.pPr)+ if (v !== undefined) return { v, from: s.from }+ }+ return undefined+ }+ const defRPr = (p: XElem) => kid(p, NS.a, 'defRPr')++ const szHit = first((p) => {+ const rp = defRPr(p)+ const v = rp ? attr(rp, 'sz') : undefined+ if (v === undefined) return undefined+ const n = parseInt(v, 10)+ return Number.isFinite(n) ? n : undefined+ })+ const fontSize = szHit ? szHit.v / 100 : 18+ ctx.report.trace('font-size', szHit ? szHit.from : 'default')++ const bHit = first((p) => {+ const rp = defRPr(p)+ return rp ? attr(rp, 'b') : undefined+ })+ const bold = bHit ? flag(bHit.v) : false++ const fHit = first((p) => {+ const rp = defRPr(p)+ const lat = rp ? kid(rp, NS.a, 'latin') : undefined+ return lat ? attr(lat, 'typeface') : undefined+ })+ const raw = fHit ? fHit.v : '+mn-lt'+ const font = raw === '+mj-lt' ? ctx.theme.majorFont : raw === '+mn-lt' ? ctx.theme.minorFont : raw+ ctx.report.trace('font', fHit ? fHit.from : 'default')++ const cHit = first((p) => {+ const rp = defRPr(p)+ const sf = rp ? kid(rp, NS.a, 'solidFill') : undefined+ return sf ? kids(sf)[0] : undefined+ })+ ctx.report.trace('text-color', cHit ? cHit.from : 'default')++ const aHit = first((p) => attr(p, 'algn'))+ const algn = aHit?.v+ const align = algn === 'ctr' ? 'center' as const : algn === 'r' ? 'right' as const : 'left' as const++ const lHit = first((p) => kid(p, NS.a, 'lnSpc'))+ let lineHeight = 1+ if (lHit) {+ const pct = kid(lHit.v, NS.a, 'spcPct')+ const pts = kid(lHit.v, NS.a, 'spcPts')+ if (pct) lineHeight = intAttr(pct, 'val', 100000) / 100000+ else if (pts && fontSize > 0) lineHeight = intAttr(pts, 'val', fontSize * 100) / 100 / fontSize+ }++ const buHit = first<TextBullet>((p) => {+ if (kid(p, NS.a, 'buNone')) return { kind: 'none' }+ const auto = kid(p, NS.a, 'buAutoNum')+ if (auto) return { kind: 'autoNum', scheme: attr(auto, 'type') ?? 'arabicPeriod' }+ const ch = kid(p, NS.a, 'buChar')+ if (ch) {+ const out: TextBullet = { kind: 'char', char: attr(ch, 'char') ?? '•' }+ const bf = kid(p, NS.a, 'buFont')+ const face = bf ? attr(bf, 'typeface') : undefined+ if (face) out.font = face+ return out+ }+ return undefined+ })+ const bullet: TextBullet = buHit ? buHit.v : { kind: 'none' }+ ctx.report.trace('bullet', buHit ? buHit.from : 'default')++ const out: TextDefaults = {+ fontSize, bold, font, align, lineHeight,+ hasSpcBef: first((p) => kid(p, NS.a, 'spcBef')) !== undefined,+ hasSpcAft: first((p) => kid(p, NS.a, 'spcAft')) !== undefined,+ bullet,+ }+ if (cHit) out.color = cHit.v+ if (algn !== undefined && algn !== 'l' && algn !== 'ctr' && algn !== 'r') out.alignRaw = algn+ return out+}++// --- body insets -------------------------------------------------------------++export interface BodyInsets { l: number; t: number; r: number; b: number }++/**+ * Text-box insets in EMU from a:bodyPr, walked up the chain PER ATTRIBUTE (a+ * nearer bodyPr that only sets lIns does not reset the others). OOXML+ * defaults: 91440 left/right, 45720 top/bottom — the spike measured that+ * ignoring them silently costs every box ~19px of width, which then moves+ * every wrap point.+ */+export function bodyInsets(sp: XElem, ctx: InheritCtx): BodyInsets {+ const bodies: XElem[] = []+ for (const link of labeledChain(sp, ctx)) {+ const tb = kid(link.el, NS.p, 'txBody')+ const bp = tb ? kid(tb, NS.a, 'bodyPr') : undefined+ if (bp) bodies.push(bp)+ }+ const pick = (name: string, dflt: number): number => {+ for (const bp of bodies) {+ const v = attr(bp, name)+ if (v !== undefined) {+ const n = parseInt(v, 10)+ if (Number.isFinite(n)) return n+ }+ }+ return dflt+ }+ return {+ l: pick('lIns', 91440),+ t: pick('tIns', 45720),+ r: pick('rIns', 91440),+ b: pick('bIns', 45720),+ }+}diff --git a/kernel/src/convert/media.ts b/kernel/src/convert/media.tsnew file mode 100644index 00000000..58f747c1--- /dev/null+++ b/kernel/src/convert/media.ts@@ -0,0 +1,352 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+//+// Pictures and package relationships — the .rels graph, the asset store, and+// p:pic → OutImage (675 pictures across the six census decks).+//+// THE SVG RULE is the one decision in this file that protects the whole deck.+// The census corpus is overwhelmingly vector — 386 .svg media parts against 18+// raster parts in the template alone, referenced through asvg:svgBlip in the+// blip's extLst — and the tempting destination, an inline bento `svg` element,+// silently corrupts every icon: render.ts deliberately never strips `id`, svg+// `url(#…)` resolves DOCUMENT-globally, and icon libraries all name their+// clipPath/gradient `a` — so 386 icons each defining `#a` all paint with the+// first one's clip. The safe destination is an `image` element holding a+// `data:image/svg+xml` asset (its own document, ids scoped) — the same route+// render.ts already takes on the svgAsImage thumbnail path. The raster blip+// beside an svgBlip is only PowerPoint's compatibility preview; we use it only+// when the vector part is actually missing, and say so.+//+// The store dedups by CONTENT, not by part name, because the template reuses+// the same image across dozens of slides and layouts — and because the emitted+// document is one self-contained HTML file (6.9MB of media → ~9.2MB of base64+// if embedded once; catastrophic if embedded per reference). Keys are a pure+// function of the bytes so a re-import emits identical assets and a diff means+// a real change.++import { NS, attr, intAttr, kid, kids, descendants, type XElem } from './xml.ts'+import { EMU_PER_PX, type InheritCtx, type OutImage } from './types.ts'+import type { ZipParts } from './zip.ts'++// --- relationships -----------------------------------------------------------++export interface Rel {+ /** resolved part name ('ppt/media/image1.png'), or the verbatim URI when+ * mode is 'External' — an external target is never a package part and must+ * never be fetched */+ target: string+ type: string+ mode?: string+}++/**+ * Parse one .rels part into id → relationship.+ *+ * `baseDir` is the directory of the SOURCE part the .rels belongs to (e.g.+ * 'ppt/slides/' for slide1.xml.rels), because targets are relative to the+ * part, not to the _rels folder that physically holds the file:+ * 'ppt/slides/' + '../media/x.png' → 'ppt/media/x.png'.+ */+export function parseRels(relsXml: XElem, baseDir: string): Map<string, Rel> {+ const out = new Map<string, Rel>()+ for (const r of kids(relsXml, NS.rel, 'Relationship')) {+ const id = attr(r, 'Id')+ const target = attr(r, 'Target')+ if (!id || target === undefined) continue+ const type = attr(r, 'Type') ?? ''+ const mode = attr(r, 'TargetMode')+ // An External target is a URI into the outside world (a linked picture, a+ // hyperlink). It stays verbatim — resolving it against baseDir would+ // mangle it, and fetching it is the caller's line never to cross.+ if (mode === 'External') out.set(id, { target, type, mode })+ else out.set(id, { target: resolveTarget(baseDir, target), type })+ }+ return out+}++/** Join + normalize an OPC target against a base directory. Targets are URIs:+ * '%20' in the XML is a literal space in the ZIP part name. */+function resolveTarget(baseDir: string, target: string): string {+ let t = target+ try { t = decodeURIComponent(target) } catch { /* malformed escape: use as written */ }+ const segs = t.startsWith('/')+ ? t.split('/') // pack-absolute: '/ppt/media/x.png' ignores the base+ : [...baseDir.split('/'), ...t.split('/')]+ const out: string[] = []+ for (const s of segs) {+ if (s === '' || s === '.') continue+ if (s === '..') out.pop() // clamped at the package root+ else out.push(s)+ }+ return out.join('/')+}++// --- content types -----------------------------------------------------------++export interface ContentTypes {+ /** extension (lowercased, no dot) → mime, from ct:Default */+ defaults: Map<string, string>+ /** part name (no leading slash) → mime, from ct:Override */+ overrides: Map<string, string>+}++export function parseContentTypes(root: XElem): ContentTypes {+ const defaults = new Map<string, string>()+ const overrides = new Map<string, string>()+ for (const c of kids(root, NS.ct)) {+ const t = attr(c, 'ContentType')+ if (!t) continue+ if (c.local === 'Default') {+ const ext = attr(c, 'Extension')+ if (ext) defaults.set(ext.toLowerCase(), t)+ } else if (c.local === 'Override') {+ const p = attr(c, 'PartName')+ if (p) overrides.set(p.replace(/^\//, ''), t)+ }+ }+ return { defaults, overrides }+}++/** Extension fallbacks for a package with no (or an incomplete)+ * [Content_Types].xml — the package's own declarations win when present. */+const MIME_BY_EXT: Record<string, string> = {+ png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif',+ svg: 'image/svg+xml', bmp: 'image/bmp', tif: 'image/tiff', tiff: 'image/tiff',+ webp: 'image/webp', ico: 'image/x-icon',+ emf: 'image/x-emf', wmf: 'image/x-wmf', wdp: 'image/vnd.ms-photo',+}++export function mimeFor(partName: string, types?: ContentTypes): string {+ const clean = partName.replace(/^\//, '')+ const override = types?.overrides.get(clean)+ if (override) return override+ const dot = clean.lastIndexOf('.')+ const ext = dot < 0 ? '' : clean.slice(dot + 1).toLowerCase()+ return types?.defaults.get(ext) ?? MIME_BY_EXT[ext] ?? 'application/octet-stream'+}++// --- base64 ------------------------------------------------------------------++const B64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'++/** No Buffer (browser), no btoa assumption (bare JS runtimes): btoa where the+ * platform has it, the manual encoder elsewhere. One function, both worlds. */+export function toBase64(bytes: Uint8Array): string {+ if (typeof btoa === 'function') {+ // btoa wants a binary string; apply() in bounded chunks — one call over a+ // multi-MB image blows the argument-count limit.+ let bin = ''+ for (let i = 0; i < bytes.length; i += 0x8000) {+ bin += String.fromCharCode.apply(null, bytes.subarray(i, i + 0x8000) as unknown as number[])+ }+ return btoa(bin)+ }+ return b64Manual(bytes)+}++function b64Manual(bytes: Uint8Array): string {+ let out = ''+ const n = bytes.length+ let i = 0+ for (; i + 2 < n; i += 3) {+ const v = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2]+ out += B64[v >> 18] + B64[(v >> 12) & 63] + B64[(v >> 6) & 63] + B64[v & 63]+ }+ if (i + 1 === n) {+ const v = bytes[i] << 16+ out += B64[v >> 18] + B64[(v >> 12) & 63] + '=='+ } else if (i + 2 === n) {+ const v = (bytes[i] << 16) | (bytes[i + 1] << 8)+ out += B64[v >> 18] + B64[(v >> 12) & 63] + B64[(v >> 6) & 63] + '='+ }+ return out+}++// --- the asset store ---------------------------------------------------------++/** Two independent FNV-1a passes over the bytes, base36-joined. The key must+ * be a pure function of the CONTENT (stable across re-imports, dedups across+ * parts); 64 bits keeps accidental collisions out of reach for a few hundred+ * assets, and `register` byte-compares on a hash hit anyway, so a collision+ * costs a suffix, never a wrong image. */+function fnvKey(b: Uint8Array): string {+ let h1 = 0x811c9dc5 | 0+ let h2 = 0x7ee36211 | 0 // a second, unrelated basis+ for (let i = 0; i < b.length; i++) {+ h1 = Math.imul(h1 ^ b[i], 0x01000193)+ h2 = Math.imul(h2 ^ b[i], 0x01000193)+ }+ return (h1 >>> 0).toString(36) + (h2 >>> 0).toString(36)+}++function bytesEq(a: Uint8Array, b: Uint8Array): boolean {+ if (a.length !== b.length) return false+ for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false+ return true+}++/**+ * Content-addressed media for the emitted document.+ *+ * `register` takes a resolved part name, returns the stable asset key (or+ * undefined for a missing part — the CALLER decides what that means and+ * reports it, because "svg part missing" and "raster missing" are different+ * findings). Elements reference `asset:<key>`; `assets()` is the+ * `doc.assets` record of data: URIs.+ */+export class AssetStore {+ /** hash → every distinct content seen under it (in practice one) */+ private byHash = new Map<string, Array<{ bytes: Uint8Array; key: string }>>()+ private uris = new Map<string, string>()+ // plain declarations, not parameter properties — node's strip-only TS+ // refuses non-erasable syntax, and every rig runs under it+ private parts: ZipParts+ private types?: ContentTypes++ constructor(parts: ZipParts, types?: ContentTypes) {+ this.parts = parts+ this.types = types+ }++ register(partName: string): string | undefined {+ const bytes = this.parts.get(partName.replace(/^\//, ''))+ if (!bytes) return undefined+ return this.registerBytes(bytes, mimeFor(partName, this.types))+ }++ /** Dedup is by bytes alone: the first registration's mime sticks, which is+ * right — identical bytes under two names are the same file. */+ registerBytes(bytes: Uint8Array, mime: string): string {+ const h = fnvKey(bytes)+ let bucket = this.byHash.get(h)+ if (!bucket) { bucket = []; this.byHash.set(h, bucket) }+ for (const e of bucket) if (bytesEq(e.bytes, bytes)) return e.key+ const key = bucket.length === 0 ? `m${h}` : `m${h}x${bucket.length}`+ bucket.push({ bytes, key })+ this.uris.set(key, `data:${mime};base64,${toBase64(bytes)}`)+ return key+ }++ /** The doc.assets record: key → data: URI. */+ assets(): Record<string, string> {+ return Object.fromEntries(this.uris)+ }+}++// --- p:pic → OutImage --------------------------------------------------------++/**+ * Convert one p:pic. Returns undefined when there is nothing displayable —+ * every undefined is reported, never silent.+ *+ * The frame is read from the pic's OWN a:xfrm (pictures nearly always carry+ * one); a pic without it — a picture placeholder — comes back at 0,0,0,0 and+ * the caller's inheritance walk must supply the frame, exactly as for shapes.+ * Group transforms (p:grpSp chOff/chExt) are likewise the geometry pass's job.+ */+export function imageFrom(+ pic: XElem,+ ctx: InheritCtx,+ rels: Map<string, Rel>,+ assets: AssetStore,+ where = 'slide',+): OutImage | undefined {+ const report = ctx.report+ const blipFill = kid(pic, NS.p, 'blipFill')+ const blip = blipFill && kid(blipFill, NS.a, 'blip')+ if (!blipFill || !blip) {+ report.add('dropped', 'image-no-blip', where, 'a picture carries no image reference at all')+ return undefined+ }++ // The SVG rule (see header): a blip whose extLst carries asvg:svgBlip is a+ // vector icon; the r:embed raster beside it is only a compatibility preview.+ let key: string | undefined+ const svgBlip = descendants(blip, NS.asvg, 'svgBlip')[0]+ if (svgBlip) {+ const svgId = attr(svgBlip, 'embed')+ const svgRel = svgId ? rels.get(svgId) : undefined+ if (svgRel && !svgRel.mode) key = assets.register(svgRel.target)+ if (key === undefined) {+ report.add('approximated', 'svg-raster-fallback', where,+ 'a vector icon\'s SVG part is missing — its raster preview is used instead')+ }+ }++ if (key === undefined) {+ const relId = attr(blip, 'embed') ?? attr(blip, 'link')+ const rel = relId ? rels.get(relId) : undefined+ if (!rel) {+ report.add('dropped', 'image-missing-rel', where,+ 'a picture references a relationship the .rels part does not define')+ return undefined+ }+ if (rel.mode === 'External') {+ // A linked (not embedded) picture. The bytes live on someone's+ // filesystem or a URL; fetching is out of the question for a converter,+ // so the picture is lost and the report says where it pointed.+ report.add('dropped', 'image-external-dropped', where,+ `a linked (not embedded) picture points outside the file: ${rel.target}`)+ return undefined+ }+ if (rel.target.toLowerCase().endsWith('.wdp')) {+ // JPEG XR — no browser decodes it. PowerPoint pairs these with an+ // mc:Fallback pic carrying a real raster; the caller resolves that pair+ // (resolveAlternate) and calls us with the fallback pic instead.+ report.add('dropped', 'wdp-fallback', where,+ 'a JPEG XR (.wdp) image no browser can decode — use the mc:Fallback picture if the file carries one')+ return undefined+ }+ key = assets.register(rel.target)+ if (key === undefined) {+ report.add('dropped', 'image-missing-part', where,+ `a picture's media part is missing from the package: ${rel.target}`)+ return undefined+ }+ }++ // Framing. 335 census crops (~half of all pictures) have no model field to+ // land in; 'cover' at least keeps the box filled and centred rather than+ // squashing the whole original into it — but an off-centre headshot crop+ // WILL reframe, which is why this is 'approximated', not carried.+ const srcRect = kid(blipFill, NS.a, 'srcRect')+ const cropped = srcRect !== undefined &&+ (intAttr(srcRect, 'l') !== 0 || intAttr(srcRect, 't') !== 0 ||+ intAttr(srcRect, 'r') !== 0 || intAttr(srcRect, 'b') !== 0)+ let fit: OutImage['fit'] = 'fill' // a:stretch (the norm, and the default)+ if (cropped) {+ fit = 'cover'+ report.add('approximated', 'image-crop-dropped', where,+ 'a source-rectangle crop has no model field — the image fills its box as a centred cover instead')+ } else if (kid(blipFill, NS.a, 'tile')) {+ report.add('approximated', 'image-tile-dropped', where,+ 'a tiled picture fill renders as a single stretched copy')+ }++ const spPr = kid(pic, NS.p, 'spPr')+ const xfrm = spPr && kid(spPr, NS.a, 'xfrm')+ let x = 0, y = 0, w = 0, h = 0, rotation = 0+ if (xfrm) {+ const off = kid(xfrm, NS.a, 'off')+ const ext = kid(xfrm, NS.a, 'ext')+ if (off) { x = px(intAttr(off, 'x')); y = px(intAttr(off, 'y')) }+ if (ext) { w = px(intAttr(ext, 'cx')); h = px(intAttr(ext, 'cy')) }+ rotation = intAttr(xfrm, 'rot') / 60000 // 60,000ths of a degree+ }++ const nv = kid(pic, NS.p, 'nvPicPr')+ const cNvPr = nv && kid(nv, NS.p, 'cNvPr')+ return {+ id: `pic${cNvPr ? intAttr(cNvPr, 'id') : 0}`,+ type: 'image',+ x, y, w, h, rotation,+ opacity: 1,+ src: `asset:${key}`,+ fit,+ }+}++/** EMU → px, rounded to 1/100 px so emitted JSON stays diffable. */+const px = (emu: number): number => Math.round((emu / EMU_PER_PX) * 100) / 100++export const _internals = { b64Manual, resolveTarget, fnvKey, bytesEq }diff --git a/kernel/src/convert/pptx.ts b/kernel/src/convert/pptx.tsnew file mode 100644index 00000000..426f940b--- /dev/null+++ b/kernel/src/convert/pptx.ts@@ -0,0 +1,567 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+//+// The .pptx orchestrator — package in, ONE bento/slides document + fidelity+// report out. All the domain knowledge lives in the sibling modules (theme,+// inherit, media, text, shapes); this file owns the walks that stitch them+// together, and the walks are where a converter quietly loses whole decks:+//+// - PART ROUTING IS RELS, NEVER NAMES. slide → layout → master → theme is a+// chain of .rels hops; guessing "slideLayout1.xml" works on the demo file+// and breaks on every deck with 2–4 masters (all six census decks).+// - SLIDE ORDER IS p:sldIdLst ORDER, and z-order is spTree document order —+// both formats agree, so the walk just has to not reorder anything.+// - mc:AlternateContent is resolved with an EMPTY understood set: every+// mc:Choice in the census requires an extension namespace (p14 morph+// transitions and friends) whose semantics we do not implement, and the+// Fallback is the producer's own hand-built downlevel rendering. Taking+// it is strictly more honest than half-reading a Choice — and an mc-blind+// walk would import Choice AND Fallback, i.e. everything twice.+// - transition is ALWAYS 'none'. slides' own constructors default to 'fade'+// while 71 of 79 census slides specify no transition (a hard cut); the+// corpus's only real transition is Morph, and a failed morph pairing+// degrades WORSE than a cut (spike: unwanted whole-slide fade). M0+// imports no motion at all.+// - PRUNE. 500 layout parts serve 79 slides — ~85% of the package is dead+// template. Layouts are resolved through (inherit.ts) but never imported+// as doc.layouts, and only media an imported slide actually references is+// registered, or the emitted file is megabytes of unreachable base64.+//+// Element ids are DETERMINISTIC: `s<slideIndex>-<cNvPr id>` — the scheme+// shapes.ts mints, which is also what makes connector a:stCxn/a:endCxn refs+// resolve without a lookup table. The box-with-text split emits the text half+// as `s<n>-<spId>-t` immediately after its shape (later paints above), welded+// by groupId. Ids are unique per slide only, by design (the morph idiom).++import { readZip, type ZipParts } from './zip.ts'+import {+ NS, parseXml, kid, kids, attr, intAttr, textOf, resolveAlternate, type XElem,+} from './xml.ts'+import { Report } from './report.ts'+import { parseTheme, resolveColor, resolveFillRef } from './theme.ts'+import { resolveFrame, effectivePhType, textDefaults, labeledChain } from './inherit.ts'+import {+ parseRels, parseContentTypes, AssetStore, imageFrom, type Rel, type ContentTypes,+} from './media.ts'+import { textFrom, type TextDeps } from './text.ts'+import { shapeFrom, groupChildren, type ShapeDeps, type GroupFrame } from './shapes.ts'+import {+ EMU_PER_PX, METRIC_SUBSTITUTES,+ type ConvertResult, type OutDoc, type OutSlide, type OutElement, type OutShape,+ type InheritCtx, type ThemeCtx,+} from './types.ts'++const DC = 'http://purl.org/dc/elements/1.1/'+const dec = new TextDecoder()++/** EMU → px, 1/100px — the engine-wide convention media.ts set. */+const px = (emu: number): number => Math.round((emu / EMU_PER_PX) * 100) / 100+const r2 = (v: number): number => Math.round(v * 100) / 100++// --- package plumbing --------------------------------------------------------++function xmlOf(parts: ZipParts, name: string): XElem | undefined {+ const bytes = parts.get(name.replace(/^\//, ''))+ return bytes ? parseXml(dec.decode(bytes)) : undefined+}++/** The .rels for one part ('' = the package root → _rels/.rels). Missing or+ * absent .rels reads as no relationships, never as an error — plenty of+ * valid parts have none. */+function relsOf(parts: ZipParts, partName: string): Map<string, Rel> {+ const slash = partName.lastIndexOf('/')+ const dir = slash < 0 ? '' : partName.slice(0, slash + 1)+ const base = slash < 0 ? partName : partName.slice(slash + 1)+ const xml = xmlOf(parts, `${dir}_rels/${base}.rels`)+ return xml ? parseRels(xml, dir) : new Map()+}++/** First internal relationship whose type ends with `suffix` (the OPC type+ * URIs all share long prefixes; the tail is the discriminator). */+function relOfType(rels: Map<string, Rel>, suffix: string): Rel | undefined {+ for (const r of rels.values()) if (!r.mode && r.type.endsWith(suffix)) return r+ return undefined+}++/** The r:id of a reference element. NOT attr(el, 'id'): p:sldId carries BOTH+ * @id (the slide's number) and @r:id, and attr's exact-name-first match+ * returns the wrong one. */+function rIdOf(el: XElem): string | undefined {+ for (const [k, v] of el.attrs) if (k !== 'id' && k.endsWith(':id')) return v+ return undefined+}++// --- shape bookkeeping -------------------------------------------------------++function cNvPrOf(el: XElem): XElem | undefined {+ for (const c of kids(el)) {+ const cnv = kid(c, NS.p, 'cNvPr')+ if (cnv) return cnv+ }+ return undefined+}++const cNvPrIdOf = (el: XElem): string => {+ const c = cNvPrOf(el)+ return c ? attr(c, 'id') ?? '0' : '0'+}++function whereOf(el: XElem, n: number): string {+ const c = cNvPrOf(el)+ const name = c && attr(c, 'name')+ return `slide ${n} / sp ${name ? `"${name}"` : c ? attr(c, 'id') ?? '?' : '?'}`+}++/** See the header: Choices all require extensions we do not implement, so the+ * resolution set stays empty and every mc lands on its Fallback. */+const MC_NOTHING = new Set<string>()++function flattenMc(children: Array<XElem | string>): XElem[] {+ const out: XElem[] = []+ for (const c of children) {+ if (typeof c === 'string') continue+ if (c.ns === NS.mc && c.local === 'AlternateContent') {+ out.push(...flattenMc(resolveAlternate(c, MC_NOTHING)))+ } else out.push(c)+ }+ return out+}++// --- background --------------------------------------------------------------++const BG_FILLS = new Set(['solidFill', 'gradFill', 'blipFill', 'pattFill', 'grpFill', 'noFill'])++/** Cheapest honest read of a gradient when the target is one colour: the+ * lowest-position stop (the gradient's visual anchor). */+function lowestStop(grad: XElem, theme: ThemeCtx, phClr: string | undefined): string | undefined {+ const lst = kid(grad, NS.a, 'gsLst')+ if (!lst) return undefined+ let best: string | undefined+ let bestPos = Infinity+ for (const gs of kids(lst, NS.a, 'gs')) {+ const pos = intAttr(gs, 'pos')+ const c = resolveColor(gs, theme, phClr)+ if (c && pos < bestPos) { best = c.css; bestPos = pos }+ }+ return best+}++/**+ * slide.background from p:bg, walked slide → layout → master; the FIRST level+ * declaring a p:bg settles the question (a slide-level bg overrides, never+ * merges). bento's background is one colour, so a gradient flattens to its+ * first stop with a report, and a picture background is dropped loudly.+ * Default white — the one colour a missing background actually paints.+ */+function backgroundOf(ctx: InheritCtx, n: number): string {+ const report = ctx.report+ const where = `slide ${n}`+ const levels: Array<{ root: XElem | undefined; from: 'own' | 'layout' | 'master' }> = [+ { root: ctx.slide, from: 'own' },+ { root: ctx.layout, from: 'layout' },+ { root: ctx.master, from: 'master' },+ ]+ for (const { root, from } of levels) {+ const cSld = root && kid(root, NS.p, 'cSld')+ const bg = cSld && kid(cSld, NS.p, 'bg')+ if (!bg) continue++ const bgPr = kid(bg, NS.p, 'bgPr')+ if (bgPr) {+ const fill = kids(bgPr, NS.a).find((k) => BG_FILLS.has(k.local))+ if (!fill || fill.local === 'noFill') {+ report.trace('background', from)+ return '#FFFFFF'+ }+ if (fill.local === 'solidFill') {+ const c = resolveColor(fill, ctx.theme)+ if (c) { report.trace('background', from); return c.css }+ report.add('dropped', 'background-unresolved', where,+ 'slide background colour did not resolve — painted white')+ return '#FFFFFF'+ }+ if (fill.local === 'gradFill') {+ const c = lowestStop(fill, ctx.theme, undefined)+ if (c) {+ report.add('approximated', 'background-approximated', where,+ 'gradient background flattened to its first stop — slide.background is one colour')+ report.trace('background', from)+ return c+ }+ report.add('dropped', 'background-unresolved', where,+ 'gradient background had no resolvable stop — painted white')+ return '#FFFFFF'+ }+ report.add('dropped', 'background-image-dropped', where,+ `a:${fill.local} slide background has no bento counterpart — painted white`)+ return '#FFFFFF'+ }++ const bgRef = kid(bg, NS.p, 'bgRef')+ if (bgRef) {+ const idx = intAttr(bgRef, 'idx')+ if (idx === 0) { report.trace('background', from); return '#FFFFFF' }+ // bgRef's colour child is the phClr; resolveFillRef wants bare hex+ const ph = resolveColor(bgRef, ctx.theme)+ const phClr = ph && ph.css.startsWith('#') ? ph.css : '#FFFFFF'+ const got = resolveFillRef(idx, phClr, ctx.theme)+ if (got) {+ if (got.kind === 'none') { report.trace('background', from); return '#FFFFFF' }+ if (got.kind === 'solid') { report.trace('background', 'theme'); return got.color.css }+ if (got.el.local === 'gradFill') {+ const c = lowestStop(got.el, ctx.theme, got.phClr)+ if (c) {+ report.add('approximated', 'background-approximated', where,+ 'theme gradient background flattened to its first stop — slide.background is one colour')+ report.trace('background', 'theme')+ return c+ }+ }+ }+ report.add('dropped', 'background-unresolved', where,+ `a:bgRef idx="${idx}" did not resolve — painted white`)+ return '#FFFFFF'+ }+ }+ report.trace('background', 'default')+ return '#FFFFFF'+}++// --- notes -------------------------------------------------------------------++/** Plain text from a notesSlide part: the body placeholder(s) only. sldImg is+ * the slide's own thumbnail (census: 14) and sldNum/hdr/ftr/dt are page+ * furniture — none of them are the speaker's words. */+function notesTextOf(notesXml: XElem): string {+ const cSld = kid(notesXml, NS.p, 'cSld')+ const tree = cSld && kid(cSld, NS.p, 'spTree')+ if (!tree) return ''+ const out: string[] = []+ for (const sp of kids(tree, NS.p, 'sp')) {+ let phType = ''+ for (const c of kids(sp)) {+ const nv = kid(c, NS.p, 'nvPr')+ const ph = nv && kid(nv, NS.p, 'ph')+ if (ph) { phType = attr(ph, 'type') ?? ''; break }+ }+ if (phType !== 'body') continue+ const tb = kid(sp, NS.p, 'txBody')+ if (!tb) continue+ const text = kids(tb, NS.a, 'p').map((p) => textOf(p)).join('\n').trim()+ if (text) out.push(text)+ }+ return out.join('\n')+}++// --- misc --------------------------------------------------------------------++const cssFace = (name: string): string => (/[^A-Za-z0-9-]/.test(name) ? `'${name}'` : name)++/** The theme face as a CSS stack: the original first (a machine that has the+ * real font uses it), its metric-compatible substitute second. */+function fontStack(face: string): string {+ const sub = METRIC_SUBSTITUTES[face]+ return sub ? `${cssFace(face)}, ${cssFace(sub)}, sans-serif` : `${cssFace(face)}, sans-serif`+}++function picFlipped(pic: XElem): boolean {+ const spPr = kid(pic, NS.p, 'spPr')+ const xf = spPr && kid(spPr, NS.a, 'xfrm')+ const f = (v: string | undefined): boolean => v === '1' || v === 'true'+ return xf !== undefined && (f(attr(xf, 'flipH')) || f(attr(xf, 'flipV')))+}++function coreTitle(parts: ZipParts, rootRels: Map<string, Rel>): string | undefined {+ const rel = relOfType(rootRels, '/core-properties')+ const core = xmlOf(parts, rel ? rel.target : 'docProps/core.xml')+ if (!core) return undefined+ const t = kid(core, DC, 'title')+ const s = t ? textOf(t).trim() : ''+ return s || undefined+}++/** A theme for packages whose chain is broken: empty scheme, Calibri faces.+ * Lazily built so the module costs nothing to import. */+let emptyThemeCache: ThemeCtx | undefined+const emptyTheme = (): ThemeCtx =>+ (emptyThemeCache ??= parseTheme(parseXml(`<a:theme xmlns:a="${NS.a}"/>`), undefined))++interface MasterBundle { theme: ThemeCtx; themeXml?: XElem }++// --- the conversion ----------------------------------------------------------++/**+ * Convert one .pptx to a bento/slides document. Throws (ZipError / XmlError /+ * Error) only for a package that is not a presentation at all; everything+ * recoverable lands in the report instead.+ */+export async function convertPptx(bytes: Uint8Array): Promise<ConvertResult> {+ const report = new Report()+ const parts = await readZip(bytes)+ const ctRoot = xmlOf(parts, '[Content_Types].xml')+ const types: ContentTypes | undefined = ctRoot ? parseContentTypes(ctRoot) : undefined+ const assets = new AssetStore(parts, types)++ const rootRels = relsOf(parts, '')+ const presPart = relOfType(rootRels, '/officeDocument')?.target ?? 'ppt/presentation.xml'+ const pres = xmlOf(parts, presPart)+ if (!pres) throw new Error('this file is not a PowerPoint package — it has no presentation part')+ const presRels = relsOf(parts, presPart)++ // 12192000×6858000 EMU / 9525 = 1280×720 EXACTLY — converted, never assumed+ // (4:3 decks are 9144000×6858000 → 960×720 through the same arithmetic).+ const sldSz = kid(pres, NS.p, 'sldSz')+ const size = {+ width: Math.round((sldSz ? intAttr(sldSz, 'cx', 12192000) : 12192000) / EMU_PER_PX),+ height: Math.round((sldSz ? intAttr(sldSz, 'cy', 6858000) : 6858000) / EMU_PER_PX),+ }++ const masterCache = new Map<string, MasterBundle>()+ let deckTheme: ThemeCtx | undefined+ let titleText: string | undefined+ const slides: OutSlide[] = []++ const sldIdLst = kid(pres, NS.p, 'sldIdLst')+ const sldIds = sldIdLst ? kids(sldIdLst, NS.p, 'sldId') : []+ let n = 0+ for (const sldId of sldIds) {+ n++ // 1-based SOURCE position — ids stay deterministic even past a bad slide+ const relId = rIdOf(sldId)+ const rel = relId ? presRels.get(relId) : undefined+ const slidePart = rel && !rel.mode ? rel.target : undefined+ const slideXml = slidePart ? xmlOf(parts, slidePart) : undefined+ if (!slidePart || !slideXml) {+ report.add('dropped', 'slide-missing', `slide ${n}`,+ 'a slide named by p:sldIdLst is missing from the package')+ continue+ }+ const slideRels = relsOf(parts, slidePart)++ // ---- the inheritance chain: layout → master → theme, all via rels+ const layoutRel = relOfType(slideRels, '/slideLayout')+ const layoutXml = layoutRel ? xmlOf(parts, layoutRel.target) : undefined+ if (layoutRel && !layoutXml) {+ report.add('dropped', 'part-missing', `slide ${n}`, `layout part missing: ${layoutRel.target}`)+ }+ const layoutRels = layoutXml && layoutRel ? relsOf(parts, layoutRel.target) : new Map<string, Rel>()+ const masterRel = relOfType(layoutRels, '/slideMaster')+ const masterXml = masterRel ? xmlOf(parts, masterRel.target) : undefined+ if (masterRel && !masterXml) {+ report.add('dropped', 'part-missing', `slide ${n}`, `master part missing: ${masterRel.target}`)+ }++ let bundle: MasterBundle = { theme: emptyTheme() }+ if (masterRel && masterXml) {+ const cached = masterCache.get(masterRel.target)+ if (cached) bundle = cached+ else {+ const masterRels = relsOf(parts, masterRel.target)+ const themeRel = relOfType(masterRels, '/theme')+ const themeXml = themeRel ? xmlOf(parts, themeRel.target) : undefined+ if (themeRel && !themeXml) {+ report.add('dropped', 'part-missing', `slide ${n}`, `theme part missing: ${themeRel.target}`)+ }+ bundle = themeXml+ ? { theme: parseTheme(themeXml, kid(masterXml, NS.p, 'clrMap')), themeXml }+ : { theme: emptyTheme() }+ masterCache.set(masterRel.target, bundle)+ }+ }+ // p:clrMapOvr re-routes the SAME scheme for this slide only+ let theme = bundle.theme+ const ovr = kid(slideXml, NS.p, 'clrMapOvr')+ const mapping = ovr && kid(ovr, NS.a, 'overrideClrMapping')+ if (mapping && bundle.themeXml) theme = parseTheme(bundle.themeXml, mapping)+ deckTheme ??= theme++ const ctx: InheritCtx = { slide: slideXml, theme, report }+ if (layoutXml) ctx.layout = layoutXml+ if (masterXml) ctx.master = masterXml++ // ---- elements, in spTree document order (z-order in both formats)+ const cSldEl = kid(slideXml, NS.p, 'cSld')+ const spTree = cSldEl && kid(cSldEl, NS.p, 'spTree')+ const elements: OutElement[] = []++ // every cNvPr id on the slide — connector refs outside this set are dangling+ const spIds = new Set<string>()+ const collectIds = (list: Array<XElem | string>): void => {+ for (const e of flattenMc(list)) {+ if (e.ns !== NS.p) continue+ if (e.local === 'grpSp') collectIds(e.children)+ else if (e.local === 'sp' || e.local === 'pic' || e.local === 'cxnSp' || e.local === 'graphicFrame') {+ spIds.add(cNvPrIdOf(e))+ }+ }+ }+ if (spTree) collectIds(spTree.children)++ let refitPending = false+ const baseTextDeps: TextDeps = {+ effectivePhType, textDefaults, resolveFrame, labeledChain, resolveColor,+ needsRefit: () => { refitPending = true },+ }++ const emit = (el: XElem, frame?: GroupFrame, groupId?: string): void => {+ if (el.ns !== NS.p) return+ const local = el.local++ if (local === 'sp' || local === 'cxnSp') {+ const spId = cNvPrIdOf(el)+ const deps: ShapeDeps = { slideIndex: n, spIds }+ if (frame) deps.frame = frame+ if (groupId) deps.groupId = groupId+ const res = shapeFrom(el, ctx, deps)+ if (res) elements.push(res.shape)+ if (local === 'cxnSp') return // connectors carry no txBody++ // an untitled package is named by its first title placeholder's text+ if (titleText === undefined) {+ const t = effectivePhType(el, ctx)+ if (t === 'title' || t === 'ctrTitle') {+ const tb = kid(el, NS.p, 'txBody')+ const s = tb ? textOf(tb).replace(/\s+/g, ' ').trim() : ''+ if (s) titleText = s+ }+ }++ refitPending = false+ // group members carry their COMPOSED frame; textFrom must see it, not+ // the leaf's own local-coordinate xfrm+ const tdeps: TextDeps = frame+ ? { ...baseTextDeps, resolveFrame: () => ({ ...frame, from: 'own' as const }) }+ : baseTextDeps+ const text = textFrom(el, ctx, tdeps)+ if (text) {+ if (res) {+ // the box-with-text split: text right after its shape (later+ // paints above), welded by groupId so they move as one object+ const gid = res.textGroupId ?? res.shape.groupId ?? `s${n}-${spId}-g`+ res.shape.groupId = gid+ text.groupId = gid+ text.id = `s${n}-${spId}-t`+ } else {+ text.id = `s${n}-${spId}`+ if (groupId) text.groupId = groupId+ }+ elements.push(text)+ if (refitPending) {+ report.add('approximated', 'text-needs-refit', `slide ${n}`,+ 'text box relies on autofit (or substituted font metrics) — the host must re-measure through the shell')+ }+ }+ return+ }++ if (local === 'pic') {+ const where = whereOf(el, n)+ const img = imageFrom(el, ctx, slideRels, assets, where)+ if (!img) return+ img.id = `s${n}-${cNvPrIdOf(el)}`+ if (frame) {+ img.x = px(frame.x); img.y = px(frame.y)+ img.w = px(frame.w); img.h = px(frame.h)+ img.rotation = r2(frame.rotation)+ } else if (img.w === 0 && img.h === 0) {+ // picture placeholder (census: 122 p:ph type=pic) — the frame lives+ // up the chain, exactly as for shapes+ const fr = resolveFrame(el, ctx)+ img.x = px(fr.x); img.y = px(fr.y)+ img.w = px(fr.w); img.h = px(fr.h)+ img.rotation = r2(fr.rotation)+ }+ if (groupId) img.groupId = groupId+ if (frame ? frame.flipH || frame.flipV : picFlipped(el)) {+ report.add('approximated', 'flip-dropped', where,+ 'flipH/flipV on a picture has no bento field — rendered unflipped')+ }+ elements.push(img)+ return+ }++ if (local === 'grpSp') {+ const deps: ShapeDeps = { slideIndex: n, spIds }+ if (groupId) deps.groupId = groupId+ for (const leaf of groupChildren(el, ctx, deps)) emit(leaf.el, leaf.frame, leaf.groupId)+ return+ }++ if (local === 'graphicFrame') {+ // tables and charts are follow-up modules: a placeholder box marks the+ // spot and the report says so HONESTLY — 'not yet', not 'unsupported'+ const where = whereOf(el, n)+ const graphic = kid(el, NS.a, 'graphic')+ const gd = graphic && kid(graphic, NS.a, 'graphicData')+ if (gd && kid(gd, NS.a, 'tbl')) {+ report.add('dropped', 'table-not-yet', where,+ 'tables are not imported yet (follow-up module) — a placeholder box marks the spot')+ } else if (gd && kids(gd).some((c) => c.ns === NS.c && c.local === 'chart')) {+ report.add('dropped', 'chart-not-yet', where,+ 'charts are not imported yet (follow-up module) — a placeholder box marks the spot')+ } else {+ report.add('dropped', 'graphic-dropped', where,+ `graphicFrame content (${gd ? attr(gd, 'uri') ?? 'unknown' : 'empty'}) has no importer — a placeholder box marks the spot`)+ }+ const fr: GroupFrame = frame ?? resolveFrame(el, ctx)+ const box: OutShape = {+ id: `s${n}-${cNvPrIdOf(el)}`, type: 'shape', shape: 'rect',+ x: px(fr.x), y: px(fr.y), w: px(fr.w), h: px(fr.h),+ rotation: r2(fr.rotation), opacity: 1,+ fill: 'transparent', stroke: '#9AA3AD', strokeWidth: 1, radius: 0,+ strokeStyle: 'dashed',+ }+ if (groupId) box.groupId = groupId+ elements.push(box)+ }+ }+ if (spTree) for (const el of flattenMc(spTree.children)) emit(el)++ // ---- notes+ let notes = ''+ const notesRel = relOfType(slideRels, '/notesSlide')+ if (notesRel) {+ const notesXml = xmlOf(parts, notesRel.target)+ if (notesXml) notes = notesTextOf(notesXml)+ else report.add('dropped', 'part-missing', `slide ${n}`, `notes part missing: ${notesRel.target}`)+ }++ const slide: OutSlide = {+ id: `s${n}`,+ name: (cSldEl && attr(cSldEl, 'name')) || `Slide ${n}`,+ background: backgroundOf(ctx, n),+ transition: 'none',+ notes,+ elements,+ }+ if (attr(slideXml, 'show') === '0') slide.hidden = true+ slides.push(slide)+ }++ // parseDoc refuses a slideless document; a blank page is the honest minimum+ if (slides.length === 0) {+ report.add('dropped', 'deck-empty', 'deck',+ 'the package names no importable slides — one blank slide emitted so the document loads')+ slides.push({+ id: 's1', name: 'Slide 1', background: '#FFFFFF',+ transition: 'none', notes: '', elements: [],+ })+ }++ const scheme = deckTheme ? deckTheme.scheme : {}+ const doc: OutDoc = {+ format: 'bento/slides',+ version: '1.0.0',+ title: coreTitle(parts, rootRels) ?? titleText ?? 'Imported deck',+ size,+ theme: {+ background: scheme['bg1'] ?? '#FFFFFF',+ color: scheme['tx1'] ?? '#000000',+ accent: scheme['accent1'] ?? scheme['tx1'] ?? '#000000',+ fontFamily: fontStack(deckTheme ? deckTheme.minorFont : 'Calibri'),+ },+ assets: assets.assets(),+ fonts: null,+ slides,+ }+ return { doc, report: report.build() }+}diff --git a/kernel/src/convert/report.ts b/kernel/src/convert/report.tsnew file mode 100644index 00000000..ec007ce8--- /dev/null+++ b/kernel/src/convert/report.ts@@ -0,0 +1,72 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+//+// The fidelity report — the spine of the convert engine.+//+// Every conversion emits one. It is not logging: it is the product's honesty.+// Every converter in the world silently drops things; this one says what was+// carried, what was approximated, and what was dropped, each entry coded and+// pointing at where. Its first job is TRUST — a chart whose blank cells became+// zeros changes what the slide asserts, and must be reported whether or not+// anyone repairs it. Its second job is to be a work list for assisted repair,+// which only touches a named allowlist of judgement-shaped codes.+//+// Provenance is a hard requirement, not a nicety. ~91% of the colour in real+// decks resolves through a six-source cascade that fails SILENTLY — a+// backwards clrMap still renders, just dark-on-dark — so every resolved value+// records which level supplied it, and the report tallies the classes. A human+// then spot-checks "1,700 fills came from the theme" rather than each fill.++/** Which cascade level supplied a resolved value. */+export type Provenance = 'own' | 'layout' | 'master' | 'theme' | 'default'++export type Verdict = 'carried' | 'approximated' | 'dropped'++export interface FidelityEntry {+ /** stable kebab-case code, e.g. 'image-crop-dropped' */+ code: string+ verdict: Verdict+ /** where in the SOURCE, e.g. 'slide 4' or 'slide 4 / sp 12' */+ where: string+ /** one line a human can act on; written once per code, counted thereafter */+ detail: string+ /** occurrences folded into this entry (same code + where collapses) */+ count: number+}++export interface FidelityReport {+ entries: FidelityEntry[]+ counts: Record<Verdict, number>+ /** resolved-value provenance tallies, keyed `<kind>:<level>` e.g. 'fill:theme' */+ provenance: Record<string, number>+}++export class Report {+ private entries = new Map<string, FidelityEntry>()+ private prov = new Map<string, number>()++ /**+ * Record one finding. Same (code, where) folds into a count — a deck with+ * forty cropped images is one fact per slide, not forty alerts (an instinct+ * adopted from PR #88's exporter, which learned it the noisy way).+ */+ add(verdict: Verdict, code: string, where: string, detail: string): void {+ const key = `${code}${where}`+ const cur = this.entries.get(key)+ if (cur) cur.count+++ else this.entries.set(key, { code, verdict, where, detail, count: 1 })+ }++ /** Tally where a resolved value came from, e.g. trace('fill', 'theme'). */+ trace(kind: string, level: Provenance): void {+ const key = `${kind}:${level}`+ this.prov.set(key, (this.prov.get(key) ?? 0) + 1)+ }++ build(): FidelityReport {+ const entries = [...this.entries.values()]+ const counts: Record<Verdict, number> = { carried: 0, approximated: 0, dropped: 0 }+ for (const e of entries) counts[e.verdict] += e.count+ return { entries, counts, provenance: Object.fromEntries(this.prov) }+ }+}diff --git a/kernel/src/convert/shapes.ts b/kernel/src/convert/shapes.tsnew file mode 100644index 00000000..c1ccad08--- /dev/null+++ b/kernel/src/convert/shapes.ts@@ -0,0 +1,865 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+//+// Geometry, fills and groups: p:sp / p:cxnSp / p:grpSp → OutShape.+//+// The census makes this module's budget clear: the entire preset vocabulary of+// six real decks is 12 names, a:custGeom is ZERO, and rect/roundRect/ellipse/+// line cover 95.9% of 4,927 shapes. So there is no geometry engine here — a+// map for the exact presets, three-and-a-half path generators for the rest+// (chevron 89, upArrowCallout 35, round2SameRect 32, bentConnector2/3/4 27),+// and 'rect' + a report for anything outside the census.+//+// Where the actual work lives, per the spike:+//+// - 1,727 shapes carry NO local fill: it comes from p:style's a:fillRef into+// the theme's fillStyleLst with phClr substituted — read only spPr and+// they render unfilled with no error to notice. Same for a:lnRef strokes.+// - An EMPTY <a:effectLst/> is an OVERRIDE that cancels an inherited effect;+// only a chain level with no effectLst at all defers downward. Presence+// and emptiness are therefore distinguished when walking the chain.+// - Bento line shapes take their colour from `fill`, not `stroke` (the+// stroke attr is what morphs tween) — shape 'line' gets BOTH set.+// - flipH/flipV (68+22 slide-level uses in the re-census) have no bento+// field. Where the flip is free it is CONSUMED exactly: line endpoints+// swap, synthesized path coordinates mirror, a flipV triangle becomes a+// path, a gradient angle mirrors. Only a flip nothing can absorb is+// reported ('flip-dropped').+//+// ID SCHEME (integrator contract): a shape's element id is+// `s<slideIndex>-<cNvPr id>` — deterministic, so connector a:stCxn/a:endCxn+// refs resolve WITHOUT a lookup table (deps.spIds only validates existence;+// a dangling ref drops that end with a report). A source group's members share+// groupId `s<slideIndex>-g<cNvPr id>`; a filled box with text in it (the+// spike's ~1,000-per-corpus split case) reserves `s<slideIndex>-<spId>-g` —+// see ShapeResult.textGroupId. The morph/identity pass may rewrite ids later;+// within one slide's conversion they are stable.++import { NS, kid, kids, attr, intAttr, textOf, descendants, type XElem } from './xml.ts'+import {+ EMU_PER_PX,+ type InheritCtx, type OutShape, type OutGradient, type OutShadow,+} from './types.ts'+import { resolveColor, resolveFillRef, resolveLnRef, type ColorResult } from './theme.ts'+import { resolveFrame, labeledChain } from './inherit.ts'+import type { Provenance } from './report.ts'++// --- small arithmetic --------------------------------------------------------++/** EMU → px, 1/100px precision (the engine-wide convention media.ts set). */+const px = (emu: number): number => Math.round((emu / EMU_PER_PX) * 100) / 100+const r2 = (v: number): number => Math.round(v * 100) / 100+const pin = (lo: number, v: number, hi: number): number => Math.min(Math.max(v, lo), hi)+const DEG = Math.PI / 180++/** Report `where` — slide plus the shape's authored name. */+function whereOf(sp: XElem, slideIndex: number): string {+ for (const c of kids(sp)) {+ const cnv = kid(c, NS.p, 'cNvPr')+ if (cnv) {+ const name = attr(cnv, 'name')+ return `slide ${slideIndex} / sp ${name ? `"${name}"` : attr(cnv, 'id') ?? '?'}`+ }+ }+ return `slide ${slideIndex} / sp`+}++function cNvPrId(sp: XElem): string {+ for (const c of kids(sp)) {+ const cnv = kid(c, NS.p, 'cNvPr')+ if (cnv) return attr(cnv, 'id') ?? '0'+ }+ return '0'+}++// --- public types ------------------------------------------------------------++/** A frame in EMU + degrees — resolveFrame's shape, minus provenance. */+export interface GroupFrame {+ x: number; y: number; w: number; h: number+ rotation: number+ flipH: boolean+ flipV: boolean+}++export interface ShapeDeps {+ /** 1-based slide position — the id scheme needs it */+ slideIndex: number+ /** cNvPr ids present on the slide; connector refs outside it are dangling */+ spIds?: Set<string>+ /** absolute frame override (EMU) — groupChildren computed it; when set the+ * placeholder chain walk is skipped */+ frame?: GroupFrame+ /** group membership — groupChildren minted it */+ groupId?: string+}++export interface ShapeResult {+ shape: OutShape+ /**+ * Set when the sp ALSO carries text (the box-with-text split): the+ * integrator must emit the text element with THIS groupId, placed+ * immediately AFTER the shape in the element array — later paints above,+ * so the text sits on the box. The shape's own groupId is already set.+ */+ textGroupId?: string+}++// --- adjust values -----------------------------------------------------------++/** a:avLst gd name→val. An EMPTY <a:avLst/> (the overwhelmingly common form)+ * reads the same as an absent one: every preset default applies. */+function adjOf(geom: XElem | undefined): Map<string, number> {+ const out = new Map<string, number>()+ const av = geom && kid(geom, NS.a, 'avLst')+ if (!av) return out+ for (const gd of kids(av, NS.a, 'gd')) {+ const name = attr(gd, 'name')+ const fmla = attr(gd, 'fmla') ?? ''+ const m = /^val (-?\d+)$/.exec(fmla)+ if (name && m) out.set(name, parseInt(m[1], 10))+ }+ return out+}++// --- path synthesis ----------------------------------------------------------++// Paths are synthesized at the element's REAL px size (pathBox = [0,0,w,h])+// rather than a fixed 100×100: preset guides scale by min(w,h), so a fixed+// box would bake the wrong aspect into every non-square shape. pathBox+// stretches on later resize, exactly like any bento path.++type Seg =+ | { c: 'M' | 'L'; x: number; y: number }+ | { c: 'A'; r: number; x: number; y: number }+ | { c: 'Z' }++/** Serialize, baking flips into the coordinates. Mirroring across ONE axis+ * reverses arc orientation, so the sweep flag toggles with flipH xor flipV. */+function serializeSegs(segs: Seg[], w: number, h: number, flipH: boolean, flipV: boolean): string {+ const fx = (x: number) => r2(flipH ? w - x : x)+ const fy = (y: number) => r2(flipV ? h - y : y)+ const sweep = flipH !== flipV ? 0 : 1+ return segs+ .map((s) => s.c === 'Z' ? 'Z'+ : s.c === 'A' ? `A${r2(s.r)} ${r2(s.r)} 0 0 ${sweep} ${fx(s.x)} ${fy(s.y)}`+ : `${s.c}${fx(s.x)} ${fy(s.y)}`)+ .join(' ')+}++/** The preset generators. Guides transcribed from ECMA-376's+ * presetShapeDefinitions (ss = min(w,h), pin = the spec's pin). */+function presetSegs(prst: string, w: number, h: number, adj: Map<string, number>): Seg[] | undefined {+ const ss = Math.min(w, h)+ const a = (name: string, dflt: number) => adj.get(name) ?? dflt+ switch (prst) {+ case 'chevron': {+ const x1 = ss * pin(0, a('adj', 50000), (100000 * w) / ss) / 100000+ return [+ { c: 'M', x: 0, y: 0 }, { c: 'L', x: w - x1, y: 0 }, { c: 'L', x: w, y: h / 2 },+ { c: 'L', x: w - x1, y: h }, { c: 'L', x: 0, y: h }, { c: 'L', x: x1, y: h / 2 },+ { c: 'Z' },+ ]+ }+ case 'upArrowCallout': {+ const a2 = pin(0, a('adj2', 25000), (50000 * w) / ss)+ const a1 = pin(0, a('adj1', 25000), a2 * 2)+ const a3 = pin(0, a('adj3', 25000), (100000 * h) / ss)+ const a4 = pin(0, a('adj4', 64977), 100000 - (a3 * ss) / h)+ const dx1 = (ss * a2) / 100000, dx2 = (ss * a1) / 200000+ const y1 = (ss * a3) / 100000, y2 = h - (h * a4) / 100000+ const hc = w / 2+ return [+ { c: 'M', x: 0, y: y2 }, { c: 'L', x: hc - dx2, y: y2 }, { c: 'L', x: hc - dx2, y: y1 },+ { c: 'L', x: hc - dx1, y: y1 }, { c: 'L', x: hc, y: 0 }, { c: 'L', x: hc + dx1, y: y1 },+ { c: 'L', x: hc + dx2, y: y1 }, { c: 'L', x: hc + dx2, y: y2 }, { c: 'L', x: w, y: y2 },+ { c: 'L', x: w, y: h }, { c: 'L', x: 0, y: h }, { c: 'Z' },+ ]+ }+ case 'round2SameRect': {+ // top pair rounded by adj1, bottom pair by adj2 (default square)+ const r1 = r2((ss * pin(0, a('adj1', 16667), 50000)) / 100000)+ const rb = r2((ss * pin(0, a('adj2', 0), 50000)) / 100000)+ const segs: Seg[] = [{ c: 'M', x: r1, y: 0 }, { c: 'L', x: w - r1, y: 0 }]+ if (r1 > 0) segs.push({ c: 'A', r: r1, x: w, y: r1 })+ segs.push({ c: 'L', x: w, y: h - rb })+ if (rb > 0) segs.push({ c: 'A', r: rb, x: w - rb, y: h })+ segs.push({ c: 'L', x: rb, y: h })+ if (rb > 0) segs.push({ c: 'A', r: rb, x: 0, y: h - rb })+ segs.push({ c: 'L', x: 0, y: r1 })+ if (r1 > 0) segs.push({ c: 'A', r: r1, x: r1, y: 0 })+ segs.push({ c: 'Z' })+ return segs+ }+ case 'bentConnector2':+ return [{ c: 'M', x: 0, y: 0 }, { c: 'L', x: w, y: 0 }, { c: 'L', x: w, y: h }]+ case 'bentConnector3': {+ const x1 = (w * a('adj1', 50000)) / 100000+ return [+ { c: 'M', x: 0, y: 0 }, { c: 'L', x: x1, y: 0 },+ { c: 'L', x: x1, y: h }, { c: 'L', x: w, y: h },+ ]+ }+ case 'bentConnector4': {+ const x1 = (w * a('adj1', 50000)) / 100000+ const y1 = (h * a('adj2', 50000)) / 100000+ return [+ { c: 'M', x: 0, y: 0 }, { c: 'L', x: x1, y: 0 }, { c: 'L', x: x1, y: y1 },+ { c: 'L', x: w, y: y1 }, { c: 'L', x: w, y: h },+ ]+ }+ default:+ return undefined+ }+}++/** Bent connectors are open stroked polylines — never filled, no tip markers+ * (render.ts only puts markers on shape 'line'). */+const OPEN_PATHS = new Set(['bentConnector2', 'bentConnector3', 'bentConnector4'])++// --- fills -------------------------------------------------------------------++const FILL_LOCALS = new Set(['solidFill', 'gradFill', 'blipFill', 'pattFill', 'grpFill', 'noFill'])++/** First fill element up the placeholder chain — a nearer noFill is a real+ * declaration, so ANY fill child stops the walk. */+function chainFill(sp: XElem, ctx: InheritCtx): { el: XElem; from: Provenance } | undefined {+ for (const link of labeledChain(sp, ctx)) {+ const spPr = kid(link.el, NS.p, 'spPr')+ const f = spPr && kids(spPr, NS.a).find((k) => FILL_LOCALS.has(k.local))+ if (f) return { el: f, from: link.from }+ }+ return undefined+}++/** First p:style up the chain (a layout placeholder can carry one too). */+function chainStyle(sp: XElem, ctx: InheritCtx): XElem | undefined {+ for (const link of labeledChain(sp, ctx)) {+ const st = kid(link.el, NS.p, 'style')+ if (st) return st+ }+ return undefined+}++/**+ * The phClr a style ref substitutes, as the '#RRGGBB' resolveFillRef requires.+ * Style ref colours with alpha do not occur in the census (theme.ts's note);+ * if one shows up the alpha is stripped and reported rather than failing the+ * whole fill.+ */+function phClrOf(ref: XElem, ctx: InheritCtx, where: string): string {+ const c = resolveColor(ref, ctx.theme)+ if (!c) {+ ctx.report.add('dropped', 'style-color-unresolved', where,+ 'p:style reference colour did not resolve — phClr substituted as black')+ return '#000000'+ }+ if (c.css.startsWith('#')) return c.css+ const m = /^rgba\((\d+),(\d+),(\d+),/.exec(c.css)+ if (m) {+ ctx.report.add('approximated', 'phclr-alpha-dropped', where,+ 'style reference colour carries alpha — dropped for phClr substitution')+ const h2 = (v: string) => parseInt(v, 10).toString(16).padStart(2, '0').toUpperCase()+ return `#${h2(m[1])}${h2(m[2])}${h2(m[3])}`+ }+ return '#000000'+}++/**+ * a:gradFill → bento GradientFill. ANGLES: OOXML a:lin@ang is 60,000ths of a+ * degree clockwise from 3 o'clock in a y-down space — ang 0 runs left→right,+ * 5400000 (90°) runs top→bottom. Bento/CSS convention (render.ts+ * gradientLineCoords): 0deg = bottom→top, 90deg = left→right, 180deg =+ * top→bottom. Both rotate the same way, offset a quarter turn:+ * css = ooxmlDeg + 90. (The tempting straight read — 5400000 → 90deg CSS —+ * paints every vertical gradient sideways; the rig pins 5400000 → 180.)+ */+function gradientFrom(g: XElem, ctx: InheritCtx, phClr: string | undefined, where: string): OutGradient | undefined {+ const gsLst = kid(g, NS.a, 'gsLst')+ const stops: Array<{ at: number; color: string }> = []+ if (gsLst) {+ for (const gs of kids(gsLst, NS.a, 'gs')) {+ const color = resolveColor(gs, ctx.theme, phClr)+ if (!color) {+ ctx.report.add('dropped', 'gradient-stop-unresolved', where,+ 'a gradient stop colour did not resolve and was skipped')+ continue+ }+ stops.push({ at: pin(0, intAttr(gs, 'pos') / 100000, 1), color: color.css })+ }+ }+ stops.sort((s1, s2) => s1.at - s2.at)+ if (stops.length < 2) return undefined++ let angle: number+ const lin = kid(g, NS.a, 'lin')+ if (lin) angle = ((intAttr(lin, 'ang') / 60000 + 90) % 360 + 360) % 360+ else if (kid(g, NS.a, 'path')) {+ ctx.report.add('approximated', 'radial-gradient-linearized', where,+ 'radial/path gradient approximated as a vertical linear gradient')+ angle = 180+ } else angle = 90 // no a:lin: OOXML's implicit ang 0, left→right+ return { angle, stops }+}++interface FillOut {+ fill: string+ gradient?: OutGradient+ /** resolution FAILED (reported) — distinct from an intentional noFill; a+ * failed shape still emits so the report entry has something to point at */+ failed: boolean+}++function resolveShapeFill(sp: XElem, ctx: InheritCtx, style: XElem | undefined, where: string): FillOut {+ const own = chainFill(sp, ctx)+ if (own) {+ switch (own.el.local) {+ case 'noFill':+ ctx.report.trace('fill', own.from)+ return { fill: 'transparent', failed: false }+ case 'solidFill': {+ const c = resolveColor(own.el, ctx.theme)+ if (!c) break+ ctx.report.trace('fill', own.from === 'own' ? c.from : own.from)+ return { fill: c.css, failed: false }+ }+ case 'gradFill': {+ const g = gradientFrom(own.el, ctx, undefined, where)+ if (!g) break+ ctx.report.trace('fill', own.from)+ // solid fallback: the last stop (bento keeps `fill` beneath a gradient)+ return { fill: g.stops[g.stops.length - 1].color, gradient: g, failed: false }+ }+ case 'blipFill':+ ctx.report.add('dropped', 'picture-fill-dropped', where,+ 'picture fill on a shape has no bento counterpart — filled transparent')+ return { fill: 'transparent', failed: true }+ default: // pattFill / grpFill: 0/6 in the census+ ctx.report.add('dropped', 'fill-unsupported', where,+ `a:${own.el.local} has no bento counterpart — filled transparent`)+ return { fill: 'transparent', failed: true }+ }+ ctx.report.add('dropped', 'fill-unresolved', where,+ 'fill colour did not resolve — filled transparent')+ return { fill: 'transparent', failed: true }+ }++ // no fill element anywhere up the chain: the style matrix (1,727 census+ // shapes live or die on this walk)+ const ref = style && kid(style, NS.a, 'fillRef')+ if (ref) {+ const idx = intAttr(ref, 'idx')+ const got = resolveFillRef(idx, phClrOf(ref, ctx, where), ctx.theme)+ if (!got) {+ ctx.report.add('dropped', 'fill-unresolved', where,+ `a:fillRef idx="${idx}" points outside the theme's fill styles — filled transparent`)+ return { fill: 'transparent', failed: true }+ }+ if (got.kind === 'none') return { fill: 'transparent', failed: false }+ if (got.kind === 'solid') {+ ctx.report.trace('fill', 'theme')+ return { fill: got.color.css, failed: false }+ }+ // 'other': the raw fillStyleLst entry — gradFill here, blipFill never+ // (theme bg image styles are not shape styles in practice)+ if (got.el.local === 'gradFill') {+ const g = gradientFrom(got.el, ctx, got.phClr, where)+ if (g) {+ ctx.report.trace('fill', 'theme')+ return { fill: g.stops[g.stops.length - 1].color, gradient: g, failed: false }+ }+ }+ ctx.report.add('dropped', 'fill-unresolved', where,+ `theme fill style ${idx} (a:${got.el.local}) did not resolve — filled transparent`)+ return { fill: 'transparent', failed: true }+ }++ ctx.report.trace('fill', 'default')+ return { fill: 'transparent', failed: false }+}++// --- strokes -----------------------------------------------------------------++interface LnOut {+ color?: ColorResult+ widthPx: number+ style: 'solid' | 'dashed' | 'dotted'+ start: 'none' | 'arrow' | 'dot' | 'bar'+ end: 'none' | 'arrow' | 'dot' | 'bar'+ failed: boolean+}++const NO_LINE: LnOut = { widthPx: 0, style: 'solid', start: 'none', end: 'none', failed: false }++const dashOf = (v: string | undefined): LnOut['style'] =>+ v === undefined || v === 'solid' ? 'solid' : v === 'dot' || v === 'sysDot' ? 'dotted' : 'dashed'++const tipOf = (v: string | undefined): LnOut['start'] =>+ v === 'triangle' || v === 'arrow' || v === 'stealth' ? 'arrow'+ : v === 'oval' || v === 'diamond' ? 'dot' : 'none'++function chainLn(sp: XElem, ctx: InheritCtx): { el: XElem; from: Provenance } | undefined {+ for (const link of labeledChain(sp, ctx)) {+ const spPr = kid(link.el, NS.p, 'spPr')+ const ln = spPr && kid(spPr, NS.a, 'ln')+ if (ln) return { el: ln, from: link.from }+ }+ return undefined+}++/**+ * The stroke: a local a:ln overrides per-attribute over the lnRef style base+ * (width/dash/tips read local-first), colour precedence local solidFill →+ * lnRef's pre-resolved colour → black (DrawingML's documented line default —+ * an a:ln with no fill child still draws).+ */+function resolveStroke(sp: XElem, ctx: InheritCtx, style: XElem | undefined, where: string): LnOut {+ const own = chainLn(sp, ctx)+ const ref = style && kid(style, NS.a, 'lnRef')+ let styleLn: XElem | undefined+ let styleColor: ColorResult | undefined+ if (ref) {+ const idx = intAttr(ref, 'idx')+ const got = resolveLnRef(idx, phClrOf(ref, ctx, where), ctx.theme)+ if (got === undefined && idx > 0) {+ ctx.report.add('dropped', 'stroke-unresolved', where,+ `a:lnRef idx="${idx}" points outside the theme's line styles — no stroke`)+ } else if (got && got.kind === 'ln') {+ styleLn = got.ln+ styleColor = got.color+ if (!styleColor && kid(got.ln, NS.a, 'gradFill')) {+ const g = gradientFrom(kid(got.ln, NS.a, 'gradFill')!, ctx, got.phClr, where)+ if (g) {+ styleColor = { css: g.stops[0].color, alpha: 1, from: 'theme' }+ ctx.report.add('approximated', 'gradient-stroke-approximated', where,+ 'gradient stroke flattened to its first stop colour')+ }+ }+ }+ }+ if (!own && !styleLn) return NO_LINE++ const base = own?.el+ const pick = (name: string): string | undefined =>+ (base && attr(base, name)) ?? (styleLn && attr(styleLn, name))+ const pickKid = (local: string): XElem | undefined =>+ (base && kid(base, NS.a, local)) ?? (styleLn && kid(styleLn, NS.a, local))++ // explicit noFill on the nearest ln = no outline, full stop+ if (base && kid(base, NS.a, 'noFill')) return NO_LINE++ const wAttr = pick('w')+ const widthPx = px(wAttr !== undefined ? parseInt(wAttr, 10) : 9525) // OOXML default: 0.75pt++ let color: ColorResult | undefined+ let failed = false+ const ownFill = base && kid(base, NS.a, 'solidFill')+ if (ownFill) {+ color = resolveColor(ownFill, ctx.theme)+ if (!color) {+ ctx.report.add('dropped', 'stroke-unresolved', where,+ 'stroke colour did not resolve — no stroke painted')+ failed = true+ } else ctx.report.trace('stroke', own ? (own.from === 'own' ? color.from : own.from) : 'theme')+ } else if (base && kid(base, NS.a, 'gradFill')) {+ const g = gradientFrom(kid(base, NS.a, 'gradFill')!, ctx, undefined, where)+ if (g) {+ color = { css: g.stops[0].color, alpha: 1, from: 'own' }+ ctx.report.add('approximated', 'gradient-stroke-approximated', where,+ 'gradient stroke flattened to its first stop colour')+ } else failed = true+ } else if (styleColor) {+ color = styleColor+ ctx.report.trace('stroke', 'theme')+ } else {+ color = { css: '#000000', alpha: 1, from: 'own' }+ ctx.report.trace('stroke', 'default')+ }++ const dash = pickKid('prstDash')+ const head = pickKid('headEnd')+ const tail = pickKid('tailEnd')+ const out: LnOut = {+ widthPx,+ style: dashOf(dash ? attr(dash, 'val') : undefined),+ start: tipOf(head ? attr(head, 'type') : undefined),+ end: tipOf(tail ? attr(tail, 'type') : undefined),+ failed,+ }+ if (color) out.color = color+ return out+}++// --- effects -----------------------------------------------------------------++/**+ * The chain walk distinguishes PRESENT-BUT-EMPTY from ABSENT (the spike trap):+ * the nearest level carrying an a:effectLst element wins whole — an empty one+ * is an override cancelling an inherited shadow, only a level with no+ * effectLst at all defers to the next.+ */+function resolveShadow(sp: XElem, ctx: InheritCtx, where: string): OutShadow | undefined {+ for (const link of labeledChain(sp, ctx)) {+ const spPr = kid(link.el, NS.p, 'spPr')+ const lst = spPr && kid(spPr, NS.a, 'effectLst')+ if (!lst) continue+ const shdw = kid(lst, NS.a, 'outerShdw')+ for (const other of kids(lst, NS.a)) {+ if (other.local !== 'outerShdw') {+ ctx.report.add('dropped', 'effect-dropped', where,+ `a:${other.local} has no bento counterpart`)+ }+ }+ if (!shdw) return undefined // declared list without outerShdw = no shadow+ const color = resolveColor(shdw, ctx.theme)+ if (!color) {+ ctx.report.add('dropped', 'shadow-color-unresolved', where,+ 'outer shadow colour did not resolve — shadow dropped')+ return undefined+ }+ const dist = px(intAttr(shdw, 'dist'))+ const dir = (intAttr(shdw, 'dir') / 60000) * DEG // clockwise from 3 o'clock, y-down — matches CSS offsets+ return {+ x: r2(Math.cos(dir) * dist),+ y: r2(Math.sin(dir) * dist),+ blur: px(intAttr(shdw, 'blurRad')),+ color: color.css,+ }+ }+ return undefined+}++// --- shapeFrom ---------------------------------------------------------------++/** First prstGeom (or custGeom) up the chain — ~513 census shapes carry no+ * geometry of their own and read the layout placeholder's. */+function chainGeom(sp: XElem, ctx: InheritCtx): XElem | undefined {+ for (const link of labeledChain(sp, ctx)) {+ const spPr = kid(link.el, NS.p, 'spPr')+ const g = spPr && (kid(spPr, NS.a, 'prstGeom') ?? kid(spPr, NS.a, 'custGeom'))+ if (g) return g+ }+ return undefined+}++function hasTextContent(sp: XElem): boolean {+ const tb = kid(sp, NS.p, 'txBody')+ if (!tb) return false+ return textOf(tb).trim() !== '' || descendants(tb, NS.a, 'fld').length > 0+}++/** Mirror a CSS-convention gradient angle: flips a symmetric shape cannot+ * express still move its gradient, and that part is free to keep exact. */+function mirrorAngle(angle: number, flipH: boolean, flipV: boolean): number {+ let out = angle+ if (flipH) out = (360 - out) % 360+ if (flipV) out = ((180 - out) % 360 + 360) % 360+ return out+}++/**+ * Convert one p:sp or p:cxnSp. Returns undefined for INVISIBLE geometry — the+ * bare text box (noFill, no stroke, no shadow), whose txBody the text module+ * carries alone. A shape whose fill/stroke FAILED to resolve still emits (the+ * report entry needs an element to point at); an intentional noFill does not.+ */+export function shapeFrom(sp: XElem, ctx: InheritCtx, deps: ShapeDeps): ShapeResult | undefined {+ const where = whereOf(sp, deps.slideIndex)+ const spId = cNvPrId(sp)+ const fr = deps.frame ?? resolveFrame(sp, ctx)+ const x = px(fr.x), y = px(fr.y), w = px(fr.w), h = px(fr.h)+ let rotation = r2(fr.rotation)+ let { flipH, flipV } = fr++ const geom = chainGeom(sp, ctx)+ let prst = geom && geom.local === 'prstGeom' ? attr(geom, 'prst') ?? 'rect' : 'rect'+ if (geom && geom.local === 'custGeom') {+ // 0/6 in the census — approximated loudly, never parsed+ ctx.report.add('approximated', 'shape-approximated', where,+ 'a:custGeom approximated as a rectangle')+ }+ const adj = adjOf(geom)++ const style = chainStyle(sp, ctx)+ const stroke = resolveStroke(sp, ctx, style, where)++ const shape: OutShape = {+ id: `s${deps.slideIndex}-${spId}`,+ type: 'shape',+ x, y, w, h, rotation,+ opacity: 1,+ shape: 'rect',+ fill: 'transparent',+ stroke: 'transparent',+ strokeWidth: 0,+ radius: 0,+ }++ // ---- line-family presets: bento draws lines horizontally through the box+ // centre and orients by rotation, so the OOXML box diagonal (start at the+ // box's top-left, flips choosing which diagonal) becomes length + angle.+ // Colour-from-fill gotcha: line shapes paint el.fill as the stroke.+ if (prst === 'line' || prst === 'straightConnector1') {+ const color = stroke.color?.css ?? '#000000'+ if (!stroke.color && !stroke.failed) ctx.report.trace('stroke', 'default')+ let p1: [number, number] = [x, y]+ let p2: [number, number] = [x + w, y + h]+ if (flipH) { p1 = [x + w, p1[1]]; p2 = [x, p2[1]] }+ if (flipV) { p1 = [p1[0], y + h]; p2 = [p2[0], y] }+ const len = Math.hypot(w, h)+ const diag = Math.atan2(p2[1] - p1[1], p2[0] - p1[0]) / DEG+ const elH = Math.max(stroke.widthPx, 2)+ shape.shape = 'line'+ shape.x = r2(x + w / 2 - len / 2)+ shape.y = r2(y + h / 2 - elH / 2)+ shape.w = r2(len)+ shape.h = r2(elH)+ shape.rotation = r2(rotation + diag)+ shape.fill = color+ shape.stroke = color+ shape.strokeWidth = stroke.widthPx || 1+ if (stroke.style !== 'solid') shape.strokeStyle = stroke.style+ if (stroke.start !== 'none') shape.lineStart = stroke.start+ if (stroke.end !== 'none') shape.lineEnd = stroke.end+ const lnShadow = resolveShadow(sp, ctx, where)+ if (lnShadow) shape.shadow = lnShadow+ attachConnectorEnds(sp, shape, ctx, deps, where)+ if (deps.groupId) shape.groupId = deps.groupId+ return { shape }+ }++ // ---- fills / effects (everything with an interior)+ const fill = resolveShapeFill(sp, ctx, style, where)+ const shadow = resolveShadow(sp, ctx, where)++ const openPath = OPEN_PATHS.has(prst)+ let flipConsumed = false++ // a flipped triangle cannot stay 'triangle' (bento's points up); its+ // synthesized polygon absorbs the flip exactly+ const kindHint =+ prst === 'rect' || prst === 'roundRect' ? 'rect'+ : prst === 'ellipse' ? 'ellipse'+ : prst === 'triangle' ? (flipV ? 'path' : 'triangle')+ : prst === 'rightArrow' ? 'arrow'+ : undefined++ if (kindHint) {+ shape.shape = kindHint+ if (prst === 'roundRect') {+ const a = pin(0, adj.get('adj') ?? 16667, 50000)+ shape.radius = r2((Math.min(w, h) * a) / 100000)+ }+ if (prst === 'triangle' && flipV) {+ shape.d = serializeSegs(+ [{ c: 'M', x: w / 2, y: 0 }, { c: 'L', x: w, y: h }, { c: 'L', x: 0, y: h }, { c: 'Z' }],+ w, h, flipH, flipV)+ shape.pathBox = [0, 0, w, h]+ flipConsumed = true+ }+ // rect/roundRect/ellipse are mirror-symmetric (and a triangle across its+ // vertical axis): a flip only moves a gradient, and mirroring its angle+ // carries that exactly+ if (kindHint === 'rect' || kindHint === 'ellipse' || kindHint === 'triangle') flipConsumed = true+ } else {+ const segs = presetSegs(prst, w, h, adj)+ if (segs) {+ shape.shape = 'path'+ shape.d = serializeSegs(segs, w, h, flipH, flipV)+ shape.pathBox = [0, 0, w, h]+ flipConsumed = true+ if (openPath && (stroke.start !== 'none' || stroke.end !== 'none')) {+ ctx.report.add('approximated', 'connector-tip-dropped', where,+ 'bent-connector arrowheads are not rendered on bento path shapes')+ }+ } else {+ shape.shape = 'rect'+ ctx.report.add('approximated', 'shape-approximated', where,+ `preset "${prst}" approximated as a rectangle`)+ }+ }++ if (fill.gradient && !openPath) {+ shape.fillGradient = { ...fill.gradient, angle: mirrorAngle(fill.gradient.angle, flipH, flipV) }+ }+ if (!openPath) shape.fill = fill.fill+ if (stroke.color && stroke.widthPx > 0) {+ shape.stroke = stroke.color.css+ shape.strokeWidth = stroke.widthPx+ if (stroke.style !== 'solid') shape.strokeStyle = stroke.style+ }+ if (shadow) shape.shadow = shadow++ if ((flipH || flipV) && !flipConsumed) {+ ctx.report.add('approximated', 'flip-dropped', where,+ 'flipH/flipV have no bento field and this geometry cannot absorb them — rendered unflipped')+ }++ if (openPath) attachConnectorEnds(sp, shape, ctx, deps, where)++ const fillVisible = shape.fill !== 'transparent' || !!shape.fillGradient+ const strokeVisible = shape.strokeWidth > 0 && shape.stroke !== 'transparent'+ const visible = fillVisible || strokeVisible || !!shadow || openPath || fill.failed || stroke.failed+ if (!visible) return undefined++ const out: ShapeResult = { shape }+ if (deps.groupId) shape.groupId = deps.groupId+ if (hasTextContent(sp)) {+ // the box-with-text split: shape now, text (the text module's element)+ // right after it, welded by groupId so they move as the one object the+ // author had+ const gid = deps.groupId ?? `s${deps.slideIndex}-${spId}-g`+ shape.groupId = gid+ out.textGroupId = gid+ }+ return out+}++/** a:stCxn/a:endCxn → from/to on the converter's deterministic ids. A ref to+ * a shape that is not on the slide is dropped (its end stays free). */+function attachConnectorEnds(sp: XElem, shape: OutShape, ctx: InheritCtx, deps: ShapeDeps, where: string): void {+ const nv = kids(sp).find((c) => kid(c, NS.p, 'cNvCxnSpPr'))+ const cNv = nv && kid(nv, NS.p, 'cNvCxnSpPr')+ if (!cNv) return+ const end = (local: string): { el: string; side: string } | undefined => {+ const e = kid(cNv, NS.a, local)+ if (!e) return undefined+ const id = attr(e, 'id')+ if (!id) return undefined+ if (deps.spIds && !deps.spIds.has(id)) {+ ctx.report.add('dropped', 'connector-ref-dangling', where,+ 'connector references a shape id not present on the slide — end left free')+ return undefined+ }+ return { el: `s${deps.slideIndex}-${id}`, side: 'auto' }+ }+ const from = end('stCxn')+ const to = end('endCxn')+ if (from) shape.from = from+ if (to) shape.to = to+}++// --- groups ------------------------------------------------------------------++export interface GroupChild {+ /** p:sp | p:pic | p:graphicFrame | p:cxnSp — nested p:grpSp recursed away */+ el: XElem+ /** absolute slide-space frame (EMU) — feed it back as deps.frame */+ frame: GroupFrame+ /** shared per source group — feed it back as deps.groupId */+ groupId: string+}++/** The child→parent coordinate map one grpSpPr xfrm defines. */+interface GroupMap {+ sx: number; sy: number+ ox: number; oy: number+ chx: number; chy: number+ rot: number+ flipH: boolean; flipV: boolean+ cx: number; cy: number+}++function applyMap(m: GroupMap, f: GroupFrame): GroupFrame {+ // child space → group space: axis-aligned scale + translate+ let fx = m.ox + (f.x - m.chx) * m.sx+ let fy = m.oy + (f.y - m.chy) * m.sy+ const fw = f.w * m.sx+ const fh = f.h * m.sy+ let rot = f.rotation+ let flipH = f.flipH+ let flipV = f.flipV+ // group flips mirror the child's centre across the group centre, toggle the+ // child's own flags and negate its rotation+ let ccx = fx + fw / 2+ let ccy = fy + fh / 2+ if (m.flipH) { ccx = 2 * m.cx - ccx; flipH = !flipH; rot = -rot }+ if (m.flipV) { ccy = 2 * m.cy - ccy; flipV = !flipV; rot = -rot }+ // group rotation turns the child's centre about the group centre and adds+ // to the child's own angle (clockwise, y-down — same sense as CSS rotate)+ if (m.rot !== 0) {+ const a = m.rot * DEG+ const dx = ccx - m.cx+ const dy = ccy - m.cy+ ccx = m.cx + dx * Math.cos(a) - dy * Math.sin(a)+ ccy = m.cy + dx * Math.sin(a) + dy * Math.cos(a)+ rot += m.rot+ }+ fx = ccx - fw / 2+ fy = ccy - fh / 2+ return { x: fx, y: fy, w: fw, h: fh, rotation: rot, flipH, flipV }+}++function grpXfrm(grpSp: XElem): XElem | undefined {+ const pr = kid(grpSp, NS.p, 'grpSpPr')+ return pr && kid(pr, NS.a, 'xfrm')+}++const MEMBER_LOCALS = new Set(['sp', 'pic', 'graphicFrame', 'cxnSp', 'grpSp'])++/**+ * Flatten one p:grpSp (recursively — 94 census groups, and groups nest) into+ * leaf children with composed ABSOLUTE frames. The caller converts each leaf+ * with its own module, passing frame+groupId back through deps. Every leaf —+ * including members of nested groups — shares the OUTERMOST group's id: bento+ * groupId is single-level, and the outermost group is the selection unit the+ * author actually had. A rotated child inside a non-uniformly scaled group+ * shears in PowerPoint; this frame model cannot say that, so such a child+ * keeps its summed rotation and axis-scaled box (no census sighting).+ */+export function groupChildren(grpSp: XElem, ctx: InheritCtx, deps: ShapeDeps): GroupChild[] {+ const out: GroupChild[] = []+ const groupId = deps.groupId ?? `s${deps.slideIndex}-g${cNvPrId(grpSp)}`++ const walk = (grp: XElem, parent: GroupMap | undefined, nested: boolean): void => {+ const xf = grpXfrm(grp)+ const off = xf && kid(xf, NS.a, 'off')+ const ext = xf && kid(xf, NS.a, 'ext')+ const chOff = xf && kid(xf, NS.a, 'chOff')+ const chExt = xf && kid(xf, NS.a, 'chExt')+ let gFrame: GroupFrame = {+ x: off ? intAttr(off, 'x') : 0,+ y: off ? intAttr(off, 'y') : 0,+ w: ext ? intAttr(ext, 'cx') : 0,+ h: ext ? intAttr(ext, 'cy') : 0,+ rotation: xf ? intAttr(xf, 'rot') / 60000 : 0,+ flipH: xf ? attr(xf, 'flipH') === '1' || attr(xf, 'flipH') === 'true' : false,+ flipV: xf ? attr(xf, 'flipV') === '1' || attr(xf, 'flipV') === 'true' : false,+ }+ if (parent) gFrame = applyMap(parent, gFrame)+ if (nested) {+ ctx.report.add('approximated', 'nested-group-flattened', whereOf(grp, deps.slideIndex),+ 'nested group flattened into its outermost group (bento groups are one level)')+ }+ const chW = chExt ? intAttr(chExt, 'cx') : 0+ const chH = chExt ? intAttr(chExt, 'cy') : 0+ const map: GroupMap = {+ sx: chW > 0 ? gFrame.w / chW : 1,+ sy: chH > 0 ? gFrame.h / chH : 1,+ ox: gFrame.x, oy: gFrame.y,+ chx: chOff ? intAttr(chOff, 'x') : 0,+ chy: chOff ? intAttr(chOff, 'y') : 0,+ rot: gFrame.rotation,+ flipH: gFrame.flipH, flipV: gFrame.flipV,+ cx: gFrame.x + gFrame.w / 2, cy: gFrame.y + gFrame.h / 2,+ }+ for (const child of kids(grp, NS.p)) {+ if (!MEMBER_LOCALS.has(child.local)) continue+ if (child.local === 'grpSp') {+ walk(child, map, true)+ continue+ }+ const f = resolveFrame(child, ctx)+ out.push({+ el: child,+ frame: applyMap(map, {+ x: f.x, y: f.y, w: f.w, h: f.h,+ rotation: f.rotation, flipH: f.flipH, flipV: f.flipV,+ }),+ groupId,+ })+ }+ }+ walk(grpSp, undefined, false)+ return out+}diff --git a/kernel/src/convert/text.ts b/kernel/src/convert/text.tsnew file mode 100644index 00000000..725b2233--- /dev/null+++ b/kernel/src/convert/text.ts@@ -0,0 +1,435 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+//+// p:txBody → OutText — the census's biggest domain (10,268 a:latin, 4,495+// a:buChar) and its biggest loss surface, because the two formats disagree+// about where formatting lives. PowerPoint styles per RUN; bento holds ONE+// fontSize/color/family per element, and render.ts's sanitizeHtml strips every+// attribute off every surviving tag, so of per-run formatting only+// b/i/u/strike can be carried as markup. Everything else flattens to the+// DOMINANT run — dominant by character count, because the big stat number+// next to its small unit label should style the element after the number,+// not after whichever run came first — and the report says so once per+// element ('run-formatting-flattened'), which is the honest half of the deal.+//+// Bullets flatten the same way: no UL/LI survives the sanitizer, so buChar+// becomes a literal glyph + NBSP baked into the line, buAutoNum is numbered+// HERE, at convert time, and frozen ('auto-number-frozen' — renumbering will+// not follow edits). buNone stays a silence, not an absence: the bullet unit+// resolved by inherit.textDefaults is overlaid by the paragraph's own pPr AS A+// UNIT, never property-merged, or the master's bullet would resurrect under a+// paragraph that turned bullets off (the trap inherit.ts documents).+//+// The one EXACT match in this domain: a:fld type="slidenum" → {{page}} (330+// census occurrences) and datetime → {{date}} — bento's dynamic fields have+// the same re-resolve-on-render semantics, so these are carried, not+// approximated.+//+// Sizes: a:rPr sz is CENTIPOINTS; bento fontSize is PX. pt = sz/100, px =+// pt * 4/3 (the panel shows pt = px * 0.75 — same ratio, inverted). A+// converter that skips either hop emits text at 3/4 size or 100x size, both+// of which have been "seen working" in other importers.++import { NS, kid, kids, attr, intAttr, textOf, type XElem } from './xml.ts'+import {+ EMU_PER_PX, METRIC_SUBSTITUTES,+ type InheritCtx, type OutText, type ThemeCtx,+} from './types.ts'+import type { TextDefaults, ResolvedFrame, ChainLink } from './inherit.ts'+import type { ColorResult } from './theme.ts'+import type { Verdict } from './report.ts'++/**+ * The resolver functions textFrom leans on, injected so this module has no+ * runtime coupling to inherit.ts/theme.ts and the rig wires in the real ones.+ */+export interface TextDeps {+ effectivePhType(sp: XElem, ctx: InheritCtx): string+ textDefaults(sp: XElem, ctx: InheritCtx, level: number, phType: string): TextDefaults+ resolveFrame(sp: XElem, ctx: InheritCtx): ResolvedFrame+ labeledChain(sp: XElem, ctx: InheritCtx): ChainLink[]+ resolveColor(el: XElem | undefined, theme: ThemeCtx, phClr?: string): ColorResult | undefined+ /**+ * Called with the element id when the HOST must re-measure the box: the box+ * declared a:spAutoFit (grow-to-fit) or no autofit at all, and with 0/6+ * census decks embedding fonts every glyph is a substitution with different+ * metrics — the engine cannot know where the text now wraps. normAutofit is+ * NOT hinted (its fontScale is applied here); noAutofit is NOT hinted (an+ * explicitly fixed box is the author's stated intent).+ */+ needsRefit?(id: string): void+}++/** EMU → px, rounded to 1/100 px so emitted JSON stays diffable. */+const px = (emu: number): number => Math.round((emu / EMU_PER_PX) * 100) / 100++const round2 = (v: number): number => Math.round(v * 100) / 100+const round3 = (v: number): number => Math.round(v * 1000) / 1000++const flag = (v: string | undefined): boolean => v === '1' || v === 'true'++/** &, <, > only — the emitted html is markup we build, quotes never matter. */+const esc = (s: string): string =>+ s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')++/** Report `where` for one shape: its cNvPr name when it has one. */+function whereOf(shape: XElem): string {+ for (const c of kids(shape)) {+ const cnv = kid(c, NS.p, 'cNvPr')+ if (cnv) {+ const name = attr(cnv, 'name')+ return name ? `sp "${name}"` : `sp ${attr(cnv, 'id') ?? '?'}`+ }+ }+ return 'sp'+}++function cnvIdOf(shape: XElem): string {+ for (const c of kids(shape)) {+ const cnv = kid(c, NS.p, 'cNvPr')+ if (cnv) return attr(cnv, 'id') ?? '?'+ }+ return '?'+}++/** CSS font-family token: quote anything a bare identifier cannot say. */+const cssFace = (name: string): string => (/[^A-Za-z0-9-]/.test(name) ? `'${name}'` : name)++/** ST_TextAutonumberScheme → the literal a frozen list shows. Census carries+ * only arabicPeriod (46), but alpha/roman are cheap enough to number right —+ * the FREEZING is the loss, not the numeral system. */+function formatAutoNum(scheme: string, n: number): string {+ const alpha = (v: number): string => {+ let s = ''+ while (v > 0) { v--; s = String.fromCharCode(65 + (v % 26)) + s; v = Math.floor(v / 26) }+ return s+ }+ const ROMAN: Array<[number, string]> = [+ [1000, 'M'], [900, 'CM'], [500, 'D'], [400, 'CD'], [100, 'C'], [90, 'XC'],+ [50, 'L'], [40, 'XL'], [10, 'X'], [9, 'IX'], [5, 'V'], [4, 'IV'], [1, 'I'],+ ]+ const roman = (v: number): string => {+ let s = ''+ for (const [val, sym] of ROMAN) while (v >= val) { s += sym; v -= val }+ return s+ }+ const body = scheme.startsWith('alphaLc') ? alpha(n).toLowerCase()+ : scheme.startsWith('alphaUc') ? alpha(n)+ : scheme.startsWith('romanLc') ? roman(n).toLowerCase()+ : scheme.startsWith('romanUc') ? roman(n)+ : String(n)+ return scheme.includes('ParenBoth') ? `(${body})`+ : scheme.endsWith('ParenR') ? `${body})`+ : scheme.endsWith('Period') ? `${body}.`+ : body+}++/** One run's contribution: pre-escaped html + the style facts that decide+ * dominance. `<br>` pieces carry zero chars and no flags. */+interface Piece {+ html: string+ chars: number+ sizePt: number+ color: string+ family: string+ bold: boolean+ italic: boolean+ underline: boolean+ strike: boolean+}++interface Para {+ pieces: Piece[]+ chars: number+ align: OutText['align']+ lineHeight: number+ /** already-escaped bullet/number prefix, '' when none */+ prefix: string+}++/**+ * One p:sp's txBody as a bento text element, or undefined when there is no+ * visible text at all (empty placeholder prompts, decoration-only shapes) —+ * the caller simply emits no text half.+ *+ * The frame comes from deps.resolveFrame (own → layout ph → master ph), in px.+ * A shape that pairs with a fill (the rect-with-text split) shares that frame;+ * the id is 'txt' + cNvPr@id — unique per slide only, the identity pass may+ * rewrite it, and it is what needsRefit reports.+ */+export function textFrom(sp: XElem, ctx: InheritCtx, deps: TextDeps): OutText | undefined {+ const txBody = kid(sp, NS.p, 'txBody')+ if (!txBody) return undefined+ const where = whereOf(sp)+ const phType = deps.effectivePhType(sp, ctx)++ const defCache = new Map<number, TextDefaults>()+ const defsFor = (lvl: number): TextDefaults => {+ let d = defCache.get(lvl)+ if (!d) { d = deps.textDefaults(sp, ctx, lvl, phType); defCache.set(lvl, d) }+ return d+ }++ // bodyPr facts up the chain: anchor per-attribute, autofit AS A UNIT (a+ // nearer bodyPr declaring any autofit settles the question for all three).+ const bodyPrs: XElem[] = []+ for (const link of deps.labeledChain(sp, ctx)) {+ const tb = kid(link.el, NS.p, 'txBody')+ const bp = tb ? kid(tb, NS.a, 'bodyPr') : undefined+ if (bp) bodyPrs.push(bp)+ }+ let anchor: string | undefined+ for (const bp of bodyPrs) {+ const a = attr(bp, 'anchor')+ if (a !== undefined) { anchor = a; break }+ }+ let fontScale = 1+ let lnScale = 1+ let autofit: 'norm' | 'sp' | 'no' | 'absent' = 'absent'+ for (const bp of bodyPrs) {+ const norm = kid(bp, NS.a, 'normAutofit')+ if (norm) {+ autofit = 'norm'+ fontScale = intAttr(norm, 'fontScale', 100000) / 100000+ lnScale = 1 - intAttr(norm, 'lnSpcReduction', 0) / 100000+ break+ }+ if (kid(bp, NS.a, 'spAutoFit')) { autofit = 'sp'; break }+ if (kid(bp, NS.a, 'noAutofit')) { autofit = 'no'; break }+ }++ // Findings are queued until we know the element is real — an all-empty+ // txBody must not leave reports about an element that was never emitted.+ const pending: Array<{ v: Verdict; code: string; detail: string }> = []+ const note = (v: Verdict, code: string, detail: string): void => { pending.push({ v, code, detail }) }++ /** Effective ink for one run: rPr solidFill → level defaults → p:style+ * a:fontRef (1,775 census — the base ink of style-referenced shapes) →+ * theme tx1 → black. A colour that EXISTS but fails to resolve is reported+ * and falls through; absence falls through silently. */+ const inkFor = (rPr: XElem | undefined, d: TextDefaults): string => {+ const own = rPr ? kid(rPr, NS.a, 'solidFill') : undefined+ if (own) {+ const c = deps.resolveColor(own, ctx.theme)+ if (c) return c.css+ note('dropped', 'text-color-unresolved', 'a run colour reference did not resolve; the next source in the cascade was used')+ }+ if (d.color) {+ const c = deps.resolveColor(d.color, ctx.theme)+ if (c) return c.css+ note('dropped', 'text-color-unresolved', 'a run colour reference did not resolve; the next source in the cascade was used')+ }+ const style = kid(sp, NS.p, 'style')+ const fontRef = style ? kid(style, NS.a, 'fontRef') : undefined+ if (fontRef) {+ const c = deps.resolveColor(fontRef, ctx.theme)+ if (c) return c.css+ }+ return ctx.theme.scheme['tx1'] ?? '#000000'+ }++ const runPiece = (rPr: XElem | undefined, text: string, d: TextDefaults, preEscaped: boolean): Piece => {+ const szRaw = rPr ? attr(rPr, 'sz') : undefined+ const szNum = szRaw !== undefined ? parseInt(szRaw, 10) : NaN+ const sizePt = Number.isFinite(szNum) ? szNum / 100 : d.fontSize+ const bAttr = rPr ? attr(rPr, 'b') : undefined+ const bold = bAttr !== undefined ? flag(bAttr) : d.bold+ const u = rPr ? attr(rPr, 'u') : undefined+ const st = rPr ? attr(rPr, 'strike') : undefined+ const latin = rPr ? kid(rPr, NS.a, 'latin') : undefined+ const face = (latin ? attr(latin, 'typeface') : undefined) ?? d.font+ const family = face === '+mj-lt' ? ctx.theme.majorFont : face === '+mn-lt' ? ctx.theme.minorFont : face+ return {+ html: preEscaped ? text : esc(text),+ chars: text.length,+ sizePt,+ color: inkFor(rPr, d),+ family,+ bold,+ italic: rPr !== undefined && flag(attr(rPr, 'i')),+ underline: u !== undefined && u !== 'none',+ strike: st !== undefined && st !== 'noStrike',+ }+ }++ // ------------------------------------------------------------- paragraphs+ const paras: Para[] = []+ const counters = new Map<number, number>() // frozen autoNum, keyed by level+ let spacingSeen = false++ for (const p of kids(txBody, NS.a, 'p')) {+ const pPr = kid(p, NS.a, 'pPr')+ const lvl = pPr ? intAttr(pPr, 'lvl', 0) : 0+ const d = defsFor(lvl)++ let align: OutText['align'] = d.align+ let alignRaw = d.alignRaw+ const ownAlgn = pPr ? attr(pPr, 'algn') : undefined+ if (ownAlgn !== undefined) {+ align = ownAlgn === 'ctr' ? 'center' : ownAlgn === 'r' ? 'right' : 'left'+ alignRaw = ownAlgn !== 'l' && ownAlgn !== 'ctr' && ownAlgn !== 'r' ? ownAlgn : undefined+ }+ if (alignRaw !== undefined) {+ note('approximated', 'align-approximated', `algn="${alignRaw}" has no bento equivalent; emitted left-aligned`)+ }++ let lineHeight = d.lineHeight+ const lnSpc = pPr ? kid(pPr, NS.a, 'lnSpc') : undefined+ if (lnSpc) {+ const spcPct = kid(lnSpc, NS.a, 'spcPct')+ const spcPts = kid(lnSpc, NS.a, 'spcPts')+ if (spcPct) lineHeight = intAttr(spcPct, 'val', 100000) / 100000+ else if (spcPts && d.fontSize > 0) lineHeight = intAttr(spcPts, 'val', d.fontSize * 100) / 100 / d.fontSize+ }++ if (d.hasSpcBef || d.hasSpcAft || (pPr && (kid(pPr, NS.a, 'spcBef') || kid(pPr, NS.a, 'spcAft')))) {+ spacingSeen = true+ }++ // bullet: the paragraph's own declaration overlays the resolved default+ // AS A UNIT — a pPr buNone silences an inherited buChar, never merges.+ let bullet: { kind: 'none' | 'char' | 'autoNum'; char?: string; scheme?: string; startAt?: number } = d.bullet+ if (pPr) {+ if (kid(pPr, NS.a, 'buNone')) bullet = { kind: 'none' }+ else {+ const auto = kid(pPr, NS.a, 'buAutoNum')+ const ch = kid(pPr, NS.a, 'buChar')+ if (auto) bullet = { kind: 'autoNum', scheme: attr(auto, 'type') ?? 'arabicPeriod', startAt: intAttr(auto, 'startAt', 1) }+ else if (ch) bullet = { kind: 'char', char: attr(ch, 'char') ?? '•' }+ }+ }++ const pieces: Piece[] = []+ let chars = 0+ for (const c of kids(p, NS.a)) {+ if (c.local === 'r') {+ const t = kid(c, NS.a, 't')+ const text = t ? textOf(t) : ''+ if (!text) continue+ const piece = runPiece(kid(c, NS.a, 'rPr'), text, d, false)+ pieces.push(piece)+ chars += piece.chars+ } else if (c.local === 'br') {+ pieces.push({ html: '<br>', chars: 0, sizePt: d.fontSize, color: '', family: '', bold: false, italic: false, underline: false, strike: false })+ } else if (c.local === 'fld') {+ // {{page}}/{{date}} re-resolve at render time exactly like the source+ // field — an EXACT semantic match, carried without a report. Unknown+ // field types freeze to their cached text.+ const type = attr(c, 'type') ?? ''+ let token: string+ if (type === 'slidenum') token = '{{page}}'+ else if (type.startsWith('datetime')) token = '{{date}}'+ else {+ const t = kid(c, NS.a, 't')+ token = esc(t ? textOf(t) : '')+ if (!token) continue+ note('approximated', 'field-frozen', `a:fld type="${type}" has no bento field; frozen to its cached text`)+ }+ const piece = runPiece(kid(c, NS.a, 'rPr'), token, d, true)+ pieces.push(piece)+ chars += piece.chars+ }+ }++ // PowerPoint paints no bullet on an empty paragraph; neither do we.+ // Both prefixes below end in a LITERAL NBSP (U+00A0) before the backtick —+ // a plain space would collapse against the glyph in html, and the char+ // does not survive retyping (edit these lines with line-targeted tools).+ let prefix = ''+ if (chars > 0 && bullet.kind === 'char') {+ prefix = `${esc(bullet.char ?? '•')} `+ note('approximated', 'bullet-flattened', 'bullet glyphs are baked into the text — no list structure, so bullet colour/size and hanging indent are lost')+ } else if (chars > 0 && bullet.kind === 'autoNum') {+ const n = counters.get(lvl) ?? bullet.startAt ?? 1+ counters.set(lvl, n + 1)+ prefix = `${esc(formatAutoNum(bullet.scheme ?? 'arabicPeriod', n))} `+ note('approximated', 'auto-number-frozen', 'auto-numbered list frozen to literal numbers at convert time; renumbering will not follow edits')+ }++ paras.push({ pieces, chars, align, lineHeight, prefix })+ }++ // Trailing empty paragraphs are producer noise (a bare endParaRPr closes+ // most txBodies); interior empties are deliberate blank lines and stay.+ while (paras.length && paras[paras.length - 1].chars === 0 && paras[paras.length - 1].pieces.length === 0) {+ paras.pop()+ }++ const total = paras.reduce((s, p) => s + p.chars, 0)+ if (total === 0) return undefined+ for (const f of pending) ctx.report.add(f.v, f.code, where, f.detail)++ // ------------------------------------------------- dominance + flattening+ let dom: Piece | undefined+ for (const p of paras) for (const piece of p.pieces) {+ if (piece.chars > 0 && (!dom || piece.chars > dom.chars)) dom = piece+ }+ if (!dom) return undefined // unreachable given total > 0; satisfies narrowing++ let flattened = false+ for (const p of paras) for (const piece of p.pieces) {+ if (piece.chars === 0) continue+ // bold/italic/underline/strike survive as tags — only the properties the+ // sanitizer cannot carry count as loss, plus the one inexpressible bold+ // case (a lighter run inside a bold-dominant element).+ if (piece.sizePt !== dom.sizePt || piece.color !== dom.color || piece.family !== dom.family+ || (dom.bold && !piece.bold)) flattened = true+ }+ if (flattened) {+ ctx.report.add('approximated', 'run-formatting-flattened', where,+ 'runs disagree on size/colour/family; the element carries the dominant run (by character count) and the rest adopt its styling')+ }++ let domPara = paras[0]+ for (const p of paras) if (p.chars > domPara.chars) domPara = p+ if (paras.some((p) => p.chars > 0 && p.align !== domPara.align)) {+ ctx.report.add('approximated', 'align-flattened', where,+ 'paragraphs disagree on alignment; the element carries the dominant paragraph’s')+ }+ if (spacingSeen) {+ ctx.report.add('approximated', 'paragraph-spacing-dropped', where,+ 'spcBef/spcAft have no bento equivalent; paragraphs are joined at uniform line height')+ }++ // ------------------------------------------------------------- assembly+ const elementBold = dom.bold+ const html = paras.map((p) => {+ let out = p.prefix+ for (const piece of p.pieces) {+ let h = piece.html+ if (piece.strike) h = `<s>${h}</s>`+ if (piece.underline) h = `<u>${h}</u>`+ if (piece.italic) h = `<i>${h}</i>`+ if (piece.bold && !elementBold && piece.chars > 0) h = `<b>${h}</b>`+ out += h+ }+ return out+ }).join('<br>')++ const sub = METRIC_SUBSTITUTES[dom.family]+ if (sub) {+ ctx.report.add('approximated', 'font-substituted', `font "${dom.family}"`,+ `'${dom.family}' is not embedded; emitted as a metric-compatible stack with '${sub}'`)+ }+ const fontFamily = sub ? `${cssFace(dom.family)}, ${cssFace(sub)}, sans-serif` : `${cssFace(dom.family)}, sans-serif`++ const frame = deps.resolveFrame(sp, ctx)+ const id = `txt${cnvIdOf(sp)}`+ if (autofit === 'sp' || autofit === 'absent') deps.needsRefit?.(id)++ return {+ type: 'text',+ id,+ x: px(frame.x), y: px(frame.y), w: px(frame.w), h: px(frame.h),+ rotation: frame.rotation,+ opacity: 1,+ html,+ fontSize: round2(dom.sizePt * (4 / 3) * fontScale),+ fontFamily,+ fontWeight: elementBold ? 700 : 400,+ color: dom.color,+ align: domPara.align,+ valign: anchor === 'ctr' ? 'middle' : anchor === 'b' ? 'bottom' : 'top',+ lineHeight: round3(domPara.lineHeight * lnScale),+ }+}diff --git a/kernel/src/convert/theme.ts b/kernel/src/convert/theme.tsnew file mode 100644index 00000000..ab584640--- /dev/null+++ b/kernel/src/convert/theme.ts@@ -0,0 +1,380 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+//+// The colour and font resolver — the foundation the rest of the importer+// stands on. In the census 22,279 a:schemeClr stand against 2,092 a:srgbClr:+// ~91% of every colour in a real deck is an indirect reference, and every hop+// in the chain fails SILENTLY. A backwards clrMap still renders (dark text on+// dark section slides); a missed fillRef renders 1,727 shapes unfilled with no+// error; a transform computed in the wrong colour space renders every brand+// colour plausibly, consistently, invisibly wrong. Nothing here may guess:+// when a reference cannot be resolved the functions return undefined and the+// CALLER reports the drop — a loud undefined beats a quiet approximation.+//+// THE TWO COLOUR SPACES (the trap the spike names explicitly). PowerPoint's+// colour transforms straddle two spaces and must not be mixed:+//+// a:shade / a:tint (1,235 / census) — LINEAR-LIGHT RGB. Each channel is+// linearized (c/255)^2.2, scaled — shade multiplies by val, tint+// interpolates toward white — then re-encoded ^(1/2.2). A naive sRGB-space+// multiply gives e.g. shade(50%) of #808080 = #404040 where PowerPoint+// paints #5D5D5D; the rig pins both values so the spaces stay apart.+// a:lumMod / a:lumOff / a:satMod / a:satOff (2,500+ combined) — HSL.+// lumMod multiplies L, lumOff adds to it (negative offsets are real:+// the census carries lumOff val="-123").+//+// Transforms apply in DOCUMENT ORDER (lumMod-then-lumOff differs from the+// reverse), channels stay floating through the whole chain, and rounding+// happens exactly once at the end — half-up, the way PowerPoint lands.+//+// What is deliberately NOT here: a:comp/a:inv/a:gray/a:gamma/a:invGamma and+// the hue transforms beyond hueMod/hueOff are 0/6 in the census and are+// skipped; a:scrgbClr (also ~0) maps percentage→channel directly rather than+// through scRGB linearization, matching the major converters.++import { NS, kid, kids, descendants, attr, intAttr, type XElem } from './xml.ts'+import type { ThemeCtx, ResolvedColor } from './types.ts'++/** One resolved colour, with the alpha the css already encodes. */+export interface ColorResult extends ResolvedColor { alpha: number }++// --- channel math ------------------------------------------------------------++/** 0..255 floats until the single final rounding. */+type Rgb = [number, number, number]++const clamp01 = (v: number): number => (v < 0 ? 0 : v > 1 ? 1 : v)++const toLin = (c: number): number => Math.pow(c / 255, 2.2)+const fromLin = (v: number): number => 255 * Math.pow(clamp01(v), 1 / 2.2)++function hexRgb(hex: string | undefined): Rgb | undefined {+ if (!hex) return undefined+ const m = /^#?([0-9a-fA-F]{6})$/.exec(hex)+ if (!m) return undefined+ const n = parseInt(m[1], 16)+ return [(n >> 16) & 0xff, (n >> 8) & 0xff, n & 0xff]+}++interface Hsl { h: number; s: number; l: number }++function rgbToHsl([r, g, b]: Rgb): Hsl {+ const rn = r / 255, gn = g / 255, bn = b / 255+ const max = Math.max(rn, gn, bn), min = Math.min(rn, gn, bn)+ const l = (max + min) / 2+ const d = max - min+ if (d === 0) return { h: 0, s: 0, l }+ const s = l > 0.5 ? d / (2 - max - min) : d / (max + min)+ let h: number+ if (max === rn) h = ((gn - bn) / d) % 6+ else if (max === gn) h = (bn - rn) / d + 2+ else h = (rn - gn) / d + 4+ h *= 60+ if (h < 0) h += 360+ return { h, s, l }+}++function hslToRgb({ h, s, l }: Hsl): Rgb {+ if (s === 0) return [l * 255, l * 255, l * 255]+ const q = l < 0.5 ? l * (1 + s) : l + s - l * s+ const p = 2 * l - q+ const hk = (((h % 360) + 360) % 360) / 360+ const chan = (t: number): number => {+ if (t < 0) t += 1+ if (t > 1) t -= 1+ if (t < 1 / 6) return p + (q - p) * 6 * t+ if (t < 1 / 2) return q+ if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6+ return p+ }+ return [chan(hk + 1 / 3) * 255, chan(hk) * 255, chan(hk - 1 / 3) * 255]+}++function hslOp(rgb: Rgb, op: (hsl: Hsl) => void): Rgb {+ const hsl = rgbToHsl(rgb)+ op(hsl)+ hsl.s = clamp01(hsl.s)+ hsl.l = clamp01(hsl.l)+ return hslToRgb(hsl)+}++/** ST_Percentage as a fraction: modern "75000" and the transitional "75%"+ * spelling both occur in the wild. */+function pct(el: XElem, name = 'val'): number {+ const raw = attr(el, name)+ if (raw === undefined) return 0+ if (raw.endsWith('%')) {+ const n = parseFloat(raw)+ return Number.isFinite(n) ? n / 100 : 0+ }+ const n = parseInt(raw, 10)+ return Number.isFinite(n) ? n / 100000 : 0+}++// --- base colours ------------------------------------------------------------++const COLOR_LOCALS = new Set(['srgbClr', 'schemeClr', 'sysClr', 'prstClr', 'scrgbClr'])++/** a:sysClr with no lastClr is rare enough that only the two values real+ * producers emit (39 windowText / 8 window in the census) get a fallback. */+const SYS_FALLBACK: Record<string, string> = { windowText: '000000', window: 'FFFFFF' }++// ST_PresetColorVal is the X11 palette camelCased. The census uses exactly one+// value (black, 618 times) so this table carries the standard names and lets+// the abbreviated spellings (dkBlue/ltGray/medPurple) normalize onto the full+// ones; an unknown name resolves to undefined so the caller reports it instead+// of painting a guess.+const PRST: Record<string, string> = {+ black: '000000', white: 'FFFFFF', red: 'FF0000', green: '008000', blue: '0000FF',+ yellow: 'FFFF00', cyan: '00FFFF', magenta: 'FF00FF', gray: '808080', silver: 'C0C0C0',+ maroon: '800000', olive: '808000', navy: '000080', purple: '800080', teal: '008080',+ lime: '00FF00', aqua: '00FFFF', fuchsia: 'FF00FF', orange: 'FFA500', brown: 'A52A2A',+ pink: 'FFC0CB', gold: 'FFD700', indigo: '4B0082', violet: 'EE82EE', crimson: 'DC143C',+ chocolate: 'D2691E', coral: 'FF7F50', khaki: 'F0E68C', lavender: 'E6E6FA', plum: 'DDA0DD',+ orchid: 'DA70D6', salmon: 'FA8072', sienna: 'A0522D', tan: 'D2B48C', tomato: 'FF6347',+ turquoise: '40E0D0', wheat: 'F5DEB3', beige: 'F5F5DC', ivory: 'FFFFF0', snow: 'FFFAFA',+ azure: 'F0FFFF', aliceBlue: 'F0F8FF', ghostWhite: 'F8F8FF', whiteSmoke: 'F5F5F5',+ gainsboro: 'DCDCDC', dimGray: '696969', slateGray: '708090', steelBlue: '4682B4',+ royalBlue: '4169E1', skyBlue: '87CEEB', deepSkyBlue: '00BFFF', dodgerBlue: '1E90FF',+ cornflowerBlue: '6495ED', midnightBlue: '191970', slateBlue: '6A5ACD', blueViolet: '8A2BE2',+ forestGreen: '228B22', seaGreen: '2E8B57', springGreen: '00FF7F', limeGreen: '32CD32',+ oliveDrab: '6B8E23', yellowGreen: '9ACD32', goldenrod: 'DAA520', firebrick: 'B22222',+ indianRed: 'CD5C5C', hotPink: 'FF69B4', deepPink: 'FF1493', orangeRed: 'FF4500',+ aquamarine: '7FFFD4', cadetBlue: '5F9EA0', chartreuse: '7FFF00', honeydew: 'F0FFF0',+ mistyRose: 'FFE4E1', moccasin: 'FFE4B5', navajoWhite: 'FFDEAD', oldLace: 'FDF5E6',+ peachPuff: 'FFDAB9', peru: 'CD853F', powderBlue: 'B0E0E6', rosyBrown: 'BC8F8F',+ saddleBrown: '8B4513', sandyBrown: 'F4A460', seaShell: 'FFF5EE', thistle: 'D8BFD8',+ burlyWood: 'DEB887',+ darkBlue: '00008B', darkCyan: '008B8B', darkGoldenrod: 'B8860B', darkGray: 'A9A9A9',+ darkGreen: '006400', darkKhaki: 'BDB76B', darkMagenta: '8B008B', darkOliveGreen: '556B2F',+ darkOrange: 'FF8C00', darkOrchid: '9932CC', darkRed: '8B0000', darkSalmon: 'E9967A',+ darkSeaGreen: '8FBC8F', darkSlateBlue: '483D8B', darkSlateGray: '2F4F4F',+ darkTurquoise: '00CED1', darkViolet: '9400D3',+ lightBlue: 'ADD8E6', lightCoral: 'F08080', lightCyan: 'E0FFFF', lightGray: 'D3D3D3',+ lightGreen: '90EE90', lightPink: 'FFB6C1', lightSalmon: 'FFA07A', lightSeaGreen: '20B2AA',+ lightSkyBlue: '87CEFA', lightSlateGray: '778899', lightSteelBlue: 'B0C4DE',+ lightYellow: 'FFFFE0',+ mediumAquamarine: '66CDAA', mediumBlue: '0000CD', mediumOrchid: 'BA55D3',+ mediumPurple: '9370DB', mediumSeaGreen: '3CB371', mediumSlateBlue: '7B68EE',+ mediumSpringGreen: '00FA9A', mediumTurquoise: '48D1CC', mediumVioletRed: 'C71585',+}++/** dkBlue → darkBlue, ltGray → lightGray, medPurple → mediumPurple. */+function normPrst(name: string): string {+ if (/^dk[A-Z]/.test(name)) return `dark${name.slice(2)}`+ if (/^lt[A-Z]/.test(name)) return `light${name.slice(2)}`+ if (/^med[A-Z]/.test(name)) return `medium${name.slice(3)}`+ return name+}++// --- resolveColor ------------------------------------------------------------++/**+ * Resolve the colour inside `el` — either a container (a:solidFill, a:gs, a+ * scheme slot) holding one colour child, or the colour element itself. `phClr`+ * ('#rrggbb') substitutes for a:schemeClr val="phClr", the style-matrix+ * placeholder colour. Returns undefined for anything unresolvable — the+ * caller decides what to report; nothing here invents a value.+ */+export function resolveColor(el: XElem | undefined, theme: ThemeCtx, phClr?: string): ColorResult | undefined {+ if (!el) return undefined+ const c = el.ns === NS.a && COLOR_LOCALS.has(el.local)+ ? el+ : kids(el, NS.a).find((k) => COLOR_LOCALS.has(k.local))+ if (!c) return undefined++ let from: ResolvedColor['from'] = 'own'+ let rgb: Rgb | undefined+ switch (c.local) {+ case 'srgbClr':+ rgb = hexRgb(attr(c, 'val'))+ break+ case 'schemeClr': {+ from = 'theme'+ const v = attr(c, 'val') ?? ''+ rgb = v === 'phClr' ? hexRgb(phClr) : hexRgb(theme.scheme[v])+ break+ }+ case 'sysClr':+ // lastClr is what the producing machine actually painted; trust it over+ // any idea of what "window" means here.+ rgb = hexRgb(attr(c, 'lastClr') ?? SYS_FALLBACK[attr(c, 'val') ?? ''])+ break+ case 'prstClr':+ rgb = hexRgb(PRST[normPrst(attr(c, 'val') ?? '')])+ break+ case 'scrgbClr':+ rgb = [pct(c, 'r') * 255, pct(c, 'g') * 255, pct(c, 'b') * 255]+ break+ }+ if (!rgb) return undefined++ let alpha = 1+ for (const t of kids(c, NS.a)) {+ switch (t.local) {+ case 'alpha': alpha = clamp01(pct(t)); break+ case 'alphaMod': alpha = clamp01(alpha * pct(t)); break+ case 'alphaOff': alpha = clamp01(alpha + pct(t)); break+ case 'shade': {+ const f = pct(t)+ rgb = rgb.map((v) => fromLin(toLin(v) * f)) as Rgb+ break+ }+ case 'tint': {+ const f = pct(t)+ rgb = rgb.map((v) => fromLin(toLin(v) * f + (1 - f))) as Rgb+ break+ }+ case 'lumMod': rgb = hslOp(rgb, (h) => { h.l *= pct(t) }); break+ case 'lumOff': rgb = hslOp(rgb, (h) => { h.l += pct(t) }); break+ case 'satMod': rgb = hslOp(rgb, (h) => { h.s *= pct(t) }); break+ case 'satOff': rgb = hslOp(rgb, (h) => { h.s += pct(t) }); break+ case 'hueMod': rgb = hslOp(rgb, (h) => { h.h *= pct(t) }); break+ // hue offsets are 1/60000ths of a degree, not a percentage+ case 'hueOff': rgb = hslOp(rgb, (h) => { h.h += intAttr(t, 'val') / 60000 }); break+ default: break // comp/inv/gray/gamma/invGamma: 0/6 in the census+ }+ }++ const [r, g, b] = rgb.map((v) => Math.min(255, Math.max(0, Math.round(v))))+ if (alpha >= 1) {+ const h2 = (v: number) => v.toString(16).padStart(2, '0').toUpperCase()+ return { css: `#${h2(r)}${h2(g)}${h2(b)}`, alpha: 1, from }+ }+ const a = Math.round(alpha * 1000) / 1000+ return { css: `rgba(${r},${g},${b},${a})`, alpha: a, from }+}++// --- parseTheme --------------------------------------------------------------++const SCHEME_SLOTS = [+ 'dk1', 'lt1', 'dk2', 'lt2',+ 'accent1', 'accent2', 'accent3', 'accent4', 'accent5', 'accent6',+ 'hlink', 'folHlink',+] as const++// The standard master clrMap. "bg1" in a colour reference does NOT mean the+// dk/lt slot of the same name-shape — it routes through this map, and a+// converter that reads it backwards produces dark-on-dark that still renders.+const CLR_MAP_DEFAULT: Record<string, string> = {+ bg1: 'lt1', tx1: 'dk1', bg2: 'lt2', tx2: 'dk2',+ accent1: 'accent1', accent2: 'accent2', accent3: 'accent3',+ accent4: 'accent4', accent5: 'accent5', accent6: 'accent6',+ hlink: 'hlink', folHlink: 'folHlink',+}++/** The base hex of one clrScheme slot (a:dk1 … a:folHlink). Scheme slots hold+ * a bare a:srgbClr or a:sysClr, never transforms. */+function slotHex(slot: XElem): string | undefined {+ const srgb = kid(slot, NS.a, 'srgbClr')+ if (srgb) {+ const v = attr(srgb, 'val')+ return v && /^[0-9a-fA-F]{6}$/.test(v) ? `#${v.toUpperCase()}` : undefined+ }+ const sys = kid(slot, NS.a, 'sysClr')+ if (sys) {+ const v = attr(sys, 'lastClr') ?? SYS_FALLBACK[attr(sys, 'val') ?? '']+ return v ? `#${v.toUpperCase()}` : undefined+ }+ return undefined+}++/**+ * Parse a theme part (theme1.xml root, or a themeOverride) plus the owning+ * master's p:clrMap. The returned scheme is keyed BOTH by the raw slot names+ * (dk1, lt1, … — schemeClr val="dk1" is the single most frequent colour+ * reference in the census at 5,289) and by the logical names the map produces+ * (bg1, tx1, … — 2,146 bg1 references), so resolveColor never has to know+ * which family a reference belongs to.+ */+export function parseTheme(themeXml: XElem, clrMapEl: XElem | undefined): ThemeCtx {+ const scheme: Record<string, string> = {}+ const clrScheme = descendants(themeXml, NS.a, 'clrScheme')[0]+ if (clrScheme) {+ for (const name of SCHEME_SLOTS) {+ const slot = kid(clrScheme, NS.a, name)+ const hex = slot && slotHex(slot)+ if (hex) scheme[name] = hex+ }+ }+ for (const [logical, def] of Object.entries(CLR_MAP_DEFAULT)) {+ const target = (clrMapEl && attr(clrMapEl, logical)) || def+ const hex = scheme[target]+ if (hex) scheme[logical] = hex+ }++ const fontScheme = descendants(themeXml, NS.a, 'fontScheme')[0]+ const face = (which: string): string => {+ const fam = fontScheme && kid(fontScheme, NS.a, which)+ const latin = fam && kid(fam, NS.a, 'latin')+ // Calibri is what an Office file with a broken fontScheme would actually+ // show — the least-wrong stand-in, and METRIC_SUBSTITUTES covers it.+ return (latin && attr(latin, 'typeface')) || 'Calibri'+ }++ const fmtScheme = descendants(themeXml, NS.a, 'fmtScheme')[0]+ const styleList = (name: string): XElem[] => {+ const lst = fmtScheme && kid(fmtScheme, NS.a, name)+ return lst ? kids(lst) : []+ }++ return {+ scheme,+ majorFont: face('majorFont'),+ minorFont: face('minorFont'),+ fillStyles: styleList('fillStyleLst'),+ lineStyles: styleList('lnStyleLst'),+ bgFillStyles: styleList('bgFillStyleLst'),+ }+}++// --- the format-scheme style matrix (fillRef / lnRef) ------------------------++/**+ * A fill resolved through a:fillRef. 'none' is idx 0 — an INTENTIONAL absence,+ * distinct from the undefined an out-of-range or unresolvable reference+ * returns (that one the caller must report). 'solid' is fully resolved;+ * 'other' hands the raw style entry (gradFill/blipFill/…) plus the phClr to+ * substitute back to shapes.ts, which owns gradient parsing.+ */+export type StyleFill =+ | { kind: 'none' }+ | { kind: 'solid'; color: ColorResult }+ | { kind: 'other'; el: XElem; phClr: string }++/**+ * The style matrix's fill lookup: idx 0 = none, 1..999 index fillStyleLst+ * (1-based), >=1000 index bgFillStyleLst (idx-1000, 1-based). 1,727 census+ * shapes carry NO local fill — without this walk they render unfilled with no+ * error to notice.+ */+export function resolveFillRef(idx: number, phClr: string, theme: ThemeCtx): StyleFill | undefined {+ if (idx === 0) return { kind: 'none' }+ if (idx < 0) return undefined+ const bg = idx >= 1000+ const el = (bg ? theme.bgFillStyles : theme.fillStyles)[(bg ? idx - 1000 : idx) - 1]+ if (!el) return undefined+ if (el.ns === NS.a && el.local === 'solidFill') {+ const color = resolveColor(el, theme, phClr)+ return color ? { kind: 'solid', color } : undefined+ }+ return { kind: 'other', el, phClr }+}++/**+ * A line style resolved through a:lnRef. The raw a:ln element rides along —+ * shapes.ts reads width/cap/dash from it — with its solid colour pre-resolved+ * when it has one (gradient strokes stay in `ln` for shapes.ts).+ */+export type StyleLine =+ | { kind: 'none' }+ | { kind: 'ln'; ln: XElem; phClr: string; color?: ColorResult }++export function resolveLnRef(idx: number, phClr: string, theme: ThemeCtx): StyleLine | undefined {+ if (idx === 0) return { kind: 'none' }+ if (idx < 0) return undefined+ const ln = theme.lineStyles[idx - 1]+ if (!ln) return undefined+ const color = resolveColor(kid(ln, NS.a, 'solidFill'), theme, phClr)+ return { kind: 'ln', ln, phClr, color }+}diff --git a/kernel/src/convert/types.ts b/kernel/src/convert/types.tsnew file mode 100644index 00000000..d4f6c95d--- /dev/null+++ b/kernel/src/convert/types.ts@@ -0,0 +1,172 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+//+// The convert engine's shared contract.+//+// STRUCTURAL OUTPUT TYPES, NOT AN IMPORT FROM slides/. The kernel is shared+// code and must not depend on an app; the same inversion the charts engine+// uses (kernel/src/charts.ts declares its own option shape, slides satisfies+// it structurally). These types describe the SUBSET of bento/slides the+// importer emits — slides' parseDoc validates the real thing on load, and the+// e2e rig asserts the emitted JSON loads there. Field names and semantics must+// match slides/src/model.ts exactly; when in doubt, that file wins.++import type { Report } from './report.ts'+import type { XElem } from './xml.ts'++// --- the emitted document (bento/slides subset) ------------------------------++export interface OutShadow { x?: number; y?: number; blur: number; color: string }++export interface OutElementBase {+ id: string+ x: number; y: number; w: number; h: number+ rotation: number+ opacity: number+ link?: string+ groupId?: string+ role?: string+ shadow?: OutShadow | OutShadow[]+}++export interface OutText extends OutElementBase {+ type: 'text'+ html: string+ fontSize: number+ fontFamily: string+ fontWeight: number+ color: string+ align: 'left' | 'center' | 'right'+ valign: 'top' | 'middle' | 'bottom'+ lineHeight: number+ letterSpacing?: number+}++export interface OutGradient { angle: number; stops: Array<{ at: number; color: string }> }++export interface OutShape extends OutElementBase {+ type: 'shape'+ shape: 'rect' | 'ellipse' | 'triangle' | 'arrow' | 'line' | 'path'+ fill: string+ stroke: string+ strokeWidth: number+ radius: number+ strokeStyle?: 'solid' | 'dashed' | 'dotted'+ lineStart?: 'none' | 'arrow' | 'dot' | 'bar'+ lineEnd?: 'none' | 'arrow' | 'dot' | 'bar'+ fillGradient?: OutGradient+ d?: string+ pathBox?: [number, number, number, number]+ from?: { el: string; side: string }+ to?: { el: string; side: string }+}++export interface OutImage extends OutElementBase {+ type: 'image'+ src: string+ fit: 'cover' | 'contain' | 'fill'+ radius?: number+}++export interface OutTableCell { html: string; align?: string; color?: string; bg?: string; bold?: boolean }++export interface OutTable extends OutElementBase {+ type: 'table'+ columns: Array<{ w: number }>+ rows: Array<{ cells: OutTableCell[] }>+ header: boolean+ style?: Record<string, unknown>+}++export interface OutChart extends OutElementBase {+ type: 'chart'+ preset: 'bar' | 'line' | 'pie' | 'scatter'+ option: Record<string, unknown>+}++export type OutElement = OutText | OutShape | OutImage | OutTable | OutChart++export interface OutSlide {+ id: string+ name: string+ background: string+ /** ALWAYS set explicitly — slides' own constructors default to 'fade', and+ * 71 of 79 census slides carry no transition at all */+ transition: 'none' | 'fade' | 'slide' | 'zoom' | 'morph'+ notes: string+ elements: OutElement[]+ hidden?: boolean+}++export interface OutDoc {+ format: 'bento/slides'+ version: '1.0.0'+ title: string+ size: { width: number; height: number }+ theme: { background: string; color: string; accent: string; fontFamily: string }+ assets: Record<string, string>+ fonts: Array<{ family: string; asset: string; weight?: number }> | null+ slides: OutSlide[]+}++// --- resolution context ------------------------------------------------------++/** A parsed theme part (theme1.xml) plus the master's colour map. */+export interface ThemeCtx {+ /** scheme slot → resolved hex, AFTER clrMap application: keys are the+ * logical names colour references use (bg1, tx1, bg2, tx2, accent1..6,+ * hlink, folHlink) */+ scheme: Record<string, string>+ /** major (heading) and minor (body) latin typefaces, as named in the file */+ majorFont: string+ minorFont: string+ /** raw fmtScheme lists for fillRef/lnRef resolution (fill styles, line+ * styles, background fill styles) — resolved lazily with phClr substituted */+ fillStyles: XElem[]+ lineStyles: XElem[]+ bgFillStyles: XElem[]+}++/** One resolved colour. */+export interface ResolvedColor {+ /** css color, '#rrggbb' or rgba(...) when alpha < 1 */+ css: string+ from: 'own' | 'theme'+}++/**+ * The inheritance chain for one slide: everything a shape may need to look up+ * when its own XML is silent. ~513 census shapes carry no geometry and 100++ * no transform at all — their values live only up this chain.+ */+export interface InheritCtx {+ slide: XElem+ layout?: XElem+ master?: XElem+ theme: ThemeCtx+ report: Report+}++// --- conversion result -------------------------------------------------------++export interface ConvertResult {+ doc: OutDoc+ report: import('./report.ts').FidelityReport+}++/** EMU per pixel at 96dpi — OOXML's unit; 12192000 EMU = 1280px exactly. */+export const EMU_PER_PX = 9525++/**+ * Metric-compatible substitutes: same advance widths, so line breaks land+ * where PowerPoint put them. The engine maps NAMES (byte embedding is a host+ * concern); the emitted stack keeps the original first so a machine that has+ * the real face uses it.+ */+export const METRIC_SUBSTITUTES: Record<string, string> = {+ Calibri: 'Carlito',+ Cambria: 'Caladea',+ Arial: 'Liberation Sans',+ 'Times New Roman': 'Liberation Serif',+ 'Courier New': 'Liberation Mono',+}diff --git a/kernel/src/convert/xml.ts b/kernel/src/convert/xml.tsnew file mode 100644index 00000000..f5b22dfc--- /dev/null+++ b/kernel/src/convert/xml.ts@@ -0,0 +1,304 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+//+// A small namespace-aware XML parser — the one dash's regex scanner cannot be.+//+// dash/src/xlsx.ts reads spreadsheet XML with regex, and its header is explicit+// that this is safe ONLY because none of the elements it reads can nest inside+// themselves. PresentationML breaks that guarantee immediately: `p:grpSp`+// contains `p:grpSp` (94 groups across the census decks), so the convert+// engine needs a real parser. It also needs to run in node — every rig in this+// repo does — which rules out DOMParser, and it must never execute or fetch+// anything, which a real DOM parser must be configured out of.+//+// So: a tokenizing parser producing a plain tree. What it accepts is the XML+// that OOXML producers actually write; what it refuses, it refuses loudly:+//+// - DOCTYPE is REJECTED outright. OOXML never carries one, and refusing it+// kills the entire entity-expansion attack class (billion laughs, external+// entities) by construction rather than by limits.+// - Only the five predefined entities and numeric character references+// expand. Anything else is an error, not a silent pass-through.+// - A mismatched close tag is an error with an offset, never a re-sync — a+// half-parsed document is a wrong document.+//+// Namespaces are resolved for real (xmlns tracking with proper scoping), not+// assumed from prefixes. Real files essentially always use the conventional+// prefixes, but a resolver keyed on `a:` would silently read nothing from a+// file that says `xmlns:d="…drawingml…"` — and "silently read nothing" is the+// exact failure mode this engine exists to avoid.++export class XmlError extends Error {+ // NOT a constructor parameter property: rigs run under plain node type+ // stripping, which refuses non-erasable TS syntax — a parameter property+ // here made every convert rig unrunnable.+ offset: number+ constructor(message: string, offset: number) {+ super(`${message} (at offset ${offset})`)+ this.offset = offset+ }+}++export interface XElem {+ /** tag name as written in the file, e.g. "p:grpSp" */+ name: string+ /** local part, e.g. "grpSp" */+ local: string+ /** resolved namespace URI; '' when the element is in no namespace */+ ns: string+ /** attribute names exactly as written (a Map: `__proto__="…"` is legal XML) */+ attrs: Map<string, string>+ children: Array<XElem | string>+}++/** The OOXML namespaces this engine reads. */+export const NS = {+ a: 'http://schemas.openxmlformats.org/drawingml/2006/main',+ p: 'http://schemas.openxmlformats.org/presentationml/2006/main',+ r: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships',+ rel: 'http://schemas.openxmlformats.org/package/2006/relationships',+ ct: 'http://schemas.openxmlformats.org/package/2006/content-types',+ c: 'http://schemas.openxmlformats.org/drawingml/2006/chart',+ mc: 'http://schemas.openxmlformats.org/markup-compatibility/2006',+ asvg: 'http://schemas.microsoft.com/office/drawing/2016/SVG/main',+} as const++const ENTITIES: Record<string, string> = { lt: '<', gt: '>', amp: '&', apos: "'", quot: '"' }++function decodeEntities(s: string, at: number): string {+ if (!s.includes('&')) return s+ return s.replace(/&(#x?[0-9a-fA-F]+|\w+);/g, (m, body: string) => {+ if (body[0] === '#') {+ const code = body[1] === 'x' || body[1] === 'X'+ ? parseInt(body.slice(2), 16)+ : parseInt(body.slice(1), 10)+ if (!Number.isFinite(code) || code < 0 || code > 0x10ffff) {+ throw new XmlError(`bad character reference ${m}`, at)+ }+ return String.fromCodePoint(code)+ }+ const v = ENTITIES[body]+ if (v === undefined) throw new XmlError(`unknown entity ${m}`, at)+ return v+ })+}++const NAME_RE = /^[A-Za-z_][\w.-]*(?::[A-Za-z_][\w.-]*)?$/++/**+ * Parse one XML document to its root element.+ *+ * Comments and processing instructions are skipped; CDATA becomes text; text+ * is kept verbatim (leading/trailing whitespace included — `a:t` content with+ * `xml:space="preserve"` depends on it; callers that want tag-only children+ * filter for themselves).+ */+export function parseXml(src: string): XElem {+ let i = 0+ const n = src.length++ // prolog: BOM, xml declaration, comments/PIs, whitespace — and no DOCTYPE+ if (src.charCodeAt(0) === 0xfeff) i = 1+ const skipMisc = () => {+ for (;;) {+ while (i < n && /\s/.test(src[i])) i+++ if (src.startsWith('<?', i)) {+ const end = src.indexOf('?>', i)+ if (end < 0) throw new XmlError('unterminated processing instruction', i)+ i = end + 2+ } else if (src.startsWith('<!--', i)) {+ const end = src.indexOf('-->', i)+ if (end < 0) throw new XmlError('unterminated comment', i)+ i = end + 3+ } else if (src.startsWith('<!DOCTYPE', i)) {+ throw new XmlError('DOCTYPE is not allowed', i)+ } else return+ }+ }+ skipMisc()+ if (src[i] !== '<') throw new XmlError('expected an element', i)++ // xmlns scopes: a stack of prefix→uri maps, innermost last+ const scopes: Array<Map<string, string>> = [new Map([['xml', 'http://www.w3.org/XML/1998/namespace']])]+ const lookup = (prefix: string, at: number): string => {+ for (let s = scopes.length - 1; s >= 0; s--) {+ const uri = scopes[s].get(prefix)+ if (uri !== undefined) return uri+ }+ if (prefix === '') return ''+ throw new XmlError(`undeclared namespace prefix "${prefix}"`, at)+ }++ function parseAttrs(at: number): { attrs: Map<string, string>; scope: Map<string, string> | null } {+ const attrs = new Map<string, string>()+ let scope: Map<string, string> | null = null+ for (;;) {+ while (i < n && /\s/.test(src[i])) i+++ const ch = src[i]+ if (ch === '>' || ch === '/' || ch === '?') return { attrs, scope }+ if (i >= n) throw new XmlError('unterminated start tag', at)+ const eq = src.indexOf('=', i)+ if (eq < 0) throw new XmlError('malformed attribute', i)+ const name = src.slice(i, eq).trim()+ if (!NAME_RE.test(name) && !name.startsWith('xmlns')) throw new XmlError(`bad attribute name "${name}"`, i)+ let j = eq + 1+ while (j < n && /\s/.test(src[j])) j+++ const quote = src[j]+ if (quote !== '"' && quote !== "'") throw new XmlError('attribute value must be quoted', j)+ const close = src.indexOf(quote, j + 1)+ if (close < 0) throw new XmlError('unterminated attribute value', j)+ const value = decodeEntities(src.slice(j + 1, close), j)+ if (name === 'xmlns') (scope ??= new Map()).set('', value)+ else if (name.startsWith('xmlns:')) (scope ??= new Map()).set(name.slice(6), value)+ attrs.set(name, value)+ i = close + 1+ }+ }++ function parseElement(): XElem {+ const at = i+ i++ // consume '<'+ let j = i+ while (j < n && !/[\s/>]/.test(src[j])) j+++ const name = src.slice(i, j)+ if (!NAME_RE.test(name)) throw new XmlError(`bad element name "${name}"`, at)+ i = j+ const { attrs, scope } = parseAttrs(at)+ if (scope) scopes.push(scope)+ const colon = name.indexOf(':')+ const prefix = colon < 0 ? '' : name.slice(0, colon)+ const local = colon < 0 ? name : name.slice(colon + 1)+ const el: XElem = { name, local, ns: lookup(prefix, at), attrs, children: [] }++ if (src[i] === '/') {+ if (src[i + 1] !== '>') throw new XmlError('malformed self-closing tag', i)+ i += 2+ if (scope) scopes.pop()+ return el+ }+ if (src[i] !== '>') throw new XmlError('malformed start tag', i)+ i++++ // content+ for (;;) {+ if (i >= n) throw new XmlError(`unclosed element <${name}>`, at)+ if (src[i] === '<') {+ if (src.startsWith('</', i)) {+ const end = src.indexOf('>', i)+ if (end < 0) throw new XmlError('unterminated close tag', i)+ const closing = src.slice(i + 2, end).trim()+ if (closing !== name) throw new XmlError(`expected </${name}>, found </${closing}>`, i)+ i = end + 1+ if (scope) scopes.pop()+ return el+ }+ if (src.startsWith('<!--', i)) {+ const end = src.indexOf('-->', i)+ if (end < 0) throw new XmlError('unterminated comment', i)+ i = end + 3+ } else if (src.startsWith('<![CDATA[', i)) {+ const end = src.indexOf(']]>', i)+ if (end < 0) throw new XmlError('unterminated CDATA', i)+ el.children.push(src.slice(i + 9, end))+ i = end + 3+ } else if (src.startsWith('<?', i)) {+ const end = src.indexOf('?>', i)+ if (end < 0) throw new XmlError('unterminated processing instruction', i)+ i = end + 2+ } else if (src.startsWith('<!DOCTYPE', i)) {+ throw new XmlError('DOCTYPE is not allowed', i)+ } else {+ el.children.push(parseElement())+ }+ } else {+ const next = src.indexOf('<', i)+ const end = next < 0 ? n : next+ const text = decodeEntities(src.slice(i, end), i)+ if (text) el.children.push(text)+ i = end+ }+ }+ }++ const root = parseElement()+ skipMisc()+ if (i < n) throw new XmlError('content after the root element', i)+ return root+}++// --- tree helpers -----------------------------------------------------------++/** Child elements, optionally filtered by namespace URI + local name. */+export function kids(el: XElem, ns?: string, local?: string): XElem[] {+ const out: XElem[] = []+ for (const c of el.children) {+ if (typeof c === 'string') continue+ if (ns !== undefined && c.ns !== ns) continue+ if (local !== undefined && c.local !== local) continue+ out.push(c)+ }+ return out+}++/** First matching child element, or undefined. */+export function kid(el: XElem, ns: string, local: string): XElem | undefined {+ for (const c of el.children) {+ if (typeof c !== 'string' && c.ns === ns && c.local === local) return c+ }+ return undefined+}++/** Every matching descendant, document order, the element itself excluded. */+export function descendants(el: XElem, ns: string, local: string): XElem[] {+ const out: XElem[] = []+ const walk = (e: XElem) => {+ for (const c of e.children) {+ if (typeof c === 'string') continue+ if (c.ns === ns && c.local === local) out.push(c)+ walk(c)+ }+ }+ walk(el)+ return out+}++/** Concatenated text content of the subtree. */+export function textOf(el: XElem): string {+ let out = ''+ for (const c of el.children) out += typeof c === 'string' ? c : textOf(c)+ return out+}++/** Attribute by name, prefix-insensitive (`r:id` matches `id` and vice versa). */+export function attr(el: XElem, name: string): string | undefined {+ const v = el.attrs.get(name)+ if (v !== undefined) return v+ for (const [k, val] of el.attrs) {+ if (k === name || k.endsWith(`:${name}`)) return val+ }+ return undefined+}++/** Integer attribute, or the fallback when absent/unparseable. */+export function intAttr(el: XElem, name: string, fallback = 0): number {+ const v = attr(el, name)+ if (v === undefined) return fallback+ const num = parseInt(v, 10)+ return Number.isFinite(num) ? num : fallback+}++/**+ * Resolve mc:AlternateContent: take the FIRST mc:Choice whose Requires prefix+ * we understand, else mc:Fallback's children. An mc-blind reader double-imports+ * (it sees Choice AND Fallback); the census has 61 of these carrying 100% of+ * the transitions and every SVG image pair.+ */+export function resolveAlternate(el: XElem, understood: Set<string>): Array<XElem | string> {+ if (el.ns !== NS.mc || el.local !== 'AlternateContent') return [el]+ for (const choice of kids(el, NS.mc, 'Choice')) {+ const req = attr(choice, 'Requires') ?? ''+ if (req.split(/\s+/).every((p) => !p || understood.has(p))) return choice.children+ }+ const fb = kid(el, NS.mc, 'Fallback')+ return fb ? fb.children : []+}diff --git a/kernel/src/convert/zip.ts b/kernel/src/convert/zip.tsnew file mode 100644index 00000000..89026584--- /dev/null+++ b/kernel/src/convert/zip.ts@@ -0,0 +1,348 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// A minimal ZIP reader and writer — the container .xlsx, .pptx and .docx+// are all made of. Lifted verbatim from dash/src/zip.ts (which now re-exports+// it) when the convert engine became its second consumer.+//+// WHY THIS EXISTS RATHER THAN A DEPENDENCY. The shell ships as one+// self-contained HTML file and the whole app is ~98 KB compressed. JSZip is+// ~100 KB and SheetJS is larger than the entire product, so either one doubles+// the file every user downloads in order to open a format most of them will+// never touch. What .xlsx actually needs from ZIP is a fraction of the spec: a+// few dozen small parts, DEFLATE or stored, no encryption, no spanning, no+// streaming producer. That fraction is this file, and the browser already+// carries the expensive half — `DecompressionStream`/`CompressionStream`+// ('deflate-raw') are the same primitives the compressed-shell loader boots on,+// so the baseline is established and costs us nothing.+//+// THE READER TRUSTS THE CENTRAL DIRECTORY, NOT THE LOCAL HEADERS, and that is+// the single decision that makes a hand-written reader survive real files.+// A writer that does not know a part's size in advance (every streaming+// producer — which is most server-side xlsx generators) sets general-purpose+// bit 3, writes zeroes for crc/sizes in the local header, and appends a data+// DESCRIPTOR after the compressed bytes. Reading sizes from the local header+// then yields zero, and the naive fix — scanning forward for the next signature+// — collides with compressed data that happens to contain those four bytes.+// The central directory always has the true sizes. The local header is read for+// exactly one thing: its name and extra-field lengths, which give the offset+// where the data begins, and which may legitimately DIFFER from the central+// copy's (Excel itself writes a Zip64 extra field in one and not the other).+//+// WHAT IS DELIBERATELY NOT HERE: encryption (an encrypted xlsx must be refused,+// loudly, not half-read), multi-disk archives (a floppy-era feature), ZIP64+// WRITING (we would have to be emitting >4 GB from a browser tab, which the+// document budget rules out long before), and CP437 filename decoding — every+// part name inside an OPC package is ASCII by specification, so UTF-8 decodes+// it correctly whether or not the flag bit is set.++/** Thrown for a container that is not a ZIP, or is one we refuse to guess at. */+export class ZipError extends Error {+ constructor(message: string) { super(message); this.name = 'ZipError' }+}++const SIG_LOCAL = 0x04034b50+const SIG_CD = 0x02014b50+const SIG_EOCD = 0x06054b50+const SIG_EOCD64 = 0x06064b50+const SIG_EOCD64_LOC = 0x07064b50++const enc = new TextEncoder()+const dec = new TextDecoder()++// --- CRC-32 -----------------------------------------------------------------+// Built once, on first use. A ZIP whose CRCs are wrong is a ZIP that `unzip -t`+// rejects and Excel calls corrupt, and there is no way to notice by eye — which+// is exactly why the reader verifies them too (see `readZip`).++let CRC_TABLE: Uint32Array | null = null++function crcTable(): Uint32Array {+ if (CRC_TABLE) return CRC_TABLE+ const t = new Uint32Array(256)+ for (let n = 0; n < 256; n++) {+ let c = n+ for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1+ t[n] = c >>> 0+ }+ CRC_TABLE = t+ return t+}++/** The ZIP/PNG CRC-32 of a byte range. Exported because the rig checks it+ * against a known vector — a self-consistent wrong CRC would be invisible. */+export function crc32(b: Uint8Array): number {+ const t = crcTable()+ let c = 0xffffffff+ for (let i = 0; i < b.length; i++) c = t[(c ^ b[i]) & 0xff] ^ (c >>> 8)+ return (c ^ 0xffffffff) >>> 0+}++// --- DEFLATE, through the platform -------------------------------------------++const hasCompression = (): boolean => typeof CompressionStream !== 'undefined'++async function through(b: Uint8Array, s: ReadableWritablePair<Uint8Array, Uint8Array>): Promise<Uint8Array> {+ // A Blob is the shortest route from bytes to a ReadableStream that works+ // identically in a browser and in node's rigs; `Response.arrayBuffer` is the+ // shortest route back. Neither allocates more than one extra copy.+ const out = new Blob([b as BlobPart]).stream().pipeThrough(s as ReadableWritablePair<BufferSource, BufferSource>)+ return new Uint8Array(await new Response(out as BodyInit).arrayBuffer())+}++const inflateRaw = (b: Uint8Array): Promise<Uint8Array> =>+ through(b, new DecompressionStream('deflate-raw') as unknown as ReadableWritablePair<Uint8Array, Uint8Array>)++const deflateRaw = (b: Uint8Array): Promise<Uint8Array> =>+ through(b, new CompressionStream('deflate-raw') as unknown as ReadableWritablePair<Uint8Array, Uint8Array>)++// --- Reading -----------------------------------------------------------------++export interface ZipEntry {+ name: string+ data: Uint8Array+}++/**+ * Every part of a ZIP archive, by name.+ *+ * A Map rather than an object because part names are attacker-adjacent data:+ * `__proto__` is a perfectly legal ZIP entry name, and an object keyed by it is+ * a prototype-pollution hole in a file format people will open from email.+ */+export type ZipParts = Map<string, Uint8Array>++const u16 = (v: DataView, at: number): number => v.getUint16(at, true)+const u32 = (v: DataView, at: number): number => v.getUint32(at, true)+/** 64-bit little-endian as a JS number. Exact below 2^53, which every real+ * archive is; beyond it we would already have failed on allocation. */+const u64 = (v: DataView, at: number): number =>+ v.getUint32(at, true) + v.getUint32(at + 4, true) * 0x100000000++/** Locate the end-of-central-directory record, searching back over the+ * (almost always empty) archive comment. */+function findEocd(v: DataView, len: number): number {+ const min = Math.max(0, len - 22 - 0xffff)+ for (let i = len - 22; i >= min; i--) if (u32(v, i) === SIG_EOCD) return i+ throw new ZipError('this file does not end in a ZIP central directory — it is not an .xlsx')+}++/**+ * Read an archive into its parts.+ *+ * CRCs ARE VERIFIED. It costs one extra pass over data we have just inflated+ * anyway, and it converts the entire class of "the file was truncated by a mail+ * gateway / a partial download / a bad USB stick" from *silently short data*+ * into a refusal. Silently short data in a spreadsheet importer means a column+ * that stops early and a total that is wrong by exactly the missing rows, and+ * nothing on screen says so.+ */+export async function readZip(bytes: Uint8Array): Promise<ZipParts> {+ if (bytes.length < 22) throw new ZipError('this file is too small to be a ZIP archive')+ const v = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)+ const eocd = findEocd(v, bytes.length)++ let count = u16(v, eocd + 10)+ let cdOffset = u32(v, eocd + 16)++ // ZIP64 — reading only. Both markers must be honoured: an archive with more+ // than 65535 parts saturates the count, one over 4 GB saturates the offset,+ // and Excel writes ZIP64 for either. Missing this reads the central directory+ // from offset 0xFFFFFFFF, i.e. off the end, and the file "is not a ZIP".+ if (count === 0xffff || cdOffset === 0xffffffff) {+ const loc = eocd - 20+ if (loc < 0 || u32(v, loc) !== SIG_EOCD64_LOC) {+ throw new ZipError('this archive claims ZIP64 sizes but carries no ZIP64 locator')+ }+ const at = u64(v, loc + 8)+ if (u32(v, at) !== SIG_EOCD64) throw new ZipError('the ZIP64 central directory record is missing')+ count = u64(v, at + 32)+ cdOffset = u64(v, at + 48)+ }++ const parts: ZipParts = new Map()+ let p = cdOffset+ for (let i = 0; i < count; i++) {+ if (u32(v, p) !== SIG_CD) throw new ZipError('the ZIP central directory is damaged')+ const flags = u16(v, p + 8)+ const method = u16(v, p + 10)+ const crc = u32(v, p + 16)+ let csize = u32(v, p + 20)+ let usize = u32(v, p + 24)+ const nameLen = u16(v, p + 28)+ const extraLen = u16(v, p + 30)+ const commentLen = u16(v, p + 32)+ let local = u32(v, p + 42)+ const name = dec.decode(bytes.subarray(p + 46, p + 46 + nameLen))++ // Bit 0 is the 1989 password scheme; bit 6 is AES. Either way the bytes are+ // not the bytes, and half-reading them would produce garbage that looks+ // like a parse failure rather than a locked file.+ if (flags & 1) throw new ZipError(`"${name}" is encrypted — dash cannot open a password-protected workbook`)++ // The ZIP64 extra field replaces exactly the fields that saturated, in a+ // fixed order, and ONLY those. Reading it positionally without checking+ // which ones saturated is the classic way to shift every value by 8 bytes.+ if (usize === 0xffffffff || csize === 0xffffffff || local === 0xffffffff) {+ let e = p + 46 + nameLen+ const end = e + extraLen+ while (e + 4 <= end) {+ const id = u16(v, e)+ const size = u16(v, e + 2)+ if (id === 0x0001) {+ let q = e + 4+ if (usize === 0xffffffff) { usize = u64(v, q); q += 8 }+ if (csize === 0xffffffff) { csize = u64(v, q); q += 8 }+ if (local === 0xffffffff) { local = u64(v, q) }+ break+ }+ e += 4 + size+ }+ }++ if (u32(v, local) !== SIG_LOCAL) throw new ZipError(`"${name}" does not start with a ZIP local header`)+ // The LOCAL header's own name/extra lengths, never the central copy's:+ // Excel writes a ZIP64 extra field into one and not the other, and using+ // the wrong pair starts the data a few bytes early. The symptom is an+ // inflate error on a file every other tool opens.+ const dataAt = local + 30 + u16(v, local + 26) + u16(v, local + 28)+ const raw = bytes.subarray(dataAt, dataAt + csize)++ let data: Uint8Array+ if (method === 0) data = raw+ else if (method === 8) {+ // DecompressionStream rejects with a bare TypeError whose message is+ // often EMPTY, which is how a damaged file first showed up here: the+ // caller saw an unnamed exception from somewhere inside a stream and had+ // nothing to tell the user. Every failure this file can produce has to+ // arrive as a ZipError naming the part, or the refusal is not a refusal.+ try {+ data = await inflateRaw(raw)+ } catch {+ throw new ZipError(`"${name}" could not be decompressed — the file is damaged or truncated`)+ }+ } else throw new ZipError(`"${name}" uses compression method ${method}, which dash does not implement`)++ if (data.length !== usize) {+ throw new ZipError(`"${name}" unpacked to ${data.length} bytes but the directory says ${usize} — the file is truncated or damaged`)+ }+ if (crc32(data) !== crc) {+ throw new ZipError(`"${name}" failed its checksum — the file is damaged, and reading it anyway would give you data that is wrong without looking wrong`)+ }+ parts.set(name, data)+ p += 46 + nameLen + extraLen + commentLen+ }+ return parts+}++// --- Writing ------------------------------------------------------------------++export interface WriteOpts {+ /** Timestamp stamped into every entry. Fixed by default, so two exports of+ * one workbook are byte-identical and a diff means a real change. */+ at?: Date+ /** Skip DEFLATE. Only for the rig and for a browser without CompressionStream. */+ store?: boolean+}++/** DOS date/time. 1980-01-01 is the epoch of the field and the safe default —+ * an all-zero date is out of range and makes some tools print a warning. */+function dosStamp(d: Date | undefined): { time: number; date: number } {+ if (!d) return { time: 0, date: 33 } // 1980-01-01 00:00+ const y = Math.max(1980, d.getFullYear())+ return {+ time: (d.getHours() << 11) | (d.getMinutes() << 5) | (d.getSeconds() >> 1),+ date: ((y - 1980) << 9) | ((d.getMonth() + 1) << 5) | d.getDate(),+ }+}++/**+ * Build a ZIP archive.+ *+ * Entries are written in the order given, which for OPC matters more than it+ * looks: `[Content_Types].xml` must be the FIRST part, because a consumer is+ * entitled to stream the package and it cannot type any part until it has read+ * it. Excel tolerates it elsewhere; other readers have not always.+ *+ * DEFLATE is skipped when it does not pay (tiny parts, and anything that grew),+ * and the whole archive falls back to STORED where `CompressionStream` is+ * missing. A stored ZIP is a completely valid ZIP — just bigger — so an old+ * browser exports a working file instead of an error.+ */+export async function writeZip(entries: ZipEntry[], opts: WriteOpts = {}): Promise<Uint8Array> {+ const { time, date } = dosStamp(opts.at)+ const store = opts.store || !hasCompression()+ const locals: Uint8Array[] = []+ const central: Uint8Array[] = []+ let offset = 0+ let cdSize = 0++ for (const e of entries) {+ const name = enc.encode(e.name)+ const usize = e.data.length+ const crc = crc32(e.data)+ let method = 0+ let body = e.data+ if (!store && usize > 64) {+ const z = await deflateRaw(e.data)+ // A part that got BIGGER (already-compressed media, tiny XML) is stored.+ if (z.length < usize) { method = 8; body = z }+ }++ const lh = new Uint8Array(30 + name.length)+ const lv = new DataView(lh.buffer)+ lv.setUint32(0, SIG_LOCAL, true)+ lv.setUint16(4, 20, true) // version needed: 2.0 = DEFLATE+ lv.setUint16(6, 0x800, true) // bit 11: the name is UTF-8+ lv.setUint16(8, method, true)+ lv.setUint16(10, time, true)+ lv.setUint16(12, date, true)+ lv.setUint32(14, crc, true)+ lv.setUint32(18, body.length, true)+ lv.setUint32(22, usize, true)+ lv.setUint16(26, name.length, true)+ lv.setUint16(28, 0, true)+ lh.set(name, 30)++ const ch = new Uint8Array(46 + name.length)+ const cv = new DataView(ch.buffer)+ cv.setUint32(0, SIG_CD, true)+ cv.setUint16(4, 20, true) // version made by+ cv.setUint16(6, 20, true)+ cv.setUint16(8, 0x800, true)+ cv.setUint16(10, method, true)+ cv.setUint16(12, time, true)+ cv.setUint16(14, date, true)+ cv.setUint32(16, crc, true)+ cv.setUint32(20, body.length, true)+ cv.setUint32(24, usize, true)+ cv.setUint16(28, name.length, true)+ cv.setUint32(42, offset, true)+ ch.set(name, 46)++ locals.push(lh, body)+ central.push(ch)+ offset += lh.length + body.length+ cdSize += ch.length+ }++ const eocd = new Uint8Array(22)+ const ev = new DataView(eocd.buffer)+ ev.setUint32(0, SIG_EOCD, true)+ ev.setUint16(8, entries.length, true)+ ev.setUint16(10, entries.length, true)+ ev.setUint32(12, cdSize, true)+ ev.setUint32(16, offset, true)++ return concat([...locals, ...central, eocd])+}++export function concat(chunks: Uint8Array[]): Uint8Array {+ let n = 0+ for (const c of chunks) n += c.length+ const out = new Uint8Array(n)+ let at = 0+ for (const c of chunks) { out.set(c, at); at += c.length }+ return out+}++export const _internals = { findEocd, dosStamp, inflateRaw, deflateRaw }diff --git a/scripts/test-convert.ts b/scripts/test-convert.tsnew file mode 100644index 00000000..777c06f3--- /dev/null+++ b/scripts/test-convert.ts@@ -0,0 +1,34 @@+#!/usr/bin/env node+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// bento/convert suite runner — every rig in scripts/test-convert/, each in its+// own node process (a rig that crashes at import must fail ITS run, not take+// the suite's reporting down with it).+//+// node scripts/test-convert.ts+//+// Underscore-prefixed files are shared fixtures/helpers, not rigs. Order is+// alphabetical and deliberate: load.ts (the loadability gate) runs among the+// rest, and any child's non-zero exit fails the suite.++import { readdirSync } from 'node:fs'+import { spawnSync } from 'node:child_process'+import { join, dirname } from 'node:path'+import { fileURLToPath } from 'node:url'++const dir = join(dirname(fileURLToPath(import.meta.url)), 'test-convert')+const rigs = readdirSync(dir)+ .filter((f) => f.endsWith('.ts') && !f.startsWith('_'))+ .sort()++const failed: string[] = []+for (const rig of rigs) {+ console.log(`\n== ${rig} ==`)+ const r = spawnSync(process.execPath, [join(dir, rig)], { stdio: 'inherit' })+ if (r.status !== 0) failed.push(rig)+}++console.log(failed.length+ ? `\n${failed.length}/${rigs.length} rigs FAILED: ${failed.join(', ')}`+ : `\nall ${rigs.length} rigs passed`)+if (failed.length) process.exit(1)diff --git a/scripts/test-convert/_fixtures.ts b/scripts/test-convert/_fixtures.tsnew file mode 100644index 00000000..0a2eee1e--- /dev/null+++ b/scripts/test-convert/_fixtures.ts@@ -0,0 +1,405 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// bento/convert e2e fixtures — .pptx packages built IN CODE with writeZip, so+// there is not one binary file in the repo and every fixture is readable as+// source. Shared by the pptx rig (scripts/test-convert/pptx.ts, which asserts+// content + exact report sets) and the loadability gate+// (scripts/test-convert/load.ts, which asserts the emitted JSON survives the+// real slides parseDoc/validateDoc). The underscore prefix keeps the suite+// runner from executing this as a rig of its own.+//+// Every EMU number here is chosen so the expected px value is HAND-COMPUTABLE+// (multiples of 9525·N): 914400 EMU = 96px, 457200 = 48px, and so on. The+// expected values in the rigs are computed from these constants by hand, never+// by running the converter against itself.++import { writeZip, type ZipEntry } from '../../kernel/src/convert/zip.ts'++const enc = new TextEncoder()++const NSP = 'http://schemas.openxmlformats.org/presentationml/2006/main'+const NSA = 'http://schemas.openxmlformats.org/drawingml/2006/main'+const NSR = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'+const REL = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'+const PKG = 'http://schemas.openxmlformats.org/package/2006/relationships'++export const XMLNS = `xmlns:p="${NSP}" xmlns:a="${NSA}" xmlns:r="${NSR}"`++const CONTENT_TYPES =+ '<?xml version="1.0" encoding="UTF-8"?>' ++ '<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">' ++ '<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>' ++ '<Default Extension="xml" ContentType="application/xml"/>' ++ '<Default Extension="png" ContentType="image/png"/>' ++ '<Default Extension="svg" ContentType="image/svg+xml"/>' ++ '</Types>'++const relsXml = (entries: string): string =>+ `<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="${PKG}">${entries}</Relationships>`++const ROOT_RELS = relsXml(+ `<Relationship Id="rId1" Type="${REL}/officeDocument" Target="ppt/presentation.xml"/>` ++ `<Relationship Id="rId2" Type="${PKG}/metadata/core-properties" Target="docProps/core.xml"/>`,+)++// --- default chain parts -----------------------------------------------------++/** dk1 #000000 · lt1 #FFFFFF · dk2 #28303A · lt2 #E7E6E6 · accent1 #4472C4;+ * minor face Calibri (METRIC_SUBSTITUTES maps it to Carlito). */+export const DEFAULT_THEME = `<a:theme ${XMLNS} name="fixture"><a:themeElements>` ++ '<a:clrScheme name="fixture">' ++ '<a:dk1><a:srgbClr val="000000"/></a:dk1><a:lt1><a:srgbClr val="FFFFFF"/></a:lt1>' ++ '<a:dk2><a:srgbClr val="28303A"/></a:dk2><a:lt2><a:srgbClr val="E7E6E6"/></a:lt2>' ++ '<a:accent1><a:srgbClr val="4472C4"/></a:accent1><a:accent2><a:srgbClr val="FBAE40"/></a:accent2>' ++ '<a:accent3><a:srgbClr val="808080"/></a:accent3><a:accent4><a:srgbClr val="FF0000"/></a:accent4>' ++ '<a:accent5><a:srgbClr val="70AD47"/></a:accent5><a:accent6><a:srgbClr val="C00000"/></a:accent6>' ++ '<a:hlink><a:srgbClr val="0563C1"/></a:hlink><a:folHlink><a:srgbClr val="954F72"/></a:folHlink>' ++ '</a:clrScheme>' ++ '<a:fontScheme name="fixture">' ++ '<a:majorFont><a:latin typeface="Calibri Light"/></a:majorFont>' ++ '<a:minorFont><a:latin typeface="Calibri"/></a:minorFont>' ++ '</a:fontScheme>' ++ '<a:fmtScheme name="fixture">' ++ '<a:fillStyleLst>' ++ '<a:solidFill><a:schemeClr val="phClr"/></a:solidFill>' ++ '<a:solidFill><a:schemeClr val="phClr"/></a:solidFill>' ++ '<a:solidFill><a:schemeClr val="phClr"/></a:solidFill>' ++ '</a:fillStyleLst>' ++ '<a:lnStyleLst>' ++ '<a:ln w="6350"><a:solidFill><a:schemeClr val="phClr"/></a:solidFill></a:ln>' ++ '<a:ln w="12700"><a:solidFill><a:schemeClr val="phClr"/></a:solidFill></a:ln>' ++ '<a:ln w="19050"><a:solidFill><a:schemeClr val="phClr"/></a:solidFill></a:ln>' ++ '</a:lnStyleLst>' ++ '<a:bgFillStyleLst>' ++ '<a:solidFill><a:schemeClr val="phClr"/></a:solidFill>' ++ '<a:solidFill><a:schemeClr val="phClr"/></a:solidFill>' ++ '<a:solidFill><a:schemeClr val="phClr"/></a:solidFill>' ++ '</a:bgFillStyleLst>' ++ '</a:fmtScheme>' ++ '</a:themeElements></a:theme>'++export const STANDARD_CLRMAP =+ '<p:clrMap bg1="lt1" tx1="dk1" bg2="lt2" tx2="dk2" accent1="accent1" accent2="accent2"' ++ ' accent3="accent3" accent4="accent4" accent5="accent5" accent6="accent6" hlink="hlink" folHlink="folHlink"/>'++/** Title style 44pt — the value fixture 3 asserts through the master hop. */+export const DEFAULT_MASTER = (clrMap: string = STANDARD_CLRMAP): string =>+ `<p:sldMaster ${XMLNS}><p:cSld><p:spTree/></p:cSld>${clrMap}` ++ '<p:txStyles>' ++ '<p:titleStyle><a:lvl1pPr><a:defRPr sz="4400"/></a:lvl1pPr></p:titleStyle>' ++ '<p:bodyStyle><a:lvl1pPr><a:defRPr sz="1800"/></a:lvl1pPr></p:bodyStyle>' ++ '<p:otherStyle/>' ++ '</p:txStyles></p:sldMaster>'++/** Title placeholder frame: off (914400, 457200) ext (1828800, 914400)+ * → 96, 48, 192, 96 px. The slide-side ph is written BARE (`<p:ph/>`, the+ * census reality) and pairs by idx-absent-means-0. */+export const DEFAULT_LAYOUT = `<p:sldLayout ${XMLNS}><p:cSld><p:spTree>` ++ '<p:sp><p:nvSpPr><p:cNvPr id="100" name="Title Placeholder"/><p:cNvSpPr/>' ++ '<p:nvPr><p:ph type="title"/></p:nvPr></p:nvSpPr>' ++ '<p:spPr><a:xfrm><a:off x="914400" y="457200"/><a:ext cx="1828800" cy="914400"/></a:xfrm></p:spPr></p:sp>' ++ '<p:sp><p:nvSpPr><p:cNvPr id="101" name="Body Placeholder"/><p:cNvSpPr/>' ++ '<p:nvPr><p:ph type="body" idx="1"/></p:nvPr></p:nvSpPr>' ++ '<p:spPr><a:xfrm><a:off x="914400" y="1828800"/><a:ext cx="5486400" cy="2743200"/></a:xfrm></p:spPr></p:sp>' ++ '</p:spTree></p:cSld></p:sldLayout>'++// --- the package builder -----------------------------------------------------++export interface FixtureSlide {+ xml: string+ /** extra Relationship entries appended verbatim to the slide's .rels */+ rels?: string+ /** a notesSlide part, auto-wired via rIdNotes */+ notes?: string+}++export interface FixtureSpec {+ slides: FixtureSlide[]+ /** wire the full slide→layout→master→theme chain (default true) */+ chain?: boolean+ theme?: string+ master?: string+ layout?: string+ /** docProps/core.xml content */+ core?: string+ /** part name → bytes (strings are UTF-8 encoded) */+ media?: Record<string, string | Uint8Array>+ sldSz?: { cx: number; cy: number }+}++export async function buildPptx(spec: FixtureSpec): Promise<Uint8Array> {+ const chain = spec.chain !== false+ const entries: ZipEntry[] = []+ const put = (name: string, content: string | Uint8Array): void => {+ entries.push({ name, data: typeof content === 'string' ? enc.encode(content) : content })+ }++ // [Content_Types].xml first — OPC consumers may stream+ put('[Content_Types].xml', CONTENT_TYPES)+ put('_rels/.rels', ROOT_RELS)++ const { cx, cy } = spec.sldSz ?? { cx: 12192000, cy: 6858000 }+ const sldIds = spec.slides+ .map((_, i) => `<p:sldId id="${256 + i}" r:id="rId${i + 1}"/>`)+ .join('')+ put('ppt/presentation.xml',+ `<p:presentation ${XMLNS}><p:sldIdLst>${sldIds}</p:sldIdLst>` ++ `<p:sldSz cx="${cx}" cy="${cy}"/></p:presentation>`)+ put('ppt/_rels/presentation.xml.rels', relsXml(+ spec.slides+ .map((_, i) => `<Relationship Id="rId${i + 1}" Type="${REL}/slide" Target="slides/slide${i + 1}.xml"/>`)+ .join(''),+ ))++ spec.slides.forEach((s, i) => {+ const name = `slide${i + 1}`+ put(`ppt/slides/${name}.xml`, s.xml)+ let rels = s.rels ?? ''+ if (chain) rels += `<Relationship Id="rIdL" Type="${REL}/slideLayout" Target="../slideLayouts/slideLayout1.xml"/>`+ if (s.notes) {+ rels += `<Relationship Id="rIdN" Type="${REL}/notesSlide" Target="../notesSlides/notesSlide${i + 1}.xml"/>`+ put(`ppt/notesSlides/notesSlide${i + 1}.xml`, s.notes)+ }+ if (rels) put(`ppt/slides/_rels/${name}.xml.rels`, relsXml(rels))+ })++ if (chain) {+ put('ppt/slideLayouts/slideLayout1.xml', spec.layout ?? DEFAULT_LAYOUT)+ put('ppt/slideLayouts/_rels/slideLayout1.xml.rels', relsXml(+ `<Relationship Id="rId1" Type="${REL}/slideMaster" Target="../slideMasters/slideMaster1.xml"/>`,+ ))+ put('ppt/slideMasters/slideMaster1.xml', spec.master ?? DEFAULT_MASTER())+ put('ppt/slideMasters/_rels/slideMaster1.xml.rels', relsXml(+ `<Relationship Id="rId1" Type="${REL}/theme" Target="../theme/theme1.xml"/>`,+ ))+ put('ppt/theme/theme1.xml', spec.theme ?? DEFAULT_THEME)+ }++ if (spec.core) put('docProps/core.xml', spec.core)+ for (const [name, content] of Object.entries(spec.media ?? {})) put(name, content)++ return writeZip(entries)+}++// --- shared building blocks --------------------------------------------------++export const sp = (id: number, name: string, body: string): string =>+ `<p:sp><p:nvSpPr><p:cNvPr id="${id}" name="${name}"/><p:cNvSpPr/><p:nvPr/></p:nvSpPr>${body}</p:sp>`++export const xfrm = (x: number, y: number, w: number, h: number): string =>+ `<a:xfrm><a:off x="${x}" y="${y}"/><a:ext cx="${w}" cy="${h}"/></a:xfrm>`++export const slide = (body: string, attrs = ''): string =>+ `<p:sld ${XMLNS}${attrs ? ` ${attrs}` : ''}><p:cSld><p:spTree>${body}</p:spTree></p:cSld></p:sld>`++// --- the fixtures ------------------------------------------------------------++/** 1 · minimal: one bare text box, no chain at all, title from core.xml.+ * Expected report: NO entries. */+export function fxMinimal(): Promise<Uint8Array> {+ return buildPptx({+ chain: false,+ core: '<cp:coreProperties xmlns:cp="http://schemas.openxmlformats.org/package/2006/metadata/core-properties"' ++ ' xmlns:dc="http://purl.org/dc/elements/1.1/"><dc:title>Rig Deck</dc:title></cp:coreProperties>',+ slides: [{+ xml: slide(sp(2, 'Box',+ `<p:spPr>${xfrm(914400, 914400, 2743200, 457200)}` ++ '<a:prstGeom prst="rect"><a:avLst/></a:prstGeom><a:noFill/><a:ln><a:noFill/></a:ln></p:spPr>' ++ '<p:txBody><a:bodyPr><a:noAutofit/></a:bodyPr><a:lstStyle/>' ++ '<a:p><a:r><a:rPr lang="en-US" sz="1800"><a:solidFill><a:srgbClr val="28303A"/></a:solidFill>' ++ '<a:latin typeface="Georgia"/></a:rPr><a:t>Hello, Bento</a:t></a:r></a:p></p:txBody>')),+ }],+ })+}++/** 2 · themed: a SWAPPED clrMap (bg1→dk2, tx1→lt1) so a naive default-map+ * read fails loudly; a linear-light shade; the box-with-text split.+ * Expected report: NO entries. */+export function fxThemed(): Promise<Uint8Array> {+ const swapped =+ '<p:clrMap bg1="dk2" tx1="lt1" bg2="dk1" tx2="lt2" accent1="accent1" accent2="accent2"' ++ ' accent3="accent3" accent4="accent4" accent5="accent5" accent6="accent6" hlink="hlink" folHlink="folHlink"/>'+ const body =+ sp(2, 'BgRect',+ `<p:spPr>${xfrm(0, 0, 914400, 914400)}<a:prstGeom prst="rect"><a:avLst/></a:prstGeom>` ++ '<a:solidFill><a:schemeClr val="bg1"/></a:solidFill></p:spPr>') ++ sp(3, 'ShadeRect',+ `<p:spPr>${xfrm(914400, 0, 914400, 914400)}<a:prstGeom prst="rect"><a:avLst/></a:prstGeom>` ++ '<a:solidFill><a:srgbClr val="808080"><a:shade val="50000"/></a:srgbClr></a:solidFill></p:spPr>') ++ sp(4, 'LabelBox',+ `<p:spPr>${xfrm(0, 1828800, 1828800, 457200)}<a:prstGeom prst="rect"><a:avLst/></a:prstGeom>` ++ '<a:solidFill><a:schemeClr val="accent1"/></a:solidFill></p:spPr>' ++ '<p:txBody><a:bodyPr><a:noAutofit/></a:bodyPr><a:lstStyle/>' ++ '<a:p><a:r><a:rPr sz="1400"><a:latin typeface="Georgia"/></a:rPr><a:t>Label</a:t></a:r></a:p></p:txBody>')+ const xml =+ `<p:sld ${XMLNS}><p:cSld>` ++ '<p:bg><p:bgPr><a:solidFill><a:schemeClr val="bg1"/></a:solidFill><a:effectLst/></p:bgPr></p:bg>' ++ `<p:spTree>${body}</p:spTree></p:cSld></p:sld>`+ return buildPptx({ master: DEFAULT_MASTER(swapped), slides: [{ xml }] })+}++/** 3 · placeholder: a slide title written `<p:ph/>` (no type, no xfrm) whose+ * frame comes from the layout and whose size comes from the master's+ * titleStyle. No core.xml — the deck is titled by this text.+ * Expected report: text-needs-refit + font-substituted (Calibri). */+export function fxPlaceholder(): Promise<Uint8Array> {+ const xml = slide(+ '<p:sp><p:nvSpPr><p:cNvPr id="5" name="Title 1"/><p:cNvSpPr/>' ++ '<p:nvPr><p:ph/></p:nvPr></p:nvSpPr><p:spPr/>' ++ '<p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:r><a:t>Quarterly Review</a:t></a:r></a:p></p:txBody></p:sp>')+ return buildPptx({ slides: [{ xml }] })+}++/** 4 · nested group, 4:3 deck. Outer scales ×2 (ext 3657600×1828800 over+ * chExt 1828800×914400, off x 914400); inner group sits at (457200, 228600)+ * size 457200×228600 in outer child space → absolute (1828800, 457200,+ * 914400, 457200), which makes the inner map ANOTHER ×2. Leaf at (114300,+ * 57150) size 114300×57150 → absolute EMU (2057400, 571500, 228600, 114300)+ * = 216, 60, 24, 12 px. The single-scale wrong answer (outer map applied to+ * the leaf directly) is 914400+114300·2 = 1143000 → 120 px.+ * Expected report: nested-group-flattened. */+export function fxGroup(): Promise<Uint8Array> {+ const xml = slide(+ '<p:grpSp><p:nvGrpSpPr><p:cNvPr id="10" name="Outer"/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr>' ++ '<p:grpSpPr><a:xfrm><a:off x="914400" y="0"/><a:ext cx="3657600" cy="1828800"/>' ++ '<a:chOff x="0" y="0"/><a:chExt cx="1828800" cy="914400"/></a:xfrm></p:grpSpPr>' ++ '<p:grpSp><p:nvGrpSpPr><p:cNvPr id="11" name="Inner"/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr>' ++ '<p:grpSpPr><a:xfrm><a:off x="457200" y="228600"/><a:ext cx="457200" cy="228600"/>' ++ '<a:chOff x="0" y="0"/><a:chExt cx="457200" cy="228600"/></a:xfrm></p:grpSpPr>' ++ sp(12, 'Leaf',+ `<p:spPr>${xfrm(114300, 57150, 114300, 57150)}<a:prstGeom prst="rect"><a:avLst/></a:prstGeom>` ++ '<a:solidFill><a:srgbClr val="FF0000"/></a:solidFill></p:spPr>') ++ '</p:grpSp></p:grpSp>')+ return buildPptx({ chain: false, sldSz: { cx: 9144000, cy: 6858000 }, slides: [{ xml }] })+}++/** 5 · bullets: an lstStyle buChar silenced by one paragraph's buNone, and a+ * frozen buAutoNum that starts at 3.+ * Expected report: bullet-flattened + auto-number-frozen. */+export function fxBullets(): Promise<Uint8Array> {+ const xml = slide(+ sp(2, 'Bullets',+ `<p:spPr>${xfrm(914400, 914400, 4572000, 1828800)}</p:spPr>` ++ '<p:txBody><a:bodyPr><a:noAutofit/></a:bodyPr>' ++ '<a:lstStyle><a:lvl1pPr><a:buFont typeface="Arial"/><a:buChar char="•"/>' ++ '<a:defRPr sz="1800"><a:latin typeface="Georgia"/></a:defRPr></a:lvl1pPr></a:lstStyle>' ++ '<a:p><a:r><a:t>One</a:t></a:r></a:p>' ++ '<a:p><a:pPr><a:buNone/></a:pPr><a:r><a:t>Two</a:t></a:r></a:p>' ++ '<a:p><a:r><a:t>Three</a:t></a:r></a:p></p:txBody>') ++ sp(3, 'Numbers',+ `<p:spPr>${xfrm(914400, 3657600, 4572000, 914400)}</p:spPr>` ++ '<p:txBody><a:bodyPr><a:noAutofit/></a:bodyPr>' ++ '<a:lstStyle><a:lvl1pPr><a:defRPr sz="1800"><a:latin typeface="Georgia"/></a:defRPr></a:lvl1pPr></a:lstStyle>' ++ '<a:p><a:pPr><a:buAutoNum type="arabicPeriod" startAt="3"/></a:pPr><a:r><a:t>Alpha</a:t></a:r></a:p>' ++ '<a:p><a:pPr><a:buAutoNum type="arabicPeriod"/></a:pPr><a:r><a:t>Beta</a:t></a:r></a:p></p:txBody>'))+ return buildPptx({ chain: false, slides: [{ xml }] })+}++export const SVG_BYTES = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><circle cx="8" cy="8" r="7"/></svg>'+export const PNG_BYTES = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 1, 2, 3, 4])++/** 6 · svg+raster pair (svg must win) plus an unreferenced media part that+ * must be PRUNED from doc.assets.+ * Expected report: NO entries. */+export function fxSvg(): Promise<Uint8Array> {+ const xml = slide(+ '<p:pic><p:nvPicPr><p:cNvPr id="7" name="Icon"/><p:cNvPicPr/><p:nvPr/></p:nvPicPr>' ++ '<p:blipFill><a:blip r:embed="rId2"><a:extLst>' ++ '<a:ext uri="{96DAC541-7B7A-43D3-8B79-37D633B846F1}">' ++ '<asvg:svgBlip xmlns:asvg="http://schemas.microsoft.com/office/drawing/2016/SVG/main" r:embed="rId3"/>' ++ '</a:ext></a:extLst></a:blip><a:stretch><a:fillRect/></a:stretch></p:blipFill>' ++ `<p:spPr>${xfrm(914400, 914400, 914400, 914400)}</p:spPr></p:pic>`)+ return buildPptx({+ chain: false,+ slides: [{+ xml,+ rels:+ `<Relationship Id="rId2" Type="${REL}/image" Target="../media/image1.png"/>` ++ `<Relationship Id="rId3" Type="${REL}/image" Target="../media/icon.svg"/>`,+ }],+ media: {+ 'ppt/media/image1.png': PNG_BYTES,+ 'ppt/media/icon.svg': SVG_BYTES,+ 'ppt/media/unused.png': new Uint8Array([9, 9, 9, 9]),+ },+ })+}++/** 7 · connectors: one fully anchored (stCxn 2 → endCxn 3), one with a+ * DANGLING end (endCxn 99 — nothing on the slide has that id).+ * Expected report: connector-ref-dangling. */+export function fxConnectors(): Promise<Uint8Array> {+ const cxn = (id: number, st: number, end: number, y: number): string =>+ `<p:cxnSp><p:nvCxnSpPr><p:cNvPr id="${id}" name="Conn ${id}"/>` ++ `<p:cNvCxnSpPr><a:stCxn id="${st}" idx="3"/><a:endCxn id="${end}" idx="1"/></p:cNvCxnSpPr>` ++ `<p:nvPr/></p:nvCxnSpPr>` ++ `<p:spPr><a:xfrm><a:off x="1828800" y="${y}"/><a:ext cx="914400" cy="0"/></a:xfrm>` ++ '<a:prstGeom prst="straightConnector1"><a:avLst/></a:prstGeom>' ++ '<a:ln w="9525"><a:solidFill><a:srgbClr val="000000"/></a:solidFill><a:tailEnd type="triangle"/></a:ln>' ++ '</p:spPr></p:cxnSp>'+ const xml = slide(+ sp(2, 'A',+ `<p:spPr>${xfrm(457200, 228600, 1371600, 457200)}<a:prstGeom prst="rect"><a:avLst/></a:prstGeom>` ++ '<a:solidFill><a:srgbClr val="4472C4"/></a:solidFill></p:spPr>') ++ sp(3, 'B',+ `<p:spPr>${xfrm(2743200, 228600, 1371600, 457200)}<a:prstGeom prst="rect"><a:avLst/></a:prstGeom>` ++ '<a:solidFill><a:srgbClr val="FBAE40"/></a:solidFill></p:spPr>') ++ cxn(4, 2, 3, 457200) ++ cxn(5, 2, 99, 914400))+ return buildPptx({ chain: false, slides: [{ xml }] })+}++/** 8 · structure: a table and a chart graphicFrame (placeholder + honest+ * "not yet"), speaker notes (sldImg/sldNum placeholders skipped), a hidden+ * second slide carrying an mc:AlternateContent whose Fallback must be taken+ * exactly once, and NO transition anywhere (emitted 'none', never 'fade').+ * Expected report: table-not-yet + chart-not-yet. */+export function fxStructure(): Promise<Uint8Array> {+ const gframe = (id: number, name: string, y: number, data: string): string =>+ `<p:graphicFrame><p:nvGraphicFramePr><p:cNvPr id="${id}" name="${name}"/>` ++ '<p:cNvGraphicFramePr/><p:nvPr/></p:nvGraphicFramePr>' ++ `<p:xfrm><a:off x="914400" y="${y}"/><a:ext cx="4572000" cy="1828800"/></p:xfrm>` ++ `<a:graphic><a:graphicData ${data}</a:graphicData></a:graphic></p:graphicFrame>`+ const slide1 = slide(+ gframe(6, 'Table 1', 914400,+ 'uri="http://schemas.openxmlformats.org/drawingml/2006/table"><a:tbl/>') ++ gframe(7, 'Chart 1', 3657600,+ 'uri="http://schemas.openxmlformats.org/drawingml/2006/chart">' ++ '<c:chart xmlns:c="http://schemas.openxmlformats.org/drawingml/2006/chart" r:id="rId9"/>'))+ const notes =+ `<p:notes ${XMLNS}><p:cSld><p:spTree>` ++ '<p:sp><p:nvSpPr><p:cNvPr id="2" name="Slide Image"/><p:cNvSpPr/>' ++ '<p:nvPr><p:ph type="sldImg"/></p:nvPr></p:nvSpPr><p:spPr/></p:sp>' ++ '<p:sp><p:nvSpPr><p:cNvPr id="3" name="Notes"/><p:cNvSpPr/>' ++ '<p:nvPr><p:ph type="body" idx="1"/></p:nvPr></p:nvSpPr><p:spPr/>' ++ '<p:txBody><a:bodyPr/><a:p><a:r><a:t>Remember the demo</a:t></a:r></a:p></p:txBody></p:sp>' ++ '<p:sp><p:nvSpPr><p:cNvPr id="4" name="Num"/><p:cNvSpPr/>' ++ '<p:nvPr><p:ph type="sldNum" idx="10"/></p:nvPr></p:nvSpPr><p:spPr/>' ++ '<p:txBody><a:bodyPr/><a:p><a:r><a:t>1</a:t></a:r></a:p></p:txBody></p:sp>' ++ '</p:spTree></p:cSld></p:notes>'+ const rect = (id: number, color: string): string =>+ sp(id, `R${id}`,+ `<p:spPr>${xfrm(0, 0, 914400, 914400)}<a:prstGeom prst="rect"><a:avLst/></a:prstGeom>` ++ `<a:solidFill><a:srgbClr val="${color}"/></a:solidFill></p:spPr>`)+ const slide2 = slide(+ '<mc:AlternateContent xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006">' ++ `<mc:Choice Requires="p14">${rect(20, '00FF00')}</mc:Choice>` ++ `<mc:Fallback>${rect(21, '0000FF')}</mc:Fallback>` ++ '</mc:AlternateContent>',+ 'show="0"')+ return buildPptx({ chain: false, slides: [{ xml: slide1, notes }, { xml: slide2 }] })+}++/** Every fixture, for the loadability gate. */+export function allFixtures(): Array<{ name: string; build: () => Promise<Uint8Array> }> {+ return [+ { name: 'minimal', build: fxMinimal },+ { name: 'themed', build: fxThemed },+ { name: 'placeholder', build: fxPlaceholder },+ { name: 'group', build: fxGroup },+ { name: 'bullets', build: fxBullets },+ { name: 'svg', build: fxSvg },+ { name: 'connectors', build: fxConnectors },+ { name: 'structure', build: fxStructure },+ ]+}diff --git a/scripts/test-convert/inherit.ts b/scripts/test-convert/inherit.tsnew file mode 100644index 00000000..02a2042c--- /dev/null+++ b/scripts/test-convert/inherit.ts@@ -0,0 +1,319 @@+#!/usr/bin/env node+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// bento/convert inheritance-resolver rig.+//+// node scripts/test-convert/inherit.ts (Node ≥ 23.6 strips types natively)+//+// Hand-built master/layout/slide trees with hand-computed expected values, so+// nothing here is "the resolver agrees with itself". The scenarios are the+// census traps, each with its wrong-implementation counterpart demonstrated+// inline as the NEGATIVE control:+//+// • a slide title written `<p:ph/>` (no type — the census records ZERO+// type="title" slide placeholders) must pair with the layout's title by+// idx-0 default; the rig computes what a type-first matcher would pick+// and asserts it is the WRONG shape, so the check fails on that design.+// • buNone at a nearer source must SILENCE the master's buChar; the rig+// computes what a property-merging resolver would emit (a live bullet)+// and asserts ours does not.+// • sz is centipoints; lIns="0" is an explicit zero, not an absence.+// • a frame absent everywhere is zero + a report entry, never invented.++import { parseXml, kid, kids, descendants, attr, NS } from '../../kernel/src/convert/xml.ts'+import type { XElem } from '../../kernel/src/convert/xml.ts'+import { Report } from '../../kernel/src/convert/report.ts'+import type { ThemeCtx, InheritCtx } from '../../kernel/src/convert/types.ts'+import {+ placeholderChain, labeledChain, effectivePhType, resolveFrame, textDefaults, bodyInsets,+} from '../../kernel/src/convert/inherit.ts'++let failures = 0+let checks = 0+function ok(cond: boolean, msg: string) {+ checks+++ if (!cond) { failures++; console.log(` FAIL ${msg}`) }+ else console.log(` ok ${msg}`)+}++const XMLNS = 'xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main" ' ++ 'xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"'++// --------------------------------------------------------------- the fixtures++const master = parseXml(`<p:sldMaster ${XMLNS}>+ <p:cSld><p:spTree>+ <p:sp>+ <p:nvSpPr><p:cNvPr id="2" name="master-title"/><p:cNvSpPr/><p:nvPr><p:ph type="title"/></p:nvPr></p:nvSpPr>+ <p:spPr><a:xfrm><a:off x="838200" y="365125"/><a:ext cx="10515600" cy="1325563"/></a:xfrm></p:spPr>+ <p:txBody><a:bodyPr lIns="0"/><a:lstStyle/><a:p/></p:txBody>+ </p:sp>+ <p:sp>+ <p:nvSpPr><p:cNvPr id="3" name="master-body"/><p:cNvSpPr/><p:nvPr><p:ph type="body" idx="1"/></p:nvPr></p:nvSpPr>+ <p:spPr><a:xfrm><a:off x="838200" y="1825625"/><a:ext cx="10515600" cy="4351338"/></a:xfrm></p:spPr>+ <p:txBody><a:bodyPr tIns="91440"/><a:lstStyle/><a:p/></p:txBody>+ </p:sp>+ </p:spTree></p:cSld>+ <p:txStyles>+ <p:titleStyle>+ <a:lvl1pPr algn="ctr"><a:defRPr sz="4400" b="1"><a:solidFill><a:schemeClr val="tx1"/></a:solidFill><a:latin typeface="+mj-lt"/></a:defRPr></a:lvl1pPr>+ </p:titleStyle>+ <p:bodyStyle>+ <a:lvl1pPr algn="l"><a:lnSpc><a:spcPct val="90000"/></a:lnSpc><a:spcBef><a:spcPts val="1000"/></a:spcBef><a:buFont typeface="Arial"/><a:buChar char="•"/><a:defRPr sz="2800"/></a:lvl1pPr>+ <a:lvl2pPr><a:buFont typeface="Arial"/><a:buChar char="–"/><a:defRPr sz="2400"/></a:lvl2pPr>+ </p:bodyStyle>+ <p:otherStyle>+ <a:lvl1pPr><a:defRPr sz="1800"/></a:lvl1pPr>+ </p:otherStyle>+ </p:txStyles>+</p:sldMaster>`)++const layout = parseXml(`<p:sldLayout ${XMLNS}>+ <p:cSld><p:spTree>+ <p:sp>+ <p:nvSpPr><p:cNvPr id="2" name="layout-title"/><p:cNvSpPr/><p:nvPr><p:ph type="title"/></p:nvPr></p:nvSpPr>+ <p:spPr><a:xfrm><a:off x="914400" y="457200"/><a:ext cx="9144000" cy="1143000"/></a:xfrm></p:spPr>+ <p:txBody><a:bodyPr/><a:lstStyle><a:lvl1pPr><a:defRPr sz="3200"/></a:lvl1pPr></a:lstStyle><a:p/></p:txBody>+ </p:sp>+ <p:sp>+ <p:nvSpPr><p:cNvPr id="3" name="layout-body1"/><p:cNvSpPr/><p:nvPr><p:ph type="body" idx="1"/></p:nvPr></p:nvSpPr>+ <p:spPr/>+ <p:txBody><a:bodyPr rIns="0"/><a:lstStyle/><a:p/></p:txBody>+ </p:sp>+ <p:sp>+ <p:nvSpPr><p:cNvPr id="4" name="layout-decoy5"/><p:cNvSpPr/><p:nvPr><p:ph idx="5"/></p:nvPr></p:nvSpPr>+ <p:spPr><a:xfrm><a:off x="111" y="222"/><a:ext cx="333" cy="444"/></a:xfrm></p:spPr>+ <p:txBody><a:bodyPr/><a:lstStyle/><a:p/></p:txBody>+ </p:sp>+ </p:spTree></p:cSld>+</p:sldLayout>`)++const slide = parseXml(`<p:sld ${XMLNS}>+ <p:cSld><p:spTree>+ <p:sp>+ <p:nvSpPr><p:cNvPr id="10" name="slide-title"/><p:cNvSpPr/><p:nvPr><p:ph/></p:nvPr></p:nvSpPr>+ <p:spPr/>+ <p:txBody><a:bodyPr/><a:lstStyle/><a:p/></p:txBody>+ </p:sp>+ <p:sp>+ <p:nvSpPr><p:cNvPr id="11" name="slide-body"/><p:cNvSpPr/><p:nvPr><p:ph idx="1"/></p:nvPr></p:nvSpPr>+ <p:spPr/>+ <p:txBody><a:bodyPr lIns="182880"/><a:lstStyle><a:lvl1pPr><a:buNone/></a:lvl1pPr></a:lstStyle><a:p/></p:txBody>+ </p:sp>+ <p:sp>+ <p:nvSpPr><p:cNvPr id="12" name="slide-plain-body"/><p:cNvSpPr/><p:nvPr><p:ph idx="1"/></p:nvPr></p:nvSpPr>+ <p:spPr/>+ <p:txBody><a:bodyPr/><a:lstStyle/><a:p/></p:txBody>+ </p:sp>+ <p:sp>+ <p:nvSpPr><p:cNvPr id="13" name="slide-idx5"/><p:cNvSpPr/><p:nvPr><p:ph idx="5"/></p:nvPr></p:nvSpPr>+ <p:spPr/>+ <p:txBody><a:bodyPr/><a:lstStyle/><a:p/></p:txBody>+ </p:sp>+ <p:sp>+ <p:nvSpPr><p:cNvPr id="14" name="slide-fallback"/><p:cNvSpPr/><p:nvPr><p:ph type="body" idx="3"/></p:nvPr></p:nvSpPr>+ <p:spPr/>+ <p:txBody><a:bodyPr/><a:lstStyle/><a:p/></p:txBody>+ </p:sp>+ <p:sp>+ <p:nvSpPr><p:cNvPr id="15" name="slide-ctr"/><p:cNvSpPr/><p:nvPr><p:ph type="ctrTitle" idx="9"/></p:nvPr></p:nvSpPr>+ <p:spPr/>+ <p:txBody><a:bodyPr/><a:lstStyle/><a:p/></p:txBody>+ </p:sp>+ <p:sp>+ <p:nvSpPr><p:cNvPr id="16" name="slide-own"/><p:cNvSpPr/><p:nvPr><p:ph idx="1"/></p:nvPr></p:nvSpPr>+ <p:spPr><a:xfrm rot="5400000" flipH="1"><a:off x="100" y="200"/><a:ext cx="300" cy="400"/></a:xfrm></p:spPr>+ <p:txBody><a:bodyPr/><a:lstStyle/><a:p/></p:txBody>+ </p:sp>+ <p:sp>+ <p:nvSpPr><p:cNvPr id="17" name="slide-orphan"/><p:cNvSpPr/><p:nvPr><p:ph type="pic" idx="7"/></p:nvPr></p:nvSpPr>+ <p:spPr/>+ <p:txBody><a:bodyPr/><a:lstStyle/><a:p/></p:txBody>+ </p:sp>+ <p:sp>+ <p:nvSpPr><p:cNvPr id="18" name="slide-noph"/><p:cNvSpPr/><p:nvPr/></p:nvSpPr>+ <p:spPr/>+ <p:txBody><a:bodyPr/><a:lstStyle/><a:p/></p:txBody>+ </p:sp>+ </p:spTree></p:cSld>+</p:sld>`)++const theme: ThemeCtx = {+ scheme: {}, majorFont: 'TestMajor', minorFont: 'TestMinor',+ fillStyles: [], lineStyles: [], bgFillStyles: [],+}+const report = new Report()+const ctx: InheritCtx = { slide, layout, master, theme, report }++function nameOf(shape: XElem): string {+ for (const c of kids(shape)) {+ const cnv = kid(c, NS.p, 'cNvPr')+ if (cnv) return attr(cnv, 'name') ?? '?'+ }+ return '?'+}+function sp(root: XElem, name: string): XElem {+ for (const s of descendants(root, NS.p, 'sp')) if (nameOf(s) === name) return s+ throw new Error(`no sp named ${name}`)+}+function phTypeOf(shape: XElem): string | undefined {+ for (const c of kids(shape)) {+ const nv = kid(c, NS.p, 'nvPr')+ const ph = nv ? kid(nv, NS.p, 'ph') : undefined+ if (ph) return attr(ph, 'type')+ }+ return undefined+}++// ------------------------------------------------- chain matching (idx first)+{+ // The census-critical case: a slide title is `<p:ph/>` — no type, no idx.+ // Absent idx defaults to 0 on BOTH sides, which is the only thing that pairs+ // it with the layout's `<p:ph type="title"/>`.+ const chain = placeholderChain(sp(slide, 'slide-title'), ctx)+ ok(chain.length === 3, 'bare <p:ph/> chain reaches shape + layout + master')+ ok(nameOf(chain[1]) === 'layout-title', 'and the layout match is the TITLE (idx-0 default), not a body')+ ok(nameOf(chain[2]) === 'master-title', 'and the master match is the master title')++ // NEGATIVE control: what a type-first matcher would have picked. `<p:ph/>`+ // normalizes to 'body', so type matching lands on layout-body1 — the wrong+ // shape. Seen to fail: swapping the module to type-first matching makes the+ // chain check above pick layout-body1.+ const typeFirst = descendants(layout, NS.p, 'sp').find((s) => {+ const t = phTypeOf(s)+ return t === undefined || t === 'body'+ })+ ok(typeFirst !== undefined && nameOf(typeFirst) === 'layout-body1',+ 'negative control: a type-first matcher WOULD grab layout-body1 for the bare title ph')++ // idx beats type: slide idx=5 must take the idx-5 decoy even though a typed+ // body (idx=1) appears earlier in document order.+ const c5 = placeholderChain(sp(slide, 'slide-idx5'), ctx)+ ok(nameOf(c5[1]) === 'layout-decoy5', 'idx-match beats type-match (idx=5 takes the decoy, not the first body)')++ // type fallback fires only when no candidate shares the idx+ const cf = placeholderChain(sp(slide, 'slide-fallback'), ctx)+ ok(nameOf(cf[1]) === 'layout-body1', 'idx=3 matches nothing, so type="body" falls back to the body placeholder')+ ok(nameOf(cf[2]) === 'master-body', 'and the master hop matches by the layout ph')++ // ctrTitle ≡ title (idx=9 forces the type path)+ const cc = placeholderChain(sp(slide, 'slide-ctr'), ctx)+ ok(nameOf(cc[1]) === 'layout-title', 'ctrTitle matches a title placeholder')++ const cn = placeholderChain(sp(slide, 'slide-noph'), ctx)+ ok(cn.length === 1, 'a non-placeholder shape has a one-link chain')++ ok(effectivePhType(sp(slide, 'slide-title'), ctx) === 'title',+ 'effectivePhType lifts "title" from the layout side (the slide ph never says it)')+ ok(effectivePhType(sp(slide, 'slide-body'), ctx) === 'body', 'and a typeless body resolves to "body"')+ ok(effectivePhType(sp(slide, 'slide-noph'), ctx) === '', 'and a non-placeholder to ""')+}++// ------------------------------------------------------------------- frames+{+ const f1 = resolveFrame(sp(slide, 'slide-title'), ctx)+ ok(f1.x === 914400 && f1.y === 457200 && f1.w === 9144000 && f1.h === 1143000,+ 'a slide with no xfrm takes its frame from the layout placeholder')+ ok(f1.from === 'layout', 'and says so (provenance layout)')++ const f2 = resolveFrame(sp(slide, 'slide-plain-body'), ctx)+ ok(f2.x === 838200 && f2.y === 1825625 && f2.w === 10515600 && f2.h === 4351338,+ 'slide AND layout silent: the frame comes from the master placeholder')+ ok(f2.from === 'master', 'and says so (provenance master)')++ const f3 = resolveFrame(sp(slide, 'slide-own'), ctx)+ ok(f3.x === 100 && f3.y === 200 && f3.w === 300 && f3.h === 400 && f3.from === 'own',+ 'an own xfrm wins over the whole chain')+ ok(f3.rotation === 90, 'rot="5400000" is 60,000ths of a degree → 90°')+ ok(f3.flipH && !f3.flipV, 'flipH="1" reads as a flip, flipV absent does not')++ // absent everywhere: zero, reported, never invented+ const r2 = new Report()+ const f4 = resolveFrame(sp(slide, 'slide-orphan'), { ...ctx, report: r2 })+ ok(f4.x === 0 && f4.y === 0 && f4.w === 0 && f4.h === 0 && f4.from === 'default',+ 'a frame absent everywhere is all-zero (never invented)')+ const built = r2.build()+ ok(built.entries.some((e) => e.code === 'frame-missing' && e.verdict === 'dropped' && e.where.includes('slide-orphan')),+ 'and lands in the report as frame-missing/dropped naming the shape')++ ok(report.build().provenance['frame:layout'] >= 1 && report.build().provenance['frame:master'] >= 1,+ 'frame provenance is tallied per level')+}++// ------------------------------------------------------------- text defaults+{+ // title: sz from the LAYOUT lstStyle (3200 centipoints), everything else+ // from the master's titleStyle — per-property nearest-wins, not per-source.+ const t = textDefaults(sp(slide, 'slide-title'), ctx, 0, 'title')+ ok(t.fontSize === 32, 'layout lstStyle sz="3200" resolves to 32pt (centipoints ÷ 100) and beats the master’s 44')+ ok(t.fontSize !== 3200, 'negative control: a resolver skipping the ÷100 would say 3200')+ ok(t.bold === true, 'bold still comes from the master titleStyle (layout is silent on it)')+ ok(t.font === 'TestMajor', '+mj-lt resolves through ThemeCtx.majorFont')+ ok(t.align === 'center', 'algn="ctr" → center')+ ok(t.color !== undefined && t.color.local === 'schemeClr' && attr(t.color, 'val') === 'tx1',+ 'the colour comes back as the raw element for theme.resolveColor')++ // body level 2 (0-based 1): master bodyStyle lvl2pPr+ const b2 = textDefaults(sp(slide, 'slide-plain-body'), ctx, 1, 'body')+ ok(b2.fontSize === 24, 'level 1 (lvl2pPr) fontSize comes from master bodyStyle: 24pt')+ ok(b2.bullet.kind === 'char' && b2.bullet.char === '–', 'and its own level’s bullet (–), not lvl1’s')++ // body level 1: the full bodyStyle lvl1 row+ const b1 = textDefaults(sp(slide, 'slide-plain-body'), ctx, 0, 'body')+ ok(b1.fontSize === 28 && b1.align === 'left', 'bodyStyle lvl1: 28pt, left')+ ok(b1.lineHeight === 0.9, 'lnSpc spcPct val="90000" → 0.9')+ ok(b1.hasSpcBef && !b1.hasSpcAft, 'spcBef presence is surfaced for the caller to report')+ ok(b1.bullet.kind === 'char' && b1.bullet.char === '•' && b1.bullet.font === 'Arial',+ 'an untouched body inherits the master’s • bullet with its buFont')+ ok(b1.font === 'TestMinor', 'no latin anywhere → the minor (body) theme face')++ // THE PRECEDENCE TRAP: slide-body carries <a:buNone/> in its own lstStyle.+ const bn = textDefaults(sp(slide, 'slide-body'), ctx, 0, 'body')+ ok(bn.bullet.kind === 'none', 'buNone at the shape SILENCES the master’s inherited buChar')+ // NEGATIVE control: a property-merging resolver unions the sources, and the+ // master's buChar survives the union — demonstrate the wrong answer is live+ // in this data, then that ours differs from it. Seen to fail: making the+ // module scan past a buNone-only source to the next buChar flips bn to 'char'.+ const merged = (() => {+ const styles = kid(master, NS.p, 'txStyles')!+ const lvl1 = kid(kid(styles, NS.p, 'bodyStyle')!, NS.a, 'lvl1pPr')!+ return kid(lvl1, NS.a, 'buChar') ? 'char' : 'none'+ })()+ ok(merged === 'char', 'negative control: a merging resolver would emit the master’s bullet here')+ ok(bn.bullet.kind !== merged, 'and ours does not')+ ok(bn.fontSize === 28, 'while sz still flows past the buNone source (per-property, per-bullet-unit)')++ // non-placeholder → otherStyle+ const o = textDefaults(sp(slide, 'slide-noph'), ctx, 0, '')+ ok(o.fontSize === 18, 'a non-placeholder resolves through otherStyle (18pt)')+ ok(o.bullet.kind === 'none' && o.lineHeight === 1, 'and gets the quiet defaults: no bullet, single spacing')+}++// --------------------------------------------------------------- body insets+{+ // Explicit zero is a value, not an absence — a falsy check re-defaults to+ // 91440 and mis-widens the title by ~19px.+ const ti = bodyInsets(sp(slide, 'slide-title'), ctx)+ ok(ti.l === 0, 'master title lIns="0" survives as an explicit zero')+ ok(ti.t === 45720 && ti.r === 91440 && ti.b === 45720, 'unspecified insets take the OOXML defaults')++ // per-attribute walk: each side may come from a different level+ const bi = bodyInsets(sp(slide, 'slide-body'), ctx)+ ok(bi.l === 182880, 'own bodyPr lIns wins')+ ok(bi.r === 0, 'rIns="0" comes from the layout placeholder')+ ok(bi.t === 91440, 'tIns comes from the master placeholder')+ ok(bi.b === 45720, 'and bIns, said nowhere, is the 45720 default')++ const ni = bodyInsets(sp(slide, 'slide-noph'), ctx)+ ok(ni.l === 91440 && ni.t === 45720 && ni.r === 91440 && ni.b === 45720,+ 'no bodyPr attrs anywhere → all four defaults')+}++// chain shape sanity for downstream: labeledChain labels line up with the els+{+ const lc = labeledChain(sp(slide, 'slide-title'), ctx)+ ok(lc.map((l) => l.from).join(',') === 'own,layout,master', 'labeledChain provenance labels are own,layout,master')+}++console.log(`\n${checks - failures}/${checks} checks passed`)+if (failures) process.exit(1)diff --git a/scripts/test-convert/load.ts b/scripts/test-convert/load.tsnew file mode 100644index 00000000..dcd7daae--- /dev/null+++ b/scripts/test-convert/load.ts@@ -0,0 +1,71 @@+#!/usr/bin/env node+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// bento/convert loadability gate — the most important check in the suite.+//+// node scripts/test-convert/load.ts+//+// Every fixture package is converted and the emitted JSON is pushed through+// the REAL slides loader: parseDoc must return a document and validateDoc+// (measure:false) must report ZERO errors. The convert engine's own rigs+// prove the engine agrees with itself; only this gate proves the output loads+// in the actual app — and if it does not, nothing else matters.+//+// Mechanics: slides' validate.ts pulls render.ts, whose imports are+// extensionless and include the temml package, so plain node type-stripping+// cannot run it. Same answer as scripts/test-validate.ts: bundle with esbuild+// first. This rig does that itself — when run directly it bundles ITSELF and+// re-executes the bundle, so the runner (and a bare `node`) need no wrapper.++import { spawnSync } from 'node:child_process'+import { mkdtempSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join, dirname } from 'node:path'+import { fileURLToPath } from 'node:url'++if (!process.env.BENTO_CONVERT_LOAD_BUNDLED) {+ const self = fileURLToPath(import.meta.url)+ const root = join(dirname(self), '..', '..')+ const esbuild = join(root, 'slides', 'node_modules', '.bin', 'esbuild')+ const out = join(mkdtempSync(join(tmpdir(), 'convert-load-')), 'load.mjs')+ const b = spawnSync(esbuild, [self, '--bundle', '--platform=node', '--format=esm', `--outfile=${out}`],+ { stdio: 'inherit' })+ if (b.status !== 0) {+ console.log(' FAIL esbuild bundle step failed')+ process.exit(1)+ }+ const r = spawnSync(process.execPath, [out], {+ stdio: 'inherit',+ env: { ...process.env, BENTO_CONVERT_LOAD_BUNDLED: '1' },+ })+ process.exit(r.status ?? 1)+}++const { convertPptx } = await import('../../kernel/src/convert/pptx.ts')+const { allFixtures } = await import('./_fixtures.ts')+const { parseDoc } = await import('../../slides/src/model.ts')+const { validateDoc } = await import('../../slides/src/validate.ts')++let failures = 0+let checks = 0+function ok(cond: boolean, msg: string) {+ checks+++ if (!cond) { failures++; console.log(` FAIL ${msg}`) }+ else console.log(` ok ${msg}`)+}++for (const { name, build } of allFixtures()) {+ const result = await convertPptx(await build())+ // through JSON — the emitted document must survive as TEXT, the way it+ // actually travels (Replace from JSON…, window.bento.loadDoc)+ const parsed = parseDoc(JSON.stringify(result.doc))+ ok(parsed !== null, `${name}: parseDoc accepts the emitted document`)+ if (!parsed) continue+ const v = validateDoc(parsed, { measure: false })+ const errors = v.findings.filter((f) => f.severity === 'error')+ ok(errors.length === 0,+ `${name}: validateDoc reports zero errors (got ${errors.length}${errors.length ? `: ${errors.map((f) => f.code).join(', ')}` : ''})`)+}++console.log(`\n${checks - failures}/${checks} checks passed`)+if (failures) process.exit(1)diff --git a/scripts/test-convert/media.ts b/scripts/test-convert/media.tsnew file mode 100644index 00000000..70a4ff0d--- /dev/null+++ b/scripts/test-convert/media.ts@@ -0,0 +1,302 @@+#!/usr/bin/env node+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// bento/convert media rig — rels resolution, the asset store, p:pic → OutImage.+//+// node scripts/test-convert/media.ts (Node ≥ 23.6 strips types natively)+//+// Expected values are computed BY HAND (the '../' resolution, the base64+// vectors, the mime table) or by an implementation that is not ours+// (node:buffer for base64), never by round-tripping our own code. Each trap+// from the spike carries a NEGATIVE control — an input a naive converter gets+// wrong — verified to fail against deliberately broken variants of this module+// while it was written:+//+// • blip-as-bitmap: an svgBlip picture whose emitted asset must be the SVG+// bytes and must NOT contain the raster bytes.+// • base-blind rels: 'media/x.png' from 'ppt/slides/' must land in+// ppt/slides/media/, not ppt/media/.+// • dedup by name instead of content: same bytes under two part names = one+// key; different bytes of the SAME length = two keys.+// • fetch-the-External-target: an External image rel must come back+// undefined with the right code, not as a missing-part fetch attempt.++import { Buffer } from 'node:buffer'+import { parseXml } from '../../kernel/src/convert/xml.ts'+import { Report } from '../../kernel/src/convert/report.ts'+import type { InheritCtx } from '../../kernel/src/convert/types.ts'+import {+ parseRels, parseContentTypes, mimeFor, toBase64, AssetStore, imageFrom, _internals,+} from '../../kernel/src/convert/media.ts'++let failures = 0+let checks = 0+function ok(cond: boolean, msg: string) {+ checks+++ if (!cond) { failures++; console.log(` FAIL ${msg}`) }+ else console.log(` ok ${msg}`)+}++const enc = new TextEncoder()++// ------------------------------------------------------------------ .rels+{+ const rels = parseRels(parseXml(+ '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">' ++ '<Relationship Id="rId1" Type="http://x/image" Target="../media/image1.png"/>' ++ '<Relationship Id="rId2" Type="http://x/image" Target="media/local.png"/>' ++ '<Relationship Id="rId3" Type="http://x/image" Target="/ppt/media/abs.png"/>' ++ '<Relationship Id="rId4" Type="http://x/hyperlink" Target="https://example.com/a" TargetMode="External"/>' ++ '<Relationship Id="rId5" Type="http://x/image" Target="../media/image%202.png"/>' ++ '<Relationship Id="rId6" Type="http://x/image" Target="../../docProps/../ppt/media/up.png"/>' ++ '</Relationships>'), 'ppt/slides/')++ ok(rels.get('rId1')!.target === 'ppt/media/image1.png', "'../media/x' from ppt/slides/ resolves to ppt/media/")+ // NEGATIVE (base-blind resolver): no '..' means the target stays UNDER the base.+ ok(rels.get('rId2')!.target === 'ppt/slides/media/local.png',+ "'media/x' (no ../) stays under ppt/slides/ — a resolver ignoring the base would say ppt/media/")+ ok(rels.get('rId3')!.target === 'ppt/media/abs.png', 'a pack-absolute /ppt/… target ignores the base dir')+ ok(rels.get('rId4')!.mode === 'External' && rels.get('rId4')!.target === 'https://example.com/a',+ 'an External target keeps its URI verbatim, flagged by mode')+ ok(rels.get('rId5')!.target === 'ppt/media/image 2.png', "'%20' in the target is a literal space in the part name")+ ok(rels.get('rId6')!.target === 'ppt/media/up.png', "a '../../…/../' chain normalizes step by step")+ ok(_internals.resolveTarget('ppt/slides/', '../../../../x.png') === 'x.png', "'..' clamps at the package root")+}++// ---------------------------------------------------------- content types+const ctXml = parseXml(+ '<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">' ++ '<Default Extension="png" ContentType="image/x-census-png"/>' ++ '<Default Extension="svg" ContentType="image/svg+xml"/>' ++ '<Override PartName="/ppt/media/special.bin" ContentType="image/gif"/>' ++ '</Types>')+{+ const types = parseContentTypes(ctXml)+ // The package's declaration is the source of truth even when it contradicts+ // the well-known extension mapping.+ ok(mimeFor('ppt/media/a.png', types) === 'image/x-census-png',+ 'a [Content_Types].xml Default overrides the built-in extension table')+ ok(mimeFor('ppt/media/special.bin', types) === 'image/gif', 'an Override wins by part name')+ ok(mimeFor('ppt/media/a.png') === 'image/png', 'without content types the built-in table answers')+ ok(mimeFor('ppt/media/a.PNG') === 'image/png', 'extension matching is case-insensitive')+ ok(mimeFor('ppt/media/mystery.zzz') === 'application/octet-stream', 'an unknown extension degrades to octet-stream')+}++// ------------------------------------------------------------------ base64+{+ // Known vectors, computed by hand from RFC 4648: every padding length.+ ok(toBase64(enc.encode('Man')) === 'TWFu', "base64 of 'Man' is TWFu")+ ok(toBase64(enc.encode('Ma')) === 'TWE=', 'two bytes pad with one =')+ ok(toBase64(enc.encode('M')) === 'TQ==', 'one byte pads with two ==')+ ok(toBase64(new Uint8Array(0)) === '', 'zero bytes encode to the empty string')++ // All 256 byte values plus awkward lengths, against node:buffer — an+ // implementation that is not ours.+ for (const len of [1, 2, 3, 255, 256, 257, 0x8000 - 1, 0x8000, 0x8000 + 1]) {+ const b = new Uint8Array(len)+ for (let i = 0; i < len; i++) b[i] = (i * 7 + 13) & 0xff+ const want = Buffer.from(b).toString('base64')+ if (toBase64(b) !== want || _internals.b64Manual(b) !== want) {+ ok(false, `base64 of ${len} bytes matches node:buffer (both paths)`)+ } else ok(true, `base64 of ${len} bytes matches node:buffer (both paths)`)+ }+}++// -------------------------------------------------------------- asset store+{+ const logo = enc.encode('PNGBYTES-logo')+ const logoCopy = enc.encode('PNGBYTES-logo') // same content, its own buffer+ const other = enc.encode('PNGBYTES-lXgo') // SAME length, different bytes+ const parts = new Map<string, Uint8Array>([+ ['ppt/media/image1.png', logo],+ ['ppt/media/image2.png', logoCopy],+ ['ppt/media/image3.png', other],+ ])+ const store = new AssetStore(parts, parseContentTypes(ctXml))+ const k1 = store.register('ppt/media/image1.png')!+ const k2 = store.register('ppt/media/image2.png')!+ const k3 = store.register('ppt/media/image3.png')!+ ok(k1 === k2, 'identical bytes under two part names dedup to ONE key')+ // NEGATIVE (dedup-by-name-or-length): same length, different content.+ ok(k1 !== k3, 'same-length different bytes get different keys')+ ok(k1.startsWith('m'), "keys carry the 'm' prefix")+ ok(store.register('ppt/media/image1.png') === k1, 'a re-registration is stable')+ ok(store.register('ppt/media/nope.png') === undefined, 'a missing part returns undefined, never throws')++ const assets = store.assets()+ ok(Object.keys(assets).length === 2, 'the assets record holds exactly the two distinct contents')+ ok(assets[k1] === `data:image/x-census-png;base64,${Buffer.from(logo).toString('base64')}`,+ 'the data URI carries the content-types mime and the exact bytes')++ // key determinism across store instances (a re-import must re-emit the same keys)+ const again = new AssetStore(parts).register('ppt/media/image1.png')+ ok(again === k1, 'the key is a pure function of the bytes — stable across stores')++ // fnv collision safety net: force two contents into one bucket by hand+ ok(_internals.fnvKey(logo) !== _internals.fnvKey(other), 'the 64-bit hash separates these contents')+ ok(_internals.bytesEq(logo, logoCopy) && !_internals.bytesEq(logo, other), 'bytesEq compares content, not identity')+}++// ------------------------------------------------------------ p:pic → image+// One picture XML builder so each case varies exactly one thing.+const NSDECL =+ 'xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main" ' ++ 'xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" ' ++ 'xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" ' ++ 'xmlns:asvg="http://schemas.microsoft.com/office/drawing/2016/SVG/main"'++function pic(opts: { embed?: string; svg?: string; srcRect?: string; tile?: boolean; link?: string }): ReturnType<typeof parseXml> {+ const blipInner = opts.svg+ ? `<a:extLst><a:ext uri="{96DAC541-7B7A-43D3-8B79-37D633B846F1}"><asvg:svgBlip r:embed="${opts.svg}"/></a:ext></a:extLst>`+ : ''+ const blipAttr = opts.embed ? ` r:embed="${opts.embed}"` : opts.link ? ` r:link="${opts.link}"` : ''+ return parseXml(+ `<p:pic ${NSDECL}>` ++ '<p:nvPicPr><p:cNvPr id="7" name="Picture 7"/><p:cNvPicPr/><p:nvPr/></p:nvPicPr>' ++ `<p:blipFill><a:blip${blipAttr}>${blipInner}</a:blip>` ++ (opts.srcRect ?? '') ++ (opts.tile ? '<a:tile/>' : '<a:stretch><a:fillRect/></a:stretch>') ++ '</p:blipFill>' ++ '<p:spPr><a:xfrm rot="2700000"><a:off x="914400" y="457200"/><a:ext cx="1828800" cy="914400"/></a:xfrm>' ++ '<a:prstGeom prst="rect"><a:avLst/></a:prstGeom></p:spPr>' ++ '</p:pic>')+}++const rasterBytes = enc.encode('RASTER-PREVIEW-BYTES')+const svgBytes = enc.encode('<svg xmlns="http://www.w3.org/2000/svg"><clipPath id="a"/></svg>')+const picParts = new Map<string, Uint8Array>([+ ['ppt/media/image1.png', rasterBytes],+ ['ppt/media/icon1.svg', svgBytes],+])+const picRels = parseRels(parseXml(+ '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">' ++ '<Relationship Id="rId1" Type="http://x/image" Target="../media/image1.png"/>' ++ '<Relationship Id="rId2" Type="http://x/image" Target="../media/icon1.svg"/>' ++ '<Relationship Id="rId3" Type="http://x/image" Target="../media/gone.svg"/>' ++ '<Relationship Id="rId4" Type="http://x/image" Target="file:///C:/pics/x.png" TargetMode="External"/>' ++ '<Relationship Id="rId5" Type="http://x/image" Target="../media/hdphoto1.wdp"/>' ++ '</Relationships>'), 'ppt/slides/')++function ctxAnd(): { ctx: InheritCtx; report: Report } {+ const report = new Report()+ // imageFrom touches only .report; the chain members are the other modules' business+ const ctx = { slide: parseXml('<sld/>'), theme: undefined, report } as unknown as InheritCtx+ return { ctx, report }+}+const codes = (r: Report) => r.build().entries.map((e) => `${e.verdict}:${e.code}`).join(' ')++// the plain raster picture — the boring common case must stay clean+{+ const { ctx, report } = ctxAnd()+ const store = new AssetStore(picParts)+ const el = imageFrom(pic({ embed: 'rId1' }), ctx, picRels, store, 'slide 1')!+ ok(el !== undefined && el.type === 'image', 'a plain raster pic converts')+ ok(el.src === `asset:${store.register('ppt/media/image1.png')!}`, 'its src references the registered asset')+ ok(el.fit === 'fill', 'a:stretch maps to fill')+ // hand-computed: 914400/9525 = 96, 457200/9525 = 48, 1828800/9525 = 192, rot 2700000/60000 = 45+ ok(el.x === 96 && el.y === 48 && el.w === 192 && el.h === 96, 'EMU frame lands at 96,48 192×96')+ ok(el.rotation === 45 && el.id === 'pic7' && el.opacity === 1, 'rotation 45°, id from cNvPr')+ ok(report.build().entries.length === 0, 'and nothing is reported — this case is fully carried')+}++// THE SVG RULE: vector part preferred, raster preview ignored+{+ const { ctx, report } = ctxAnd()+ const store = new AssetStore(picParts)+ const el = imageFrom(pic({ embed: 'rId1', svg: 'rId2' }), ctx, picRels, store, 'slide 1')!+ const uri = store.assets()[el.src.slice('asset:'.length)]!+ ok(uri.startsWith('data:image/svg+xml;base64,'), 'an svgBlip pic emits the SVG bytes as a data:image/svg+xml asset')+ // NEGATIVE (blip-as-bitmap): a naive converter reads r:embed and emits the raster.+ ok(uri !== `data:image/png;base64,${Buffer.from(rasterBytes).toString('base64')}` &&+ Buffer.from(uri.split(',')[1]!, 'base64').toString() === Buffer.from(svgBytes).toString(),+ 'and the asset is NOT the raster preview')+ ok(report.build().entries.length === 0, 'the preferred-svg path reports nothing')+}++// raster fallback when the svg part is missing+{+ const { ctx, report } = ctxAnd()+ const store = new AssetStore(picParts)+ const el = imageFrom(pic({ embed: 'rId1', svg: 'rId3' }), ctx, picRels, store, 'slide 1')!+ const uri = store.assets()[el.src.slice('asset:'.length)]!+ ok(uri.startsWith('data:image/png;base64,'), 'a missing SVG part falls back to the raster preview')+ ok(codes(report) === 'approximated:svg-raster-fallback', 'and says so')+}++// crop → cover, reported+{+ const { ctx, report } = ctxAnd()+ const el = imageFrom(pic({ embed: 'rId1', srcRect: '<a:srcRect l="10000" r="25000"/>' }),+ ctx, picRels, new AssetStore(picParts), 'slide 2')!+ ok(el.fit === 'cover', 'a srcRect crop maps to cover')+ ok(codes(report) === 'approximated:image-crop-dropped', 'and is reported as approximated')+}++// an all-zero srcRect is not a crop+{+ const { ctx, report } = ctxAnd()+ const el = imageFrom(pic({ embed: 'rId1', srcRect: '<a:srcRect l="0" t="0"/>' }),+ ctx, picRels, new AssetStore(picParts), 'slide 2')!+ ok(el.fit === 'fill' && report.build().entries.length === 0,+ 'an all-zero srcRect stays fill and unreported')+}++// tile → fill, reported+{+ const { ctx, report } = ctxAnd()+ const el = imageFrom(pic({ embed: 'rId1', tile: true }), ctx, picRels, new AssetStore(picParts), 'slide 3')!+ ok(el.fit === 'fill', 'a:tile maps to fill')+ ok(codes(report) === 'approximated:image-tile-dropped', 'and is reported')+}++// NEGATIVE (fetch-the-External): a linked picture is dropped by name, never fetched+{+ const { ctx, report } = ctxAnd()+ const el = imageFrom(pic({ link: 'rId4' }), ctx, picRels, new AssetStore(picParts), 'slide 4')+ ok(el === undefined, 'an External (linked) picture converts to nothing')+ ok(codes(report) === 'dropped:image-external-dropped',+ 'with the external code — not missing-part, which would mean we tried to fetch it from the package')+}++// .wdp → dropped with the fallback hint+{+ const { ctx, report } = ctxAnd()+ const el = imageFrom(pic({ embed: 'rId5' }), ctx, picRels, new AssetStore(picParts), 'slide 5')+ ok(el === undefined && codes(report) === 'dropped:wdp-fallback',+ 'a JPEG XR picture is dropped with the wdp-fallback code (caller takes mc:Fallback)')+}++// dangling rel and missing part are distinct findings+{+ const { ctx, report } = ctxAnd()+ ok(imageFrom(pic({ embed: 'rId99' }), ctx, picRels, new AssetStore(picParts), 'slide 6') === undefined &&+ codes(report) === 'dropped:image-missing-rel', 'a dangling r:embed is image-missing-rel')+}+{+ const { ctx, report } = ctxAnd()+ const rels = parseRels(parseXml(+ '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">' ++ '<Relationship Id="rId1" Type="http://x/image" Target="../media/vanished.png"/></Relationships>'), 'ppt/slides/')+ ok(imageFrom(pic({ embed: 'rId1' }), ctx, rels, new AssetStore(picParts), 'slide 6') === undefined &&+ codes(report) === 'dropped:image-missing-part', 'a rel to a part the package lacks is image-missing-part')+}++// a blip with no reference at all+{+ const { ctx, report } = ctxAnd()+ ok(imageFrom(pic({}), ctx, picRels, new AssetStore(picParts), 'slide 7') === undefined &&+ codes(report) === 'dropped:image-missing-rel', 'a blip with neither embed nor link is reported, not thrown on')+}++// dedup across pictures: the template's reused logo costs one asset+{+ const { ctx } = ctxAnd()+ const store = new AssetStore(picParts)+ const a = imageFrom(pic({ embed: 'rId1' }), ctx, picRels, store, 'slide 1')!+ const b = imageFrom(pic({ embed: 'rId1' }), ctx, picRels, store, 'slide 2')!+ ok(a.src === b.src && Object.keys(store.assets()).length === 1,+ 'two pictures of the same bytes share one asset entry')+}++console.log(`\n${checks - failures}/${checks} checks passed`)+if (failures) process.exit(1)diff --git a/scripts/test-convert/pptx.ts b/scripts/test-convert/pptx.tsnew file mode 100644index 00000000..adfc4e19--- /dev/null+++ b/scripts/test-convert/pptx.ts@@ -0,0 +1,248 @@+#!/usr/bin/env node+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// bento/convert end-to-end rig — whole .pptx packages through convertPptx.+//+// node scripts/test-convert/pptx.ts (Node ≥ 23.6 strips types natively)+//+// The packages are built in code (_fixtures.ts) and every expected value is+// hand-computed from the fixture constants — EMU arithmetic in the comments,+// colour values pinned from published/spec sources — never by running the+// converter against itself. Report CODES are asserted as EXACT sets per+// fixture: a new code appearing (or one silently ceasing to fire) fails here+// rather than in somebody's deck.+//+// Negative controls, one per trap, each seen to fail against a deliberately+// broken input or implementation while this rig was written:+//+// • clrMap: the fixture SWAPS the map (bg1→dk2); the default-map answer+// (#FFFFFF) is asserted absent.+// • shade: linear-light 50% of #808080 is #5D5D5D; the sRGB-space answer+// (#404040) is asserted absent.+// • nested group: the single-scale answer (outer map applied to the leaf+// directly → 120px) is asserted absent.+// • transition: 'fade' — the model constructors' default — is asserted+// absent on every slide.+// • mc: the Fallback rect appears EXACTLY once; the Choice rect (which an+// mc-blind walk would also import) is asserted absent.+// • svg pair: exactly ONE asset, and it is the SVG bytes, not the raster.+// • connector: the dangling end (id 99) is asserted absent while the valid+// end on the SAME connector survives.++import { Buffer } from 'node:buffer'+import { convertPptx } from '../../kernel/src/convert/pptx.ts'+import type { ConvertResult } from '../../kernel/src/convert/types.ts'+import type { OutShape, OutText, OutImage } from '../../kernel/src/convert/types.ts'+import {+ fxMinimal, fxThemed, fxPlaceholder, fxGroup, fxBullets, fxSvg, fxConnectors, fxStructure,+ SVG_BYTES,+} from './_fixtures.ts'++let failures = 0+let checks = 0+function ok(cond: boolean, msg: string) {+ checks+++ if (!cond) { failures++; console.log(` FAIL ${msg}`) }+ else console.log(` ok ${msg}`)+}++/** Exact report-code set: extras and absences both fail, with a readable diff. */+function reportIs(r: ConvertResult, expected: string[], label: string) {+ const got = [...new Set(r.report.entries.map((e) => e.code))].sort()+ const want = [...new Set(expected)].sort()+ ok(got.length === want.length && got.every((c, i) => c === want[i]),+ `${label}: report codes are exactly [${want.join(', ')}] (got [${got.join(', ')}])`)+}++const byId = (r: ConvertResult, slide: number, id: string) =>+ r.doc.slides[slide].elements.find((e) => e.id === id)++// ------------------------------------------------------------------- minimal+{+ const r = await convertPptx(await fxMinimal())+ const d = r.doc+ ok(d.format === 'bento/slides' && d.version === '1.0.0', 'minimal: format/version stamped')+ // 12192000×6858000 EMU / 9525 = 1280×720 EXACTLY+ ok(d.size.width === 1280 && d.size.height === 720, 'minimal: 12192000×6858000 EMU converts to exactly 1280×720')+ ok(d.title === 'Rig Deck', 'minimal: title comes from docProps/core.xml dc:title')+ ok(d.slides.length === 1 && d.slides[0].id === 's1', 'minimal: one slide, deterministic id')+ ok(d.slides[0].transition === 'none', 'minimal: transition is explicit none')+ ok(d.slides[0].background === '#FFFFFF', 'minimal: no p:bg anywhere defaults to white')+ ok(d.fonts === null, 'minimal: fonts is null (byte embedding is a host concern)')++ const els = d.slides[0].elements+ ok(els.length === 1 && els[0].type === 'text', 'minimal: a noFill/noLn box emits its text half only')+ const t = els[0] as OutText+ ok(t.id === 's1-2', 'minimal: element id is s<slide>-<cNvPr id>')+ // off 914400,914400 ext 2743200,457200 → 96, 96, 288, 48 px+ ok(t.x === 96 && t.y === 96 && t.w === 288 && t.h === 48, 'minimal: frame 96,96,288,48 from the sp’s own xfrm')+ ok(t.fontSize === 24, 'minimal: sz="1800" = 18pt = 24px (centipoints → pt → px, both hops)')+ ok(t.color === '#28303A', 'minimal: run solidFill carried exactly')+ ok(t.fontFamily === 'Georgia, sans-serif', 'minimal: non-substituted face gets a plain stack')+ ok(t.html === 'Hello, Bento', 'minimal: text content carried verbatim')+ ok(d.theme.fontFamily === 'Calibri, Carlito, sans-serif',+ 'minimal: broken-chain theme falls back to Calibri with its metric substitute')+ reportIs(r, [], 'minimal')+}++// -------------------------------------------------------------------- themed+{+ const r = await convertPptx(await fxThemed())+ const d = r.doc++ const bgRect = byId(r, 0, 's1-2') as OutShape+ // clrMap SWAPS bg1→dk2 (#28303A). The default map would give bg1→lt1 #FFFFFF.+ ok(bgRect.fill === '#28303A', 'themed: schemeClr bg1 resolves through the SWAPPED clrMap to #28303A')+ ok(bgRect.fill !== '#FFFFFF', 'themed: NEGATIVE — the default-clrMap answer (#FFFFFF) is absent')+ ok(d.slides[0].background === '#28303A', 'themed: slide background resolves through the same map')+ ok(d.theme.background === '#28303A' && d.theme.color === '#FFFFFF' && d.theme.accent === '#4472C4',+ 'themed: doc.theme bakes bg1/tx1/accent1 through the map')++ const shadeRect = byId(r, 0, 's1-3') as OutShape+ // linear-light shade: ((128/255)^2.2 · 0.5)^(1/2.2) · 255 ≈ 93 → #5D5D5D+ ok(shadeRect.fill === '#5D5D5D', 'themed: shade 50% of #808080 is #5D5D5D (linear-light)')+ ok(shadeRect.fill !== '#404040', 'themed: NEGATIVE — the sRGB-space multiply (#404040) is absent')++ // the box-with-text split: shape, then text, welded by groupId+ const els = d.slides[0].elements+ ok(els.map((e) => e.id).join(',') === 's1-2,s1-3,s1-4,s1-4-t',+ 'themed: document order is z-order, text half right after its shape')+ const box = byId(r, 0, 's1-4') as OutShape+ const label = byId(r, 0, 's1-4-t') as OutText+ ok(box.fill === '#4472C4', 'themed: accent1 fill on the label box')+ ok(box.groupId === 's1-4-g' && label.groupId === 's1-4-g',+ 'themed: shape and text share the minted split groupId')+ ok(label.color === '#FFFFFF', 'themed: default ink is theme tx1 through the swapped map (lt1 = white)')+ ok(label.fontSize === 18.67, 'themed: sz="1400" = 14pt = 18.67px')+ ok((r.report.provenance['fill:theme'] ?? 0) >= 2,+ 'themed: scheme-resolved fills are traced fill:theme')+ ok((r.report.provenance['fill:own'] ?? 0) >= 1,+ 'themed: the literal srgbClr fill is traced fill:own')+ reportIs(r, [], 'themed')+}++// --------------------------------------------------------------- placeholder+{+ const r = await convertPptx(await fxPlaceholder())+ const d = r.doc+ const els = d.slides[0].elements+ ok(els.length === 1 && els[0].type === 'text', 'placeholder: the bare title box emits text only')+ const t = els[0] as OutText+ ok(t.id === 's1-5', 'placeholder: id from the slide sp, not the layout donor')+ // layout title ph: off 914400,457200 ext 1828800,914400 → 96, 48, 192, 96+ ok(t.x === 96 && t.y === 48 && t.w === 192 && t.h === 96,+ 'placeholder: frame comes from the LAYOUT placeholder (slide sp has no xfrm)')+ // master titleStyle sz="4400" = 44pt = 58.666… → 58.67px+ ok(t.fontSize === 58.67, 'placeholder: size comes from the master’s titleStyle through the type hop')+ ok(t.color === '#000000', 'placeholder: default ink is theme tx1 (standard map → dk1)')+ ok(d.title === 'Quarterly Review', 'placeholder: no core.xml — the deck is titled by its first title text')+ // two resolveFrame walks reach the layout: the shape pass (which finds the+ // box invisible) and the text pass — both must land on 'layout'+ ok((r.report.provenance['frame:layout'] ?? 0) >= 1 && r.report.provenance['frame:own'] === undefined,+ 'placeholder: the frame is traced to the layout level, never to own')+ ok((r.report.provenance['font-size:master'] ?? 0) >= 1, 'placeholder: the size is traced to the master level')+ reportIs(r, ['text-needs-refit', 'font-substituted'], 'placeholder')+}++// -------------------------------------------------------------------- group+{+ const r = await convertPptx(await fxGroup())+ const d = r.doc+ ok(d.size.width === 960 && d.size.height === 720, 'group: 9144000×6858000 EMU converts to exactly 960×720')+ const els = d.slides[0].elements+ ok(els.length === 1, 'group: the nested group flattens to its one leaf')+ const leaf = els[0] as OutShape+ ok(leaf.id === 's1-12', 'group: leaf keeps its own cNvPr-derived id')+ // hand-composed (see _fixtures.ts): abs EMU 2057400, 571500, 228600, 114300+ ok(leaf.x === 216 && leaf.y === 60 && leaf.w === 24 && leaf.h === 12,+ 'group: leaf frame composes BOTH group maps (216, 60, 24, 12 px)')+ ok(leaf.x !== 120, 'group: NEGATIVE — the single-scale answer (120px) is absent')+ ok(leaf.groupId === 's1-g10', 'group: every leaf shares the OUTERMOST group’s id')+ ok(leaf.fill === '#FF0000', 'group: leaf fill carried')+ reportIs(r, ['nested-group-flattened'], 'group')+}++// ------------------------------------------------------------------- bullets+{+ const r = await convertPptx(await fxBullets())+ const bullets = byId(r, 0, 's1-2') as OutText+ // glyph + LITERAL NBSP prefixes; the buNone paragraph gets none+ ok(bullets.html === '• One<br>Two<br>• Three',+ 'bullets: lstStyle buChar baked per line, buNone paragraph silenced')+ const nums = byId(r, 0, 's1-3') as OutText+ ok(nums.html === '3. Alpha<br>4. Beta',+ 'bullets: buAutoNum honours startAt=3 and counts on (frozen numbering)')+ ok(!nums.html.startsWith('1.'), 'bullets: NEGATIVE — startAt ignored (1.) is absent')+ reportIs(r, ['bullet-flattened', 'auto-number-frozen'], 'bullets')+}++// ----------------------------------------------------------------------- svg+{+ const r = await convertPptx(await fxSvg())+ const d = r.doc+ const img = byId(r, 0, 's1-7') as OutImage+ ok(img !== undefined && img.type === 'image', 'svg: the pic emits an image element')+ ok(img.x === 96 && img.y === 96 && img.w === 96 && img.h === 96, 'svg: frame from the pic’s own xfrm')+ const keys = Object.keys(d.assets)+ ok(keys.length === 1, `svg: exactly ONE asset registered — raster preview and unused media PRUNED (got ${keys.length})`)+ const expected = `data:image/svg+xml;base64,${Buffer.from(SVG_BYTES).toString('base64')}`+ ok(d.assets[keys[0]] === expected, 'svg: the asset is the SVG bytes (node:buffer base64, not ours)')+ ok(img.src === `asset:${keys[0]}`, 'svg: the element references the registered key')+ ok(!Object.values(d.assets).some((u) => u.startsWith('data:image/png')),+ 'svg: NEGATIVE — the raster compatibility preview is absent')+ reportIs(r, [], 'svg')+}++// ---------------------------------------------------------------- connectors+{+ const r = await convertPptx(await fxConnectors())+ const conn = byId(r, 0, 's1-4') as OutShape+ ok(conn.shape === 'line', 'connectors: straightConnector1 becomes a bento line')+ ok(conn.from?.el === 's1-2' && conn.to?.el === 's1-3',+ 'connectors: stCxn/endCxn resolve to the deterministic element ids')+ ok(conn.lineEnd === 'arrow', 'connectors: tailEnd triangle becomes lineEnd arrow')+ ok(conn.fill === '#000000' && conn.stroke === '#000000',+ 'connectors: line shapes carry the colour in BOTH fill and stroke (morphs tween stroke)')+ // box 1828800,457200 + 914400×0 → x 192, y 48; len 96, elH 2 → 192, 47, 96, 2+ ok(conn.x === 192 && conn.y === 47 && conn.w === 96 && conn.h === 2,+ 'connectors: box diagonal recentred to length+height (192, 47, 96, 2)')+ const dangling = byId(r, 0, 's1-5') as OutShape+ ok(dangling.from?.el === 's1-2', 'connectors: the valid end of the half-dangling connector survives')+ ok(dangling.to === undefined, 'connectors: NEGATIVE — the endCxn to id 99 is dropped, not invented')+ reportIs(r, ['connector-ref-dangling'], 'connectors')+}++// ----------------------------------------------------------------- structure+{+ const r = await convertPptx(await fxStructure())+ const d = r.doc+ ok(d.slides.length === 2, 'structure: both slides imported in sldIdLst order')+ ok(d.slides.every((s) => s.transition === 'none'),+ 'structure: every slide gets transition none')+ ok(!d.slides.some((s) => (s.transition as string) === 'fade'),+ 'structure: NEGATIVE — the model-constructor default (fade) never leaks in')++ const table = byId(r, 0, 's1-6') as OutShape+ ok(table !== undefined && table.shape === 'rect' && table.strokeStyle === 'dashed'+ && table.fill === 'transparent',+ 'structure: a table graphicFrame leaves a dashed placeholder box')+ ok(table.x === 96 && table.y === 96 && table.w === 480 && table.h === 192,+ 'structure: the placeholder sits in the graphicFrame’s own p:xfrm frame')+ ok(byId(r, 0, 's1-7') !== undefined, 'structure: the chart graphicFrame leaves one too')++ ok(d.slides[0].notes === 'Remember the demo',+ 'structure: notes come from the body placeholder only (sldImg and sldNum skipped)')+ ok(d.slides[1].hidden === true, 'structure: show="0" imports as hidden')+ ok(d.slides[0].hidden === undefined, 'structure: an ordinary slide carries no hidden flag')++ // mc: Fallback taken exactly once+ const s2 = d.slides[1].elements+ ok(s2.length === 1 && s2[0].id === 's2-21' && (s2[0] as OutShape).fill === '#0000FF',+ 'structure: mc:AlternateContent resolves to its Fallback, imported ONCE')+ ok(!s2.some((e) => e.id === 's2-20'),+ 'structure: NEGATIVE — the mc:Choice content (which a blind walk double-imports) is absent')+ reportIs(r, ['table-not-yet', 'chart-not-yet'], 'structure')+}++console.log(`\n${checks - failures}/${checks} checks passed`)+if (failures) process.exit(1)diff --git a/scripts/test-convert/shapes.ts b/scripts/test-convert/shapes.tsnew file mode 100644index 00000000..d9ddaedd--- /dev/null+++ b/scripts/test-convert/shapes.ts@@ -0,0 +1,468 @@+#!/usr/bin/env node+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// bento/convert shapes rig — geometry, fills, groups, connectors.+//+// node scripts/test-convert/shapes.ts (Node ≥ 23.6 strips types natively)+//+// Every expected value is HAND-COMPUTED in the comments; nothing is derived by+// running the module against itself. The traps each carry a NEGATIVE control —+// a value a plausible wrong implementation WOULD produce, asserted absent:+//+// • gradient angles: the naive read (ang/60000 → CSS degrees) gives 90 for+// OOXML 5400000; render.ts's convention (0 = bottom→top, from+// gradientLineCoords: dy = -cos) makes the correct answer 180. Both pinned.+// • an EMPTY <a:effectLst/> must CANCEL the layout's shadow; an ABSENT one+// must inherit it. An implementation conflating empty with absent fails+// one of the pair whichever way it conflates.+// • nested groups: the single-scale answer (outer map applied to the leaf+// directly, skipping the inner group's own scaling) is computed and+// asserted to differ from the composed one.++import { parseXml } from '../../kernel/src/convert/xml.ts'+import type { XElem } from '../../kernel/src/convert/xml.ts'+import { parseTheme } from '../../kernel/src/convert/theme.ts'+import { Report } from '../../kernel/src/convert/report.ts'+import type { InheritCtx, ThemeCtx } from '../../kernel/src/convert/types.ts'+import { shapeFrom, groupChildren } from '../../kernel/src/convert/shapes.ts'+import type { ShapeDeps } from '../../kernel/src/convert/shapes.ts'++let failures = 0+let checks = 0+function ok(cond: boolean, msg: string) {+ checks+++ if (!cond) { failures++; console.log(` FAIL ${msg}`) }+ else console.log(` ok ${msg}`)+}++const XMLNS = 'xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main" ' ++ 'xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"'++// ------------------------------------------------------------------ the theme+// accent1 = #4472C4; fillStyleLst[0] solid phClr, [1] a phClr gradient with+// the theme's own vertical (5400000) direction; lnStyleLst widths 6350 /+// 12700 / 19050 EMU.+const theme: ThemeCtx = parseTheme(parseXml(`<a:theme ${XMLNS} name="rig">+ <a:themeElements>+ <a:clrScheme name="rig">+ <a:dk1><a:srgbClr val="000000"/></a:dk1>+ <a:lt1><a:srgbClr val="FFFFFF"/></a:lt1>+ <a:dk2><a:srgbClr val="1E2A3A"/></a:dk2>+ <a:lt2><a:srgbClr val="E7E6E6"/></a:lt2>+ <a:accent1><a:srgbClr val="4472C4"/></a:accent1>+ <a:accent2><a:srgbClr val="FBAE40"/></a:accent2>+ <a:accent3><a:srgbClr val="808080"/></a:accent3>+ <a:accent4><a:srgbClr val="FF0000"/></a:accent4>+ <a:accent5><a:srgbClr val="70AD47"/></a:accent5>+ <a:accent6><a:srgbClr val="C00000"/></a:accent6>+ <a:hlink><a:srgbClr val="0563C1"/></a:hlink>+ <a:folHlink><a:srgbClr val="954F72"/></a:folHlink>+ </a:clrScheme>+ <a:fontScheme name="rig">+ <a:majorFont><a:latin typeface="Georgia"/></a:majorFont>+ <a:minorFont><a:latin typeface="Verdana"/></a:minorFont>+ </a:fontScheme>+ <a:fmtScheme name="rig">+ <a:fillStyleLst>+ <a:solidFill><a:schemeClr val="phClr"/></a:solidFill>+ <a:gradFill>+ <a:gsLst>+ <a:gs pos="0"><a:schemeClr val="phClr"><a:tint val="50000"/></a:schemeClr></a:gs>+ <a:gs pos="100000"><a:schemeClr val="phClr"/></a:gs>+ </a:gsLst>+ <a:lin ang="5400000" scaled="1"/>+ </a:gradFill>+ <a:solidFill><a:schemeClr val="phClr"/></a:solidFill>+ </a:fillStyleLst>+ <a:lnStyleLst>+ <a:ln w="6350"><a:solidFill><a:schemeClr val="phClr"/></a:solidFill></a:ln>+ <a:ln w="12700"><a:solidFill><a:schemeClr val="phClr"/></a:solidFill></a:ln>+ <a:ln w="19050"><a:solidFill><a:schemeClr val="phClr"/></a:solidFill></a:ln>+ </a:lnStyleLst>+ <a:bgFillStyleLst>+ <a:solidFill><a:schemeClr val="phClr"/></a:solidFill>+ <a:solidFill><a:schemeClr val="phClr"/></a:solidFill>+ <a:solidFill><a:schemeClr val="phClr"/></a:solidFill>+ </a:bgFillStyleLst>+ </a:fmtScheme>+ </a:themeElements>+</a:theme>`), undefined)++const dummySlide = parseXml(`<p:sld ${XMLNS}><p:cSld><p:spTree/></p:cSld></p:sld>`)++function ctxOf(layout?: XElem): InheritCtx {+ const c: InheritCtx = { slide: dummySlide, theme, report: new Report() }+ if (layout) c.layout = layout+ return c+}+const deps = (extra?: Partial<ShapeDeps>): ShapeDeps => ({ slideIndex: 1, ...extra })+const sp = (inner: string) => parseXml(`<p:sp ${XMLNS}>${inner}</p:sp>`)++/** minimal nv block + spPr assembled around a geometry/fill/effect payload */+const spOf = (id: string, spPr: string, after = '') => sp(+ `<p:nvSpPr><p:cNvPr id="${id}" name="sp${id}"/><p:cNvSpPr/><p:nvPr/></p:nvSpPr>` ++ `<p:spPr>${spPr}</p:spPr>${after}`)++const XFRM_100 = '<a:xfrm><a:off x="0" y="0"/><a:ext cx="952500" cy="952500"/></a:xfrm>'+const RED = '<a:solidFill><a:srgbClr val="FF0000"/></a:solidFill>'++// -------------------------------------------------------- EMU/rot arithmetic+{+ // off 914400,457200 EMU = 96,48 px; ext 2743200×914400 = 288×96 px;+ // rot 2700000/60000 = 45°+ const r = shapeFrom(spOf('10',+ '<a:xfrm rot="2700000"><a:off x="914400" y="457200"/><a:ext cx="2743200" cy="914400"/></a:xfrm>' ++ `<a:prstGeom prst="rect"><a:avLst/></a:prstGeom>${RED}`), ctxOf(), deps())+ ok(!!r, 'a filled rect emits')+ const s = r!.shape+ ok(s.id === 's1-10', `id follows the s<slide>-<spId> scheme (got ${s.id})`)+ ok(s.x === 96 && s.y === 48, `EMU offsets land on 96,48 px (got ${s.x},${s.y})`)+ ok(s.w === 288 && s.h === 96, `EMU extents land on 288×96 px (got ${s.w}×${s.h})`)+ ok(s.rotation === 45, `rot 2700000 = 45° (got ${s.rotation})`)+ ok(s.shape === 'rect' && s.fill === '#FF0000', 'rect preset + own srgb fill carried')+ ok(s.strokeWidth === 0 && s.stroke === 'transparent', 'no a:ln and no style = no stroke')+}++// ------------------------------------------------- roundRect radius (a:avLst)+{+ // 1905000×952500 EMU = 200×100 px; absent adj → the preset default 16667;+ // radius = min(w,h) × 16667/100000 = 100 × 0.16667 = 16.67+ const dflt = shapeFrom(spOf('11',+ '<a:xfrm><a:off x="0" y="0"/><a:ext cx="1905000" cy="952500"/></a:xfrm>' ++ `<a:prstGeom prst="roundRect"><a:avLst/></a:prstGeom>${RED}`), ctxOf(), deps())+ ok(dflt!.shape.shape === 'rect' && dflt!.shape.radius === 16.67,+ `roundRect with empty avLst takes the 16667 default → radius 16.67 (got ${dflt!.shape.radius})`)+ // explicit adj 50000 → 100 × 0.5 = 50+ const expl = shapeFrom(spOf('12',+ '<a:xfrm><a:off x="0" y="0"/><a:ext cx="1905000" cy="952500"/></a:xfrm>' ++ `<a:prstGeom prst="roundRect"><a:avLst><a:gd name="adj" fmla="val 50000"/></a:avLst></a:prstGeom>${RED}`),+ ctxOf(), deps())+ ok(expl!.shape.radius === 50, `explicit adj 50000 → radius 50 (got ${expl!.shape.radius})`)+}++// --------------------------------------------------- the 12-preset kind table+{+ const expected: Array<[string, string]> = [+ ['rect', 'rect'], ['roundRect', 'rect'], ['ellipse', 'ellipse'], ['triangle', 'triangle'],+ ['line', 'line'], ['straightConnector1', 'line'],+ ['chevron', 'path'], ['upArrowCallout', 'path'], ['round2SameRect', 'path'],+ ['bentConnector2', 'path'], ['bentConnector3', 'path'], ['bentConnector4', 'path'],+ ]+ for (const [prst, kind] of expected) {+ const c = ctxOf()+ const r = shapeFrom(spOf('13',+ `${XFRM_100}<a:prstGeom prst="${prst}"><a:avLst/></a:prstGeom>${RED}` ++ '<a:ln w="12700"><a:solidFill><a:srgbClr val="000000"/></a:solidFill></a:ln>'), c, deps())+ ok(r!.shape.shape === kind, `${prst} → '${kind}' (got '${r!.shape.shape}')`)+ ok(!c.report.build().entries.some((e) => e.code === 'shape-approximated'),+ `${prst} converts without a shape-approximated report`)+ }+}++// ------------------------------------------------------------- unknown preset+{+ const c = ctxOf()+ const r = shapeFrom(spOf('14', `${XFRM_100}<a:prstGeom prst="hexagon"><a:avLst/></a:prstGeom>${RED}`), c, deps())+ ok(r!.shape.shape === 'rect', 'off-census preset falls back to rect')+ const e = c.report.build().entries.find((x) => x.code === 'shape-approximated')+ ok(!!e && e.verdict === 'approximated' && e.detail.includes('hexagon'),+ 'shape-approximated names the preset in its detail')+}++// -------------------------------------------------- gradient angle conversion+{+ // OOXML a:lin@ang is clockwise from 3 o'clock, y-down: 5400000/60000 = 90°+ // points DOWN, so the gradient runs top→bottom. render.ts gradientLineCoords+ // (dy = -cos(angle)) makes top→bottom = 180deg in bento's CSS convention.+ const c = ctxOf()+ const r = shapeFrom(spOf('15', `${XFRM_100}<a:prstGeom prst="rect"><a:avLst/></a:prstGeom>` ++ '<a:gradFill><a:gsLst>' ++ '<a:gs pos="0"><a:srgbClr val="FF0000"/></a:gs>' ++ '<a:gs pos="100000"><a:srgbClr val="0000FF"/></a:gs>' ++ '</a:gsLst><a:lin ang="5400000" scaled="1"/></a:gradFill>'), c, deps())+ const g = r!.shape.fillGradient!+ ok(g.angle === 180, `OOXML 5400000 → CSS-convention 180deg (got ${g.angle})`)+ ok(g.angle !== 90, 'NEGATIVE: the naive ang/60000 read (90) is not what we emit')+ ok(g.stops.length === 2 && g.stops[0].at === 0 && g.stops[0].color === '#FF0000'+ && g.stops[1].at === 1 && g.stops[1].color === '#0000FF', 'stops carry pos/100000 and resolved colours')+ ok(r!.shape.fill === '#0000FF', 'solid fallback fill = the last stop')++ // radial → linear approximation, reported+ const c2 = ctxOf()+ const r2 = shapeFrom(spOf('16', `${XFRM_100}<a:prstGeom prst="rect"><a:avLst/></a:prstGeom>` ++ '<a:gradFill><a:gsLst>' ++ '<a:gs pos="0"><a:srgbClr val="FF0000"/></a:gs>' ++ '<a:gs pos="100000"><a:srgbClr val="0000FF"/></a:gs>' ++ '</a:gsLst><a:path path="circle"/></a:gradFill>'), c2, deps())+ ok(r2!.shape.fillGradient!.angle === 180+ && c2.report.build().entries.some((e) => e.code === 'radial-gradient-linearized' && e.verdict === 'approximated'),+ 'radial gradient linearizes and reports it')+}++// ------------------------------------------- fillRef / lnRef style fallback+{+ // no spPr fill, no spPr ln: everything comes from p:style through the theme+ // matrix with phClr = accent1 #4472C4. fillRef idx 1 → fillStyleLst[0]+ // (solid phClr); lnRef idx 2 → lnStyleLst[1] (w 12700 EMU = 1.33px).+ const c = ctxOf()+ const r = shapeFrom(spOf('17', `${XFRM_100}<a:prstGeom prst="rect"><a:avLst/></a:prstGeom>`,+ '<p:style>' ++ '<a:lnRef idx="2"><a:schemeClr val="accent1"/></a:lnRef>' ++ '<a:fillRef idx="1"><a:schemeClr val="accent1"/></a:fillRef>' ++ '<a:effectRef idx="0"><a:schemeClr val="accent1"/></a:effectRef>' ++ '<a:fontRef idx="minor"/></p:style>'), c, deps())+ const s = r!.shape+ ok(s.fill === '#4472C4', `fillRef idx 1 resolves phClr accent1 (got ${s.fill})`)+ ok(s.stroke === '#4472C4' && s.strokeWidth === 1.33,+ `lnRef idx 2 gives a 1.33px accent stroke (got ${s.stroke} @ ${s.strokeWidth})`)+ ok((c.report.build().provenance['fill:theme'] ?? 0) >= 1, 'style-matrix fill traces provenance fill:theme')++ // fillRef idx 2 = the theme's phClr GRADIENT: shapes.ts owns the parse and+ // must substitute phClr per stop; the theme's own lin 5400000 → 180deg+ const c2 = ctxOf()+ const r2 = shapeFrom(spOf('18', `${XFRM_100}<a:prstGeom prst="rect"><a:avLst/></a:prstGeom>`,+ '<p:style><a:lnRef idx="0"/><a:fillRef idx="2"><a:schemeClr val="accent1"/></a:fillRef></p:style>'), c2, deps())+ const g = r2!.shape.fillGradient!+ ok(g.stops.length === 2 && g.stops[1].color === '#4472C4' && g.angle === 180,+ 'style gradient parses with phClr substituted per stop')+}++// ----------------------------------- empty a:effectLst cancels; absent defers+{+ // layout placeholder carries the shadow: blurRad 47625 EMU = 5px,+ // dist 95250 = 10px, dir 2700000 = 45° → x = y = 10·cos45 = 7.07,+ // black at alpha 40000 → rgba(0,0,0,0.4)+ const layout = parseXml(`<p:sldLayout ${XMLNS}><p:cSld><p:spTree>+ <p:sp>+ <p:nvSpPr><p:cNvPr id="2" name="lay"/><p:cNvSpPr/><p:nvPr><p:ph type="title"/></p:nvPr></p:nvSpPr>+ <p:spPr><a:effectLst><a:outerShdw blurRad="47625" dist="95250" dir="2700000">+ <a:srgbClr val="000000"><a:alpha val="40000"/></a:srgbClr>+ </a:outerShdw></a:effectLst></p:spPr>+ </p:sp>+ </p:spTree></p:cSld></p:sldLayout>`)+ const phSp = (id: string, ownEffect: string) => sp(+ `<p:nvSpPr><p:cNvPr id="${id}" name="sp${id}"/><p:cNvSpPr/><p:nvPr><p:ph/></p:nvPr></p:nvSpPr>` ++ `<p:spPr>${XFRM_100}<a:prstGeom prst="rect"><a:avLst/></a:prstGeom>${RED}${ownEffect}</p:spPr>`)++ const cancelled = shapeFrom(phSp('20', '<a:effectLst/>'), ctxOf(layout), deps())+ ok(cancelled!.shape.shadow === undefined,+ 'an EMPTY own a:effectLst CANCELS the layout shadow (empty ≠ absent)')++ const inherited = shapeFrom(phSp('21', ''), ctxOf(layout), deps())+ const sh = inherited!.shape.shadow+ ok(!!sh && !Array.isArray(sh) && sh.x === 7.07 && sh.y === 7.07 && sh.blur === 5+ && sh.color === 'rgba(0,0,0,0.4)',+ `NEGATIVE pair: an ABSENT effectLst inherits the layout shadow (got ${JSON.stringify(sh)})`)+}++// --------------------------------------------- nested group frame composition+{+ // outer: off 952500,952500 (100,100px), ext 1905000×952500 (200×100),+ // chOff 0,0, chExt 952500×952500 → sx=2, sy=1+ // inner (in outer's child units): off 238125,238125, ext 476250×476250+ // → abs 1428750,1190625, 952500×476250; its chExt 238125×238125+ // → inner sx = 952500/238125 = 4, sy = 476250/238125 = 2+ // leaf local off 95250,95250 ext 95250×95250+ // → abs x = 1428750 + 95250·4 = 1809750 EMU (190px)+ // abs y = 1190625 + 95250·2 = 1381125 EMU (145px)+ // abs w = 381000 (40px), h = 190500 (20px)+ const grp = parseXml(`<p:grpSp ${XMLNS}>+ <p:nvGrpSpPr><p:cNvPr id="20" name="outer"/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr>+ <p:grpSpPr><a:xfrm>+ <a:off x="952500" y="952500"/><a:ext cx="1905000" cy="952500"/>+ <a:chOff x="0" y="0"/><a:chExt cx="952500" cy="952500"/>+ </a:xfrm></p:grpSpPr>+ <p:grpSp>+ <p:nvGrpSpPr><p:cNvPr id="21" name="inner"/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr>+ <p:grpSpPr><a:xfrm>+ <a:off x="238125" y="238125"/><a:ext cx="476250" cy="476250"/>+ <a:chOff x="0" y="0"/><a:chExt cx="238125" cy="238125"/>+ </a:xfrm></p:grpSpPr>+ <p:sp>+ <p:nvSpPr><p:cNvPr id="22" name="leaf"/><p:cNvSpPr/><p:nvPr/></p:nvSpPr>+ <p:spPr><a:xfrm><a:off x="95250" y="95250"/><a:ext cx="95250" cy="95250"/></a:xfrm>+ <a:prstGeom prst="rect"><a:avLst/></a:prstGeom>${RED}</p:spPr>+ </p:sp>+ </p:grpSp>+ </p:grpSp>`)+ const c = ctxOf()+ const children = groupChildren(grp, c, deps())+ ok(children.length === 1, 'nested groups flatten to leaves')+ const leaf = children[0]+ ok(leaf.frame.x === 1809750 && leaf.frame.y === 1381125,+ `composed child offset is 1809750,1381125 EMU (got ${leaf.frame.x},${leaf.frame.y})`)+ ok(leaf.frame.w === 381000 && leaf.frame.h === 190500,+ `composed child extent is 381000×190500 EMU (got ${leaf.frame.w}×${leaf.frame.h})`)+ // NEGATIVE: skipping the inner group's own scaling (applying only the outer+ // map to the leaf) would land x at 952500 + 95250·2 = 1143000+ ok(leaf.frame.x !== 1143000, 'NEGATIVE: not the single-scale (outer-map-only) x')+ ok(leaf.groupId === 's1-g20', `every leaf shares the OUTERMOST group id (got ${leaf.groupId})`)+ ok(c.report.build().entries.some((e) => e.code === 'nested-group-flattened'),+ 'nested group is reported as flattened')++ // the frame feeds back through deps and lands in px on the element+ const r = shapeFrom(leaf.el, c, deps({ frame: leaf.frame, groupId: leaf.groupId }))+ const s = r!.shape+ ok(s.x === 190 && s.y === 145 && s.w === 40 && s.h === 20,+ `deps.frame override wires through to px (got ${s.x},${s.y},${s.w},${s.h})`)+ ok(s.groupId === 's1-g20', 'deps.groupId lands on the element')+}++// ------------------------------------------------- connectors + line-as-fill+{+ const cxn = (endId: string) => parseXml(`<p:cxnSp ${XMLNS}>+ <p:nvCxnSpPr><p:cNvPr id="7" name="conn"/>+ <p:cNvCxnSpPr><a:stCxn id="4" idx="3"/><a:endCxn id="${endId}" idx="1"/></p:cNvCxnSpPr>+ <p:nvPr/></p:nvCxnSpPr>+ <p:spPr>+ <a:xfrm><a:off x="0" y="0"/><a:ext cx="952500" cy="0"/></a:xfrm>+ <a:prstGeom prst="straightConnector1"><a:avLst/></a:prstGeom>+ <a:ln w="19050"><a:solidFill><a:srgbClr val="FF0000"/></a:solidFill><a:tailEnd type="triangle"/></a:ln>+ </p:spPr>+ </p:cxnSp>`)+ const c = ctxOf()+ const r = shapeFrom(cxn('9'), c, deps({ spIds: new Set(['4', '9']) }))+ const s = r!.shape+ ok(s.shape === 'line', 'straightConnector1 is a bento line')+ // BENTO LINE GOTCHA: the renderer strokes el.fill (morphs tween the stroke+ // attr) — both carry the resolved a:ln colour+ ok(s.fill === '#FF0000' && s.stroke === '#FF0000', 'line colour lands on BOTH fill and stroke')+ ok(s.strokeWidth === 2, `19050 EMU line width = 2px (got ${s.strokeWidth})`)+ ok(s.w === 100 && s.rotation === 0 && s.x === 0 && s.y === -(s.h / 2),+ `horizontal 100px line: box centred on the segment (got x${s.x} y${s.y} w${s.w} rot${s.rotation})`)+ ok(s.lineEnd === 'arrow' && s.lineStart === undefined, 'tailEnd triangle → lineEnd arrow')+ ok(!!s.from && s.from.el === 's1-4' && s.from.side === 'auto', `stCxn → from s1-4 (got ${JSON.stringify(s.from)})`)+ ok(!!s.to && s.to.el === 's1-9', `endCxn → to s1-9 (got ${JSON.stringify(s.to)})`)++ // dangling target: the end goes free, and the report says so+ const c2 = ctxOf()+ const r2 = shapeFrom(cxn('99'), c2, deps({ spIds: new Set(['4', '9']) }))+ ok(r2!.shape.to === undefined && !!r2!.shape.from, 'a ref to a missing shape drops only that end')+ ok(c2.report.build().entries.some((e) => e.code === 'connector-ref-dangling' && e.verdict === 'dropped'),+ 'dangling connector ref is reported')+}++// -------------------------------------------------------- line flip geometry+{+ // flipV on a 100×100 box: the segment runs bottom-left→top-right, so+ // len = √2·100 = 141.42, angle = atan2(-100,100) = -45°, and the element+ // box centres on the segment: x = 50 - 141.42/2 = -20.71+ const c = ctxOf()+ const r = shapeFrom(spOf('30',+ '<a:xfrm flipV="1"><a:off x="0" y="0"/><a:ext cx="952500" cy="952500"/></a:xfrm>' ++ '<a:prstGeom prst="line"><a:avLst/></a:prstGeom>' ++ '<a:ln w="9525"><a:solidFill><a:srgbClr val="000000"/></a:solidFill></a:ln>'), c, deps())+ const s = r!.shape+ ok(s.rotation === -45, `flipV line rotates -45° (got ${s.rotation})`)+ ok(s.w === 141.42, `diagonal length 141.42 (got ${s.w})`)+ ok(s.x === -20.71, `box recentres on the segment (got x ${s.x})`)+ ok(!c.report.build().entries.some((e) => e.code === 'flip-dropped'),+ 'a line CONSUMES its flip — no flip-dropped report')+}++// ---------------------------------------------------------- path synthesis d+{+ // chevron 200×100, adj default 50000: ss=100 → x1=50+ const c = ctxOf()+ const r = shapeFrom(spOf('31',+ '<a:xfrm><a:off x="0" y="0"/><a:ext cx="1905000" cy="952500"/></a:xfrm>' ++ `<a:prstGeom prst="chevron"><a:avLst/></a:prstGeom>${RED}`), c, deps())+ ok(r!.shape.d === 'M0 0 L150 0 L200 50 L150 100 L0 100 L50 50 Z',+ `chevron d matches the hand-derived outline (got ${r!.shape.d})`)+ ok(JSON.stringify(r!.shape.pathBox) === '[0,0,200,100]', 'pathBox is the real px box')++ // upArrowCallout 100×100 defaults: a1=a2=a3=25000, a4=64977 →+ // dx1=25 dx2=12.5 y1=25 y2=100-64.977=35.02+ const r2 = shapeFrom(spOf('32',+ `${XFRM_100}<a:prstGeom prst="upArrowCallout"><a:avLst/></a:prstGeom>${RED}`), ctxOf(), deps())+ ok(r2!.shape.d ===+ 'M0 35.02 L37.5 35.02 L37.5 25 L25 25 L50 0 L75 25 L62.5 25 L62.5 35.02 L100 35.02 L100 100 L0 100 Z',+ `upArrowCallout d matches the spec guides (got ${r2!.shape.d})`)++ // round2SameRect 100×100 defaults adj1=16667 adj2=0: only the TOP corners+ // round (r=16.67); zero-radius corners emit no degenerate arcs+ const r3 = shapeFrom(spOf('33',+ `${XFRM_100}<a:prstGeom prst="round2SameRect"><a:avLst/></a:prstGeom>${RED}`), ctxOf(), deps())+ ok(r3!.shape.d ===+ 'M16.67 0 L83.33 0 A16.67 16.67 0 0 1 100 16.67 L100 100 L0 100 L0 16.67 A16.67 16.67 0 0 1 16.67 0 Z',+ `round2SameRect d rounds only the top pair (got ${r3!.shape.d})`)++ // bentConnector3 100×50, adj default 50000 → the bend at x=50; open,+ // stroke-only (never filled)+ const r4 = shapeFrom(spOf('34',+ '<a:xfrm><a:off x="0" y="0"/><a:ext cx="952500" cy="476250"/></a:xfrm>' ++ '<a:prstGeom prst="bentConnector3"><a:avLst/></a:prstGeom>' ++ '<a:ln w="12700"><a:solidFill><a:srgbClr val="000000"/></a:solidFill></a:ln>'), ctxOf(), deps())+ ok(r4!.shape.d === 'M0 0 L50 0 L50 50 L100 50', `bentConnector3 elbow at x1 (got ${r4!.shape.d})`)+ ok(r4!.shape.fill === 'transparent', 'bent connectors never take a fill')++ // flip baked into synthesized coordinates: bentConnector2 flipV mirrors y+ const r5 = shapeFrom(spOf('35',+ '<a:xfrm flipV="1"><a:off x="0" y="0"/><a:ext cx="952500" cy="476250"/></a:xfrm>' ++ '<a:prstGeom prst="bentConnector2"><a:avLst/></a:prstGeom>' ++ '<a:ln w="12700"><a:solidFill><a:srgbClr val="000000"/></a:solidFill></a:ln>'), ctxOf(), deps())+ ok(r5!.shape.d === 'M0 50 L100 50 L100 0', `flipV bakes into the path (got ${r5!.shape.d})`)+}++// --------------------------------------------------------------- flip policy+{+ // flipV triangle: bento's triangle points up, so the flip is absorbed by+ // becoming a path — NOT reported (the negative for a lazy always-report)+ const c = ctxOf()+ const r = shapeFrom(spOf('36',+ '<a:xfrm flipV="1"><a:off x="0" y="0"/><a:ext cx="952500" cy="952500"/></a:xfrm>' ++ `<a:prstGeom prst="triangle"><a:avLst/></a:prstGeom>${RED}`), c, deps())+ ok(r!.shape.shape === 'path' && r!.shape.d === 'M50 100 L100 0 L0 0 Z',+ `flipV triangle becomes a points-down path (got ${r!.shape.shape} ${r!.shape.d})`)+ ok(!c.report.build().entries.some((e) => e.code === 'flip-dropped'),+ 'an absorbable flip is not reported')++ // a flip nothing absorbs (rightArrow flipH would need to point left) IS+ ok(r!.shape.pathBox !== undefined, 'flipped triangle keeps its pathBox')+ const c2 = ctxOf()+ const r2 = shapeFrom(spOf('37',+ '<a:xfrm flipH="1"><a:off x="0" y="0"/><a:ext cx="952500" cy="952500"/></a:xfrm>' ++ `<a:prstGeom prst="rightArrow"><a:avLst/></a:prstGeom>${RED}`), c2, deps())+ ok(r2!.shape.shape === 'arrow'+ && c2.report.build().entries.some((e) => e.code === 'flip-dropped' && e.verdict === 'approximated'),+ 'an unabsorbable flip reports flip-dropped')+}++// ------------------------------------------ dash mapping / picture fill drop+{+ const dash = (val: string) => shapeFrom(spOf('40',+ `${XFRM_100}<a:prstGeom prst="rect"><a:avLst/></a:prstGeom>${RED}` ++ `<a:ln w="12700"><a:solidFill><a:srgbClr val="000000"/></a:solidFill><a:prstDash val="${val}"/></a:ln>`),+ ctxOf(), deps())!.shape+ ok(dash('sysDash').strokeStyle === 'dashed' && dash('dashDot').strokeStyle === 'dashed',+ 'dash family → dashed')+ ok(dash('sysDot').strokeStyle === 'dotted', 'dot family → dotted')+ ok(dash('solid').strokeStyle === undefined, 'solid emits no strokeStyle')++ const c = ctxOf()+ const r = shapeFrom(spOf('41', `${XFRM_100}<a:prstGeom prst="rect"><a:avLst/></a:prstGeom>` ++ '<a:blipFill><a:blip/></a:blipFill>'), c, deps())+ ok(!!r && r.shape.fill === 'transparent'+ && c.report.build().entries.some((e) => e.code === 'picture-fill-dropped'),+ 'blipFill on a shape → transparent + report (shape still emitted for the report to point at)')+}++// ----------------------------------------- text boxes and the box-text split+{+ const TX = '<p:txBody><a:bodyPr/><a:p><a:r><a:rPr lang="en-US"/><a:t>Hello</a:t></a:r></a:p></p:txBody>'+ // invisible geometry (noFill, no ln): a bare text box — no shape element+ const bare = shapeFrom(spOf('50',+ `${XFRM_100}<a:prstGeom prst="rect"><a:avLst/></a:prstGeom><a:noFill/>`, TX), ctxOf(), deps())+ ok(bare === undefined, 'a noFill/no-stroke text box emits NO shape (text module carries it alone)')++ // visible box with text: shape emits carrying the reserved groupId the+ // integrator must weld the text element to (shape first, text above)+ const boxed = shapeFrom(spOf('51',+ `${XFRM_100}<a:prstGeom prst="roundRect"><a:avLst/></a:prstGeom>${RED}`, TX), ctxOf(), deps())+ ok(!!boxed && boxed.textGroupId === 's1-51-g' && boxed.shape.groupId === 's1-51-g',+ `box-with-text reserves the shared groupId (got ${boxed?.textGroupId})`)+}++// --------------------------------------------------------------------- total+console.log(`\n${checks} checks, ${failures} failures`)+process.exit(failures ? 1 : 0)diff --git a/scripts/test-convert/text.ts b/scripts/test-convert/text.tsnew file mode 100644index 00000000..8e1f804d--- /dev/null+++ b/scripts/test-convert/text.ts@@ -0,0 +1,335 @@+#!/usr/bin/env node+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// bento/convert text-mapper rig.+//+// node scripts/test-convert/text.ts (Node ≥ 23.6 strips types natively)+//+// Hand-built p:sp fragments with hand-computed expected values, wired to the+// REAL inherit/theme resolvers (that is the deps injection working as+// designed). Each flattening trap carries a NEGATIVE control — the wrong+// implementation's answer computed inline, asserted to differ from ours:+//+// • sz=1800 must land at 24px, not 18 (pt-as-px) and not 1800 (raw+// centipoints) — both wrong readings are pinned as inequalities.+// • two IDENTICALLY styled runs must NOT report run-formatting-flattened+// (an implementation that reports whenever runs > 1 fails here — seen to+// fail exactly that way with the variance test replaced by a run count).+// • a paragraph buNone under an inherited buChar must stay silent, while+// the defaults provably carry a live bullet (the merged answer).+// • a literal '<' in a:t must come out as < — the raw-emit answer would+// open a tag (seen to fail with esc() bypassed: html gained '<script').++import { parseXml, kid, kids, attr, NS } from '../../kernel/src/convert/xml.ts'+import type { XElem } from '../../kernel/src/convert/xml.ts'+import { Report } from '../../kernel/src/convert/report.ts'+import type { ThemeCtx, InheritCtx } from '../../kernel/src/convert/types.ts'+import {+ effectivePhType, textDefaults, resolveFrame, labeledChain,+} from '../../kernel/src/convert/inherit.ts'+import { resolveColor } from '../../kernel/src/convert/theme.ts'+import { textFrom, type TextDeps } from '../../kernel/src/convert/text.ts'++let failures = 0+let checks = 0+function ok(cond: boolean, msg: string) {+ checks+++ if (!cond) { failures++; console.log(` FAIL ${msg}`) }+ else console.log(` ok ${msg}`)+}++const NBSP = ' '+const XMLNS = 'xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main" ' ++ 'xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"'++const theme: ThemeCtx = {+ scheme: { tx1: '#101010', accent1: '#4488FF' },+ majorFont: 'TestHead', minorFont: 'TestBody',+ fillStyles: [], lineStyles: [], bgFillStyles: [],+}++// off 9525,19050 ext 952500×476250 EMU = x1 y2 w100 h50 px — hand computed.+const XFRM = '<p:spPr><a:xfrm><a:off x="9525" y="19050"/><a:ext cx="952500" cy="476250"/></a:xfrm></p:spPr>'++/** A standalone (non-placeholder) shape around one txBody. */+function makeSp(txBody: string, name = 't'): XElem {+ return parseXml(`<p:sp ${XMLNS}>+ <p:nvSpPr><p:cNvPr id="7" name="${name}"/><p:cNvSpPr/><p:nvPr/></p:nvSpPr>+ ${XFRM}+ ${txBody}+ </p:sp>`)+}++const dummySlide = parseXml(`<p:sld ${XMLNS}><p:cSld><p:spTree/></p:cSld></p:sld>`)++const refits: string[] = []+const deps: TextDeps = {+ effectivePhType, textDefaults, resolveFrame, labeledChain, resolveColor,+ needsRefit: (id) => refits.push(id),+}++function run(sp: XElem): { out: ReturnType<typeof textFrom>; report: ReturnType<Report['build']> } {+ const report = new Report()+ const ctx: InheritCtx = { slide: dummySlide, theme, report }+ const out = textFrom(sp, ctx, deps)+ return { out, report: report.build() }+}+const has = (r: ReturnType<Report['build']>, code: string): boolean =>+ r.entries.some((e) => e.code === code)++// -------------------------------------------------------- single clean run+{+ const sp = makeSp(`<p:txBody><a:bodyPr><a:noAutofit/></a:bodyPr><a:lstStyle/>+ <a:p><a:r><a:rPr lang="en" sz="1800"><a:solidFill><a:srgbClr val="112233"/></a:solidFill><a:latin typeface="Calibri"/></a:rPr><a:t>Hello</a:t></a:r></a:p>+ </p:txBody>`)+ const { out, report } = run(sp)+ ok(out !== undefined, 'a clean single run emits a text element')+ if (out) {+ ok(out.html === 'Hello', 'html is the bare run text')+ ok(out.fontSize === 24, 'sz="1800" → 18pt → 24px (centipoints ÷ 100, × 4/3)')+ ok(out.fontSize !== 18, 'negative control: a pt-as-px implementation would say 18')+ ok(out.fontSize !== 1800, 'negative control: raw centipoints would say 1800')+ ok(out.color === '#112233', 'run srgbClr resolves through theme.resolveColor')+ ok(out.fontFamily === "Calibri, Carlito, sans-serif", 'Calibri maps to a metric-substitute stack')+ ok(out.x === 1 && out.y === 2 && out.w === 100 && out.h === 50, 'frame is EMU ÷ 9525 in px')+ ok(out.align === 'left' && out.valign === 'top' && out.lineHeight === 1, 'quiet defaults: left, top, single-spaced')+ ok(out.fontWeight === 400, 'no bold anywhere → weight 400')+ ok(out.id === 'txt7', 'id is txt + cNvPr@id')+ }+ ok(has(report, 'font-substituted'), 'and the substitution is reported (approximated)')+ ok(!has(report, 'run-formatting-flattened'), 'a single run never reports flattening')+}++// --------------------------------------------------------- mixed bold/italic+{+ const sp = makeSp(`<p:txBody><a:bodyPr/><a:lstStyle/>+ <a:p>+ <a:r><a:rPr sz="1800"/><a:t>the longest plain stretch </a:t></a:r>+ <a:r><a:rPr sz="1800" b="1"/><a:t>bold</a:t></a:r>+ <a:r><a:rPr sz="1800" i="1" u="sng" strike="sngStrike"/><a:t>ital</a:t></a:r>+ </a:p>+ </p:txBody>`)+ const { out, report } = run(sp)+ ok(out !== undefined && out.html.includes('<b>bold</b>'), 'b="1" survives as <b>')+ ok(out !== undefined && out.html.includes('<i><u><s>ital</s></u></i>'), 'i/u/strike survive as <i><u><s>')+ ok(out !== undefined && out.fontWeight === 400, 'the dominant (plain) run sets the element weight')+ ok(!has(report, 'run-formatting-flattened'),+ 'bold/italic carried as tags are NOT flattening (size/colour/family all agree)')+}++// ----------------------------------- dominant-run selection + flatten report+{+ const sp = makeSp(`<p:txBody><a:bodyPr/><a:lstStyle/>+ <a:p>+ <a:r><a:rPr sz="1800"><a:solidFill><a:srgbClr val="112233"/></a:solidFill></a:rPr><a:t>the long descriptive label</a:t></a:r>+ <a:r><a:rPr sz="4400"><a:solidFill><a:srgbClr val="FF0000"/></a:solidFill></a:rPr><a:t>42%</a:t></a:r>+ </a:p>+ </p:txBody>`)+ const { out, report } = run(sp)+ ok(out !== undefined && out.fontSize === 24 && out.color === '#112233',+ 'the element styles after the dominant run by character count')+ ok(has(report, 'run-formatting-flattened'), 'and the disagreement is reported once')++ // NEGATIVE control: identical styling across two runs must stay silent. An+ // implementation keyed on run COUNT (rather than style variance) fails this+ // — seen to fail exactly so with the variance test swapped for pieces>1.+ const same = makeSp(`<p:txBody><a:bodyPr/><a:lstStyle/>+ <a:p>+ <a:r><a:rPr sz="1800"/><a:t>two runs, </a:t></a:r>+ <a:r><a:rPr sz="1800"/><a:t>one style</a:t></a:r>+ </a:p>+ </p:txBody>`)+ const r2 = run(same)+ ok(r2.out !== undefined && !has(r2.report, 'run-formatting-flattened'),+ 'negative control: identically-styled runs do NOT report flattening')+}++// ------------------------------------------------------------------ bullets+{+ const sp = makeSp(`<p:txBody><a:bodyPr/><a:lstStyle/>+ <a:p><a:pPr><a:buFont typeface="Arial"/><a:buChar char="•"/></a:pPr><a:r><a:rPr sz="1800"/><a:t>first point</a:t></a:r></a:p>+ <a:p><a:pPr><a:buFont typeface="Arial"/><a:buChar char="•"/></a:pPr><a:r><a:rPr sz="1800"/><a:t>second point</a:t></a:r></a:p>+ </p:txBody>`)+ const { out, report } = run(sp)+ ok(out !== undefined && out.html === `•${NBSP}first point<br>•${NBSP}second point`,+ 'buChar prepends glyph + NBSP per paragraph, paragraphs join with <br>')+ ok(has(report, 'bullet-flattened'), 'and the flattening is reported')++ // buAutoNum freezes to literals, honouring startAt+ const auto = makeSp(`<p:txBody><a:bodyPr/><a:lstStyle/>+ <a:p><a:pPr><a:buAutoNum type="arabicPeriod" startAt="3"/></a:pPr><a:r><a:t>alpha</a:t></a:r></a:p>+ <a:p><a:pPr><a:buAutoNum type="arabicPeriod"/></a:pPr><a:r><a:t>beta</a:t></a:r></a:p>+ </p:txBody>`)+ const ra = run(auto)+ ok(ra.out !== undefined && ra.out.html === `3.${NBSP}alpha<br>4.${NBSP}beta`,+ 'buAutoNum numbers sequentially at convert time (startAt honoured)')+ ok(has(ra.report, 'auto-number-frozen'), 'and reports the freeze')++ // buNone SILENCES an inherited buChar. The shape's own lstStyle carries a+ // live bullet — the merged (wrong) answer — and the paragraph turns it off.+ const none = makeSp(`<p:txBody><a:bodyPr/>+ <a:lstStyle><a:lvl1pPr><a:buFont typeface="Arial"/><a:buChar char="♦"/></a:lvl1pPr></a:lstStyle>+ <a:p><a:pPr><a:buNone/></a:pPr><a:r><a:t>no bullet here</a:t></a:r></a:p>+ </p:txBody>`)+ const rn = run(none)+ // negative control: prove the inherited default IS a live bullet, so a+ // property-merging implementation would prepend ♦ here.+ const mergedDefaults = (() => {+ const report = new Report()+ const ctx: InheritCtx = { slide: dummySlide, theme, report }+ return textDefaults(none, ctx, 0, '')+ })()+ ok(mergedDefaults.bullet.kind === 'char', 'negative control: the inherited default carries a live ♦ bullet')+ ok(rn.out !== undefined && rn.out.html === 'no bullet here', 'buNone silences it — no glyph')+ ok(!has(rn.report, 'bullet-flattened'), 'and nothing bullet-shaped is reported')+}++// ---------------------------------------------------------- algn and anchor+{+ const sp = makeSp(`<p:txBody><a:bodyPr anchor="ctr"/><a:lstStyle/>+ <a:p><a:pPr algn="ctr"/><a:r><a:t>centered</a:t></a:r></a:p>+ </p:txBody>`)+ const { out } = run(sp)+ ok(out !== undefined && out.align === 'center' && out.valign === 'middle',+ 'algn="ctr" → center, anchor="ctr" → middle')++ const b = makeSp(`<p:txBody><a:bodyPr anchor="b"/><a:lstStyle/>+ <a:p><a:pPr algn="r"/><a:r><a:t>right-bottom</a:t></a:r></a:p>+ </p:txBody>`)+ const rb = run(b)+ ok(rb.out !== undefined && rb.out.align === 'right' && rb.out.valign === 'bottom',+ 'algn="r" → right, anchor="b" → bottom')++ const just = makeSp(`<p:txBody><a:bodyPr/><a:lstStyle/>+ <a:p><a:pPr algn="just"/><a:r><a:t>justified text goes left</a:t></a:r></a:p>+ </p:txBody>`)+ const rj = run(just)+ ok(rj.out !== undefined && rj.out.align === 'left', 'algn="just" approximates to left')+ ok(has(rj.report, 'align-approximated'), 'and is reported')++ // mixed paragraph alignment: dominant wins, disagreement reported+ const mixed = makeSp(`<p:txBody><a:bodyPr/><a:lstStyle/>+ <a:p><a:pPr algn="ctr"/><a:r><a:t>short</a:t></a:r></a:p>+ <a:p><a:r><a:t>the much longer left-aligned body paragraph</a:t></a:r></a:p>+ </p:txBody>`)+ const rm = run(mixed)+ ok(rm.out !== undefined && rm.out.align === 'left', 'mixed alignment: the dominant paragraph wins')+ ok(has(rm.report, 'align-flattened'), 'and the disagreement is reported')+}++// -------------------------------------------- line spacing + paragraph space+{+ const sp = makeSp(`<p:txBody><a:bodyPr/><a:lstStyle/>+ <a:p><a:pPr><a:lnSpc><a:spcPct val="150000"/></a:lnSpc><a:spcBef><a:spcPts val="600"/></a:spcBef></a:pPr><a:r><a:t>spaced</a:t></a:r></a:p>+ </p:txBody>`)+ const { out, report } = run(sp)+ ok(out !== undefined && out.lineHeight === 1.5, 'lnSpc spcPct val="150000" → 1.5')+ ok(has(report, 'paragraph-spacing-dropped'), 'spcBef presence is reported as dropped spacing')+}++// ------------------------------------------------------------------- fields+{+ const sp = makeSp(`<p:txBody><a:bodyPr/><a:lstStyle/>+ <a:p><a:fld id="{X}" type="slidenum"><a:rPr sz="1200"/><a:t>4</a:t></a:fld><a:r><a:rPr sz="1200"/><a:t> of 12</a:t></a:r></a:p>+ </p:txBody>`)+ const { out, report } = run(sp)+ ok(out !== undefined && out.html === '{{page}} of 12', 'a:fld slidenum → {{page}} (never the cached "4")')+ ok(report.entries.length === 0, 'an exact semantic match reports NOTHING — carried, not approximated')++ const dt = makeSp(`<p:txBody><a:bodyPr/><a:lstStyle/>+ <a:p><a:fld id="{Y}" type="datetime1"><a:t>1/1/26</a:t></a:fld></a:p>+ </p:txBody>`)+ const rd = run(dt)+ ok(rd.out !== undefined && rd.out.html === '{{date}}', 'a:fld datetime → {{date}}')+}++// -------------------------------------------------------- autofit / refit+{+ refits.length = 0+ const norm = makeSp(`<p:txBody><a:bodyPr><a:normAutofit fontScale="62500"/></a:bodyPr><a:lstStyle/>+ <a:p><a:r><a:rPr sz="3200"/><a:t>shrunk to fit</a:t></a:r></a:p>+ </p:txBody>`)+ const rn = run(norm)+ // 32pt × 4/3 = 42.6667px, × 0.625 = 26.6667 → 26.67+ ok(rn.out !== undefined && rn.out.fontSize === 26.67, 'normAutofit fontScale="62500" scales 32pt → 26.67px')+ ok(refits.length === 0, 'normAutofit does NOT ask for a refit (the scale is applied here)')++ const spa = makeSp(`<p:txBody><a:bodyPr><a:spAutoFit/></a:bodyPr><a:lstStyle/>+ <a:p><a:r><a:t>grows</a:t></a:r></a:p>+ </p:txBody>`)+ run(spa)+ ok(refits.length === 1 && refits[0] === 'txt7', 'spAutoFit emits a needsRefit hint with the element id')++ const absent = makeSp(`<p:txBody><a:bodyPr/><a:lstStyle/>+ <a:p><a:r><a:t>unfitted</a:t></a:r></a:p>+ </p:txBody>`)+ run(absent)+ ok(refits.length === 2, 'absent autofit also hints (substituted fonts re-wrap)')++ refits.length = 0+ const no = makeSp(`<p:txBody><a:bodyPr><a:noAutofit/></a:bodyPr><a:lstStyle/>+ <a:p><a:r><a:t>fixed</a:t></a:r></a:p>+ </p:txBody>`)+ run(no)+ ok(refits.length === 0, 'noAutofit is an explicit fixed box — no hint')+}++// ------------------------------------------------------------- escaping+{+ const sp = makeSp(`<p:txBody><a:bodyPr/><a:lstStyle/>+ <a:p><a:r><a:t>a <script> & b</a:t></a:r></a:p>+ </p:txBody>`)+ const { out } = run(sp)+ ok(out !== undefined && out.html === 'a <script> & b',+ 'literal <, > and & in run text are entity-escaped in the emitted html')+ ok(out !== undefined && !out.html.includes('<script'),+ 'negative control: a raw emitter would open a real tag here (seen to fail with esc() bypassed)')+}++// ------------------------------------- defaults: bold weight + fallback ink+{+ const sp = makeSp(`<p:txBody><a:bodyPr/>+ <a:lstStyle><a:lvl1pPr><a:defRPr sz="4400" b="1"/></a:lvl1pPr></a:lstStyle>+ <a:p><a:r><a:t>a heading</a:t></a:r></a:p>+ </p:txBody>`)+ const { out } = run(sp)+ ok(out !== undefined && out.fontWeight === 700, 'defRPr b="1" from the lstStyle → element weight 700')+ ok(out !== undefined && !out.html.includes('<b>'), 'and NOT doubled as a <b> tag')+ ok(out !== undefined && out.color === '#101010', 'no colour anywhere → the theme’s tx1 ink')+ ok(out !== undefined && out.fontFamily.startsWith('TestBody'), 'no latin anywhere → the minor theme face')+}++// ------------------------------------------------------------ empty bodies+{+ const empty = makeSp(`<p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:pPr/><a:endParaRPr lang="en"/></a:p></p:txBody>`)+ const { out, report } = run(empty)+ ok(out === undefined, 'a txBody with no visible text emits nothing')+ ok(report.entries.length === 0, 'and leaves no reports about the element it never was')++ const noBody = parseXml(`<p:sp ${XMLNS}><p:nvSpPr><p:cNvPr id="9" name="pic-ish"/><p:cNvSpPr/><p:nvPr/></p:nvSpPr>${XFRM}</p:sp>`)+ ok(run(noBody).out === undefined, 'a shape without p:txBody emits nothing')+}++// -------------------------------------------------- a:br and blank paragraphs+{+ const sp = makeSp(`<p:txBody><a:bodyPr/><a:lstStyle/>+ <a:p><a:r><a:t>line one</a:t></a:r><a:br/><a:r><a:t>line two</a:t></a:r></a:p>+ <a:p/>+ <a:p><a:r><a:t>after the gap</a:t></a:r></a:p>+ <a:p><a:endParaRPr/></a:p>+ </p:txBody>`)+ const { out } = run(sp)+ ok(out !== undefined && out.html === 'line one<br>line two<br><br>after the gap',+ 'a:br is <br>, an interior empty paragraph is a blank line, trailing empties are trimmed')+}++// sanity: the deps object really is wired to the shipping resolvers+{+ const chain = labeledChain(makeSp('<p:txBody><a:bodyPr/><a:p/></p:txBody>'), {+ slide: dummySlide, theme, report: new Report(),+ })+ ok(chain.length === 1 && chain[0].from === 'own', 'deps wire the real inherit resolver (not a stub)')+}++console.log(`\n${checks - failures}/${checks} checks passed`)+if (failures) process.exit(1)diff --git a/scripts/test-convert/theme.ts b/scripts/test-convert/theme.tsnew file mode 100644index 00000000..4a59eef6--- /dev/null+++ b/scripts/test-convert/theme.ts@@ -0,0 +1,211 @@+#!/usr/bin/env node+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// bento/convert theme rig — the colour/font resolver.+//+// node scripts/test-convert/theme.ts (Node ≥ 23.6 strips types natively)+//+// Every expected value below is HAND-COMPUTED (worked in the comments), never+// derived by running the module against itself — a resolver checked against+// its own output would agree perfectly, including about its bugs. The two+// traps the spike names get NEGATIVE controls: the naive sRGB-space shade and+// tint values are asserted to be what we do NOT produce (the rig can tell the+// colour spaces apart), and a deliberately swapped clrMap is asserted to+// produce a DIFFERENT bg1 than the standard one (the backwards-clrMap failure,+// made visible instead of silent).++import { parseXml } from '../../kernel/src/convert/xml.ts'+import { parseTheme, resolveColor, resolveFillRef, resolveLnRef } from '../../kernel/src/convert/theme.ts'++let failures = 0+let checks = 0+function ok(cond: boolean, msg: string) {+ checks+++ if (!cond) { failures++; console.log(` FAIL ${msg}`) }+ else console.log(` ok ${msg}`)+}++const A = 'xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"'+const P = 'xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main"'++/** A colour container as it appears in spPr — the usual resolveColor input. */+const fill = (inner: string) => parseXml(`<a:solidFill ${A}>${inner}</a:solidFill>`)++// ------------------------------------------------------------------ the theme+const themeXml = parseXml(`<a:theme ${A} name="rig">+ <a:themeElements>+ <a:clrScheme name="rig">+ <a:dk1><a:sysClr val="windowText" lastClr="0A0A0A"/></a:dk1>+ <a:lt1><a:sysClr val="window" lastClr="EEEEEE"/></a:lt1>+ <a:dk2><a:srgbClr val="1E2A3A"/></a:dk2>+ <a:lt2><a:srgbClr val="E7E6E6"/></a:lt2>+ <a:accent1><a:srgbClr val="4488CC"/></a:accent1>+ <a:accent2><a:srgbClr val="FBAE40"/></a:accent2>+ <a:accent3><a:srgbClr val="808080"/></a:accent3>+ <a:accent4><a:srgbClr val="FF0000"/></a:accent4>+ <a:accent5><a:srgbClr val="70AD47"/></a:accent5>+ <a:accent6><a:srgbClr val="C00000"/></a:accent6>+ <a:hlink><a:srgbClr val="0563C1"/></a:hlink>+ <a:folHlink><a:srgbClr val="954F72"/></a:folHlink>+ </a:clrScheme>+ <a:fontScheme name="rig">+ <a:majorFont><a:latin typeface="Georgia"/></a:majorFont>+ <a:minorFont><a:latin typeface="Verdana"/></a:minorFont>+ </a:fontScheme>+ <a:fmtScheme name="rig">+ <a:fillStyleLst>+ <a:solidFill><a:schemeClr val="phClr"/></a:solidFill>+ <a:solidFill><a:schemeClr val="phClr"><a:lumMod val="75000"/></a:schemeClr></a:solidFill>+ <a:gradFill><a:gsLst>+ <a:gs pos="0"><a:schemeClr val="phClr"/></a:gs>+ <a:gs pos="100000"><a:schemeClr val="phClr"><a:shade val="50000"/></a:schemeClr></a:gs>+ </a:gsLst><a:lin ang="5400000"/></a:gradFill>+ </a:fillStyleLst>+ <a:lnStyleLst>+ <a:ln w="9525"><a:solidFill><a:schemeClr val="phClr"/></a:solidFill></a:ln>+ <a:ln w="19050"><a:solidFill><a:schemeClr val="phClr"><a:shade val="50000"/></a:schemeClr></a:solidFill></a:ln>+ </a:lnStyleLst>+ <a:bgFillStyleLst>+ <a:solidFill><a:srgbClr val="123456"/></a:solidFill>+ </a:bgFillStyleLst>+ </a:fmtScheme>+ </a:themeElements>+</a:theme>`)++const stdMap = parseXml(`<p:clrMap ${P} bg1="lt1" tx1="dk1" bg2="lt2" tx2="dk2" accent1="accent1" accent2="accent2" accent3="accent3" accent4="accent4" accent5="accent5" accent6="accent6" hlink="hlink" folHlink="folHlink"/>`)+const swappedMap = parseXml(`<p:clrMap ${P} bg1="dk1" tx1="lt1" bg2="dk2" tx2="lt2" accent1="accent1" accent2="accent2" accent3="accent3" accent4="accent4" accent5="accent5" accent6="accent6" hlink="hlink" folHlink="folHlink"/>`)++// --------------------------------------------------- parseTheme + clrMap swap+const theme = parseTheme(themeXml, stdMap)+{+ ok(theme.scheme.dk1 === '#0A0A0A', 'sysClr scheme slot reads its lastClr (dk1 = #0A0A0A)')+ ok(theme.scheme.accent1 === '#4488CC', 'srgbClr scheme slot reads its val (accent1 = #4488CC)')+ ok(theme.scheme.bg1 === '#EEEEEE', 'standard clrMap routes bg1 → lt1')+ ok(theme.scheme.tx1 === '#0A0A0A', 'standard clrMap routes tx1 → dk1')+ ok(theme.scheme.lt1 === '#EEEEEE', 'raw slot names stay resolvable beside the logical ones')+ ok(theme.majorFont === 'Georgia' && theme.minorFont === 'Verdana', 'fontScheme major/minor latin typefaces')+ ok(theme.fillStyles.length === 3 && theme.lineStyles.length === 2 && theme.bgFillStyles.length === 1,+ 'fmtScheme style lists collected in order (3 fills, 2 lines, 1 bg fill)')++ // NEGATIVE CONTROL — the backwards-clrMap failure made visible: a swapped+ // map must give a DIFFERENT bg1, or the resolver is ignoring the map and+ // dark-on-dark section slides would render without a peep.+ const swapped = parseTheme(themeXml, swappedMap)+ ok(swapped.scheme.bg1 === '#0A0A0A', 'swapped clrMap routes bg1 → dk1')+ ok(swapped.scheme.bg1 !== theme.scheme.bg1, 'NEGATIVE: swapped map differs from standard — the map is actually read')++ const unmapped = parseTheme(themeXml, undefined)+ ok(unmapped.scheme.bg1 === '#EEEEEE' && unmapped.scheme.tx1 === '#0A0A0A',+ 'absent clrMap falls back to the standard bg1→lt1 / tx1→dk1 map')+}++// ----------------------------------------------------------- base colour kinds+{+ const c = resolveColor(fill('<a:srgbClr val="FBAE40"/>'), theme)+ ok(c?.css === '#FBAE40' && c.alpha === 1 && c.from === 'own', 'srgbClr passes through untouched, from:own')++ const s = resolveColor(fill('<a:schemeClr val="accent1"/>'), theme)+ ok(s?.css === '#4488CC' && s.from === 'theme', 'schemeClr resolves through the scheme, from:theme')++ const sys = resolveColor(fill('<a:sysClr val="windowText" lastClr="2B2B2B"/>'), theme)+ ok(sys?.css === '#2B2B2B', 'sysClr uses its lastClr attribute')++ const prst = resolveColor(fill('<a:prstClr val="black"/>'), theme)+ ok(prst?.css === '#000000', 'prstClr black (618 census uses) resolves')+ ok(resolveColor(fill('<a:prstClr val="dkBlue"/>'), theme)?.css === '#00008B',+ 'prstClr abbreviated spelling normalizes (dkBlue → darkBlue #00008B)')++ ok(resolveColor(fill('<a:schemeClr val="nope"/>'), theme) === undefined, 'unknown scheme name is undefined, never a guess')+ ok(resolveColor(undefined, theme) === undefined, 'undefined container is undefined')+ ok(resolveColor(parseXml(`<a:solidFill ${A}/>`), theme) === undefined, 'container with no colour child is undefined')+}++// --------------------------------------------------------------------- alpha+{+ const c = resolveColor(fill('<a:srgbClr val="FF0000"><a:alpha val="50000"/></a:srgbClr>'), theme)+ ok(c?.css === 'rgba(255,0,0,0.5)' && c.alpha === 0.5, 'a:alpha 50% emits rgba(255,0,0,0.5)')+}++// ------------------------------------------------------------------ HSL space+{+ // lumMod 75% of #4488CC, by hand: rgb (68,136,204)/255 → max .8 min .26667,+ // L = .53333, d = .53333, S = d/(2-max-min) = .53333/.93333 = .571429,+ // H: max is blue → ((r-g)/d + 4)·60 = (-.5+4)·60 = 210°.+ // L·.75 = .4 → q = .4·1.571429 = .628571, p = .171429.+ // R(t=.91667→p) = .171429·255 = 43.71 → 44 (2C); G = L = .4·255 = 102 (66);+ // B = q = .628571·255 = 160.29 → 160 (A0).+ const c = resolveColor(fill('<a:schemeClr val="accent1"><a:lumMod val="75000"/></a:schemeClr>'), theme)+ ok(c?.css === '#2C66A0', 'lumMod 75% of #4488CC = #2C66A0 (hand-computed HSL)')+}++// ------------------------------------------------------- linear-light space+{+ // shade 50% of #808080, by hand in LINEAR light: (128/255)^2.2 = .21952,+ // ·.5 = .10976, ^(1/2.2) = .36640, ·255 = 93.4 → 93 → #5D5D5D.+ // The naive sRGB multiply gives 128·.5 = 64 → #404040 — a DIFFERENT channel+ // value, which is how this rig tells the two spaces apart.+ const sh = resolveColor(fill('<a:srgbClr val="808080"><a:shade val="50000"/></a:srgbClr>'), theme)+ ok(sh?.css === '#5D5D5D', 'shade 50% of #808080 = #5D5D5D (linear-light, hand-computed)')+ ok(sh?.css !== '#404040', 'NEGATIVE: shade is NOT the naive sRGB multiply (#404040)')++ // tint 50% toward white: .21952·.5 + .5 = .60976, ^(1/2.2) = .79869,+ // ·255 = 203.7 → 204 → #CCCCCC. Naive: 128 + .5·127 = 191.5 → 192 → #C0C0C0.+ const ti = resolveColor(fill('<a:srgbClr val="808080"><a:tint val="50000"/></a:srgbClr>'), theme)+ ok(ti?.css === '#CCCCCC', 'tint 50% of #808080 = #CCCCCC (linear-light, hand-computed)')+ ok(ti?.css !== '#C0C0C0', 'NEGATIVE: tint is NOT the naive sRGB interpolation (#C0C0C0)')+}++// ------------------------------------------------------------ document order+{+ // On accent1 (H 210°, S .571429, L .533333):+ // lumMod 50 then lumOff 25: L = .533333·.5 + .25 = .516667+ // q = L+S−L·S = .792857, p = .240476 → R 61 (3D), G = L·255 = 131.75 →+ // 132 (84), B = q·255 = 202.2 → 202 (CA) → #3D84CA+ // lumOff 25 then lumMod 50: L = (.533333+.25)·.5 = .391667+ // q = L·(1+S) = .615476, p = .167857 → R 42.8 → 43 (2B), G = 99.875 →+ // 100 (64), B = 156.9 → 157 (9D) → #2B649D+ const ab = resolveColor(fill('<a:schemeClr val="accent1"><a:lumMod val="50000"/><a:lumOff val="25000"/></a:schemeClr>'), theme)+ const ba = resolveColor(fill('<a:schemeClr val="accent1"><a:lumOff val="25000"/><a:lumMod val="50000"/></a:schemeClr>'), theme)+ ok(ab?.css === '#3D84CA', 'lumMod then lumOff = #3D84CA (hand-computed)')+ ok(ba?.css === '#2B649D', 'lumOff then lumMod = #2B649D (hand-computed)')+ ok(ab?.css !== ba?.css, 'NEGATIVE: transform order matters — reversing it changes the colour')+}++// ------------------------------------------------------------------- phClr+{+ const c = resolveColor(fill('<a:schemeClr val="phClr"/>'), theme, '#FBAE40')+ ok(c?.css === '#FBAE40', 'schemeClr val="phClr" substitutes the placeholder colour')+ ok(resolveColor(fill('<a:schemeClr val="phClr"/>'), theme) === undefined,+ 'phClr with no substitution available is undefined, not black')+}++// ------------------------------------------------------------ the style matrix+{+ ok(resolveFillRef(0, '#FBAE40', theme)?.kind === 'none', 'fillRef idx 0 is an intentional none')++ const f1 = resolveFillRef(1, '#FBAE40', theme)+ ok(f1?.kind === 'solid' && f1.color.css === '#FBAE40', 'fillRef idx 1 = fillStyleLst[0], phClr substituted')++ const f2 = resolveFillRef(2, '#4488CC', theme)+ ok(f2?.kind === 'solid' && f2.color.css === '#2C66A0', 'fillRef idx 2 applies the entry\'s own transforms to phClr')++ const f3 = resolveFillRef(3, '#4488CC', theme)+ ok(f3?.kind === 'other' && f3.el.local === 'gradFill' && f3.phClr === '#4488CC',+ 'fillRef onto a gradFill hands the raw entry + phClr through for shapes.ts')++ const bg = resolveFillRef(1001, '#4488CC', theme)+ ok(bg?.kind === 'solid' && bg.color.css === '#123456', 'fillRef idx 1001 = bgFillStyleLst[0]')++ ok(resolveFillRef(99, '#4488CC', theme) === undefined, 'NEGATIVE: out-of-range fillRef is undefined, not silently none')++ ok(resolveLnRef(0, '#FBAE40', theme)?.kind === 'none', 'lnRef idx 0 is none')+ const l1 = resolveLnRef(1, '#FBAE40', theme)+ ok(l1?.kind === 'ln' && l1.ln.attrs.get('w') === '9525' && l1.color?.css === '#FBAE40',+ 'lnRef idx 1 carries the raw a:ln (width readable) with its solid colour resolved')+ const l2 = resolveLnRef(2, '#808080', theme)+ ok(l2?.kind === 'ln' && l2.color?.css === '#5D5D5D', 'lnRef idx 2 shades phClr in linear light (#5D5D5D again)')+ ok(resolveLnRef(9, '#808080', theme) === undefined, 'out-of-range lnRef is undefined')+}++console.log(failures ? `\n${failures} of ${checks} checks FAILED` : `\nall ${checks} checks passed`)+process.exit(failures ? 1 : 0)