diff --git a/packages/cli/src/commands/add.ts b/packages/cli/src/commands/add.ts new file mode 100644 index 0000000..2c8f995 --- /dev/null +++ b/packages/cli/src/commands/add.ts @@ -0,0 +1,111 @@ +import { Command } from "commander" +import { spawn, spawnSync, type ChildProcess, type StdioOptions } from "node:child_process" +import fs from "node:fs" +import path from "node:path" +import pc from "picocolors" +import { warn } from "../lib/ui.js" + +/** + * `helpbase add ` — thin wrapper around `shadcn add` so users + * extending a scaffolded help center stay inside one CLI surface. + * + * The scaffold is already shadcn-shaped (components.json + components/ui/), + * so this command does NOT need to run `shadcn init` first. It only needs + * to forward the user's arguments to the upstream CLI in the project root. + * + * Why a wrapper instead of "just run npx shadcn": + * - Discoverability: the helpbase CLI lists `add` in --help next to + * `new`, `ingest`, `deploy`. A first-time user doesn't have to know + * shadcn exists to extend their UI. + * - Reinforces the "shadcn for docs" stance — every helpbase project + * IS a shadcn project, and the helpbase CLI says so. + * - Future-friendly: if we ever want to add helpbase-specific + * post-install steps (re-run llms.txt generation, etc.), we have a + * hook point. + * + * Implementation notes: + * - Runs in process.cwd() so the user can `cd my-help-center && helpbase + * add card`. Mirrors how shadcn itself behaves. + * - stdio inherited so shadcn's interactive prompts (overwrite confirms, + * registry picker, dependency install) render correctly. + * - Exit code passed through verbatim so CI scripts that wrap us see the + * same status as if they'd called shadcn directly. + * - Soft pre-flight: if components.json is missing we warn but still + * forward — `shadcn add` will print its own clearer error than we can, + * and we don't want to false-positive on edge layouts. + */ +export const addCommand = new Command("add") + .description("Add shadcn components to your help center (forwards to `shadcn add`)") + .argument( + "[components...]", + "Component names, URLs, or local paths (e.g. button card @acme/auth-form)", + ) + .allowUnknownOption(true) + .addHelpText( + "after", + ` +Examples: + $ helpbase add button card dialog + $ helpbase add @acme/auth-form + $ helpbase add # interactive picker + +This is a wrapper around the upstream shadcn CLI. All flags pass through. +See https://ui.shadcn.com/docs/cli for the full option list. +`, + ) + .action((components: string[]) => { + const cwd = process.cwd() + if (!fs.existsSync(path.join(cwd, "components.json"))) { + warn( + `No components.json in ${cwd} — this doesn't look like a shadcn project.\n` + + ` If you scaffolded with create-helpbase, cd into that directory first.`, + ) + } + const [cmd = "npx", ...prefix] = resolveShadcnCommand() + // Forward the user's component args plus any unknown options Commander + // collected (e.g. --overwrite, --yes). allowUnknownOption(true) above + // is what makes those options reach us instead of erroring at parse. + const passthrough: string[] = [...prefix, "add", ...components, ...extraArgs()] + const inherit: StdioOptions = "inherit" + const child: ChildProcess = spawn(cmd, passthrough, { + cwd, + stdio: inherit, + env: process.env, + }) + child.on("exit", (code: number | null) => process.exit(code ?? 1)) + child.on("error", (err: Error) => { + console.error(`${pc.red("✗")} Failed to spawn ${cmd}: ${err.message}`) + process.exit(1) + }) + }) + +/** + * Pick the right way to invoke `shadcn@latest`. We prefer the package- + * manager dlx of whatever the user invoked us with — matches their cache + * and avoids re-downloading shadcn into a different store. Detection is + * the same PATH-probe pattern preview.ts uses. + */ +function resolveShadcnCommand(): string[] { + const has = (bin: string): boolean => + spawnSync("sh", ["-c", `command -v ${bin}`], { stdio: "ignore" }).status === 0 + if (has("pnpm")) return ["pnpm", "dlx", "shadcn@latest"] + if (has("bun")) return ["bunx", "shadcn@latest"] + if (has("yarn")) return ["yarn", "dlx", "shadcn@latest"] + return ["npx", "-y", "shadcn@latest"] +} + +/** + * Commander consumes registered options but leaves unknown flags in + * `process.argv` past the command name. Pull those out so the user can + * pass `--overwrite`, `--yes`, etc., straight through to shadcn without + * us re-declaring every option. + */ +function extraArgs(): string[] { + const argv = process.argv.slice(2) + const addIdx = argv.indexOf("add") + if (addIdx === -1) return [] + const tail = argv.slice(addIdx + 1) + // Strip the positional component names we already forwarded — anything + // starting with `-` is an option for shadcn. + return tail.filter((arg) => arg.startsWith("-")) +} diff --git a/packages/cli/src/commands/login.ts b/packages/cli/src/commands/login.ts index c44bd8c..8d645b2 100644 --- a/packages/cli/src/commands/login.ts +++ b/packages/cli/src/commands/login.ts @@ -175,11 +175,18 @@ async function runMagicLinkFlow(preset?: string): Promise { * telemetry prompt finishes fading from their scrollback, and falls * back gracefully when auto-provisioning soft-failed (ensureReservation * already logged the reason to stderr in that case). + * + * When `HELPBASE_INLINE=1` is set, the parent process (typically + * create-helpbase spawning us during scaffold) owns the trailing + * "What next" panel + outro. Suppress ours so the user doesn't see + * two competing next-steps boxes within seconds. The reservation + * `note(...)` still prints — that's the magical moment, parent or not. */ function printLoginOutro( session: AuthSession, reservation: Awaited>, ): void { + const inline = process.env.HELPBASE_INLINE === "1" if (reservation) { const label = reservation.isNew ? "Reserved" : "Your help center" note( @@ -191,6 +198,7 @@ function printLoginOutro( )}`, "helpbase", ) + if (inline) return outro(`Logged in as ${pc.cyan(session.email)}`) nextSteps({ commands: [ @@ -202,7 +210,8 @@ function printLoginOutro( return } // No reservation (auto-provision soft-failed): fall back to the - // pre-reservation-era next-steps block. + // pre-reservation-era next-steps block. Still suppressed when inline. + if (inline) return outro(`Logged in as ${pc.cyan(session.email)}`) nextSteps({ commands: ["helpbase whoami", "helpbase new"] }) } diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts index 44499dc..24caddf 100644 --- a/packages/cli/src/index.ts +++ b/packages/cli/src/index.ts @@ -14,6 +14,7 @@ import { syncCommand } from "./commands/sync.js" import { mcpCommand } from "./commands/mcp.js" import { auditCommand } from "./commands/audit.js" import { newCommand } from "./commands/new.js" +import { addCommand } from "./commands/add.js" import { deployCommand } from "./commands/deploy.js" import { loginCommand } from "./commands/login.js" import { logoutCommand } from "./commands/logout.js" @@ -87,6 +88,7 @@ program.addCommand(syncCommand) program.addCommand(mcpCommand) program.addCommand(auditCommand) program.addCommand(newCommand) +program.addCommand(addCommand) program.addCommand(deployCommand) program.addCommand(loginCommand) program.addCommand(logoutCommand) diff --git a/packages/cli/src/lib/help.ts b/packages/cli/src/lib/help.ts index 6e4e5fb..b6c93f7 100644 --- a/packages/cli/src/lib/help.ts +++ b/packages/cli/src/lib/help.ts @@ -30,7 +30,7 @@ interface GroupDef { const GROUPS: GroupDef[] = [ { label: "Get started", commands: ["ingest", "preview", "new", "dev"] }, { label: "Ship", commands: ["deploy", "link", "open", "rename"] }, - { label: "Author", commands: ["generate", "sync", "mcp", "audit"] }, + { label: "Author", commands: ["generate", "add", "sync", "mcp", "audit"] }, { label: "Account", commands: ["login", "logout", "whoami", "config"] }, { label: "Diagnose", commands: ["doctor", "feedback", "completion", "upgrade"] }, ] diff --git a/packages/create-helpbase/src/emit-mcp-json.ts b/packages/create-helpbase/src/emit-mcp-json.ts index 3780cfc..cbb0af5 100644 --- a/packages/create-helpbase/src/emit-mcp-json.ts +++ b/packages/create-helpbase/src/emit-mcp-json.ts @@ -19,20 +19,35 @@ import path from "node:path" */ export function emitMcpJson(projectDir: string): string { const contentDir = path.join(projectDir, "content") - const mcpServerBlock = { + const helpbaseBlock = { command: "npx", args: ["@helpbase/mcp@latest"], env: { HELPBASE_CONTENT_DIR: contentDir, }, } + // Shadcn ships its own MCP server. Wiring it alongside helpbase means a + // user pasting either block gets BOTH servers registered: helpbase for + // citations into their docs, shadcn for "add a card component" natural- + // language UI extension. Same registry the scaffold itself was built + // from, so the experience compounds (the help center renders shadcn- + // shaped components; the agent that edits it can install more). + // See https://ui.shadcn.com/docs/mcp for client-side prompts. + const shadcnBlock = { + command: "npx", + args: ["shadcn@latest", "mcp"], + } + const mcpServers = { + helpbase: helpbaseBlock, + shadcn: shadcnBlock, + } const hint = { _comment: - "This file is a HINT — copy one of the blocks below into your MCP client's config. Do NOT commit: HELPBASE_CONTENT_DIR is an absolute machine-local path.", + "This file is a HINT — copy one of the blocks below into your MCP client's config. Do NOT commit: HELPBASE_CONTENT_DIR is an absolute machine-local path. Two servers ship by default: `helpbase` (cite your docs) and `shadcn` (install components from natural language).", helpbaseMcpVersion: "1", - claude_desktop: { mcpServers: { helpbase: mcpServerBlock } }, - cursor: { mcpServers: { helpbase: mcpServerBlock } }, - claude_code: { mcpServers: { helpbase: mcpServerBlock } }, + claude_desktop: { mcpServers }, + cursor: { mcpServers }, + claude_code: { mcpServers }, } const mcpJsonPath = path.join(projectDir, "mcp.json") fs.writeFileSync(mcpJsonPath, JSON.stringify(hint, null, 2) + "\n", "utf8") diff --git a/packages/create-helpbase/src/index.ts b/packages/create-helpbase/src/index.ts index d80f2d4..33d9cd6 100644 --- a/packages/create-helpbase/src/index.ts +++ b/packages/create-helpbase/src/index.ts @@ -982,7 +982,13 @@ async function runHelpbaseDeploy(projectDir: string): Promise { const child = spawn(cmd, args, { stdio: ["inherit", "pipe", "pipe"], cwd: projectDir, - env: process.env, + // HELPBASE_INLINE=1 tells the spawned subcommand it's running inside + // create-helpbase's flow. Today this only matters for `helpbase login` + // (suppresses its trailing outro+nextSteps so the scaffolder owns the + // final "What next" panel). Setting it unconditionally for deploy too + // is forward-compatible: any future inline-aware behavior in deploy + // will Just Work without revisiting this call site. + env: { ...process.env, HELPBASE_INLINE: "1" }, }) child.stdout?.on("data", (chunk: Buffer) => { process.stdout.write(chunk) @@ -1035,7 +1041,14 @@ async function runHelpbaseLogin(): Promise<"ok" | "failed"> { return new Promise<"ok" | "failed">((resolve) => { const child = spawn(cmd, args, { stdio: "inherit", - env: process.env, + // HELPBASE_INLINE=1 makes `helpbase login` skip its trailing outro + + // "Next: helpbase deploy · rename · whoami" panel when we spawn it + // inside the scaffold flow. Without this, the user sees TWO competing + // next-steps boxes within seconds: login's, then create-helpbase's + // own "What next" with overlapping commands. The reservation note + // (the magical moment) still prints — only the redundant tail is + // suppressed. + env: { ...process.env, HELPBASE_INLINE: "1" }, }) child.on("exit", (code) => resolve(code === 0 ? "ok" : "failed")) child.on("error", () => resolve("failed"))