Files
hyperframes/packages/cli/src/commands/docs.ts
T
James Russo 08fb1de61f feat(cli): add command + hyperframes.json (#256)
## What

PR 5/17 of the catalog system rollout. Adds the `hyperframes add` verb for installing blocks and components from the registry into an existing project, plus the `hyperframes.json` project config that tells `add` which registry to use and where to drop files. Stacks on #255.

- **`packages/cli/src/commands/add.ts`** — new `hyperframes add <name>` command. Resolves an item, validates target paths, installs files in parallel, builds an include snippet, copies it to the clipboard. Exposes a testable `runAdd(opts)` function; the citty default wraps it with console output + exit handling
- **`packages/cli/src/utils/projectConfig.ts`** — read/write/normalize `hyperframes.json`. Tolerant to missing and partial configs
- **`packages/cli/src/utils/clipboard.ts`** — minimal cross-platform clipboard (pbcopy / clip.exe / wl-copy / xclip / xsel). Zero deps. Gracefully no-ops in headless environments
- **`packages/cli/src/commands/init.ts`** — write `hyperframes.json` during scaffold if not already present
- **`packages/cli/src/cli.ts`** + **`help.ts`** — register `add` under Getting Started (directly below `init`)

Design doc: [Hyperframes Catalog System](https://www.notion.so/heygen/Hyperframes-Catalog-System-Design-Plan-341449792c69813f899dcd53b4c0383a).

## UX

```bash
# Scaffold a project (now writes hyperframes.json too)
npx hyperframes init my-video --example blank
cd my-video

# Add a block — files land, snippet copied to clipboard
npx hyperframes add claude-code-window
#  ✓ Added claude-code-window (hyperframes:block)
#    compositions/claude-code-window.html
#
#  Include snippet:
#    <iframe src="compositions/claude-code-window.html" data-start="0" data-duration="6"></iframe>
#
#  Copied to clipboard — paste into your host composition.

# Add a component effect
npx hyperframes add shader-wipe

# Headless / CI — no clipboard, JSON output for tooling
npx hyperframes add shader-wipe --no-clipboard --json
```

Running `hyperframes add warm-grain` (an example) errors clearly pointing to `init --example`.

## Docs (bundled in this PR per the tracker principle)

- `docs/packages/cli.mdx` — new `add` subsection under Commands (flags, examples, trigger rules) + new `hyperframes.json` section describing the config file shape

## Tests

- **`packages/cli/src/commands/add.test.ts`** — 11 tests:
  - `remapTarget` / `buildSnippet` pure helpers (5 tests)
  - `runAdd` integration against a mocked `fetch` registry: block install lands files + returns snippet, component install respects `paths.components` remap, example-typed names throw `AddError` with code `example-type`, unknown names throw `AddError` with code `unknown-item` (4 tests plus 2 covering block default path and non-default path preservation)
- **`packages/cli/src/utils/projectConfig.test.ts`** — 9 tests:
  - Write/read round-trip, partial-config normalization, corrupt-file handling, absent-file fallback to defaults, custom paths preserved
- **CLI suite:** 92 passed (was 72 on #255, **+20**). Same 4 pre-existing failures unchanged

## Scope decisions

- **`init.ts` full port to new resolver deferred.** The original plan bundled a removal of the `packages/cli/src/templates/` compat shim. That's ~300 more lines and isn't required for `add` to work. The compat shim from #254 still functions; a separate cleanup PR handles it
- **No ajv runtime schema validation.** Manifests are trusted as schema-valid. Full validation lands when third-party registries arrive (PR 14/15). Path safety is still enforced by the installer's `assertSafeTarget` guard
- **Default project paths stay under `compositions/`.** Blocks → `compositions/<name>.html`; components → `compositions/components/<name>/<file>`. Users override via `hyperframes.json#paths`

## Breaking / migration

**None.** Pure additive — new command, new file types, no existing commands or flags change. `init.ts` now writes `hyperframes.json` but that's a new additional file, not a modification of existing output.

## Stacks on

#255 — base branch. When #255 merges, this rebases onto `main`.

## Next in stack

PR 6 — `feat(registry): seed block — claude-code-window`. First real registry item. Exercises the full `hyperframes add <name>` flow end-to-end against a committed item on `main`.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
2026-04-13 21:04:59 -07:00

144 lines
3.9 KiB
TypeScript

import { defineCommand } from "citty";
import type { Example } from "./_examples.js";
import { readFileSync, existsSync } from "node:fs";
export const examples: Example[] = [
["List all available topics", "hyperframes docs"],
["Read about data attributes", "hyperframes docs data-attributes"],
["Read about rendering", "hyperframes docs rendering"],
["Read about GSAP integration", "hyperframes docs gsap"],
];
import { resolve, dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { c } from "../ui/colors.js";
interface TopicEntry {
file: string;
description: string;
}
const TOPICS: Record<string, TopicEntry> = {
"data-attributes": {
file: "data-attributes.md",
description: "Timing, media, and composition attributes",
},
examples: {
file: "examples.md",
description: "Built-in project examples for init",
},
rendering: {
file: "rendering.md",
description: "Render compositions to MP4 (local & Docker)",
},
gsap: {
file: "gsap.md",
description: "GSAP animation setup and usage",
},
troubleshooting: {
file: "troubleshooting.md",
description: "Common issues and fixes",
},
compositions: {
file: "compositions.md",
description: "Composition structure, nesting, and variables",
},
};
function docsDir(): string {
const thisFile = fileURLToPath(import.meta.url);
const dir = dirname(thisFile);
// In dev: cli/src/commands/ → ../docs = cli/src/docs/
// In built: cli/dist/ → docs = cli/dist/docs/
const devPath = resolve(dir, "..", "docs");
const builtPath = resolve(dir, "docs");
return existsSync(devPath) ? devPath : builtPath;
}
function formatInlineCode(line: string): string {
// Replace inline backtick spans with accented text
return line.replace(/`([^`]+)`/g, (_match, code: string) => c.accent(code));
}
function renderMarkdown(content: string): void {
const lines = content.split("\n");
for (const line of lines) {
// Skip code fences
if (line.trim().startsWith("```")) {
continue;
}
// H1 heading
if (line.startsWith("# ")) {
console.log(c.bold(line.slice(2)));
continue;
}
// H2 subheading
if (line.startsWith("## ")) {
console.log(c.bold(c.dim(line.slice(3))));
continue;
}
// List items
if (line.startsWith("- ")) {
const rest = formatInlineCode(line.slice(2));
console.log(`${c.dim(" \u2022")} ${rest}`);
continue;
}
// Everything else
console.log(formatInlineCode(line));
}
}
const TOPIC_NAMES = Object.keys(TOPICS).join(", ");
export default defineCommand({
meta: { name: "docs", description: "View inline documentation in the terminal" },
args: {
topic: {
type: "positional",
description: `Topic: ${TOPIC_NAMES}. Omit to list all.`,
required: false,
},
},
async run({ args }) {
const topic = args.topic;
// No topic: list available topics
if (topic === undefined || topic === "") {
console.log(c.bold("Available topics:"));
console.log();
for (const [name, entry] of Object.entries(TOPICS)) {
console.log(` ${c.accent(name.padEnd(20))} ${c.dim(entry.description)}`);
}
console.log();
console.log(c.dim(`Run ${c.accent("hyperframes docs <topic>")} to view a topic.`));
return;
}
// Look up the topic
const entry = TOPICS[topic];
if (entry === undefined) {
console.error(c.error(`Unknown topic: ${topic}`));
console.error();
console.error("Available topics:");
for (const name of Object.keys(TOPICS)) {
console.error(` ${c.accent(name)}`);
}
process.exit(1);
}
const filePath = join(docsDir(), entry.file);
if (!existsSync(filePath)) {
console.error(c.error(`Doc file not found: ${filePath}`));
process.exit(1);
}
const content = readFileSync(filePath, "utf-8");
console.log();
renderMarkdown(content);
},
});