# slide-wright

Adopt this skill: https://proskills.md/skills/other/arifszn-slide-wright

Page: https://proskills.md/skills/other/arifszn-slide-wright
This document is the public skill bundle for that page. It contains SKILL.md and every helper file the catalog carries. No login is required.

## File: SKILL.md
size: 4661
sha: 928619ec0ca47ebc9371b3027950929a3d304fd8
upstream: https://github.com/arifszn/slide-wright/blob/HEAD/SKILL.md

```text
---
name: slide-wright
description: Create beautiful web presentations from a topic, rough notes, or an outline, and edit decks afterward — adding, removing, or revising slides. Generates a custom theme and a short two-slide preview, then builds the full deck only once the user confirms the direction; edits to an existing deck skip that flow and apply in place. Use when the user wants to make slides, a presentation, a talk deck, a pitch deck, or to add/remove/change a slide in one that already exists.
---

# slide-wright

Turn a topic or rough notes into a boardroom-grade presentation: slides that read like a deck from a strong strategy or product team, delivered as a single self-contained HTML file that runs in any browser.

## The rule that defines this skill

Propose the look before you build the deck. On the first pass you never produce a finished presentation. You generate a theme, build a two-slide preview in it, and stop until the user approves the direction. Only then do you build the rest.

One proposal at a time, not a menu. If the user says no, throw the direction out and try a clearly different one. Every theme is invented for the deck in front of you; there is no library of presets.

**New deck: read `slide-wright/references/new-deck.md` first.** It holds Steps 1-4 (work out the deck, propose a look, get a yes, build) and the exact approval gate.

## The engine (keep this internal)

Decks render with reveal.js loaded from a CDN, but that is an implementation detail the user never sees. Talk about slides, themes, and design; the library name appears only inside the generated `<link>` and `<script>` tags. `slide-wright/references/deck-template.md` has the exact setup.

## Editing a deck that already exists

If the user points at an existing HTML deck, check whether it's built on reveal.js (look for the reveal.js `<link>`/`<script>` tags from a CDN). If it is — whether or not this skill built it — don't start over: read it, keep its theme, and make the change in place. The look is already approved, so skip the proposal and the gate. After editing, run `node <skill-dir>/scripts/check-deck.mjs <deck.html>` and fix every line it prints (`slide-wright/references/new-deck.md` has the details).

No reference files are needed for an edit, unless you add a new exhibit type (read `slide-wright/references/exhibits.md`) or code or animation (read `slide-wright/references/code-slides.md` or `slide-wright/references/motion-recipes.md`).

If the deck is HTML but not on reveal.js (different engine, plain slides, etc.), it's outside this skill's edit path — say so rather than forcing a rewrite onto a different engine. Everything else here is for building a new deck.

## Step 5 — Hand it off

1. Open the finished deck.
2. Say where it lives, the theme name, and the slide count.
3. Tell the user how to drive it: arrow keys, space, or swipe to move; **F** for fullscreen, **Esc** or **O** for the slide overview, **S** for the speaker view with notes; add `?print-pdf` to the URL and print to save a PDF (`slide-wright/references/export-pdf.md` has the steps); theme colors live in the `:root` variables, fonts in the `<link>`.
4. Offer the obvious next moves: revise the content, change the theme, export a PDF, export a PowerPoint file (`slide-wright/references/export-pptx.md`), or **deploy to a live URL** to share it. If they want to deploy, read `slide-wright/references/deploy.md` and let them pick the host (Surge, Vercel, or Netlify) — don't assume one.

## Reference files

Read these as you reach them, not all at once:

- `slide-wright/references/new-deck.md` — Steps 1-4 for a new deck: work out the deck, propose a look, get a yes, build
- `slide-wright/references/design-aesthetics.md` — what makes a deck look designed (Step 2)
- `slide-wright/references/theme-generation.md` — the procedure for inventing a theme (Step 2)
- `slide-wright/references/deck-template.md` — the HTML skeleton, layout, and engine setup (Steps 2 and 4)
- `slide-wright/references/exhibits.md` — choosing and building the visual on each content slide (Steps 2 and 4)
- `slide-wright/references/code-slides.md` — code slides and their markup contract (Step 4)
- `slide-wright/references/motion-recipes.md` — animation, when the user asks for it (Step 4)
- `slide-wright/references/media.md` — images and video in slides (Step 4)
- `slide-wright/references/export-pdf.md` — saving a deck as a PDF (Step 5)
- `slide-wright/references/export-pptx.md` — exporting a deck to PowerPoint with editable text (Step 5)
- `slide-wright/references/deploy.md` — publishing the deck to a live URL (Step 5)
```

## File: slide-wright/SKILL.md
size: 4401
sha: 8fd7775e38c35663f6a15419a66ef6ec32af5e50
upstream: https://github.com/arifszn/slide-wright/blob/HEAD/slide-wright/SKILL.md

```text
---
name: slide-wright
description: Create beautiful web presentations from a topic, rough notes, or an outline, and edit decks afterward — adding, removing, or revising slides. Generates a custom theme and a short two-slide preview, then builds the full deck only once the user confirms the direction; edits to an existing deck skip that flow and apply in place. Use when the user wants to make slides, a presentation, a talk deck, a pitch deck, or to add/remove/change a slide in one that already exists.
---

# slide-wright

Turn a topic or rough notes into a boardroom-grade presentation: slides that read like a deck from a strong strategy or product team, delivered as a single self-contained HTML file that runs in any browser.

## The rule that defines this skill

Propose the look before you build the deck. On the first pass you never produce a finished presentation. You generate a theme, build a two-slide preview in it, and stop until the user approves the direction. Only then do you build the rest.

One proposal at a time, not a menu. If the user says no, throw the direction out and try a clearly different one. Every theme is invented for the deck in front of you; there is no library of presets.

**New deck: read `references/new-deck.md` first.** It holds Steps 1-4 (work out the deck, propose a look, get a yes, build) and the exact approval gate.

## The engine (keep this internal)

Decks render with reveal.js loaded from a CDN, but that is an implementation detail the user never sees. Talk about slides, themes, and design; the library name appears only inside the generated `<link>` and `<script>` tags. `references/deck-template.md` has the exact setup.

## Editing a deck that already exists

If the user points at an existing HTML deck, check whether it's built on reveal.js (look for the reveal.js `<link>`/`<script>` tags from a CDN). If it is — whether or not this skill built it — don't start over: read it, keep its theme, and make the change in place. The look is already approved, so skip the proposal and the gate. After editing, run `node <skill-dir>/scripts/check-deck.mjs <deck.html>` and fix every line it prints (`references/new-deck.md` has the details).

No reference files are needed for an edit, unless you add a new exhibit type (read `references/exhibits.md`) or code or animation (read `references/code-slides.md` or `references/motion-recipes.md`).

If the deck is HTML but not on reveal.js (different engine, plain slides, etc.), it's outside this skill's edit path — say so rather than forcing a rewrite onto a different engine. Everything else here is for building a new deck.

## Step 5 — Hand it off

1. Open the finished deck.
2. Say where it lives, the theme name, and the slide count.
3. Tell the user how to drive it: arrow keys, space, or swipe to move; **F** for fullscreen, **Esc** or **O** for the slide overview, **S** for the speaker view with notes; add `?print-pdf` to the URL and print to save a PDF (`references/export-pdf.md` has the steps); theme colors live in the `:root` variables, fonts in the `<link>`.
4. Offer the obvious next moves: revise the content, change the theme, export a PDF, export a PowerPoint file (`references/export-pptx.md`), or **deploy to a live URL** to share it. If they want to deploy, read `references/deploy.md` and let them pick the host (Surge, Vercel, or Netlify) — don't assume one.

## Reference files

Read these as you reach them, not all at once:

- `references/new-deck.md` — Steps 1-4 for a new deck: work out the deck, propose a look, get a yes, build
- `references/design-aesthetics.md` — what makes a deck look designed (Step 2)
- `references/theme-generation.md` — the procedure for inventing a theme (Step 2)
- `references/deck-template.md` — the HTML skeleton, layout, and engine setup (Steps 2 and 4)
- `references/exhibits.md` — choosing and building the visual on each content slide (Steps 2 and 4)
- `references/code-slides.md` — code slides and their markup contract (Step 4)
- `references/motion-recipes.md` — animation, when the user asks for it (Step 4)
- `references/media.md` — images and video in slides (Step 4)
- `references/export-pdf.md` — saving a deck as a PDF (Step 5)
- `references/export-pptx.md` — exporting a deck to PowerPoint with editable text (Step 5)
- `references/deploy.md` — publishing the deck to a live URL (Step 5)
```

## File: README.md
size: 5092
sha: 7476dc1ce98f72abdb410c9f4a1c5c1645a6f254
upstream: https://github.com/arifszn/slide-wright/blob/HEAD/README.md

````text
# slide-wright

<img src="https://github.com/user-attachments/assets/3e496913-753c-4761-873c-b7f6618a0b93" alt="slide-wright" />

## How it works

1. **Tell it what you want.** A topic, rough notes, or a full outline — whatever you have.
2. **It generates a theme.** A custom color palette, typography, and a 2-slide preview in that style. It opens the preview for you.
3. **You decide.** Love it? It builds the whole deck. Want a different vibe? It generates a fresh direction and shows a new preview. Repeat until it's right.
4. **You get your deck.** A polished, self-contained presentation. Export it to PDF or PowerPoint, or deploy it to a live URL for a link that works on any device.

https://github.com/user-attachments/assets/911a77d8-fae4-48aa-81a0-594e675534c9

## Examples

<table>
<tr><th colspan="2"><i>"/slide-wright Create a Q3 board update for Corvid Labs, a B2B observability SaaS"</i></th></tr>
<tr>
<td><img src="https://github.com/user-attachments/assets/f414f240-8cb1-4a91-b9a7-1366e8fc0c31" alt="Q3 board update example slide 1" /></td>
<td><img src="https://github.com/user-attachments/assets/fbc65739-ca60-42e7-98d2-1f0d6b34f6bf" alt="Q3 board update example slide 2" /></td>
</tr>
</table>

<table>
<tr><th colspan="2"><i>"/slide-wright Generate a presentation for ClickHouse, keep theme yellow"</i></th></tr>
<tr>
<td><img src="https://github.com/user-attachments/assets/6839eba2-a228-4324-8dc0-983e235991f7" alt="ClickHouse example slide 1" /></td>
<td><img src="https://github.com/user-attachments/assets/e9208b1f-c813-4a0f-b4ef-b760c011981d" alt="ClickHouse example slide 2" /></td>
</tr>
</table>

<table>
<tr><th colspan="2"><i>"/slide-wright Create a presentation on MCP with this outline: [outline]"</i></th></tr>
<tr>
<td><img src="https://github.com/user-attachments/assets/645ec97e-e528-4299-a194-00dc18805f8f" alt="MCP example slide 1" /></td>
<td><img src="https://github.com/user-attachments/assets/4c640b94-3e09-4bb0-b766-639f07b01d84" alt="MCP example slide 2" /></td>
</tr>
</table>

## Installation

### Claude Code (Plugin Marketplace)

1. Register the marketplace:

   ```bash
   /plugin marketplace add arifszn/slide-wright
   ```

2. Install the plugin from this marketplace:

   ```bash
   /plugin install slide-wright
   ```

### Other agents (Codex, OpenCode, Antigravity, Gemini, Cursor, …)

slide-wright is a standalone skill that works in any agent supporting the `SKILL.md` format. See **[INSTALL.md](INSTALL.md)** for per-agent skills paths.

Just tell your agent to install it — paste:

```
Fetch and follow the install instructions from
https://raw.githubusercontent.com/arifszn/slide-wright/refs/heads/main/INSTALL.md
```

Or install it via npx:

```bash
npx skills add arifszn/slide-wright
```

## Usage

After installing, invoke the skill by name with what you want:

```
/slide-wright Make me a slide deck about <your topic>
```

It builds a theme and a short preview first. Approve it and it generates the full deck. You can hand it rough notes or an outline instead of a topic, and ask it to revise the design or content anytime.

A plain request without the name ("Make me a slide deck about...") also works, but apps with their own built-in slide builder may route it there instead. Naming the skill makes sure slide-wright handles it.

## Keyboard shortcuts

| Key | Action |
| --- | --- |
| F | Fullscreen |
| Esc / O | Slide overview |
| S | Speaker view with notes |
| B / . | Pause to a black screen |
| ? | Show the full list of keys |

## Export to PowerPoint

Ask the agent to export the deck as a PowerPoint file. Text comes out as editable text boxes with speaker notes; shapes, charts, and images are baked into each slide's background, so they look the same but are not editable. Fonts are not embedded, so on a machine without the deck's fonts PowerPoint substitutes similar ones. Use the PDF export when exact typography matters.

```
/slide-wright Export my deck to PowerPoint
```

Or run it yourself (needs Node 18+ and Chrome; dependencies install on first run):

```bash
node slide-wright/scripts/export-pptx.mjs deck.html
```

## Export to PDF

Just ask the agent to export the deck, and it walks you through it:

```
/slide-wright Export my deck to PDF
```

To do it yourself: add `?print-pdf` to the deck URL, then open the print dialog (Cmd/Ctrl + P) and save as PDF. Choose Landscape, set margins to None, and turn on background graphics.

## Deploy to a live URL

The deck is a single self-contained HTML file, with the theme inline and the engine and fonts from a CDN, so there's no build step and no assets to bundle. Any static host will serve it.

The simplest route is to **ask the agent to deploy it**. It offers Surge, Vercel, and Netlify, walks you through the login for whichever you pick, and hands back the live URL:

```
/slide-wright Deploy my deck to a live URL
```

To do it yourself, put the deck in an empty folder as `index.html` and push that folder to any static host: GitHub Pages, Cloudflare Pages, S3, or anywhere else that serves static files.

## License

[MIT](LICENSE)
````

## File: .claude-plugin/marketplace.json
size: 820
sha: 858cd261fe37379b87053d3837c2c8925bc0d11e
upstream: https://github.com/arifszn/slide-wright/blob/HEAD/.claude-plugin/marketplace.json

```text
{
  "$schema": "https://json.schemastore.org/claude-code-marketplace.json",
  "name": "slide-wright",
  "description": "Create beautiful presentations — generate a custom theme and preview, then build the full deck once you confirm the direction.",
  "owner": {
    "name": "arifszn",
    "url": "https://github.com/arifszn"
  },
  "plugins": [
    {
      "name": "slide-wright",
      "description": "Create beautiful presentations from a topic, rough notes, or an outline. Generates a custom theme and a quick preview, then builds the full deck only once you confirm the direction. Distinctive, custom-designed output as a single self-contained HTML file.",
      "source": "./slide-wright",
      "category": "productivity",
      "tags": ["presentations", "slides", "html", "design", "deck", "pitch"]
    }
  ]
}
```

## File: .github/workflows/test.yml
size: 1019
sha: 0ad9bd719ddc78a6978aaa75417c6aeb6a622f05
upstream: https://github.com/arifszn/slide-wright/blob/HEAD/.github/workflows/test.yml

```text
name: test

on:
  pull_request:
  push:
    branches: [main]

jobs:
  exporter:
    runs-on: ubuntu-latest
    timeout-minutes: 15
    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-node@v4
        with:
          node-version: 22

      # The exporter installs its own dependencies (pptxgenjs, playwright-core) into this
      # directory on first use; the tests add reveal.js, pngjs and xmldom to it.
      - uses: actions/cache@v4
        with:
          path: ~/.cache/slide-wright
          key: export-deps-${{ hashFiles('slide-wright/scripts/lib/deps.mjs', 'tests/lib/offline.mjs') }}

      # LibreOffice + poppler enable the render-position tests (otherwise they skip).
      - name: Install render tools
        run: |
          sudo apt-get update
          sudo apt-get install -y --no-install-recommends libreoffice-impress poppler-utils fonts-liberation

      - name: Root SKILL.md matches slide-wright/SKILL.md
        run: tools/sync-root-skill.sh --check

      - run: npm test
```

## File: INSTALL.md
size: 2203
sha: 69629edc4852a3b7a39df547aacb5e3c147832cd
upstream: https://github.com/arifszn/slide-wright/blob/HEAD/INSTALL.md

````text
# Installing slide-wright

slide-wright is a single **standalone skill**: one folder, `slide-wright/`, with a `SKILL.md` at its root (its `name` matches the folder, as the spec requires). Every agent loads that exact folder — only the parent *skills directory* changes from tool to tool.

So installation is always the same three steps: **clone → copy the `slide-wright/` folder into your agent's skills directory → clean up.**

---

## Claude Code

### Plugin marketplace (recommended)

1. Register the marketplace:

   ```bash
   /plugin marketplace add arifszn/slide-wright
   ```

2. Install the plugin from this marketplace:

   ```bash
   /plugin install slide-wright
   ```

### Standalone skill

Not using the plugin? Use the template below.

---

## Every other agent — one template

Pick your agent's skills directory from the table, set it as `DEST`, and run:

```bash
DEST=~/.claude/skills   # ← change this line per the table below
git clone --depth 1 https://github.com/arifszn/slide-wright /tmp/slide-wright-repo
mkdir -p "$DEST"
cp -r /tmp/slide-wright-repo/slide-wright "$DEST/slide-wright"
rm -rf /tmp/slide-wright-repo
```

| Agent | Global / user `DEST` | Project / workspace `DEST` |
| --- | --- | --- |
| **Claude Code** | `~/.claude/skills` | `.claude/skills` |
| **OpenCode** | `~/.config/opencode/skills` | `.opencode/skills` |
| **Codex** | `~/.agents/skills` | `.agents/skills` |
| **Antigravity** | `~/.gemini/config/skills` | `.agents/skills` |
| **Gemini CLI / Cursor / Windsurf / Kimi / others** | see your agent's skills docs | `.agents/skills` |

Notes:

- **OpenCode** also auto-discovers `~/.claude/skills` and `.claude/skills` — a Claude install is picked up with no extra step.
- **Codex** scans `.agents/skills` from the current directory up to the repo root, so a project install at `.agents/skills` is visible across the whole repo.
- `.agents/skills` is the closest thing to a cross-agent standard — when in doubt, use it.

After copying, restart or reload your agent so it rescans its skills directory.

---

## Verify

Ask your agent **"what skills do you have?"** — `slide-wright` should appear in the list. If it does, it's loaded and ready.
````

## File: LICENSE
size: 1068
sha: 18a1cba56460d921858d5d889d793c39ad91804d
upstream: https://github.com/arifszn/slide-wright/blob/HEAD/LICENSE

```text
MIT License

Copyright (c) 2026 Ariful Alam

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```

## File: package.json
size: 250
sha: db4b2ca2c37465c2b03084cf625d08167fc3c91b
upstream: https://github.com/arifszn/slide-wright/blob/HEAD/package.json

```text
{
  "name": "slide-wright-dev",
  "private": true,
  "type": "module",
  "description": "Dev-only: tests for the PowerPoint exporter. The skill itself has no build step and no dependencies.",
  "scripts": { "test": "node --test tests/*.test.mjs" }
}
```

## File: slide-wright/.claude-plugin/plugin.json
size: 624
sha: 30092612c6308417ce6d71dedf5e0c647a8101ff
upstream: https://github.com/arifszn/slide-wright/blob/HEAD/slide-wright/.claude-plugin/plugin.json

```text
{
  "name": "slide-wright",
  "version": "1.10.0",
  "description": "Create beautiful presentations from a topic, rough notes, or an outline. Generates a custom theme and a quick preview, then builds the full deck only once you confirm the direction. Distinctive, custom-designed output as a single self-contained HTML file.",
  "license": "MIT",
  "author": {
    "name": "arifszn",
    "url": "https://github.com/arifszn"
  },
  "homepage": "https://github.com/arifszn/slide-wright",
  "repository": "https://github.com/arifszn/slide-wright",
  "keywords": ["presentations", "slides", "html", "design", "deck", "pitch"]
}
```

## File: slide-wright/references/code-slides.md
size: 3053
sha: 35f773a721bce0539f3eb7ab674e60642961c43d
upstream: https://github.com/arifszn/slide-wright/blob/HEAD/slide-wright/references/code-slides.md

````text
# Code slides

For technical decks. Code slides need three additions to the deck-template skeleton.

1. A syntax theme `<link>` in `<head>`, close to the deck palette (atom-one-dark/-light, monokai, github):

   ```html
   <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/reveal.js@5.1.0/plugin/highlight/monokai.css" />
   ```

2. The plugin script after `reveal.js`, with `RevealHighlight` added to `plugins` in `Reveal.initialize`:

   ```html
   <script src="https://cdn.jsdelivr.net/npm/reveal.js@5.1.0/plugin/highlight/highlight.js"></script>
   ```

3. Restyle the `<pre>` container so it belongs to this deck, not a stock widget, while keeping the CSS contract below.

## Markup

```html
<section>
  <div class="frame">
    <h2>Slide title</h2>
    <pre><code data-trim data-noescape data-line-numbers="3-5|8-10" class="language-python">
def query(client, sql):
    return client.execute(sql)

rows = query(ch, "SELECT count() FROM events")
for r in rows:
    print(r)
    </code></pre>
  </div>
  <aside class="notes"></aside>
</section>
```

- `data-trim` strips outer whitespace. `data-noescape` keeps raw `<`, `&` in the source (or wrap the body in `<script type="text/template">…</script>`). `class="language-x"` sets the grammar.
- `data-line-numbers` shows line numbers; omit it for a plain block. Pipe-separated ranges (`"3-5|8-10|13-15"`) make each range a **fragment step** that lights as you advance, so walk the snippet a few lines at a time. `data-ln-start-from="42"` offsets the first number. Steps collapse to one PDF page via `pdfSeparateFragments: false`.

## The code-block CSS contract

When you restyle `<pre>`/`code.hljs` to fit the theme, the step animation clones and stacks the code block, so these rules are mandatory. Skipping any one causes the ghosting, stair-stepping, and heading-cover bugs:

```css
.reveal pre {
  position: relative;   /* clones anchor to <pre>; without it they anchor to the
                           absolute .frame and balloon to full-slide height */
  flex-shrink: 0;       /* in a flex frame, don't compress <pre> below the code's
                           height — that misaligns the clones */
}
.reveal pre code.hljs {
  display: block;       /* inline + a background paints one box per wrapped line = stairs */
  background: var(--bg-alt) !important;  /* opaque, so the top clone hides the rest
                                            (transparent clones bleed through = ghosting) */
  max-height: none;     /* reveal caps code at 400px by default; the cap turns the block
                           into a scroll viewport and the steps scroll out of alignment */
  padding: 2rem 2.4rem; font-family: var(--font-mono);
}
```

- Do **not** set `white-space` (`pre-wrap`), `word-break`, or `width` on `pre code` or its `td`s — line numbers render as a `<table>` and these collapse the number column onto the code.
- Keep the snippet short enough to fit the frame — roughly ≤ 12 lines at a comfortable size. If it doesn't fit, trim the code, don't shrink the slide.
````

## File: slide-wright/references/deck-template.md
size: 9737
sha: ccde1386d868274304fe588e018b663f4a63c727
upstream: https://github.com/arifszn/slide-wright/blob/HEAD/slide-wright/references/deck-template.md

````text
# Deck template

The HTML skeleton for every deck — preview and final are the same file. One self-contained file. The presentation engine loads from a CDN; **its name appears only in these tags, never in user-facing copy.** All visual identity comes from the inline `:root` variables and the custom slide CSS you generate — never from a stock engine theme.

Pin this engine version: **`reveal.js@5.1.0`**.

## Skeleton

```html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title><!-- DECK TITLE --></title>

  <!-- Engine core + reset (no stock theme — our theme is inline below) -->
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/reveal.js@5.1.0/dist/reset.css" />
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/reveal.js@5.1.0/dist/reveal.css" />

  <!-- Fonts: load a real web-font pair through a Fontshare or Google link; don't fall back to the system stack -->
  <link rel="stylesheet" href="https://api.fontshare.com/v2/css?f[]=<!-- DISPLAY+BODY -->&display=swap" />

  <!-- Code slides add a highlight theme <link> here: see code-slides.md -->

  <style>
    /* ===========================================
       THEME — generated per deck. Edit these to restyle everything.
       =========================================== */
    :root {
      /* Palette */
      --bg:            /* #... */;
      --bg-alt:        /* #... (gradient stop / section bg) */;
      --text:          /* #... primary text */;
      --text-muted:    /* #... secondary text */;
      --line:          /* #... rules, borders, dividers */;
      --accent:        /* #... */;
      --accent-2:      /* #... optional second data series */;
      --on-accent:     /* #... text on accent fills, meets AA */;

      /* Typography */
      --font-display:  /* 'Title Font', serif */;
      --font-body:     /* 'Body Font', sans-serif */;
      --font-mono:     /* 'Mono Font', monospace (optional, labels and numbers) */;
      --fs-title:      80px;
      --fs-sub:        40px;
      --fs-body:       28px;
      --fs-label:      20px;

      /* Exhibit style */
      --radius:        /* 0 | 8px | 16px */;
    }

    /* ===========================================
       BASE — map the engine surfaces to our theme
       =========================================== */
    .reveal { font-family: var(--font-body); color: var(--text); }
    .reveal h1, .reveal h2, .reveal h3 { font-family: var(--font-display); color: var(--text); text-transform: none; }
    .reveal-viewport, html, body { background: var(--bg); }
    /* Progress bar and (if enabled) arrows take the theme's colors: the engine
       defaults are a white bar and black arrows, which vanish on some backgrounds */
    .reveal .progress { color: var(--accent); }
    .reveal .controls { color: var(--accent); }

    /* 1920x1080 canvas (init uses center:false). <section> carries ONLY the background;
       layout lives in the inner .frame. Per-slide background variants must match this
       selector's specificity: `.reveal .slides section.ink`, not a bare `section.ink`.
       overflow:hidden is a print-pdf guard against phantom extra pages, not a license
       to overflow: fix the slide so nothing is cut. */
    .reveal .slides section { height: 1080px; overflow: hidden; background: var(--bg); }
    /* .reveal .slides section.ink { background: var(--text); }  <- example variant */

    /* .frame = the layout box for every slide; owns padding + flex. CRITICAL: padding
       goes here, NOT on <section>: ?print-pdf forces `section { padding:0 }`, which
       would push content into the edges. The same layout then holds on screen and in PDF. */
     .frame {
      position: absolute;
      inset: 0;
      padding: 72px 120px 64px;
      display: flex;
      flex-direction: column;
      justify-content: flex-start;  /* top-anchored: content fills down from the title */
      gap: 40px;
      box-sizing: border-box;
       text-align: left;     /* undo the engine's global center; centered layouts set it on their .frame variant */
     }

    /* ===========================================
       RECURRING ELEMENTS (optional, per theme): a header and/or footer inside
       .frame, so they survive PDF export. Keep, restyle, or delete them.
       =========================================== */
    .chrome-head { display: flex; align-items: center; gap: 24px; font-size: var(--fs-label); color: var(--text-muted); }
    .chrome-head .rule { flex: 1; border-top: 1px solid var(--line); }
    .chrome-foot { display: flex; justify-content: space-between; align-items: baseline; gap: 40px;
                   font-size: var(--fs-label); color: var(--text-muted); }
    .chrome-foot > * { min-width: 0; }
    .chrome-foot .takeaway { flex: 1 1 auto; min-width: 0; font-size: var(--fs-body); color: var(--text);
                             overflow-wrap: break-word; }
    .chrome-foot .source { flex: 0 1 30%; overflow-wrap: anywhere; }
    .chrome-foot [data-page] { flex: 0 0 auto; white-space: nowrap; }
    .body { flex: 1; min-height: 0; display: flex; flex-direction: column; justify-content: center; }
    .action-title { font-size: var(--fs-title); line-height: 1.08; max-width: 1500px; margin: 0; }

    /* ===========================================
       SLIDE LAYOUTS — title, section, content (full-width exhibit),
       split (text + exhibit), comparison, closing
       =========================================== */
    .title-slide { justify-content: space-between; }  /* label top, title middle, meta bottom */
    /* ... */

    /* ===========================================
       EXHIBITS: flow, mockup, chart, table... (see exhibits.md)
       =========================================== */
    /* ... */

    /* CODE slides only: add the code-block CSS contract from code-slides.md */
  </style>
</head>
<body>
  <div class="reveal">
    <div class="slides">

      <!-- Every slide: <section> for background, inner .frame for layout.
           Put layout variant classes (title-slide, two-col, etc.) on .frame. -->

      <!-- TITLE SLIDE -->
      <section>
        <div class="frame title-slide">
          <h1><!-- Real deck title --></h1>
          <p class="subtitle"><!-- subtitle / presenter / date --></p>
        </div>
        <aside class="notes"><!-- speaker notes for this slide --></aside>
      </section>

      <!-- CONTENT SLIDE: action title and one exhibit, visible at once.
           The header and footer are optional; keep only what the theme uses. -->
      <section>
        <div class="frame">
          <header class="chrome-head">
            <span class="section-label">02 · Section name</span>
            <span class="rule"></span>
          </header>
          <h2 class="action-title">The slide's point, stated as a short claim.</h2>
          <div class="body">
            <!-- one exhibit from exhibits.md -->
          </div>
          <footer class="chrome-foot">
            <p class="takeaway"><!-- optional takeaway or source line --></p>
            <span class="source"><!-- Source: ... (data slides) --></span>
          </footer>
        </div>
        <aside class="notes"><!-- talking points --></aside>
      </section>

      <!-- Code slides: markup in code-slides.md -->

      <!-- more slides -->

    </div>
  </div>

  <!-- Engine + plugins.
       PDF export (?print-pdf) is handled by the engine core — no extra print CSS needed. -->
  <script src="https://cdn.jsdelivr.net/npm/reveal.js@5.1.0/dist/reveal.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/reveal.js@5.1.0/plugin/notes/notes.js"></script>
  <script>
    Reveal.initialize({
      width: 1920,
      height: 1080,
      margin: 0,            // theme controls padding; no engine letterbox margin
      center: false,        // we author full-bleed at 1920x1080; do NOT vertically auto-center
      controls: false,      // arrows off by default; turn on if the user asks
      progress: true,
      hash: true,
      transition: 'fade',
      transitionSpeed: 'fast',
      pdfSeparateFragments: false, // collapse fragments to one page per slide on ?print-pdf
      plugins: [ RevealNotes ],    // code slides: see code-slides.md
    });

    // Optional page numbers: any element with data-page gets "02 / 09", filled
    // from slide order so it stays correct when slides change.
    Reveal.on('ready', () => {
      const slides = Reveal.getSlides();
      const pad = n => String(n).padStart(2, '0');
      slides.forEach((s, i) => s.querySelectorAll('[data-page]')
        .forEach(el => { el.textContent = `${pad(i + 1)} / ${pad(slides.length)}`; }));
    });
  </script>
</body>
</html>
```

## Rules

- **No stock theme.** Load `reset.css` + `reveal.css` only; all identity is in the inline `<style>`.
- **Linear deck only — no vertical/nested slides.** Keep every slide as a direct child `<section>` of `.slides`. Don't nest `<section>`s (the engine's vertical stacks) and don't use the Markdown plugin — both fight the hand-built HTML/CSS and break the straight-line narration the deck is designed around.
- **Recurring elements live inside `.frame`.** If the theme uses a header or footer, put the header first, the footer last, and `.body` between them with `flex: 1`. If it shows page numbers, mark the element with `data-page` and let the script fill it.
- **Keep `pdfSeparateFragments: false` in `Reveal.initialize`.** Without it, every fragment step becomes its own page in `?print-pdf`.
- **Code slides:** setup, markup, and the mandatory code-block CSS contract are in `code-slides.md`.
- **Media** (images, video, backgrounds): `media.md`.
````

## File: slide-wright/references/deploy.md
size: 3607
sha: 465b69859ebf9d772d412a171b81cfc1a99624b3
upstream: https://github.com/arifszn/slide-wright/blob/HEAD/slide-wright/references/deploy.md

````text
# Deploy to a live URL

The deck is a single self-contained file, so publishing is just putting it online as `index.html`: no build, no asset copying.

All three options below are free static hosts and run through `npx`, so nothing is installed globally.

## Prepare (same for every host)

Put the deck at the root of an otherwise empty folder, named `index.html`, so the bare URL serves it:

```bash
mkdir -p .deploy && cp <deck-slug>.html .deploy/index.html
```

Deploy the `.deploy` folder, then remove it when done.

## The login reality

All three need a one-time account login, and that step is **interactive** — surge asks for email + password, Vercel/Netlify open a browser. You can't drive it from a tool call, and it can **not** go through the agent prompt's `!` shell either: `!` runs a command but can't feed an interactive multi-prompt stdin, so `npx surge login` just hangs at `email:` with nowhere to type.

So the login has to happen in the user's **own terminal window** (the real Terminal/iTerm app, not this session). Tell the user to run the login command there, complete it, and report back. The credential is saved to disk (`~/.netrc` for surge, the CLI's own config for Vercel/Netlify), and from then on the deploy command reads it — so once the user is logged in, **you** run the deploy non-interactively.

Alternative for a fully agent-driven deploy: a token. If the user pastes one, deploy with it and skip the terminal step entirely — surge takes the `SURGE_TOKEN` env var (the user creates one with `npx surge token` in their own terminal), Vercel takes `--token`, Netlify takes `--auth`.

## Option A — Surge

```bash
npx surge .deploy <deck-slug>.surge.sh
```

- Auth is email + password (no browser); the user runs `npx surge login` once in their own terminal (see above).
- Pass an explicit `<something>.surge.sh` domain or it prompts for one. Pick a slug from the deck title; if it's taken, add a short suffix.
- Re-running with the same domain overwrites it — the URL stays put.

## Option B — Vercel

```bash
npx vercel deploy .deploy --yes --prod
```

- Check auth with `npx vercel whoami`. If not logged in, have the user run `npx vercel login` in their own terminal (opens a browser), then re-run the deploy.
- Prints a production `https://…vercel.app` URL. Re-deploying the same project updates the same URL.
- Take it down later from the Vercel dashboard.

## Option C — Netlify

```bash
npx netlify deploy --dir=.deploy --prod
```

- Check auth with `npx netlify status`. If not logged in, have the user run `npx netlify login` in their own terminal (opens a browser), then re-run.
- With no linked site, the first deploy asks to create or link one, and that prompt cannot be answered from a tool call. Either have the user run `npx netlify link` in their own terminal first, or create the site in the deploy with `--site-name <name>` (it implies `--create-site`; `--site <name-or-id>` targets an existing one). Prints a `https://…netlify.app` URL.

## After deploying

1. Open the live URL once to confirm it renders (right canvas, fonts loaded). For Vercel, also open it logged out or in a private window. If it asks for a Vercel login, tell the user to set Deployment Protection to none in the project settings, or the link will not work for anyone else.
2. Give the user the URL and one line: it works on any device, share it anywhere.
3. Delete the temp folder: `rm -rf .deploy`. Keep the `.vercel` or `.netlify` link folder so a later redeploy reuses the same site and URL; remove it only for a throwaway deploy. Surge leaves nothing behind.
````

## File: slide-wright/references/design-aesthetics.md
size: 3212
sha: 17c3921bcb801c8664a2ac01568186b4bfc03a0b
upstream: https://github.com/arifszn/slide-wright/blob/HEAD/slide-wright/references/design-aesthetics.md

```text
# Boardroom-grade, not web-generated

The target is a **boardroom** deck: it reads like a finished slide from a strong strategy or product team, calm and confident. It should never look like a landing page, a web demo, or a generated page.

Every deck still gets its own theme. What stays constant is the craft below.

## Every content slide is composed

A content slide pairs two things, and together they fill the canvas:

1. **Action title**: the slide's point as a short claim, one or two lines. "Churn fell 18% after the pricing change." Avoid topic labels like "Overview" or "Why it's fast".
2. **Exhibit**: one visual that proves or explains the claim (see `exhibits.md`).

A takeaway sentence or a source line for data can sit below when it adds something. Every slide follows the theme's **layout system** (`theme-generation.md`): top-anchored, gridded, edge to edge within the margins. Big words alone in the middle of an empty canvas belong only to the title slide, section breaks, and the closing slide.

## Exhibits carry the slide

Executives scan, they do not read. The exhibit does most of the work: a flow with labeled arrows, a product mockup built from shapes, a chart, a comparison table, a timeline, a metric panel, an architecture diagram. Build exhibits in HTML/CSS/SVG in the theme's colors so they look like they were drawn in the same tool as the rest of the slide. Use a real image only when the content needs the real thing (a product screenshot, a logo, a photo of the actual hardware).

## Restraint reads as confidence

- **Color:** one dominant surface, one accent, and the neutrals for text and lines. Use the accent to point at the one thing that matters on the slide. Light or dark is a per-deck decision based on the subject and the room.
- **Type:** one family or one tight pair, set in a strict scale: title, subhead, body, label. A refined serif or a clean grotesque for titles, a highly legible sans for body, and optionally a mono for small labels and numbers. Body text stays at 26px or larger on the 1920x1080 canvas.
- **Depth:** flat surfaces, hairline rules, and at most a soft shadow on cards or a subtle gradient on the background. Keep every effect quiet enough that nobody would comment on it.
- **Alignment:** left-aligned text on a visible grid, with equal gutters and consistent margins on every slide.

## Copy sounds like an operator wrote it

Short declarative sentences. Concrete nouns and numbers. Body text on a slide is one or two sentences, or three to five bullets of under ten words each. Plain words over marketing words: "cuts payout time from 3 days to same-day" over "unlocks seamless velocity".

## Match the room

A board update, a QBR, or a security review is quiet and dense with evidence. A product vision or a partner pitch can carry more color and larger exhibits. Both use the same composed slide structure.

## The honest check

Before you show a preview, picture it projected in a boardroom, in a deck sent by a respected company. Would the slide pass without anyone wondering how it was made? Does every content slide have a claim and an exhibit? If any slide looks like a web page or a poster, fix the composition before showing it.
```

## File: slide-wright/references/exhibits.md
size: 7054
sha: 9cac415ead677f05a76b4d55d21612e1331eef87
upstream: https://github.com/arifszn/slide-wright/blob/HEAD/slide-wright/references/exhibits.md

````text
# Exhibits

The exhibit is the visual that proves or explains a content slide's action title. Pick the type from what the claim is about, build it in HTML/CSS/SVG with the theme's variables, and draw it in the theme's exhibit style. Each content slide has one exhibit, placed in `.body` between the title and the footer.

## Pick by claim

| The claim is about... | Exhibit |
| --- | --- |
| A sequence, a money or data flow, a customer journey | **Flow**: 3-5 step cards joined by labeled arrows |
| What the product does or looks like | **Mockup**: a card, a dashboard panel, a notification, a phone frame, drawn from shapes |
| A trend, growth, or a share | **Chart**: bars, a line, or a stacked bar in SVG |
| A choice between options | **Comparison**: a table or side-by-side columns, with the recommended option in the accent |
| A few headline numbers | **Metric panel**: 2-4 figures, each with a label and a one-line context |
| Phases or a roadmap | **Timeline**: a horizontal rail with dated milestones |
| How systems connect | **Architecture**: boxes and connectors, grouped by layer |
| Prioritization or positioning | **2x2**: two labeled axes, items placed as dots or chips |

A slide with a split layout (text on the left, exhibit on the right, roughly 5/7 columns) works for mockups and metric panels. Flows, charts, tables, and timelines usually take the full width.

## Flow

Flow is a family of compositions, not one canonical four-card template. Choose the rendering that matches the subject:

- **Card-and-arrow**: discrete stages with handoffs. Use when ownership or a decision changes between stages.
- **Timeline rail**: numbered nodes on a line with short state labels. Use when elapsed time or order is the claim.
- **Vertical ladder**: stacked stages joined by a spine. Use when the sequence needs room for uneven text or supporting evidence.
- **Ledger/state rail**: rows or columns showing an object changing state, owner, or balance. Use for payments, requests, inventory, and other stateful systems.
- **Swimlane**: stages run across lanes for different actors, systems, or owners. Use when handoffs are the mechanism.
- **Decision tree**: branches split on explicit decisions and converge on outcomes. Use when the path, not the list of steps, is the claim.
- **Radial cycle**: a loop around a central object with a clear entry and exit. Use for recurring rounds, feedback loops, and operating cycles.
- **Chevron chain**: connected wedges with one short phrase per state. Use for compact executive summaries, not for paragraphs.
- **State machine**: named states connected by transitions and trigger labels. Use when retries, failure paths, or reversals matter.

The card-and-arrow example below is only one rendering. Rebuild the markup and geometry for the selected variant; do not copy the example and only change colors. Do not use the same flow rendering for unrelated decks in succession when another variant proves the claim equally well. If none of these variants fits the subject, invent a new composition from the subject's own artifact or mechanism. The invented variant must have a clear visual grammar, a distinct geometry, and a short explanation in the slide code.

```html
<div class="flow">
  <div class="step">
    <span class="lab">01 · Step name</span>
    <h3>Short verb phrase</h3>
    <p>One line on what happens here.</p>
  </div>
  <div class="arrow"><span class="lab">Handoff</span></div>
  <div class="step is-key">
    <span class="lab">02 · Step name</span>
    <h3>The step that matters</h3>
    <p>One line on why it matters.</p>
  </div>
</div>
```

```css
.flow  { display: flex; align-items: stretch; gap: 0; }
.step  { flex: 1; min-width: 0; padding: 40px; border: 1px solid var(--line); border-radius: var(--radius); background: var(--bg-alt); }
.step.is-key { background: var(--accent); border-color: var(--accent); }
.step.is-key h3, .step.is-key p, .step.is-key .lab { color: var(--on-accent); }  /* base h3 color would win otherwise */
.arrow { flex: 0 0 120px; min-width: 0; position: relative; display: grid; place-items: center; }
.arrow::before { content: ''; position: absolute; left: 12px; right: 12px; top: 50%; border-top: 2px solid var(--text-muted); }
.arrow::after  { content: ''; position: absolute; right: 12px; top: calc(50% - 6px); border: 6px solid transparent; border-left-color: var(--text-muted); border-right: 0; }
.arrow .lab    { position: relative; z-index: 1; width: 100%; max-width: 100%; box-sizing: border-box;
                padding: 0 4px; transform: translateY(28px); text-align: center; white-space: normal;
                overflow-wrap: anywhere; background: var(--bg); }
```

## Chart

Draw with inline SVG and a `viewBox`, so it scales with the slide. Label values directly on or beside the bars and the axis categories under them, and leave out gridlines and legends where direct labels work. Color every series in a neutral and the one that proves the claim in the accent.

```html
<svg class="chart" viewBox="0 0 1200 520" role="img" aria-label="Revenue by year">
  <!-- one <g> per bar: rect, value label above, category label below -->
  <g><rect x="40"  y="300" width="160" height="180" fill="var(--text-muted)" opacity=".35"/>
     <text x="120" y="285" text-anchor="middle">$4.1M</text><text x="120" y="510" text-anchor="middle">2023</text></g>
  <g><rect x="280" y="120" width="160" height="360" fill="var(--accent)"/>
     <text x="360" y="105" text-anchor="middle">$8.6M</text><text x="360" y="510" text-anchor="middle">2024</text></g>
</svg>
```

Compute bar heights from the real numbers. Never invent data: if the user gave no figures, use a non-numeric exhibit or ask.

## Metric panel

2-4 figures, each with a label and a one-line context. For a hero number or one-word statement, `class="r-fit-text"` (core class) auto-scales it to the slide width: `<h1 class="r-fit-text">10×</h1>`. Use one word or a short number per line, not a sentence.

## Mockup

The subject's own product or artifact drawn as clean shapes, not a screenshot: an app screen or dashboard tile, a document or report page, a device frame, a card or badge, a notification with a status pill. Draw what this deck is about, using the theme's surface and accent, one soft shadow at most, and realistic content taken from the user's material. Tilt or overlap two pieces at most.

## Table

Real `<table>` markup. Header row in the label style, hairline row dividers, numbers right-aligned in tabular figures (`font-variant-numeric: tabular-nums`), and the recommended row or column tinted with the accent. Up to 6 rows and 5 columns per slide; split larger tables.

## Shared rules

- All exhibit colors, radii, and fonts come from `:root` variables.
- Text inside exhibits stays at 22px or larger, labels at 18px or larger.
- The exhibit fits inside `.body` with no clipping; shorten the content or split the slide when it does not.
- Flow labels stay inside their arrow column. Keep them short; allow wrapping rather than letting a label cover a step card.
````

## File: slide-wright/references/export-pdf.md
size: 1103
sha: e7e4fb9a9072ac8d0165851eda20f334eddfb501
upstream: https://github.com/arifszn/slide-wright/blob/HEAD/slide-wright/references/export-pdf.md

````text
# Export to PDF

The deck exports to PDF straight from the browser — no extra tools, no automation dependency. The deck engine switches into a print layout automatically when the URL has the `?print-pdf` flag.

## Steps

1. Open the deck with the print flag appended to the URL:

   ```
   file:///path/to/deck.html?print-pdf
   ```

   (Or `http://localhost:8000/deck.html?print-pdf` if served.)

2. Open the browser print dialog (**Cmd/Ctrl + P**).

3. Set:
   - **Destination:** Save as PDF
   - **Layout:** Landscape
   - **Margins:** None
   - **Background graphics:** ON (so theme colors/backgrounds render)

4. Save. Each slide becomes one full-bleed page.

## Notes

- Animations and fragments are flattened to their final state — the PDF is a static snapshot. Expected; mention it so the user isn't surprised.
- If colors look washed out, the user forgot **Background graphics: ON**.
- **More pages than slides?** Either the deck lacks `pdfSeparateFragments: false` (fragments split into a page each), or a slide overflows the 1080 canvas and paginates; split that slide so nothing is cut.
````

## File: slide-wright/references/export-pptx.md
size: 2760
sha: 6dd655ec37be8252ef14029f2e97f33df7f38932
upstream: https://github.com/arifszn/slide-wright/blob/HEAD/slide-wright/references/export-pptx.md

````text
# Export to PowerPoint

Run the exporter script. It opens the deck in a headless browser and writes a `.pptx` with, per slide:

- a full-slide background picture: the slide as rendered, with the text that became text boxes hidden
- native, editable text boxes on top (font, size, colour, bold/italic/underline, alignment, letter-spacing, line spacing)
- the speaker notes

Shapes, cards, charts, SVG and images stay part of the background picture, so they look identical but are not editable. Say so when handing the file over.

## Run it

```bash
node <skill-dir>/scripts/export-pptx.mjs ./deck.html              # writes ./deck.pptx
node <skill-dir>/scripts/export-pptx.mjs ./deck.html -o out.pptx
```

`<skill-dir>` is the installed `slide-wright/` folder, the one holding `references/` and `scripts/`. Needs Node 18+. The first run installs `pptxgenjs` and `playwright-core` into `~/.cache/slide-wright/export-pptx` (override with `SLIDE_WRIGHT_CACHE`) and uses the installed Chrome, downloading Chromium only when there is none. Nothing is added to the user's project.

Options: `--scale 2` renders the background pictures at 2x (sharper when projected, larger file); `--debug-dir <dir>` also writes each slide as PNG, with and without text hidden.

The script prints the `.pptx` path on stdout; progress and the list of fonts used go to stderr.

## What to tell the user

- Slide count and output path.
- **Fonts:** the deck's web fonts are not embedded in a `.pptx`. On a machine without them PowerPoint substitutes a similar font, so line breaks can move and tightly letter-spaced headings look cramped. Offer to install the fonts (named in the script output), or point to the PDF export when exact typography matters.
- Padding and backgrounds on inline chips (code pills, highlights) stay in the picture; the text after a chip can sit a few pixels left of where it was.
- Animations and click-by-click builds are flattened: each slide is exported in its final state.
- Text the exporter cannot place faithfully (SVG, gradient, outlined, rotated, scaled, clipped, or badge-mixed text) stays in the picture. The per-slide log counts these.
- Slides marked `data-visibility="hidden"` are skipped, as in the PDF.
- Text placement was checked against LibreOffice renders, not PowerPoint itself. Ask the user to open the file in PowerPoint once and report any text that sits visibly off.

## If it fails

- "No ready reveal.js instance": the file is not a reveal.js deck, or the CDN was unreachable.
- Browser start failure: install Google Chrome, or run `npx playwright-core install chromium`.
- Text appears twice in PowerPoint: an exporter bug, not a deck problem. Re-run with `--debug-dir`, compare `slide-N.png` with `slide-N.ref.png`, and report it.
````

## File: slide-wright/references/media.md
size: 1462
sha: cc2ca474275082866730cb018016076b9b2ef2ec
upstream: https://github.com/arifszn/slide-wright/blob/HEAD/slide-wright/references/media.md

```text
# Media — images, video, backgrounds

Exhibits are CSS/SVG by default (see `exhibits.md`); use media only when the content needs the real thing. Reference a remote URL (small file, needs network) or inline base64 (offline, bloats file).

- **Inline image:** `<img src="…">`. Fit with `class="r-stretch"` (one per slide, direct child of `<section>`) or cap with `max-width:100%; max-height:70vh; object-fit:contain`.
- **Video:** `<video data-autoplay muted data-src="…">` — `data-src` lazy-loads, engine auto-pauses off-slide.
- **Full-bleed background:** attributes on `<section>` — `data-background-image="…"`, `data-background-color="#111"`, `data-background-video="…" data-background-video-muted data-background-video-loop`. Two rules make it work:
  - The default `.reveal .slides section { background: var(--bg) }` is opaque and hides the photo. Add a class (e.g. `media-bg`) and clear it: `.reveal .slides section.media-bg { background: transparent }`.
  - Put any scrim/overlay on the **background element, not `.frame`** — background media fills the whole viewport, `.frame` only the centered slide, so a frame scrim leaves a bright band in the letterbox. The engine copies the section class onto its background el: `.reveal .backgrounds .slide-background.media-bg::after { content:''; position:absolute; inset:0; background:linear-gradient(...) }`. (Same copied class recolors chrome over a dark photo: `.media-bg .lab { color:… }`.)
```

## File: slide-wright/references/motion-recipes.md
size: 3217
sha: ebaa09bcb781aea829fb06e56203223c4a0570bd
upstream: https://github.com/arifszn/slide-wright/blob/HEAD/slide-wright/references/motion-recipes.md

````text
# Motion recipes

## Default: static slides

A boardroom deck moves like a well-run PowerPoint: the slide changes with a short fade (set in the template's `Reveal.initialize`) and arrives complete. Build every slide this way.

This file is for when the user asks for builds or animation (fragments, auto-animate, entrance animations, emphasis effects). The final state of each slide is still a complete, composed slide. Code slides are in `code-slides.md`.

## Auto-animate (morph between two slides)

On request only. Put `data-auto-animate` on two consecutive `<section>`s and the engine tweens matching elements — position, size, color, font-size — from one to the next. Unmatched elements fade. No plugin; it's core.

```html
<section data-auto-animate><h1 data-id="stat" style="font-size: 3rem;">1</h1></section>
<section data-auto-animate><h1 data-id="stat" style="font-size: 12rem;">1,000,000</h1></section>
```

- Matching is automatic by content/order; pin it with a shared `data-id` when elements differ (text changing, as above) or when several could match.
- Tune per slide: `data-auto-animate-easing`, `data-auto-animate-duration`, `data-auto-animate-delay`.
- Best for: a title settling into a header, a number growing, code gaining lines, a layout reflowing. Use it on a few key beats — not every slide, or the effect goes cheap.

## Fragments (staged reveal within a slide)

Items appear one click at a time. Core of speaker-led pacing.

```html
<li class="fragment">Appears on click</li>
<p class="fragment fade-up">Slides up as it fades in</p>
<div class="fragment" data-fragment-index="2">Explicit order</div>
```

Built-in fragment styles: `fade-up`, `fade-down`, `fade-left`, `fade-right`, `fade-in-then-out`, `grow`, `shrink`, `highlight-current-blue`, etc. Use staggered fragments for the "one orchestrated entrance" effect — don't make every element a fragment or pacing drags.

## Custom entrance (CSS, fires when a slide becomes current)

The engine adds `.present` to the active slide. Drive entrance animation off it:

```css
.reveal .slides section.present .reveal-up {
  animation: reveal-up var(--dur) var(--ease) both;
}
/* stagger */
.present .reveal-up:nth-child(1) { animation-delay: 0.05s; }
.present .reveal-up:nth-child(2) { animation-delay: 0.15s; }
.present .reveal-up:nth-child(3) { animation-delay: 0.25s; }

@keyframes reveal-up {
  from { opacity: 0; transform: translateY(28px); }
  to   { opacity: 1; transform: translateY(0); }
}
```

## Emphasis recipes

- **Counter / stat reveal:** scale + fade a large numeral with `grow` fragment or a CSS keyframe; pair with the accent color.
- **Underline/marker draw:** animate a pseudo-element `width` or `transform: scaleX()` on the accent under a heading.
- **Background drift:** slow, subtle `background-position` or gradient-angle animation on the signature device. Keep it low-amplitude — atmosphere, not distraction.

## Rules

- When the user asks for animation, one moment per slide beats many small ones.
- Always include reduced-motion handling:

```css
@media (prefers-reduced-motion: reduce) {
  *, *::before, *::after { animation-duration: 0.01ms !important; transition-duration: 0.2s !important; }
}
```
````

## File: slide-wright/references/new-deck.md
size: 6835
sha: cf802bdea4b26e2c4e009304b68153ec02479582
upstream: https://github.com/arifszn/slide-wright/blob/HEAD/slide-wright/references/new-deck.md

```text
# Building a new deck

Steps 1-4 of the new-deck flow. SKILL.md has the rule that defines the order (propose the look, get a yes, then build) and Step 5, the hand-off.

## Step 1 — Work out the deck from the request

Don't open with a questionnaire. Take whatever the user gave — a one-line topic, messy notes, a full outline — and infer the rest:

- **Purpose and audience** from the subject and how it's written. A raise, a lesson, a conference talk, and an internal update each call for a different treatment.
- **Length** from how much material there is. A bare topic becomes a short deck; a long outline becomes more slides. Don't fix a number up front.
- **How much evidence** the deck needs: numbers, comparisons, and diagrams available or implied by the material.
- **The topic's native visual language and exhibit family**: choose the exhibit from the object or mechanism the audience already understands, and build it fresh instead of copying the first flow snippet. `exhibits.md` lists the families.

Only ask something if the request is too thin to design from at all — a single word with no angle — and even then ask one question, not five. If the user has more to give, they usually paste it.

### Composed slides

Every content slide is self-contained: someone reading the PDF without the presenter gets the point. Add a takeaway or source line where it helps. One claim per slide; when a slide carries two claims or its exhibit won't fit, split it. Never let a slide scroll, overflow, overlap, or shrink text below the sizes in the theme. Treat narrow layout regions as real constraints: flow labels must wrap inside their arrow columns, and page counters must stay on one line without covering source or takeaway text.

## Step 2 — Propose a look

Read `theme-generation.md` and `design-aesthetics.md`. Apply the similarity guard in `theme-generation.md` before you show the preview, then:

1. Invent a theme: a palette, a type system from Fontshare or Google Fonts, the layout system, and the exhibit style. Give it a name for your own use.
2. Build a two-slide preview with `deck-template.md` — a real title slide for this deck (its actual title, never a placeholder or a label like "demo"), and one real content slide with its action title and a full exhibit from `exhibits.md`. Write it as the real deck file in the working directory, named for the deck: `./<deck-slug>.html` (e.g. `./clickhouse.html`). This is the one file the whole deck grows into — there is no separate demo or scratch file.
3. Open it in the browser.

The preview has to read as two real slides from the finished deck, not a sample card. Keep all process language off the slide and out of the filename: no "demo," "preview," theme name, or "option A." The theme's name goes in your message to the user, never on a slide.

## Step 3 — Get a yes

Stop and ask. This is the only question in the message. If your environment has a structured question or choice prompt, use it with these three options. If not, write them as a plain list. Hold every other question (file names, extra slides, scope) until they approve.

> "Here's the design direction — *[theme name]*. Does this look right, or want a different direction?"
>
> - **Looks great — build it** → go to Step 4.
> - **Try a different direction** → choose a new direction.
> - **Adjust this one** (different accent / font / lighter / bolder) → tweak and show it again.

If they choose **Try a different direction**, ask one steering question with a short, topic-specific set of directions. Invent the choices from the subject, audience, and rejected preview; do not reuse a fixed list from this skill. Put **Surprise me** first, followed by the contextual directions, and allow a custom answer.

> What should the next direction feel like?
>
> - Surprise me
> - [A subject-specific direction]
> - [Another subject-specific direction]
> - [Optional custom direction]

If they choose **Surprise me**, make a radically different, subject-led departure yourself. Then build a genuinely new theme — different palette, type, layout, composition, and exhibit style — and a fresh two-slide preview, overwriting the same `./<deck-slug>.html`. Don't just recolor the rejected one. Repeat until they approve.

Do not build the full deck before you have a yes.

On a rejected preview, edit the theme CSS and the two slides in place in that file, and work from the references already read instead of re-reading them.

## Step 4 — Build the deck

Keep building in the **same** `./<deck-slug>.html` the user just approved. The two approved slides stay as they are — append the rest around them; never regenerate them from scratch (that reintroduces drift the user already signed off against). Read `exhibits.md` for exhibit patterns. Read `code-slides.md` for code slides and `motion-recipes.md` when the user asks for animation. Read `media.md` for images, video, or background media.

- Add the rest of the slides with Edit at the `<!-- more slides -->` marker, one batch of slides per edit; the file is never rewritten whole.
- Use the exact approved palette, type system, layout system, and exhibit style throughout.
- Structure the story answer-first: the title slide, then the main point or recommendation, then the supporting slides, then the ask or next steps.
- Vary the *exhibits* (flow, mockup, chart, comparison, timeline, metric panel) and layouts (full-width, split) while keeping the one visual system. Section breaks and the closing slide may drop the exhibit.
- Every content slide has an action title and one exhibit (`design-aesthetics.md`), and appears complete when it lands; click-by-click builds (`class="fragment"`) only when the user asks, and stepped code highlights are the one built-in exception. If a slide overflows, split it.
- Put speaker notes in `<aside class="notes">` wherever the content implies something to say out loud.
- Keep it one self-contained HTML file with no build step: theme CSS inline, engine from the CDN, a clear comment on each section.

A partial deck is already a working deck; adding slides later is editing it (see "Editing a deck that already exists" in SKILL.md).

Once the deck is built, run `node <skill-dir>/scripts/check-deck.mjs ./<deck-slug>.html --sheet "$TMPDIR/sheet.png"` (`<skill-dir>` is the installed `slide-wright/` folder; it needs Node 18+ and Chrome, like the PowerPoint export). It prints one line per defect: content off the frame, clipped or overlapping text, text under 18px, fonts that did not load. Fix each and rerun until it prints `OK`. Then view the contact sheet once, as a single image, for what code cannot see: every slide complete on arrival, the canvas filled, the 16:9 frame intact, columns not running together. If the script cannot run, say the visual check was skipped.
```

## File: slide-wright/references/theme-generation.md
size: 3799
sha: d875993a56810c7b88d18da883b900d22b587777
upstream: https://github.com/arifszn/slide-wright/blob/HEAD/slide-wright/references/theme-generation.md

```text
# Building a theme

There's no library to choose from. You invent the theme for each deck, inside the boardroom standard in `design-aesthetics.md`. Before writing any HTML, decide four things and write them down: the palette, the type system, the layout system, and the exhibit style.

## Start from the subject and the room

Let the topic and the audience set the feeling. A payments platform update, a hospital operations review, and a climate fund pitch should look different from each other, yet all three should look like they came from a serious organization. Pull the palette and type from the subject's own world: the company's brand, the product's UI, the industry's conventions.

## Palette

One dominant surface, one accent, and the neutrals you need. Name them as the CSS variables in `deck-template.md`. Body text meets WCAG AA on its background. Decide light or dark on purpose. Give the palette a name like "Harbor Navy" or "Paper & Signal" to use when you present it, and keep that name off the slides.

## Type system

From Google Fonts or Fontshare, loaded in the `<link>`, set as `--font-display`, `--font-body`, and optionally `--font-mono`. Directions that hold up: an editorial serif title over a clean sans body; one grotesque throughout; a sans with a mono for labels and numbers. Choose the specific families for this deck's subject, and vary them from deck to deck. Fix the scale as variables too, starting from the `deck-template.md` values (80px titles, 40px subheads, 28px body, 20px labels). Floors: body 26px, labels 18px.

## Layout system

What makes the slides read as one designed file. Fix the outer margins and a 12-column grid that every layout snaps to, and decide where titles and exhibits sit. Record the frame metrics, title placement, content density, and whether the exhibit is full-width, split, inset, or edge-to-edge. The values in `deck-template.md` are a worked example, not defaults to copy.

Recurring elements are a choice per theme, not a requirement. A deck might carry a section label, a footer with the source or company name, a page number, a rule, or nothing at all beyond the margins. Pick what suits the subject and the room, keep it consistent once chosen, and let title, section, and closing slides drop it.

## Exhibit style

How the theme draws exhibits: card radius, border vs. fill, shadow or none, arrow style, how data series use the accent and the neutrals. Every exhibit in the deck follows it. `exhibits.md` has the building blocks.

## Similarity guard

For each new deck, make at least three of these choices deliberately different from the last unrelated deck: light or dark surface, display/body font pairing, outer geometry, title placement, exhibit family, card treatment, and recurring chrome. The one constant is the boardroom standard, not a repeated template. If the first preview could be mistaken for another recent deck after removing its words, reject it and choose a different composition before showing it.

The guard operates at composition level too. Also vary at least three of these when the subject changes: step count derived from the content, horizontal versus vertical direction, card-and-arrow versus rail versus ledger rendering, accent position based on the claim, and which slide first introduces the exhibit. If another deck is in the same working area, inspect its first content slide before choosing the new composition. A fresh session does not mean a fresh visual pattern. Invent a subject-specific composition when the variants in `exhibits.md` do not fit.

## Motion

Static. Slides change with a short fade and appear complete. See `motion-recipes.md`.

## Steering a new direction

If the user gave a steer ("lighter", "more corporate", "warmer", "more product-like"), move along that axis.
```

## File: slide-wright/scripts/check-deck.mjs
size: 6932
sha: cfd96b1f929b27623230a2424f0617e0e38327b7
upstream: https://github.com/arifszn/slide-wright/blob/HEAD/slide-wright/scripts/check-deck.mjs

```text
#!/usr/bin/env node
// Check a slide-wright deck in headless Chrome and print one line per defect.
//
//   node check-deck.mjs deck.html [--sheet sheet.png]
//
// Per slide it reports: content outside the slide frame, clipped or scrolling text, overlapping
// text blocks, text below the size floor, and web fonts that did not load. With --sheet it also
// writes one contact-sheet PNG of all slides (fragments shown) for a single visual look.
// Exit code 1 when any defect is found, 2 when the deck cannot be loaded.
import { resolve } from 'node:path';
import { pathToFileURL, fileURLToPath } from 'node:url';
import { writeFileSync } from 'node:fs';
import { ensureDeps } from './lib/deps.mjs';

const FLOOR_PX = 18; // smallest text the skill allows (labels)

async function launch(chromium) {
  let err;
  for (const opts of [{ channel: 'chrome' }, {}]) {
    try { return await chromium.launch(opts); } catch (e) { err = e; }
  }
  throw new Error(`Could not start a browser: ${err && err.message}`);
}

// Runs in the page for the current slide. Returns a list of defect strings.
function inspectSlide(floor) {
  const cur = Reveal.getCurrentSlide();
  cur.querySelectorAll('.fragment').forEach((f) => f.classList.add('visible'));
  const frame = cur.getBoundingClientRect();
  const label = (el) => (el.className && typeof el.className === 'string' ? '.' + el.className.trim().split(/\s+/)[0] : el.tagName.toLowerCase());
  const out = [];
  const textEls = [];
  for (const el of cur.querySelectorAll('*')) {
    const r = el.getBoundingClientRect();
    if (!r.width || !r.height) continue;
    const cs = getComputedStyle(el);
    if (cs.visibility === 'hidden' || cs.display === 'none' || cs.opacity === '0') continue;
    if (r.right > frame.right + 2 || r.bottom > frame.bottom + 2 || r.left < frame.left - 2 || r.top < frame.top - 2) out.push(`outside frame: ${label(el)}`);
    if ((el.scrollWidth > el.clientWidth + 2 || el.scrollHeight > el.clientHeight + 2) && /hidden|auto|scroll/.test(cs.overflow + cs.overflowX + cs.overflowY) && el.clientHeight) out.push(`clipped content: ${label(el)}`);
    const own = [...el.childNodes].some((n) => n.nodeType === 3 && n.textContent.trim());
    if (own) {
      textEls.push({ el, r });
      const fs = parseFloat(cs.fontSize) * (frame.width / (Reveal.getConfig().width || 1920));
      if (fs < floor - 0.5) out.push(`text ${fs.toFixed(0)}px below ${floor}px: ${label(el)} "${el.textContent.trim().slice(0, 24)}"`);
      const fam = cs.fontFamily.split(',')[0].replace(/["']/g, '').trim();
      if (fam && !/^(serif|sans-serif|monospace|system-ui|ui-)/.test(fam) && !(document.fonts.check(`16px "${fam}"`) || [...document.fonts].some((f) => f.family.replace(/["']/g, '') === fam && f.status === 'loaded'))) out.push(`font not loaded: ${fam}`);
    }
  }
  for (let i = 0; i < textEls.length; i++) {
    for (let j = i + 1; j < textEls.length; j++) {
      const a = textEls[i], b = textEls[j];
      if (a.el.contains(b.el) || b.el.contains(a.el)) continue;
      const w = Math.min(a.r.right, b.r.right) - Math.max(a.r.left, b.r.left);
      const h = Math.min(a.r.bottom, b.r.bottom) - Math.max(a.r.top, b.r.top);
      if (w > 4 && h > 4) out.push(`overlap: ${label(a.el)} "${a.el.textContent.trim().slice(0, 18)}" x ${label(b.el)} "${b.el.textContent.trim().slice(0, 18)}"`);
    }
  }
  return [...new Set(out)];
}

/**
 * @param {object} o
 * @param {string} o.input   path to the deck .html
 * @param {string} [o.sheet] write a contact-sheet PNG here
 * @param {(page) => Promise<void>} [o.route] request-routing hook (tests serve the CDN offline)
 * @returns {Promise<{slides: number, defects: string[]}>} defects read "slide N: ..."
 */
export async function checkDeck({ input, sheet, route }) {
  const req = ensureDeps();
  const { chromium } = req('playwright-core');
  const browser = await launch(chromium);
  const defects = [];
  try {
    const ctx = await browser.newContext({ viewport: { width: 1920, height: 1080 } });
    const page = await ctx.newPage();
    if (route) await route(page);
    await page.goto(pathToFileURL(resolve(input)).href, { waitUntil: 'load' });
    await page.waitForFunction(() => window.Reveal && Reveal.isReady && Reveal.isReady(), null, { timeout: 30000 }).catch(() => {
      throw new Error('No ready reveal.js instance. Not a reveal.js deck, or the engine could not load from its CDN.');
    });
    const cfg = await page.evaluate(() => { const c = Reveal.getConfig(); return { w: c.width, h: c.height }; });
    await page.setViewportSize({ width: cfg.w, height: cfg.h });
    await page.evaluate(async () => {
      Reveal.configure({ transition: 'none', backgroundTransition: 'none', controls: false, progress: false, slideNumber: false, autoSlide: 0 });
      Reveal.layout();
      await document.fonts.ready;
    });
    const n = await page.evaluate(() => Reveal.getSlides().filter((s) => !s.querySelector('section')).length);
    const shots = [];
    for (let i = 0; i < n; i++) {
      await page.evaluate((i) => {
        const s = Reveal.getSlides().filter((x) => !x.querySelector('section'))[i];
        const idx = Reveal.getIndices(s);
        Reveal.slide(idx.h, idx.v);
      }, i);
      await page.waitForTimeout(150);
      for (const d of await page.evaluate(inspectSlide, FLOOR_PX)) defects.push(`slide ${i + 1}: ${d}`);
      if (sheet) shots.push((await page.screenshot({ type: 'jpeg', quality: 70 })).toString('base64'));
    }
    if (sheet) {
      const cols = 3, w = 640, h = Math.round((w * cfg.h) / cfg.w);
      const sp = await ctx.newPage();
      await sp.setViewportSize({ width: cols * w, height: Math.ceil(n / cols) * h });
      await sp.setContent(`<body style="margin:0;display:grid;grid-template-columns:repeat(${cols},${w}px)">${shots.map((b) => `<img style="width:${w}px;height:${h}px" src="data:image/jpeg;base64,${b}">`).join('')}</body>`);
      writeFileSync(resolve(sheet), await sp.screenshot({ fullPage: true }));
    }
    return { slides: n, defects };
  } finally {
    await browser.close();
  }
}

if (process.argv[1] && fileURLToPath(import.meta.url) === resolve(process.argv[1])) {
  const args = process.argv.slice(2);
  const sheetIdx = args.indexOf('--sheet');
  const sheet = sheetIdx >= 0 ? args[sheetIdx + 1] : null;
  const input = args.find((a, i) => !a.startsWith('--') && !(sheetIdx >= 0 && i === sheetIdx + 1));
  if (!input) { console.error('usage: node check-deck.mjs deck.html [--sheet sheet.png]'); process.exit(2); }
  try {
    const { slides, defects } = await checkDeck({ input, sheet });
    for (const d of defects) console.log(d);
    if (sheet) console.log(`contact sheet: ${resolve(sheet)}`);
    console.log(defects.length ? `${defects.length} defect(s) in ${slides} slides` : `OK: ${slides} slides, no defects`);
    process.exit(defects.length ? 1 : 0);
  } catch (e) {
    console.error(e.message);
    process.exit(2);
  }
}
```

## File: slide-wright/scripts/export-pptx.mjs
size: 9702
sha: f55405f405acd66dd27f0aa4e98d145cf5e363c3
upstream: https://github.com/arifszn/slide-wright/blob/HEAD/slide-wright/scripts/export-pptx.mjs

```text
#!/usr/bin/env node
// Export a slide-wright deck (single HTML file) to .pptx.
//
// Each slide becomes: a full-bleed background picture (the rendered slide with the
// extracted text hidden) + native, editable text boxes + speaker notes.
//
//   node export-pptx.mjs deck.html [-o deck.pptx] [--scale 2] [--debug-dir dir]
import { mkdirSync, writeFileSync } from 'node:fs';
import { basename, dirname, join, resolve } from 'node:path';
import { pathToFileURL, fileURLToPath } from 'node:url';
import { ensureDeps } from './lib/deps.mjs';
import { extractSlide } from './lib/extract.mjs';
import { finalizePackage } from './lib/package.mjs';

const SLIDE_IN = 13.333; // slide width in inches; height follows the deck's aspect ratio
const HIDE_CSS = `
/* hit-testing (covered-text check) must see every element, including pointer-events:none ones */
.reveal *{pointer-events:auto!important}
.reveal .controls,.reveal .progress,.reveal .slide-number,.reveal .playback,.reveal .pause-overlay,.reveal .speaker-notes,.reveal .overview-controls{display:none!important}
/* transition:none matters: fragments use transition-all, which would fade the text out over 200ms and leave it in the screenshot */
[data-sw-x]{-webkit-text-fill-color:transparent!important;text-shadow:none!important;text-decoration-color:transparent!important;transition:none!important}
[data-sw-x]::marker,[data-sw-x]::before,[data-sw-x]::after{-webkit-text-fill-color:currentcolor!important}
`;

async function launch(chromium) {
  const attempts = [{ channel: 'chrome' }, {}];
  let lastErr;
  for (let pass = 0; pass < 2; pass++) {
    for (const opts of attempts) {
      try { return await chromium.launch(opts); } catch (e) { lastErr = e; }
    }
    if (pass === 0) {
      console.error('No Chrome found; downloading Chromium (first run only)...');
      const { execFileSync } = await import('node:child_process');
      const cli = ensureDeps().resolve('playwright-core/cli.js');
      try { execFileSync(process.execPath, [cli, 'install', 'chromium'], { stdio: 'inherit' }); } catch { break; }
    }
  }
  throw new Error(`Could not start a browser: ${lastErr && lastErr.message}`);
}

/**
 * @param {object} o
 * @param {string} o.input    path to the deck .html
 * @param {string} [o.output] path to the .pptx (default: next to the input)
 * @param {number} [o.scale]  screenshot device scale factor (default 1)
 * @param {number} [o.timeout] ms to wait for the deck engine to be ready (default 30000)
 * @param {string} [o.debugDir] also write slide-N.png (text hidden) and slide-N.ref.png (as rendered)
 * @param {(page) => Promise<void>} [o.route] hook to set up request routing (tests serve the CDN offline)
 * @param {(msg: string) => void} [o.log]
 */
export async function exportDeck({ input, output, scale = 1, timeout = 30000, debugDir, route, log = () => {} }) {
  const req = ensureDeps();
  const PptxGenJS = req('pptxgenjs');
  const { chromium } = req('playwright-core');
  input = resolve(input);
  output = resolve(output || input.replace(/\.html?$/i, '') + '.pptx');

  const browser = await launch(chromium);
  try {
    const ctx = await browser.newContext({ viewport: { width: 1920, height: 1080 }, deviceScaleFactor: scale });
    const page = await ctx.newPage();
    if (route) await route(page);
    await page.goto(pathToFileURL(input).href, { waitUntil: 'load' });
    await page.waitForFunction(() => window.Reveal && Reveal.isReady && Reveal.isReady(), null, { timeout }).catch(() => {
      throw new Error('No ready reveal.js instance. The file is not a reveal.js deck, or the engine could not load from its CDN (is the network blocked?).');
    });

    const cfg = await page.evaluate(() => { const c = Reveal.getConfig(); return { w: c.width, h: c.height }; });
    await page.setViewportSize({ width: cfg.w, height: cfg.h });
    await page.addStyleTag({ content: HIDE_CSS });
    const count = await page.evaluate(() => {
      Reveal.configure({ transition: 'none', backgroundTransition: 'none', progress: false, controls: false, slideNumber: false, autoSlide: 0 });
      Reveal.layout();
      const slides = Reveal.getSlides().filter((s) => s.dataset.visibility !== 'hidden' && !s.querySelector('section'));
      slides.forEach((s, i) => s.setAttribute('data-sw-slide', i));
      return slides.length;
    });
    if (!count) throw new Error('No slides found.');
    await page.evaluate(() => document.fonts.ready);

    const pptx = new PptxGenJS();
    const heightIn = (SLIDE_IN * cfg.h) / cfg.w;
    pptx.defineLayout({ name: 'SW', width: SLIDE_IN, height: heightIn });
    pptx.layout = 'SW';
    pptx.title = (await page.title()) || basename(input);
    const inPerPx = SLIDE_IN / cfg.w;
    const ptPerPx = (SLIDE_IN * 72) / cfg.w;

    const manifest = { width: cfg.w, height: cfg.h, slides: [] };
    const fonts = new Set();
    if (debugDir) mkdirSync(debugDir, { recursive: true });

    for (let i = 0; i < count; i++) {
      await page.evaluate(async (idx) => {
        const s = document.querySelector(`[data-sw-slide="${idx}"]`);
        const { h, v } = Reveal.getIndices(s);
        Reveal.slide(h, v, 9999); // 9999 = past the last fragment, so every build step is shown
        await new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r)));
        await document.fonts.ready;
        document.getAnimations().forEach((a) => { try { a.finish(); } catch { /* infinite animation: leave */ } });
        await Promise.all([...s.querySelectorAll('img')].map((im) => (im.decode ? im.decode().catch(() => {}) : null)));
        await new Promise((r) => requestAnimationFrame(r));
      }, i);

      const clip = { x: 0, y: 0, width: cfg.w, height: cfg.h };
      if (debugDir) await page.screenshot({ path: join(debugDir, `slide-${i + 1}.ref.png`), clip });
      const data = await page.evaluate(extractSlide, i);
      if (Math.abs(data.scale - 1) > 0.01) throw new Error(`Slide ${i + 1} renders at scale ${data.scale.toFixed(3)}, expected 1. Is the viewport ${cfg.w}x${cfg.h}?`);
      const png = await page.screenshot({ clip });
      if (debugDir) writeFileSync(join(debugDir, `slide-${i + 1}.png`), png);

      const slide = pptx.addSlide();
      slide.background = { data: 'image/png;base64,' + png.toString('base64') };
      for (const b of data.blocks) {
        const runs = [];
        const align = b.align;
        const lineSpacing = b.lineSpacingPx ? Math.round(b.lineSpacingPx * ptPerPx * 10) / 10 : undefined;
        let startsParagraph = true;
        b.runs.forEach((r) => {
          if (r.br) { if (runs.length) runs[runs.length - 1].options.breakLine = true; startsParagraph = true; return; }
          const s = r.style;
          fonts.add(s.fontFace);
          const options = { fontFace: s.fontFace, fontSize: Math.round(s.px * ptPerPx * 100) / 100, color: s.color, bold: s.bold, italic: s.italic };
          // Paragraph options go on the first run of a paragraph only: pptxgenjs writes a new
          // <a:pPr> for every later run that carries them, which is invalid inside one <a:p>.
          if (startsParagraph) { options.align = align; if (lineSpacing) options.lineSpacing = lineSpacing; }
          startsParagraph = false;
          if (s.underline) options.underline = { style: 'sng' };
          if (s.strike) options.strike = 'sngStrike';
          if (s.spacingPx) options.charSpacing = Math.round(s.spacingPx * ptPerPx * 100) / 100;
          const alpha = s.alpha * b.opacity;
          if (alpha < 0.995) options.transparency = Math.round((1 - alpha) * 100);
          runs.push({ text: r.text, options });
        });
        if (!runs.length) continue;
        slide.addText(runs, {
          x: b.x * inPerPx, y: b.y * inPerPx, w: b.w * inPerPx, h: b.h * inPerPx,
          margin: 0, fit: 'none', valign: 'top', wrap: b.wrap, isTextBox: true,
        });
      }
      if (data.notes) slide.addNotes(data.notes);
      manifest.slides.push({ title: data.title, notes: data.notes, skippedText: data.skippedText, blocks: data.blocks });
      log(`slide ${i + 1}/${count}: ${data.blocks.length} text boxes${data.skippedText.length ? `, ${data.skippedText.length} left as image` : ''}`);
    }

    mkdirSync(dirname(output), { recursive: true });
    const raw = await pptx.write({ outputType: 'nodebuffer' });
    writeFileSync(output, await finalizePackage(req('jszip'), raw));
    manifest.output = output;
    manifest.fonts = [...fonts];
    manifest.fontStatus = await page.evaluate(() => [...document.fonts].map((f) => `${f.family} ${f.weight}: ${f.status}`));
    manifest.loadedFonts = await page.evaluate(() => [...new Set([...document.fonts].filter((f) => f.status === 'loaded').map((f) => f.family.replace(/^["']|["']$/g, '')))]);
    return manifest;
  } finally {
    await browser.close();
  }
}

if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
  const args = process.argv.slice(2);
  const opt = (flag) => { const i = args.indexOf(flag); return i >= 0 ? args.splice(i, 2)[1] : undefined; };
  const output = opt('-o') || opt('--output');
  const scale = Number(opt('--scale') || 1);
  const debugDir = opt('--debug-dir');
  const input = args[0];
  if (!input) { console.error('usage: export-pptx.mjs deck.html [-o out.pptx] [--scale 1|2] [--debug-dir dir]'); process.exit(2); }
  exportDeck({ input, output, scale, debugDir, log: (m) => console.error(m) })
    .then((m) => {
      console.log(m.output);
      console.error(`${m.slides.length} slides. Fonts used: ${m.fonts.join(', ') || '(none)'}. Viewers without these fonts installed will see substitutes.`);
    })
    .catch((e) => { console.error(e.message); process.exit(1); });
}
```

## File: slide-wright/scripts/lib/deps.mjs
size: 1651
sha: e50d84da9616ef32ae35e04d581c22a83882b38b
upstream: https://github.com/arifszn/slide-wright/blob/HEAD/slide-wright/scripts/lib/deps.mjs

```text
// Lazy dependency bootstrap. The skill ships no node_modules: the first export
// installs pinned packages into a per-user cache and loads them from there.
import { createRequire } from 'node:module';
import { execFileSync } from 'node:child_process';
import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
import { homedir } from 'node:os';
import { join } from 'node:path';

export const PINNED = {
  pptxgenjs: '4.0.1',
  'playwright-core': '1.64.1',
};

export const CACHE_DIR =
  process.env.SLIDE_WRIGHT_CACHE || join(homedir(), '.cache', 'slide-wright', 'export-pptx');

// Returns a require() rooted at the cache, installing any missing packages first.
// `extra` is a { name: version } map (tests use it for reveal.js and pngjs).
export function ensureDeps(extra = {}) {
  const wanted = { ...PINNED, ...extra };
  mkdirSync(CACHE_DIR, { recursive: true });
  const req = createRequire(join(CACHE_DIR, 'noop.js'));
  const missing = Object.entries(wanted).filter(([name]) => {
    return !existsSync(join(CACHE_DIR, 'node_modules', name, 'package.json'));
  });
  if (missing.length) {
    const pkg = join(CACHE_DIR, 'package.json');
    if (!existsSync(pkg)) writeFileSync(pkg, '{"name":"slide-wright-export-cache","private":true}\n');
    console.error(`Installing ${missing.map(([n, v]) => `${n}@${v}`).join(', ')} into ${CACHE_DIR} (first run only)...`);
    execFileSync('npm', ['install', '--no-audit', '--no-fund', '--silent', '--prefix', CACHE_DIR, ...missing.map(([n, v]) => `${n}@${v}`)], { stdio: ['ignore', 'inherit', 'inherit'], shell: process.platform === 'win32' }); // npm is npm.cmd on Windows
  }
  return req;
}
```

## File: slide-wright/scripts/lib/extract.mjs
size: 15841
sha: dd8b8d0a1531918fffdff8ab9edf915efd2562ad
upstream: https://github.com/arifszn/slide-wright/blob/HEAD/slide-wright/scripts/lib/extract.mjs

```text
// Runs INSIDE the page (serialized by Playwright), so it must stay self-contained:
// no imports, no references to outer scope.
//
// For one active slide it (1) finds the leaf text blocks that can be rebuilt as
// native PowerPoint text, and (2) hides exactly that text in the DOM so the
// slide screenshot becomes a text-free background. Anything it cannot place
// faithfully (SVG text, gradient text, transformed text, clipped text,
// pseudo-element content) is deliberately left in the raster.
export function extractSlide(idx) {
  const sec = document.querySelector(`[data-sw-slide="${idx}"]`);
  const sr = sec.getBoundingClientRect();
  const k = sr.width / sec.offsetWidth; // layout px -> screen px (1 when the viewport matches the deck)
  const rel = (r) => ({ l: (r.left - sr.left) / k, t: (r.top - sr.top) / k, r: (r.right - sr.left) / k, b: (r.bottom - sr.top) / k });

  const cv = document.createElement('canvas').getContext('2d', { willReadFrequently: true });
  const color = (str) => {
    cv.clearRect(0, 0, 1, 1);
    cv.fillStyle = '#000';
    cv.fillStyle = str;
    cv.fillRect(0, 0, 1, 1);
    const [r, g, b, a] = cv.getImageData(0, 0, 1, 1).data;
    const h = (n) => n.toString(16).padStart(2, '0');
    return { hex: (h(r) + h(g) + h(b)).toUpperCase(), a: a / 255 };
  };

  const SKIP_TAGS = new Set(['SVG', 'CANVAS', 'IMG', 'VIDEO', 'AUDIO', 'IFRAME', 'PICTURE', 'SCRIPT', 'STYLE', 'ASIDE', 'NOSCRIPT', 'OBJECT']);
  const isInline = (cs) => cs.display === 'inline' || cs.display === 'contents';
  const hasText = (s) => /\S/.test(s);
  const paintsBox = (cs) =>
    color(cs.backgroundColor).a > 0 ||
    cs.backgroundImage !== 'none' ||
    ['Top', 'Right', 'Bottom', 'Left'].some((s) => parseFloat(cs[`border${s}Width`]) > 0 && cs[`border${s}Style`] !== 'none') ||
    ['Top', 'Right', 'Bottom', 'Left'].some((s) => parseFloat(cs[`padding${s}`]) > 0);
  const inlineHasText = (el) => {
    for (const n of el.childNodes) {
      if (n.nodeType === 3 && hasText(n.nodeValue)) return true;
      if (n.nodeType === 1 && !SKIP_TAGS.has(n.tagName.toUpperCase()) && n.tagName !== 'BR' && isInline(getComputedStyle(n)) && inlineHasText(n)) return true;
    }
    return false;
  };
  // A pure translate is already reflected in getBoundingClientRect, so such text can be placed
  // exactly; rotation, scale and skew cannot be reproduced in a text box and stay in the raster.
  const pureTranslate = (t) => t === 'none' || /^matrix\(1, 0, 0, 1, [-\d.e]+, [-\d.e]+\)$/.test(t);
  const clipsContent = (cs) => ['hidden', 'clip', 'scroll', 'auto'].some((v) => cs.overflowX === v || cs.overflowY === v);

  const blocks = [];
  const consumed = new Set(); // elements whose own text we extracted (to be hidden)
  const consumedNodes = new Set();
  const skippedText = []; // text left in the raster, reported for visibility

  const walk = (el, ctx) => {
    if (SKIP_TAGS.has(el.tagName.toUpperCase())) return;
    const cs = getComputedStyle(el);
    if (cs.display === 'none' || cs.visibility === 'hidden') return;
    const opacity = ctx.opacity * parseFloat(cs.opacity);
    if (opacity <= 0.01) return;
    const leaveReason =
      ctx.leave ||
      (!pureTranslate(cs.transform) && el !== sec && 'transform') ||
      (cs.webkitBackgroundClip === 'text' || cs.backgroundClip === 'text' ? 'gradient-text' : '') ||
      (cs.filter !== 'none' && 'filter') ||
      (cs.mixBlendMode !== 'normal' && 'blend') ||
      '';
    const clips = clipsContent(cs) ? ctx.clips.concat([rel(el.getBoundingClientRect())]) : ctx.clips;
    const next = { opacity, leave: leaveReason, clips };

    const block = !isInline(cs) && inlineHasText(el);
    if (block) emit(el, cs, next);
    visitChildren(el, block, next);
  };

  const visitChildren = (el, parentIsBlock, ctx) => {
    for (const c of el.children) {
      if (parentIsBlock && isInline(getComputedStyle(c)) && !SKIP_TAGS.has(c.tagName.toUpperCase())) {
        // inline content was consumed by the parent block; only look for block descendants
        const cs = getComputedStyle(c);
        if (cs.display === 'none') continue;
        const op = ctx.opacity * parseFloat(cs.opacity);
        const leave = ctx.leave || (!pureTranslate(cs.transform) && 'transform') || '';
        visitChildren(c, true, { opacity: op, leave, clips: ctx.clips });
      } else walk(c, ctx);
    }
  };

  const transformText = (t, tt) => {
    if (tt === 'uppercase') return t.toUpperCase();
    if (tt === 'lowercase') return t.toLowerCase();
    if (tt === 'capitalize') return t.replace(/(^|\s)(\S)/g, (_, a, b) => a + b.toUpperCase());
    return t;
  };

  const genericFont = { 'sans-serif': 'Arial', 'system-ui': 'Arial', 'ui-sans-serif': 'Arial', '-apple-system': 'Arial', serif: 'Times New Roman', 'ui-serif': 'Times New Roman', monospace: 'Courier New', 'ui-monospace': 'Courier New' };
  const fontFace = (ff) => {
    const fams = ff.split(',').map((f) => f.trim().replace(/^["']|["']$/g, ''));
    const real = fams.find((f) => !(f.toLowerCase() in genericFont));
    return real || genericFont[fams[0].toLowerCase()] || 'Arial';
  };

  const emit = (el, cs, ctx) => {
    const textNodes = [];
    const parts = []; // { text } | { br: true }
    const collect = (node, ncs) => {
      for (const n of node.childNodes) {
        if (n.nodeType === 3) {
          if (!n.nodeValue) continue;
          const pre = /^(pre|pre-wrap|break-spaces|pre-line)$/.test(ncs.whiteSpace);
          let text = n.nodeValue.replace(/\r/g, '');
          text = ncs.whiteSpace === 'pre' || ncs.whiteSpace === 'pre-wrap' || ncs.whiteSpace === 'break-spaces' ? text : pre ? text.replace(/[ \t\f]+/g, ' ') : text.replace(/[ \t\r\n\f]+/g, ' ');
          const fill = color(ncs.webkitTextFillColor || ncs.color);
          const outlined = parseFloat(ncs.webkitTextStrokeWidth) > 0; // the stroke cannot be hidden or rebuilt, so the glyphs must stay in the raster
          const col = fill.a < 0.02 || outlined ? null : fill; // transparent fill = gradient or outlined text: leave it in the raster
          parts.push({
            text: transformText(text, ncs.textTransform),
            preserve: pre,
            node: n,
            style: {
              fontFace: fontFace(ncs.fontFamily),
              px: parseFloat(ncs.fontSize),
              bold: parseInt(ncs.fontWeight, 10) >= 600 || ncs.fontWeight === 'bold',
              italic: ncs.fontStyle === 'italic' || ncs.fontStyle === 'oblique',
              underline: ncs.textDecorationLine.includes('underline'),
              strike: ncs.textDecorationLine.includes('line-through'),
              color: col && col.hex,
              alpha: col ? col.a : 1,
              spacingPx: ncs.letterSpacing === 'normal' ? 0 : parseFloat(ncs.letterSpacing) || 0,
            },
          });
          textNodes.push(n);
        } else if (n.nodeType === 1) {
          if (n.tagName === 'BR') { parts.push({ br: true }); continue; }
          if (SKIP_TAGS.has(n.tagName.toUpperCase())) continue;
          const c = getComputedStyle(n);
          if (c.display === 'none') continue;
          if (isInline(c)) {
            // a painted inline box (code pill, badge) keeps its background in the raster; text
            // moved to a native box would drift off it whenever the wrap points differ
            if (c.display === 'inline' && paintsBox(c) && hasText(n.textContent)) complex = true;
            else { consumedEls.add(n); collect(n, c); }
          }
          else if (/^inline-/.test(c.display) && hasText(n.textContent)) complex = true; // pill/badge inside a text flow
        }
      }
    };
    const consumedEls = new Set([el]);
    let complex = false;
    collect(el, cs);

    const ownText = parts.filter((p) => p.text !== undefined && hasText(p.text));
    if (!ownText.length) return;
    if (complex) { skippedText.push(`inline-box: ${ownText[0].text.trim().slice(0, 40)}`); return; }
    if (ctx.leave || parts.some((p) => p.text !== undefined && p.style.color === null && hasText(p.text))) {
      skippedText.push(`${ctx.leave || 'gradient-text'}: ${ownText[0].text.trim().slice(0, 40)}`);
      return;
    }

    // Geometry from the actual text ranges (not the element box).
    const rects = [];
    for (const part of parts) {
      const n = part.node;
      if (!n) continue;
      // whitespace-only nodes have a rect only when whitespace is preserved (code indentation);
      // measuring them keeps the box where the indentation starts, since the runs include it
      if (!hasText(n.nodeValue) && !part.preserve) continue;
      const rg = document.createRange();
      rg.selectNodeContents(n);
      for (const r of rg.getClientRects()) if (r.width > 0.5 && r.height > 0.5) rects.push(rel(r));
    }
    if (!rects.length) return;
    const u = { l: Math.min(...rects.map((r) => r.l)), t: Math.min(...rects.map((r) => r.t)), r: Math.max(...rects.map((r) => r.r)), b: Math.max(...rects.map((r) => r.b)) };
    const W = sec.offsetWidth, H = sec.offsetHeight;
    const clipped = ctx.clips.some((c) => u.l < c.l - 2 || u.t < c.t - 2 || u.r > c.r + 2 || u.b > c.b + 2);
    if (clipped || u.r < 0 || u.l > W || u.b < 0 || u.t > H) {
      skippedText.push(`clipped: ${ownText[0].text.trim().slice(0, 40)}`);
      return;
    }

    // Covered by something opaque on top (e.g. the stacked step clones of a stepped code
    // block, where only the last clone is visible)? Then it is not on screen: skip it.
    // A false positive only leaves the text in the raster, which is the safe failure.
    const covered = [rects[0], rects[rects.length - 1]].some((r) => {
      const hit = document.elementFromPoint(sr.left + ((r.l + r.r) / 2) * k, sr.top + ((r.t + r.b) / 2) * k);
      return hit && !el.contains(hit);
    });
    if (covered) { skippedText.push(`covered: ${ownText[0].text.trim().slice(0, 40)}`); return; }

    // Group the text rects into visual lines by centre line. Grouping by rect top breaks as soon
    // as one line mixes font sizes (inline code next to body text): the tops differ, one line
    // reads as several, and the pitch collapses.
    const lineSets = [];
    for (const r of rects.slice().sort((x, y) => x.t + x.b - (y.t + y.b))) {
      const c = (r.t + r.b) / 2, h = r.b - r.t;
      const cur = lineSets[lineSets.length - 1];
      if (cur && Math.abs(c - cur.sum / cur.n) <= 0.4 * Math.max(cur.h, h)) { cur.sum += c; cur.n++; cur.h = Math.max(cur.h, h); }
      else lineSets.push({ sum: c, n: 1, h });
    }
    const lines = lineSets.length;
    const glyphH = Math.max(...rects.map((r) => r.b - r.t)); // tallest inline box on the line sets the line height
    const fs = parseFloat(cs.fontSize);
    const lh = cs.lineHeight === 'normal' ? null : parseFloat(cs.lineHeight);
    const brs = parts.filter((p) => p.br).length;
    const centre = (l) => l.sum / l.n;
    let pitch = lines > 1 ? (centre(lineSets[lines - 1]) - centre(lineSets[0])) / (lines - 1) : lh || glyphH;
    if (lines > 1 && pitch < 0.6 * fs) pitch = lh || 1.2 * fs; // implausibly tight: line detection went wrong, trust the CSS
    const dir = cs.direction === 'rtl';
    const align = { left: 'left', right: 'right', center: 'center', justify: 'justify', start: dir ? 'right' : 'left', end: dir ? 'left' : 'right' }[cs.textAlign] || 'left';

    // Box: single-line text hugs its glyphs with slack and never wraps (so a wider
    // substitute font overflows like CSS would, instead of reflowing onto a second line).
    // Multi-line text uses the container's content box so wrapping stays comparable.
    const slack = Math.max(6, 0.03 * (u.r - u.l));
    let x, w;
    if (lines === 1 && brs === 0) {
      // slack goes on the side(s) the text can grow toward, so the anchored edge stays put
      const tw = u.r - u.l;
      x = align === 'right' ? u.l - 2 * slack : align === 'center' ? u.l - slack : u.l;
      w = tw + 2 * slack;
    } else {
      const er = rel(el.getBoundingClientRect());
      const cl = er.l + parseFloat(cs.borderLeftWidth) + parseFloat(cs.paddingLeft);
      const cr = er.r - parseFloat(cs.borderRightWidth) - parseFloat(cs.paddingRight);
      const bl = Math.min(cl, u.l), br = Math.max(cr, u.r);
      const s = Math.max(6, 0.03 * (br - bl));
      x = align === 'right' ? bl - s : align === 'center' ? bl - s / 2 : bl;
      w = align === 'right' ? br - x : align === 'center' ? br - bl + s : br - bl + s;
    }
    const single = lines === 1 && brs === 0;
    // CSS puts half the leading above each line; PowerPoint/LibreOffice put the whole
    // exact-spacing excess above the first line.
    const y = single ? u.t : u.t - (pitch - glyphH);
    const h = single ? glyphH : lines * pitch;

    // Merge adjacent runs with identical style, normalise collapsed whitespace.
    const runs = [];
    let prevEndsSpace = true;
    parts.forEach((p, i) => {
      if (p.br) { runs.push({ br: true }); prevEndsSpace = true; return; }
      let t = p.text;
      if (!p.preserve) {
        if (prevEndsSpace) t = t.replace(/^ /, '');
        prevEndsSpace = t.endsWith(' ');
      } else prevEndsSpace = /\s$/.test(t);
      if (!t) return;
      const last = runs[runs.length - 1];
      const same = last && !last.br && JSON.stringify(last.style) === JSON.stringify(p.style);
      if (same) last.text += t; else runs.push({ text: t, style: p.style });
    });
    while (runs.length && !runs[runs.length - 1].br && !/\S/.test(runs[runs.length - 1].text)) runs.pop();
    if (runs.length && !runs[runs.length - 1].br) runs[runs.length - 1].text = runs[runs.length - 1].text.replace(/ +$/, '');
    if (!runs.some((r) => r.text && hasText(r.text))) return;

    // preserved newlines become explicit breaks
    const flat = [];
    for (const r of runs) {
      if (r.br || !r.text.includes('\n')) { flat.push(r); continue; }
      r.text.split('\n').forEach((seg, i, arr) => {
        if (seg) flat.push({ text: seg, style: r.style });
        if (i < arr.length - 1) flat.push({ br: true });
      });
    }

    for (const e of consumedEls) consumed.add(e);
    for (const n of textNodes) consumedNodes.add(n);
    blocks.push({
      x, y, w, h, align, wrap: !single,
      lineSpacingPx: single ? null : pitch,
      opacity: ctx.opacity,
      runs: flat,
    });
  };

  walk(sec, { opacity: 1, leave: '', clips: [] });

  // ---- hide extracted text in the DOM (the screenshot then shows only what remains) ----
  // Only elements whose own text was extracted are blanked. Child elements that stay in the
  // raster get their original fill/shadow pinned inline, because the fill colour inherits.
  const pin = new Map();
  for (const e of consumed) for (const c of e.children) if (!consumed.has(c)) {
    const cs = getComputedStyle(c);
    pin.set(c, [cs.webkitTextFillColor, cs.textShadow]);
  }
  for (const e of consumed) e.setAttribute('data-sw-x', '');
  for (const [c, [fill, shadow]] of pin) {
    c.style.setProperty('-webkit-text-fill-color', fill, 'important');
    c.style.setProperty('text-shadow', shadow, 'important');
  }

  // notes: <aside class="notes"> or data-notes
  let notes = sec.getAttribute('data-notes') || '';
  const aside = sec.querySelector('aside.notes');
  if (aside) {
    const c = aside.cloneNode(true);
    c.querySelectorAll('br').forEach((b) => b.replaceWith('\n'));
    c.querySelectorAll('p,li,div,h1,h2,h3,h4,h5,h6,tr').forEach((b) => b.append('\n'));
    c.querySelectorAll('li').forEach((li) => li.prepend('- '));
    notes = c.textContent;
  }
  notes = notes.split('\n').map((l) => l.replace(/\s+/g, ' ').trim()).join('\n').replace(/\n{3,}/g, '\n\n').trim();

  const hl = sec.querySelector('h1,h2,h3');
  return { blocks, notes, skippedText, title: hl ? hl.textContent.replace(/\s+/g, ' ').trim() : '', width: sec.offsetWidth, height: sec.offsetHeight, scale: k };
}
```

## File: slide-wright/scripts/lib/package.mjs
size: 1768
sha: 1a5ff4f9ae7be52d1d56bb7e30c5460b721fafe0
upstream: https://github.com/arifszn/slide-wright/blob/HEAD/slide-wright/scripts/lib/package.mjs

```text
// Post-processing of the package pptxgenjs writes. Two things it gets wrong by the letter of
// the packaging spec; PowerPoint tolerates both, other consumers (and strict validators) do not.
//   1. [Content_Types].xml carries one Override per slide for slideMasterN.xml parts that do not exist.
//   2. <a:t> runs with leading or trailing spaces lack xml:space="preserve".
//   3. A paragraph with several runs gets a repeated <a:pPr> before each run; the schema allows one, first.
// Nothing else is touched. In particular the child order of <p:presentation> stays as written:
// reordering it makes PowerPoint refuse the file.
export async function finalizePackage(JSZip, buffer) {
  const zip = await JSZip.loadAsync(buffer);
  const parts = new Set(Object.keys(zip.files));

  const ct = await zip.file('[Content_Types].xml').async('string');
  zip.file(
    '[Content_Types].xml',
    ct.replace(/<Override\s[^>]*PartName="\/([^"]+)"[^>]*\/>/g, (m, part) => (parts.has(part) ? m : '')),
  );

  for (const name of parts) {
    if (!/^ppt\/(slides|notesSlides)\/[^/]+\.xml$/.test(name)) continue;
    const xml = await zip.file(name).async('string');
    const fixed = xml
      .replace(/<a:t>([^<]*)<\/a:t>/g, (m, t) => (/^\s|\s$/.test(t) ? `<a:t xml:space="preserve">${t}</a:t>` : m))
      .replace(/<a:p>[\s\S]*?<\/a:p>/g, (para) => {
        let seen = false;
        // paragraph options are only ever set on the first run (see export-pptx.mjs), so the repeats are redundant defaults
        return para.replace(/<a:pPr(?:\s[^>]*)?\/>|<a:pPr(?:\s[^>]*)?>[\s\S]*?<\/a:pPr>/g, (m) => (seen ? '' : ((seen = true), m)));
      });
    if (fixed !== xml) zip.file(name, fixed);
  }
  return zip.generateAsync({ type: 'nodebuffer', compression: 'DEFLATE' });
}
```

## File: tests/check-deck.test.mjs
size: 1684
sha: cd245a2b0397e53f2d2c5c5eade4adbb6d195891
upstream: https://github.com/arifszn/slide-wright/blob/HEAD/tests/check-deck.test.mjs

```text
// Tests for slide-wright/scripts/check-deck.mjs
import { test, after } from 'node:test';
import assert from 'node:assert/strict';
import { mkdtempSync, readFileSync, writeFileSync, rmSync, existsSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
import { checkDeck } from '../slide-wright/scripts/check-deck.mjs';
import { offlineRoute } from './lib/offline.mjs';

const here = dirname(fileURLToPath(import.meta.url));
const tmp = mkdtempSync(join(tmpdir(), 'sw-check-'));
after(() => rmSync(tmp, { recursive: true, force: true }));

// basic.html has one deliberately clipped sentence (slide 6); everything else is clean.
test('clean deck: only the deliberately clipped sentence is reported, contact sheet written', async () => {
  const sheet = join(tmp, 'sheet.png');
  const r = await checkDeck({ input: join(here, 'fixtures/basic.html'), sheet, route: offlineRoute() });
  assert.ok(r.slides > 0);
  assert.deepEqual(r.defects, ['slide 6: clipped content: p']);
  assert.ok(existsSync(sheet));
});

test('broken deck: reports off-frame and undersized text per slide', async () => {
  const html = readFileSync(join(here, 'fixtures/basic.html'), 'utf8').replace('<h2 class="action-title">', '<h2 class="action-title" style="position:relative;left:1200px;font-size:12px">');
  const input = join(tmp, 'broken.html');
  writeFileSync(input, html);
  const r = await checkDeck({ input, route: offlineRoute() });
  assert.ok(r.defects.some((d) => /^slide \d+: outside frame/.test(d)), r.defects.join('\n'));
  assert.ok(r.defects.some((d) => /below 18px/.test(d)), r.defects.join('\n'));
});
```

## File: tests/export-pptx.test.mjs
size: 23053
sha: e9cad58dcf95c5bbd8181593c0529b2ada46966e
upstream: https://github.com/arifszn/slide-wright/blob/HEAD/tests/export-pptx.test.mjs

```text
// Tests for slide-wright/scripts/export-pptx.mjs
//   node --test tests/
// Needs Chrome (or Chromium) and, for the render tests, LibreOffice (soffice) + pdftoppm.
// reveal.js is served from a local copy, so no network is needed after the first dependency install.
import { test, before, after, describe } from 'node:test';
import assert from 'node:assert/strict';
import { execFileSync, spawnSync } from 'node:child_process';
import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
import { exportDeck } from '../slide-wright/scripts/export-pptx.mjs';
import { ensureDeps } from '../slide-wright/scripts/lib/deps.mjs';
import { offlineRoute, TEST_DEPS } from './lib/offline.mjs';
import { decode, ink } from './lib/pixels.mjs';
import { validatePptx } from './lib/validate-ooxml.mjs';

const here = dirname(fileURLToPath(import.meta.url));
const JSZip = ensureDeps(TEST_DEPS)('jszip');
const SOFFICE = ['/Applications/LibreOffice.app/Contents/MacOS/soffice', '/usr/bin/soffice', '/usr/local/bin/soffice'].find(existsSync) || 'soffice';
const hasBin = (cmd, args) => spawnSync(cmd, args, { stdio: 'ignore' }).status === 0;
const canRender = hasBin(SOFFICE, ['--version']) && hasBin('pdftoppm', ['-v']);

const tmp = mkdtempSync(join(tmpdir(), 'sw-pptx-'));
after(() => rmSync(tmp, { recursive: true, force: true }));

// ---- helpers -------------------------------------------------------------------------
async function openPptx(file) {
  const zip = await JSZip.loadAsync(readFileSync(file));
  const text = (p) => zip.file(p).async('string');
  const slideNames = Object.keys(zip.files).filter((n) => /^ppt\/slides\/slide\d+\.xml$/.test(n)).sort((a, b) => parseInt(a.match(/\d+/)[0]) - parseInt(b.match(/\d+/)[0]));
  const slides = [];
  for (const name of slideNames) {
    const n = name.match(/slide(\d+)\.xml/)[1];
    const xml = await text(name);
    const rels = await text(`ppt/slides/_rels/slide${n}.xml.rels`);
    const notesTarget = rels.match(/Target="\.\.\/notesSlides\/(notesSlide\d+\.xml)"/);
    const notesXml = notesTarget ? await text(`ppt/notesSlides/${notesTarget[1]}`) : null;
    const bg = xml.match(/<p:bg>[\s\S]*?<a:blip r:embed="(rId\d+)"/);
    let bgPng = null;
    if (bg) {
      const target = rels.match(new RegExp(`Id="${bg[1]}"[^>]*Target="\\.\\./media/([^"]+)"|Target="\\.\\./media/([^"]+)"[^>]*Id="${bg[1]}"`));
      bgPng = target && (await zip.file(`ppt/media/${target[1] || target[2]}`).async('nodebuffer'));
    }
    const runs = [...xml.matchAll(/<a:t(?: [^>]*)?>([^<]*)<\/a:t>/g)].map((m) => m[1].replace(/&amp;/g, '&').replace(/&lt;/g, '<').replace(/&gt;/g, '>'));
    // pptxgenjs writes a notes page for every slide (with only a slide-number field when empty), so "has notes" means non-empty text
    const noteText = notesXml ? [...notesXml.replace(/<a:fld[\s\S]*?<\/a:fld>/g, '').matchAll(/<a:t(?: [^>]*)?>([^<]*)<\/a:t>/g)].map((m) => m[1]).join('\n') : '';
    const notes = noteText.trim() ? noteText : null;
    slides.push({ xml, runs, text: runs.join(' '), notes, bgPng });
  }
  return { zip, slides };
}

// Converts the pptx with LibreOffice and checks that, for every extracted box, the rendered
// text sits where the HTML put it (ink centroid) and is neither missing nor duplicated (ink amount).
function renderCheck(m, dbg, name, maxDrift = 14) {
  const out = join(tmp, `lo-${name}`);
  execFileSync(SOFFICE, ['--headless', '--convert-to', 'pdf', '--outdir', out, m.output], { stdio: 'ignore', timeout: 120000 });
  execFileSync('pdftoppm', ['-r', '144', '-png', join(out, `${name}.pdf`), join(out, 'p')]);
  const pages = readdirSync(out).filter((f) => f.endsWith('.png')).sort();
  assert.equal(pages.length, m.slides.length);
  let worst = 0;
  for (const [i, s] of m.slides.entries()) {
    const lo = decode(join(out, pages[i]));
    assert.deepEqual([lo.width, lo.height], [1920, 1080]);
    const ref = decode(join(dbg, `slide-${i + 1}.ref.png`));
    for (const b of s.blocks) {
      const rect = { x: b.x, y: b.y - 12, w: b.w - 12, h: b.h + 24 }; // right edge trimmed: boxes carry width slack
      const a = ink(ref, rect), c = ink(lo, rect);
      const label = `slide ${i + 1} "${b.runs.find((r) => r.text).text.slice(0, 30)}"`;
      const dx = Math.abs(a.cx - c.cx), dy = Math.abs(a.cy - c.cy), ratio = c.count / a.count;
      worst = Math.max(worst, dx, dy);
      assert.ok(dx <= maxDrift, `${label}: horizontal drift ${dx.toFixed(1)}px`);
      assert.ok(dy <= maxDrift, `${label}: vertical drift ${dy.toFixed(1)}px`);
      assert.ok(ratio > 0.6 && ratio < 1.6, `${label}: ink ratio ${ratio.toFixed(2)} (missing or duplicated text?)`);
    }
  }
  console.log(`    ${name}: worst drift ${worst.toFixed(1)}px`);
}

// ---- basic deck ----------------------------------------------------------------------
describe('basic deck', () => {
  let m, pptx, dbg;
  before(async () => {
    dbg = join(tmp, 'dbg');
    m = await exportDeck({ input: join(here, 'fixtures/basic.html'), output: join(tmp, 'basic.pptx'), debugDir: dbg, route: offlineRoute() });
    pptx = await openPptx(m.output);
  });

  test('package is structurally valid (relationships, content types, colours, ids)', async () => {
    assert.deepEqual(await validatePptx(readFileSync(m.output)), []);
  });

  test('one pptx slide per deck slide, 16:9', async () => {
    assert.equal(pptx.slides.length, 8);
    const pres = await pptx.zip.file('ppt/presentation.xml').async('string');
    const sz = pres.match(/<p:sldSz cx="(\d+)" cy="(\d+)"/);
    assert.ok(Math.abs(sz[1] / sz[2] - 16 / 9) < 0.002);
  });

  test('every slide has exactly one full-bleed background picture at deck resolution', () => {
    for (const [i, s] of pptx.slides.entries()) {
      assert.ok(s.bgPng, `slide ${i + 1} has no background picture`);
      const png = decode(s.bgPng);
      assert.deepEqual([png.width, png.height], [1920, 1080], `slide ${i + 1} picture size`);
      assert.equal((s.xml.match(/<p:pic>/g) || []).length, 0, `slide ${i + 1} should not use floating pictures`);
    }
  });

  test('text is present as native runs', () => {
    const must = [
      [0, ['Q3 BOARD UPDATE', 'Revenue grew 42% while burn fell', 'Corvid Labs · October 2026']],
      [1, ['Self-serve pays for itself in', 'nine', '01 · TRIAL', 'First alert', 'real data', 'Source: internal billing export', '02 / 08']],
      [2, ['What changes next quarter']],
      [3, ['SEGMENT', 'Enterprise', '$9.8M', '78%']],
      [4, ['Growth is compounding', 'Bookings up 42%', 'Burn multiple down to 1.1']],
      [6, ['One query answers it', 'SELECT account, count() AS alerts', 'GROUP BY account']],
    ];
    for (const [i, strs] of must) for (const s of strs) assert.ok(pptx.slides[i].text.includes(s), `slide ${i + 1} missing "${s}"; has: ${pptx.slides[i].text}`);
  });

  test('all fragments are exported (final state)', () => {
    for (const s of ['Approve the hiring plan', 'Endorse the pricing change', 'Intro two enterprise buyers']) assert.ok(pptx.slides[7].text.includes(s), s);
  });

  test('plain code block: exported once', () => {
    const n = (pptx.slides[6].text.match(/SELECT account/g) || []).length;
    assert.equal(n, 1);
  });

  test('text that cannot be placed faithfully stays in the image, never duplicated or lost', () => {
    const s5 = pptx.slides[4].text, s6 = pptx.slides[5].text;
    assert.ok(!/Q1|Q2|Q3/.test(s5), 'SVG text must not become a text box');
    for (const s of ['Gradient headline', 'Rotated text', 'This sentence is far too long', 'Shadowed line']) assert.ok(!s6.includes(s), `"${s}" should stay in the raster`);
    assert.ok(s6.includes('pill'));
    // ...and it really is in the raster: the slide-6 background must still contain ink where those lines are
    const bg = decode(pptx.slides[5].bgPng);
    assert.ok(ink(bg, { x: 100, y: 60, w: 900, h: 120 }).count > 5000, 'gradient headline missing from raster');
    assert.ok(ink(bg, { x: 100, y: 280, w: 700, h: 110 }).count > 1000, 'rotated text missing from raster');
  });

  test('transformations: uppercase applied, letter-spacing, sizes in points, no # in colours', () => {
    assert.ok(pptx.slides[0].runs.includes('Q3 BOARD UPDATE'));
    assert.match(pptx.slides[0].xml, /spc="200"/); // 4px at 1920px = 2pt
    assert.match(pptx.slides[1].xml, /sz="3400"/); // 68px title -> 34pt
    for (const s of pptx.slides) assert.doesNotMatch(s.xml, /srgbClr val="#/);
  });

  test('colour on dark section variant is the light text colour', () => {
    assert.match(pptx.slides[2].xml, /srgbClr val="F4EFE6"/);
  });

  test('speaker notes exist exactly where the deck has them', () => {
    const has = pptx.slides.map((s) => s.notes !== null);
    assert.deepEqual(has, [true, false, true, false, false, false, true, true]);
    assert.match(pptx.slides[0].notes, /Open with the headline number\.\s*Pause for questions\./);
    assert.equal(pptx.slides[2].notes.trim(), 'Transition to the plan.');
  });

  test('presentation title comes from the deck <title>', async () => {
    const core = await pptx.zip.file('docProps/core.xml').async('string');
    assert.match(core, /<dc:title>Fixture Deck<\/dc:title>/);
  });

  test('no ghost text: the raster is text-free inside every extracted box', () => {
    for (const [i, s] of m.slides.entries()) {
      const bg = decode(join(dbg, `slide-${i + 1}.png`));
      for (const b of s.blocks) {
        const r = ink(bg, { x: b.x + 10, y: b.y + 10, w: b.w - 20, h: b.h - 20 }); // inset: boxes can overhang their container by the width slack
        assert.ok(r.count / r.total < 0.002, `slide ${i + 1} "${b.runs[0].text}" still has ${r.count} ink pixels in the raster`);
      }
    }
  });

  test('control: the same check does catch text when it is NOT hidden', () => {
    const ref = decode(join(dbg, 'slide-1.ref.png'));
    const b = m.slides[0].blocks[1]; // the h1
    const r = ink(ref, { x: b.x, y: b.y, w: b.w, h: b.h });
    assert.ok(r.count / r.total > 0.02);
  });

  test('the raster embedded in the pptx equals the debug raster', () => {
    assert.ok(decode(pptx.slides[1].bgPng).data.equals(decode(join(dbg, 'slide-2.png')).data));
  });

  test('reports the fonts it used', () => {
    assert.ok(m.fonts.includes('Times New Roman') && m.fonts.includes('Arial'));
  });

  test('renders in LibreOffice and text lands where the HTML put it', { skip: !canRender && 'soffice/pdftoppm not available' }, () => {
    renderCheck(m, dbg, 'basic');
  });
});

// ---- stepped code ----------------------------------------------------------------------
describe('stepped code slide', () => {
  let m, pptx, dbg;
  before(async () => {
    dbg = join(tmp, 'dbg-code');
    m = await exportDeck({ input: join(here, 'fixtures/code.html'), output: join(tmp, 'code.pptx'), debugDir: dbg, route: offlineRoute() });
    pptx = await openPptx(m.output);
  });

  test('package is structurally valid', async () => {
    assert.deepEqual(await validatePptx(readFileSync(m.output)), []);
  });

  test('each code line is exported once: the stacked step clones are skipped as covered', () => {
    for (const line of ['SELECT', 'FROM', 'WHERE', 'GROUP']) {
      const n = pptx.slides[0].runs.filter((r) => r.startsWith(line)).length;
      assert.equal(n, 1, `${line} appears ${n} times`);
    }
    assert.ok(m.slides[0].skippedText.some((t) => t.startsWith('covered:')), 'test is vacuous if no clones were covered');
  });

  test('indented code line: the box starts where the indentation starts (no doubled indent)', () => {
    const joined = (x) => x.runs.map((r) => r.text || '').join('');
    const b = m.slides[0].blocks.find((x) => joined(x).includes("account != 'internal'"));
    const plain = m.slides[0].blocks.find((x) => x.runs.some((r) => r.text && r.text.startsWith('GROUP')));
    assert.ok(Math.abs(b.x - plain.x) < 3, `indented box at ${b.x}, plain line at ${plain.x}`);
    assert.match(b.runs[0].text, /^ {6}/);
  });

  test('final step: the highlighted lines are opaque, the dimmed lines carry transparency', () => {
    const alphas = [...pptx.slides[0].xml.matchAll(/<a:alpha val="(\d+)"\/>/g)].map((x) => +x[1]);
    assert.ok(alphas.length >= 2 && alphas.every((a) => a === 40000), `alphas: ${alphas}`);
  });

  test('no ghost text', () => {
    const bg = decode(join(dbg, 'slide-1.png'));
    for (const b of m.slides[0].blocks) {
      const r = ink(bg, { x: b.x + 10, y: b.y + 10, w: b.w - 20, h: b.h - 20 });
      assert.ok(r.count / r.total < 0.002, `"${b.runs[0].text}" has ${r.count} ink pixels left`);
    }
  });

  test('renders in LibreOffice with text in place', { skip: !canRender && 'soffice/pdftoppm not available' }, () => {
    renderCheck(m, dbg, 'code');
  });
});

// ---- real web fonts (needs network; skipped offline) -------------------------------------
const online = await fetch('https://api.fontshare.com/v2/css?f[]=satoshi@400&display=swap', { signal: AbortSignal.timeout(8000) }).then((r) => r.ok, () => false);

describe('web fonts and template chrome', { skip: !online && 'Fontshare not reachable' }, () => {
  let m, pptx, dbg;
  before(async () => {
    dbg = join(tmp, 'dbg-fonts');
    m = await exportDeck({ input: join(here, 'fixtures/webfonts.html'), output: join(tmp, 'webfonts.pptx'), debugDir: dbg, route: offlineRoute({ allowFonts: true }) });
    pptx = await openPptx(m.output);
  });

  test('package is structurally valid', async () => {
    assert.deepEqual(await validatePptx(readFileSync(m.output)), []);
  });

  test('web fonts were loaded before the screenshot, and the text boxes name them', () => {
    assert.ok(m.loadedFonts.includes('General Sans') && m.loadedFonts.includes('Satoshi'), `loaded: ${m.loadedFonts}; faces: ${JSON.stringify(m.fontStatus)}`);
    assert.ok(m.fonts.includes('General Sans') && m.fonts.includes('Satoshi'), `used: ${m.fonts}`);
    assert.match(pptx.slides[0].xml, /typeface="General Sans"/);
    assert.match(pptx.slides[0].xml, /typeface="Satoshi"/);
  });

  test('title, labels, footer, and the data-page counter are extracted', () => {
    const t = pptx.slides[0].runs;
    for (const s of ['02 · Customer journey', 'Activation happens inside the first day', 'First alert fires', 'Day-one activation predicts expansion.', '01 / 01']) assert.ok(t.includes(s), `missing "${s}"; have ${JSON.stringify(t)}`);
  });

  test('arrow labels (pure translateY) are extracted; the CSS arrow itself stays in the raster', () => {
    assert.ok(pptx.slides[0].runs.includes('HANDOFF') && pptx.slides[0].runs.includes('INVITE'));
    const bg = decode(pptx.slides[0].bgPng);
    assert.ok(ink(bg, { x: 700, y: 540, w: 100, h: 30 }, 40).count > 50, 'arrow line missing from the raster');
  });

  test('no ghost text with web fonts', () => {
    const bg = decode(join(dbg, 'slide-1.png'));
    for (const b of m.slides[0].blocks) {
      const r = ink(bg, { x: b.x + 10, y: b.y + 10, w: b.w - 20, h: b.h - 20 });
      assert.ok(r.count / r.total < 0.002, `"${b.runs[0].text}" has ${r.count} ink pixels left`);
    }
  });
});

// ---- edge cases ----------------------------------------------------------------------
describe('edge cases', () => {
  let m, pptx, dbg;
  before(async () => {
    dbg = join(tmp, 'dbg-edge');
    m = await exportDeck({ input: join(here, 'fixtures/edge.html'), output: join(tmp, 'edge.pptx'), debugDir: dbg, route: offlineRoute() });
    pptx = await openPptx(m.output);
  });

  test('package is structurally valid, including runs with leading/trailing spaces', async () => {
    assert.deepEqual(await validatePptx(readFileSync(m.output)), []);
    assert.match(pptx.slides[0].xml, /<a:t xml:space="preserve">\s+preserved/);
  });

  test('data-visibility="hidden" slides are skipped, like in the PDF export', () => {
    assert.equal(pptx.slides.length, 2);
    assert.ok(!pptx.slides.some((s) => s.text.includes('HIDDEN SLIDE')));
  });

  test('mixed font sizes on one line (inline code) stay one line; wrapped ones get a sane pitch', () => {
    const blocks = m.slides[0].blocks;
    const one = blocks.find((b) => b.runs.some((r) => r.text && r.text.startsWith('Each class')));
    assert.equal(one.wrap, false);
    assert.equal(one.lineSpacingPx, null, 'a single visual line must not get exact line spacing');
    const two = blocks.find((b) => b.runs.some((r) => r.text && r.text.startsWith('A longer sentence')));
    assert.equal(two.wrap, true);
    assert.ok(two.lineSpacingPx > 44 && two.lineSpacingPx < 100, `pitch ${two.lineSpacingPx}px for 44px text`);
    const spcs = [...pptx.slides[0].xml.matchAll(/<a:spcPts val="(\d+)"/g)].map((x) => +x[1]);
    assert.ok(spcs.every((v) => v >= 1500), `implausibly small line spacing in XML: ${spcs}`);
  });

  test('a paragraph with a painted inline chip stays in the raster, so the chip keeps its text', () => {
    assert.ok(!m.slides[0].blocks.some((b) => b.runs.some((r) => r.text && r.text.includes('pill-chip'))));
    assert.ok(m.slides[0].skippedText.some((t) => t.startsWith('inline-box: A padded')));
  });

  test('one <a:pPr> per paragraph', () => {
    for (const para of pptx.slides[0].xml.match(/<a:p>[\s\S]*?<\/a:p>/g)) assert.ok((para.match(/<a:pPr[\s>\/]/g) || []).length <= 1);
  });

  test('renders in LibreOffice with all text visible and in place', { skip: !canRender && 'soffice/pdftoppm not available' }, () => {
    renderCheck(m, dbg, 'edge');
  });

  test('data-notes attribute becomes speaker notes', () => {
    assert.equal(pptx.slides[0].notes.trim(), 'Notes from the attribute.');
    assert.equal(pptx.slides[1].notes, null);
  });

  test('<br> splits paragraphs; capitalize, whitespace and entities are handled', () => {
    const t = pptx.slides[0].runs;
    assert.ok(t.includes('Line one') && t.includes('Line two after a break'));
    assert.ok(t.includes('Capitalize Every Word Here'));
    assert.ok(t.some((r) => r.includes('an ampersand')) || pptx.slides[0].text.includes('& an ampersand'));
    assert.ok(t.some((r) => r.startsWith('  preserved   spacing') || r.includes('preserved   spacing')));
  });

  test('alignment, opacity, bold/italic/underline map to run properties', () => {
    const x = pptx.slides[0].xml;
    assert.match(x, /algn="r"/);
    assert.match(x, /alpha val="40000"/); // opacity .4
    assert.match(x, /b="1"/);
    assert.match(x, /i="1"/);
    assert.match(x, /u="sng"/);
  });
});

// ---- the validator itself: it must flag each defect it claims to catch ---------------------
describe('ooxml validator', () => {
  let good;
  before(async () => {
    const m = await exportDeck({ input: join(here, 'fixtures/edge.html'), output: join(tmp, 'val-src.pptx'), route: offlineRoute() });
    good = readFileSync(m.output);
  });

  // apply `edit` to the package, return the validator's verdict
  async function broken(edit) {
    const zip = await JSZip.loadAsync(good);
    await edit(zip);
    return validatePptx(await zip.generateAsync({ type: 'nodebuffer' }));
  }
  const patch = (name, fn) => async (zip) => zip.file(name, fn(await zip.file(name).async('string')));

  test('control: the untouched export is valid', async () => {
    assert.deepEqual(await validatePptx(good), []);
  });

  const cases = [
    ['colour with #', patch('ppt/slides/slide1.xml', (x) => x.replace(/srgbClr val="([0-9A-F]{6})"/, 'srgbClr val="#$1"')), /invalid colour/],
    ['8-digit colour (alpha baked into hex)', patch('ppt/slides/slide1.xml', (x) => x.replace(/srgbClr val="([0-9A-F]{6})"/, 'srgbClr val="$100"')), /invalid colour/],
    ['alpha out of range', patch('ppt/slides/slide1.xml', (x) => x.replace(/<a:alpha val="\d+"\/>/, '<a:alpha val="250000"/>')), /alpha/],
    ['font size out of range', patch('ppt/slides/slide1.xml', (x) => x.replace(/ sz="\d+"/, ' sz="5"')), /font size/],
    ['unknown alignment', patch('ppt/slides/slide1.xml', (x) => x.replace(/algn="l"/, 'algn="left"')), /alignment/],
    ['duplicate shape ids', patch('ppt/slides/slide1.xml', (x) => x.replace(/<p:cNvPr id="3"/, '<p:cNvPr id="2"')), /duplicate shape ids/],
    ['dangling relationship id in a slide', patch('ppt/slides/slide1.xml', (x) => x.replace(/r:embed="rId\d+"/, 'r:embed="rId99"')), /not declared/],
    ['truncated XML', patch('ppt/slides/slide2.xml', (x) => x.slice(0, x.length - 40)), /not well-formed/],
    ['missing leading-space preserve flag', patch('ppt/slides/slide1.xml', (x) => x.replace('<a:t xml:space="preserve">', '<a:t>')), /xml:space/],
    ['shape completely off-slide', patch('ppt/slides/slide1.xml', (x) => x.replace(/<a:off x="\d+" y="\d+"\/>(<a:ext cx="[1-9])/, '<a:off x="99999999" y="0"/>$1')), /outside the slide/],
    ['part without a content type', patch('[Content_Types].xml', (x) => x.replace(/<Override[^>]*PartName="\/ppt\/slides\/slide2.xml"[^>]*\/>/, '')), /no content type/],
    ['content-type override for a missing part', patch('[Content_Types].xml', (x) => x.replace('</Types>', '<Override PartName="/ppt/slideMasters/slideMaster9.xml" ContentType="x"/></Types>')), /not in the package/],
    ['relationship to a missing part', async (zip) => { const f = Object.keys(zip.files).find((n) => /ppt\/media\/.*\.png$/.test(n)); zip.remove(f); }, /not in the package/],
    ['slide not listed in sldIdLst', patch('ppt/presentation.xml', (x) => x.replace(/<p:sldId [^>]*\/>/, '')), /not in <p:sldIdLst>/],
    ['duplicate slide ids', patch('ppt/presentation.xml', (x) => x.replace(/(<p:sldId id=")257"/, '$1256"')), /duplicate slide ids/],
    ['notes page without notes master link', patch('ppt/notesSlides/_rels/notesSlide1.xml.rels', (x) => x.replace(/<Relationship [^>]*notesMaster[^>]*\/>/, '')), /notes master/],
    ['corrupt image', async (zip) => { const f = Object.keys(zip.files).find((n) => /ppt\/media\/.*\.png$/.test(n)); zip.file(f, Buffer.from('not a png at all')); }, /not a PNG/],
  ];
  for (const [name, edit, expected] of cases) {
    test(`flags: ${name}`, async () => {
      const errs = await broken(edit);
      assert.ok(errs.some((e) => expected.test(e)), `expected ${expected}, got ${JSON.stringify(errs)}`);
    });
  }

  test('does not flag pptxgenjs\'s unusual child order in <p:presentation> (PowerPoint needs it as written)', async () => {
    const pres = (await JSZip.loadAsync(good)).file('ppt/presentation.xml');
    const xml = await pres.async('string');
    assert.ok(xml.indexOf('<p:sldIdLst>') < xml.indexOf('<p:notesMasterIdLst>'), 'premise: pptxgenjs order changed; revisit finalizePackage');
  });
});

// ---- failure modes -------------------------------------------------------------------
describe('failure modes', () => {
  test('a non-deck HTML file fails with a clear message', async () => {
    const f = join(tmp, 'plain.html');
    (await import('node:fs')).writeFileSync(f, '<html><body><h1>hi</h1></body></html>');
    await assert.rejects(exportDeck({ input: f, output: join(tmp, 'plain.pptx'), timeout: 1500 }), /No ready reveal\.js instance/);
  });
});
```

## File: tests/lib/offline.mjs
size: 1579
sha: 0563bd1a55328512738732be5d92354d28bdad1a
upstream: https://github.com/arifszn/slide-wright/blob/HEAD/tests/lib/offline.mjs

```text
// Serves the reveal.js CDN URLs from the locally installed package so tests need no network.
import { readFileSync, existsSync } from 'node:fs';
import { join } from 'node:path';
import { ensureDeps, CACHE_DIR } from '../../slide-wright/scripts/lib/deps.mjs';

export const TEST_DEPS = { 'reveal.js': '5.1.0', pngjs: '7.0.0', '@xmldom/xmldom': '0.9.12' };

// allowFonts: let Fontshare/Google font requests through (for the web-font test)
export function offlineRoute({ allowFonts = false } = {}) {
  ensureDeps(TEST_DEPS);
  const root = join(CACHE_DIR, 'node_modules', 'reveal.js');
  const types = { '.js': 'text/javascript', '.css': 'text/css' };
  return async (page) => {
    await page.route(/cdn\.jsdelivr\.net\/npm\/reveal\.js@5\.1\.0\//, (route) => {
      const rel = new URL(route.request().url()).pathname.replace(/^\/npm\/reveal\.js@5\.1\.0\//, '');
      const file = join(root, rel);
      if (!existsSync(file)) return route.fulfill({ status: 404, body: '' });
      const ext = file.slice(file.lastIndexOf('.'));
      return route.fulfill({ status: 200, contentType: types[ext] || 'application/octet-stream', body: readFileSync(file) });
    });
    // everything else is blocked unless fonts are allowed: most fixtures use system fonts only
    const allowed = allowFonts ? /^https?:\/\/(cdn\.jsdelivr\.net|api\.fontshare\.com|cdn\.fontshare\.com|fonts\.googleapis\.com|fonts\.gstatic\.com)/ : /^https?:\/\/cdn\.jsdelivr\.net/;
    await page.route(/^https?:\/\//, (route) => (allowed.test(route.request().url()) ? route.fallback() : route.abort()));
  };
}
```

## File: tests/lib/pixels.mjs
size: 1597
sha: ec34bee1012fd0e7d2334c2fafc6de475e62cbe6
upstream: https://github.com/arifszn/slide-wright/blob/HEAD/tests/lib/pixels.mjs

```text
// Small PNG helpers for the visual tests.
import { ensureDeps } from '../../slide-wright/scripts/lib/deps.mjs';
import { TEST_DEPS } from './offline.mjs';
import { readFileSync } from 'node:fs';

const { PNG } = ensureDeps(TEST_DEPS)('pngjs');
export const decode = (bufOrPath) => PNG.sync.read(typeof bufOrPath === 'string' ? readFileSync(bufOrPath) : bufOrPath);

// Ink = pixels that differ from the region's dominant colour. Returns { count, cx, cy }.
export function ink(png, rect, threshold = 60) {
  const x0 = Math.max(0, Math.floor(rect.x)), y0 = Math.max(0, Math.floor(rect.y));
  const x1 = Math.min(png.width, Math.ceil(rect.x + rect.w)), y1 = Math.min(png.height, Math.ceil(rect.y + rect.h));
  const hist = new Map();
  for (let y = y0; y < y1; y++) for (let x = x0; x < x1; x++) {
    const i = (y * png.width + x) * 4;
    const key = (png.data[i] >> 3) << 10 | (png.data[i + 1] >> 3) << 5 | (png.data[i + 2] >> 3);
    hist.set(key, (hist.get(key) || 0) + 1);
  }
  let best = 0, bestKey = 0;
  for (const [k, v] of hist) if (v > best) { best = v; bestKey = k; }
  const bg = [((bestKey >> 10) & 31) << 3, ((bestKey >> 5) & 31) << 3, (bestKey & 31) << 3];
  let count = 0, sx = 0, sy = 0;
  for (let y = y0; y < y1; y++) for (let x = x0; x < x1; x++) {
    const i = (y * png.width + x) * 4;
    const d = Math.abs(png.data[i] - bg[0]) + Math.abs(png.data[i + 1] - bg[1]) + Math.abs(png.data[i + 2] - bg[2]);
    if (d > threshold) { count++; sx += x; sy += y; }
  }
  return { count, total: (x1 - x0) * (y1 - y0), cx: count ? sx / count : NaN, cy: count ? sy / count : NaN };
}
```

## File: tests/lib/validate-ooxml.mjs
size: 9495
sha: 4f4b46c4ed141fa26b4a4b4b10f039370dc62628
upstream: https://github.com/arifszn/slide-wright/blob/HEAD/tests/lib/validate-ooxml.mjs

Content is not inlined in the catalog. Read the upstream file: https://github.com/arifszn/slide-wright/blob/HEAD/tests/lib/validate-ooxml.mjs

## File: tools/sync-root-skill.sh
size: 451
sha: 1c4b8a095876f9ea64091da4a8ef75ef77e65393
upstream: https://github.com/arifszn/slide-wright/blob/HEAD/tools/sync-root-skill.sh

```text
#!/bin/sh
# Regenerate the root SKILL.md from slide-wright/SKILL.md (adds the slide-wright/ path prefix).
# Use --check to fail when the root copy is stale (CI).
set -e
cd "$(dirname "$0")/.."
out=$(sed 's#`references/#`slide-wright/references/#g' slide-wright/SKILL.md)
if [ "$1" = "--check" ]; then
  [ "$out" = "$(cat SKILL.md)" ] || { echo "SKILL.md is stale: run tools/sync-root-skill.sh" >&2; exit 1; }
else
  printf '%s\n' "$out" > SKILL.md
fi
```
