@usesketchbook/cli 0.1.2 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -51,6 +51,8 @@ npm exec --yes --package=@usesketchbook/cli -- sketchbook init --start library
51
51
  npx sketchbook check
52
52
  ```
53
53
 
54
+ Run `npx sketchbook` in a terminal to explore the interactive menu. Choose a number and press Enter; previews appear before changes, and Enter cancels at the confirmation prompt. Use `npx sketchbook help <command> --details` for the full command reference.
55
+
54
56
  `init` adds the CLI as a dev dependency of the design-system project. For an existing app, add `--adopt` to `init` and run it from the app directory. To bring your own tokens, use `--start import --from <tokens file>`. See the [Quickstart](https://sketchbook-docs.vercel.app/start/quickstart/) for all seven starters and the [upgrade guide](https://sketchbook-docs.vercel.app/guides/adopt-in-app/#upgrade) for updating the CLI and harness.
55
57
 
56
58
  Plain `init` creates a core-only project and writes its initial inventory to `docs/harness.md`. Add `--agent claude` to stage Claude Code, or `--agent codex,trae` to install both selected integrations. The same flag adds profiles to an existing project. Run `npx sketchbook doctor` to inspect your setup. [Agent compatibility guide](./docs/agent-compatibility.md)
package/dist/index.d.ts CHANGED
@@ -220,7 +220,7 @@ declare class SbAvatarImage extends LitElement {
220
220
  disconnectedCallback(): void;
221
221
  protected willUpdate(changed: PropertyValues<this>): void;
222
222
  protected updated(): void;
223
- protected render(): typeof nothing | lit_html.TemplateResult<1>;
223
+ protected render(): lit_html.TemplateResult<1> | typeof nothing;
224
224
  }
225
225
  declare global {
226
226
  interface HTMLElementTagNameMap {
package/docs/cli.md CHANGED
@@ -6,7 +6,8 @@ Deterministic half of the harness. Run `sketchbook <command>` (or `node harness/
6
6
 
7
7
  ## Conventions
8
8
 
9
- - Bare `sketchbook` in a terminal opens an interactive menu built from this registry: pick a group and a command, answer prompts (current values shown), see the dry run, then confirm. Piped input or `--json` prints help instead.
9
+ - Bare `sketchbook` in a terminal opens an interactive menu built from this registry: enter a number to pick a group and command, provide arguments, and optionally review settings. Mutating commands show a dry run where supported; type y and press Enter to confirm, or press Enter to cancel. Piped input or `--json` prints help instead.
10
+ - `--details` shows full human-readable output where a terminal view is abbreviated.
10
11
  - `--json` on every command prints one envelope: `{ ok, command, changed[], warnings[], errors[{file, msg, fix}], next, data? }`.
11
12
  - Exit codes: 0 ok, 1 failed, 2 ok with flags (for example overrides kept in spec/tokens/overrides.json).
12
13
  - Read-only commands never write. Mutating commands say what they change; those marked "dry run" accept `--dry-run`.
@@ -17,6 +18,7 @@ Deterministic half of the harness. Run `sketchbook <command>` (or `node harness/
17
18
  | `--json` | Print one JSON envelope instead of human output |
18
19
  | `--dry-run` | Show what would change without writing (mutating commands that support it) |
19
20
  | `--help` | Show help for the command |
21
+ | `--details` | Show the full human-readable output |
20
22
 
21
23
  ## Project
22
24
 
@@ -94,8 +94,14 @@ export function formatHuman(report, { verbose = false } = {}) {
94
94
  lines.push('', `${report.ok ? 'All checks passed' : 'Checks failed'}${report.exitCode === 2 ? ' (with overrides)' : ''}.`);
95
95
  return lines;
96
96
  }
97
- const printHuman = (report, opts) => { for (const l of formatHuman(report, opts))
98
- console.log(l); };
97
+ const printHuman = (report, opts) => {
98
+ const tty = Boolean(process.stdout.isTTY);
99
+ const color = tty && !('NO_COLOR' in process.env);
100
+ for (const line of formatHuman(report, opts)) {
101
+ const formatted = tty ? line.replace(/^(pass|FAIL|flagged|All checks passed|Checks failed)/, (label) => color ? `\u001b[${label === 'FAIL' || label === 'Checks failed' ? '31' : '38;5;208'}m${label}\u001b[0m` : label) : line;
102
+ console.log(formatted);
103
+ }
104
+ };
99
105
  if (isMain(import.meta.url)) {
100
106
  const args = process.argv.slice(2);
101
107
  const onlyArg = args.find((a) => a.startsWith('--only='));
@@ -47,15 +47,15 @@ declare const _default: {
47
47
  } | {
48
48
  data: {
49
49
  entry: {
50
- kind: "text" | "icon" | "slot";
51
- meaning: string;
52
- figma: null | import("../../../generated/types/api.js").Figma;
53
- } | {
54
50
  type: "variant" | "boolean" | "text" | "number";
55
51
  values?: string | string[];
56
52
  meaning: string;
57
53
  figma: null | import("../../../generated/types/api.js").Figma;
58
54
  proposal?: boolean;
55
+ } | {
56
+ kind: "text" | "icon" | "slot";
57
+ meaning: string;
58
+ figma: null | import("../../../generated/types/api.js").Figma;
59
59
  } | null;
60
60
  used: import("../../lib/api.mjs").PropRow[];
61
61
  aspects?: undefined;
@@ -52,7 +52,7 @@ declare const _default: {
52
52
  next?: undefined;
53
53
  data?: undefined;
54
54
  } | {
55
- exitCode: 0 | 1 | 2;
55
+ exitCode: 0 | 2 | 1;
56
56
  errors: {
57
57
  id: string;
58
58
  file?: string | null;
@@ -58,7 +58,7 @@ declare const _default: {
58
58
  };
59
59
  codexSubdirectoryLauncher: boolean | null;
60
60
  codexSubdirectoryAdapterMatches: boolean | null;
61
- copilotRepositoryHookLocation: "unknown" | "nested" | "repository-root" | null;
61
+ copilotRepositoryHookLocation: "repository-root" | "nested" | "unknown" | null;
62
62
  claude: string;
63
63
  contextBudget: {
64
64
  bytes: number;
@@ -13,7 +13,7 @@ declare const _default: {
13
13
  mutates: false;
14
14
  project: false;
15
15
  dryRun: false;
16
- run({ args, out }: Pick<CommandContext, "root" | "args" | "options" | "json" | "out">): {
16
+ run({ args, out, human, details }: Pick<CommandContext, "root" | "args" | "options" | "json" | "out" | "human" | "details">): {
17
17
  data: {
18
18
  command: {
19
19
  subcommands?: import("../types.mjs").SubcommandInfo[] | undefined;
@@ -1,5 +1,6 @@
1
1
  import { commands, find, GROUPS, subcommandsOf } from '../registry.mjs';
2
2
  import { usage, GLOBAL_OPTIONS } from '../run.mjs';
3
+ import { DOCS_URL, presentation } from '../presentation.mjs';
3
4
  // The list shows each summary's first sentence; agents call it often, `help <command>` has the rest (SB-0114).
4
5
  const brief = (s) => { const [first = ''] = s.split(/(?<=\.)\s/); return first.length <= 90 ? first : `${first.slice(0, first.lastIndexOf(' ', 88))} …`; };
5
6
  const describe = (c) => ({ name: c.name, group: c.group, summary: c.summary, usage: usage(c), args: c.args, options: c.options, examples: c.examples, mutates: c.mutates, dryRun: c.dryRun, ...(c.subcommands ? { subcommands: subcommandsOf(c) } : {}) });
@@ -14,18 +15,33 @@ export default {
14
15
  project: false,
15
16
  dryRun: false,
16
17
  // Narrower than CommandContext: dispatch runs it for --help with no dry-run or checks.
17
- run({ args, out }) {
18
+ run({ args, out, human, details }) {
19
+ const ui = presentation(Boolean(human));
18
20
  if (args[0]) {
19
21
  const c = find(args[0]);
20
22
  if (!c)
21
23
  throw Object.assign(new Error(`Unknown command "${args[0]}".`), { fix: 'Run sketchbook help to list commands.' });
24
+ if (human && !details) {
25
+ out(`${ui.section(c.name)} ${c.mutates ? 'Changes files' : 'Read-only'}\n\n${c.summary}`);
26
+ if (c.args.length) {
27
+ out('\nArguments:');
28
+ for (const a of c.args)
29
+ out(` ${a.name} ${a.description}${a.required ? '' : ' (optional)'}`);
30
+ }
31
+ if (c.subcommands)
32
+ out(`\nSubcommands: ${subcommandsOf(c).map((sc) => sc.name).join(' · ')}`);
33
+ if (c.examples.length)
34
+ out(`\nTry: ${c.examples[0]}`);
35
+ out(`\n${ui.dim('Explore')} sketchbook help ${c.name} --details\nDocumentation ${DOCS_URL}`);
36
+ return { data: { command: describe(c) } };
37
+ }
22
38
  out(`${usage(c)}\n\n${c.summary}${c.mutates ? ' Changes files.' : ' Read-only.'}`);
23
39
  if (c.args.length) {
24
40
  out('\nArguments:');
25
41
  for (const a of c.args)
26
42
  out(` ${a.name.padEnd(16)} ${a.description}${a.required ? '' : ' (optional)'}`);
27
43
  }
28
- const opts = { ...c.options, ...(c.dryRun ? { 'dry-run': GLOBAL_OPTIONS['dry-run'] } : {}), json: GLOBAL_OPTIONS.json };
44
+ const opts = { ...c.options, ...(c.dryRun ? { 'dry-run': GLOBAL_OPTIONS['dry-run'] } : {}), json: GLOBAL_OPTIONS.json, details: GLOBAL_OPTIONS.details };
29
45
  out('\nOptions:');
30
46
  for (const [k, o] of Object.entries(opts))
31
47
  out(` --${k.padEnd(14)} ${o.description}`);
@@ -37,8 +53,19 @@ export default {
37
53
  out('\nExamples:');
38
54
  for (const e of c.examples)
39
55
  out(` ${e}`);
56
+ out(`\nDocumentation: ${DOCS_URL}`);
40
57
  return { data: { command: describe(c) } };
41
58
  }
59
+ if (human && !details) {
60
+ out('Your design system, from the terminal.\n');
61
+ for (const [g, label] of Object.entries(GROUPS)) {
62
+ const list = commands().filter((c) => c.group === g);
63
+ if (list.length)
64
+ out(`${ui.section(label)}\n ${list.map((c) => c.name).join(' · ')}\n`);
65
+ }
66
+ out(`${ui.dim('Explore')} sketchbook help <command> · sketchbook help --details\nDocumentation ${DOCS_URL}`);
67
+ return { data: { commands: commands().map(describe) } };
68
+ }
42
69
  out('sketchbook <command> [arguments] [--json] [--dry-run]\n');
43
70
  for (const [g, label] of Object.entries(GROUPS)) {
44
71
  const list = commands().filter((c) => c.group === g);
@@ -48,7 +75,7 @@ export default {
48
75
  for (const c of list)
49
76
  out(` ${c.name.padEnd(9)} ${brief(c.summary)}`);
50
77
  }
51
- out('\nsketchbook help <command> for details. Every command accepts --json (envelope: ok, command, changed, warnings, errors, next).');
78
+ out(`\nsketchbook help <command> for details. Every command accepts --json (envelope: ok, command, changed, warnings, errors, next).\nDocumentation: ${DOCS_URL}`);
52
79
  return { data: { commands: commands().map(describe) } };
53
80
  },
54
81
  };
@@ -17,7 +17,7 @@ declare const _default: {
17
17
  mutates: false;
18
18
  project: false;
19
19
  dryRun: false;
20
- run({ root, options, out }: import("../types.mjs").CommandContext<{
20
+ run({ root, options, out, human, details }: import("../types.mjs").CommandContext<{
21
21
  installed: {
22
22
  type: "boolean";
23
23
  description: string;
@@ -1,4 +1,5 @@
1
1
  import { catalogIndex, manifestOf, installedComponents, kitIndex, kitInstalled, requiresOf } from '../../commands/catalog.mjs';
2
+ import { presentation } from '../presentation.mjs';
2
3
  const options = {
3
4
  installed: { type: 'boolean', description: 'Only installed components (including ones the team made)' },
4
5
  available: { type: 'boolean', description: 'Only catalog components not installed yet' },
@@ -13,7 +14,7 @@ export default {
13
14
  mutates: false,
14
15
  project: false,
15
16
  dryRun: false,
16
- run({ root, options, out }) {
17
+ run({ root, options, out, human, details }) {
17
18
  const index = catalogIndex(root);
18
19
  const present = installedComponents(root);
19
20
  let rows = [...new Set([...index.components, ...present])].sort().map((name) => {
@@ -24,8 +25,13 @@ export default {
24
25
  rows = rows.filter((r) => r.installed);
25
26
  if (options.available)
26
27
  rows = rows.filter((r) => !r.installed && r.catalog);
27
- for (const r of rows)
28
+ const visible = human && !details ? rows.slice(0, 10) : rows;
29
+ if (human)
30
+ out(`${presentation(true).section('Components')} ${rows.length} total · ${rows.filter((r) => r.installed).length} installed\n`);
31
+ for (const r of visible)
28
32
  out(`${r.installed ? '*' : ' '} ${r.name.padEnd(16)} ${r.catalog ? r.status : 'team-made'}${r.requires.length ? ` needs ${r.requires.join(', ')}` : ''}`);
33
+ if (visible.length < rows.length)
34
+ out(` … ${rows.length - visible.length} more. Use sketchbook list --details to see all.`);
29
35
  const kits = kitIndex(root).map((k) => ({ id: k.id, title: k.title, installed: kitInstalled(root, k), components: k.components }));
30
36
  if (!options.installed && !options.available && kits.length) {
31
37
  out('\nKits:');
@@ -24,7 +24,7 @@ declare const status: {
24
24
  examples: string[];
25
25
  mutates: false;
26
26
  dryRun: false;
27
- run({ root, out }: Pick<CommandContext, "root" | "args" | "options" | "out">): Promise<{
27
+ run({ root, out, human }: Pick<CommandContext, "root" | "args" | "options" | "out" | "human">): Promise<{
28
28
  data: {
29
29
  prefix: string;
30
30
  brand: {
@@ -8,6 +8,7 @@ import { tokenPayload } from '../../lib/design/tokens.mjs';
8
8
  import { contractHash, mdOf } from '../../lib/design/components.mjs';
9
9
  import { loadContracts } from '../../lib/tokens.mjs';
10
10
  import { parseJson, show } from '../../lib/files.mjs';
11
+ import { presentation } from '../presentation.mjs';
11
12
  const readJson = async (root, p) => parseJson(await readFile(join(root, p), 'utf8'));
12
13
  export async function designState(root, config) {
13
14
  const d = config.adapters?.design ?? {};
@@ -41,7 +42,7 @@ const status = {
41
42
  mutates: false,
42
43
  dryRun: false,
43
44
  // Narrower than CommandContext: the interactive menu runs it for its hints with no dispatch context.
44
- async run({ root, out }) {
45
+ async run({ root, out, human }) {
45
46
  const config = await readJson(root, 'harness.config.json');
46
47
  const brand = await readJson(root, 'brand.config.json');
47
48
  const registry = await readJson(root, 'spec/registry.json');
@@ -58,11 +59,19 @@ const status = {
58
59
  overrides: overrides.length,
59
60
  design,
60
61
  };
61
- out(`Prefix: ${data.prefix}`);
62
- out(`Brand: ${data.brand.name} (primary ${data.brand.primary}, font ${data.brand.font}, modes ${data.brand.modes.join(', ')}, spacing ${show(data.brand.spacingBase)}px, radius ${data.brand.radiusLg}px, contrast ${data.brand.contrast})`);
63
- out(`Components: ${data.components.total} (${Object.entries(byStatus).map(([s, n]) => `${n} ${s}`).join(', ')})`);
64
- out(`Overrides: ${data.overrides}${data.overrides ? ' (spec/tokens/overrides.json)' : ''}`);
65
- out(`Design: ${design.tool ?? 'none'}${design.tool ? `, tokens ${design.tokens}, ${design.components.synced} component(s) synced${design.components.stale.length ? `, stale: ${design.components.stale.join(', ')}` : ''}${design.patterns.total ? `, ${design.patterns.checked} of ${design.patterns.total} pattern docs checked` : ''}` : ''}`);
62
+ if (human) {
63
+ const ui = presentation(true);
64
+ out(`${ui.section('Overview')}\n ${data.brand.name} · ${data.prefix} · ${data.components.total} components\n`);
65
+ out(`${ui.section('Brand')}\n Primary ${data.brand.primary} · ${data.brand.font} · ${data.brand.modes.join(' / ')}\n Spacing ${show(data.brand.spacingBase)}px · Radius ${data.brand.radiusLg}px · ${data.brand.contrast}\n`);
66
+ out(`${ui.section('Health')}\n ${Object.entries(byStatus).map(([s, n]) => `${n} ${s}`).join(' · ')} · ${data.overrides} overrides\n Design: ${design.tool ?? 'none'}${design.tool ? ` · tokens ${design.tokens} · ${design.components.synced} synced${design.components.stale.length ? ` · stale: ${design.components.stale.join(', ')}` : ''}${design.patterns.total ? ` · ${design.patterns.checked}/${design.patterns.total} pattern docs checked` : ''}` : ''}`);
67
+ }
68
+ else {
69
+ out(`Prefix: ${data.prefix}`);
70
+ out(`Brand: ${data.brand.name} (primary ${data.brand.primary}, font ${data.brand.font}, modes ${data.brand.modes.join(', ')}, spacing ${show(data.brand.spacingBase)}px, radius ${data.brand.radiusLg}px, contrast ${data.brand.contrast})`);
71
+ out(`Components: ${data.components.total} (${Object.entries(byStatus).map(([s, n]) => `${n} ${s}`).join(', ')})`);
72
+ out(`Overrides: ${data.overrides}${data.overrides ? ' (spec/tokens/overrides.json)' : ''}`);
73
+ out(`Design: ${design.tool ?? 'none'}${design.tool ? `, tokens ${design.tokens}, ${design.components.synced} component(s) synced${design.components.stale.length ? `, stale: ${design.components.stale.join(', ')}` : ''}${design.patterns.total ? `, ${design.patterns.checked} of ${design.patterns.total} pattern docs checked` : ''}` : ''}`);
74
+ }
66
75
  const next = design.tokens === 'changed since last sync' || design.components.stale.length ? 'sketchbook sync tokens (or components <names>)' : 'sketchbook check';
67
76
  return { data, next };
68
77
  },
@@ -14,7 +14,8 @@ export function cliDocs() {
14
14
  '',
15
15
  '## Conventions',
16
16
  '',
17
- '- Bare `sketchbook` in a terminal opens an interactive menu built from this registry: pick a group and a command, answer prompts (current values shown), see the dry run, then confirm. Piped input or `--json` prints help instead.',
17
+ '- Bare `sketchbook` in a terminal opens an interactive menu built from this registry: enter a number to pick a group and command, provide arguments, and optionally review settings. Mutating commands show a dry run where supported; type y and press Enter to confirm, or press Enter to cancel. Piped input or `--json` prints help instead.',
18
+ '- `--details` shows full human-readable output where a terminal view is abbreviated.',
18
19
  '- `--json` on every command prints one envelope: `{ ok, command, changed[], warnings[], errors[{file, msg, fix}], next, data? }`.',
19
20
  '- Exit codes: 0 ok, 1 failed, 2 ok with flags (for example overrides kept in spec/tokens/overrides.json).',
20
21
  '- Read-only commands never write. Mutating commands say what they change; those marked "dry run" accept `--dry-run`.',
@@ -5,6 +5,7 @@
5
5
  import { createInterface } from 'node:readline';
6
6
  import { commands, GROUPS } from './registry.mjs';
7
7
  import { dispatch } from './run.mjs';
8
+ import { DOCS_URL, presentation } from './presentation.mjs';
8
9
  // Current values worth offering as hints, by option or argument name.
9
10
  export async function currentValues(root) {
10
11
  const status = (await import('./commands/status.mjs')).default;
@@ -29,45 +30,89 @@ function lineReader(input) {
29
30
  }
30
31
  export async function interactive({ root = process.cwd(), input = process.stdin, output = process.stdout, run = dispatch } = {}) {
31
32
  const write = (s) => output.write(s);
33
+ const ui = presentation(Boolean(output.isTTY));
32
34
  const lines = lineReader(input);
33
35
  const ask = async (q) => { write(q); const a = await lines.next(); if (a === null)
34
36
  throw new Quit(); return a.trim(); };
37
+ const heading = (title) => ui.enabled ? ui.section(title) : title;
38
+ const note = (value) => ui.enabled ? ui.dim(value) : value;
39
+ const line = (value) => ui.enabled ? ui.line(value) : value;
40
+ const brief = (value) => value.length > 130 ? `${value.slice(0, 127).replace(/\s+\S*$/, '')}…` : value;
35
41
  const choose = async (title, items, back) => {
36
- write(`\n${title}\n`);
37
- items.forEach((it, i) => write(` ${String(i + 1).padStart(2)}) ${it.label}\n`));
38
- write(` ${back}\n`);
42
+ write(`\n${heading(title)}\n\n`);
43
+ items.forEach((it, i) => {
44
+ const number = String(i + 1).padStart(2);
45
+ if (it.description) {
46
+ write(` ${ui.accent(number)} ${ui.bold(it.label)}\n`);
47
+ write(line(` ${it.description}`) + '\n\n');
48
+ }
49
+ else
50
+ write(line(` ${number} ${it.label}`) + '\n');
51
+ });
52
+ write(`\n ${note(back)}\n`);
39
53
  for (;;) {
40
- const a = await ask('> ');
54
+ const a = (await ask(' Enter a number and press Enter: ')).toLowerCase();
41
55
  if (a === 'q' || a === 'b')
42
56
  return a;
43
57
  const n = Number(a);
44
- const item = Number.isInteger(n) && n >= 1 ? items[n - 1] : undefined;
58
+ const item = a && Number.isInteger(n) && n >= 1 ? items[n - 1] : undefined;
45
59
  if (item)
46
60
  return item.value;
47
- write(`Type 1-${items.length}, ${back.split(')')[0]}.\n`);
61
+ write(` Type 1-${items.length}, ${back.split(')')[0]}.\n`);
62
+ }
63
+ };
64
+ // Enter is always the safe default; unexpected input must never silently confirm or cancel.
65
+ const confirm = async (question, yesLabel, noLabel) => {
66
+ write(`\n${heading(question)}\n y + Enter: ${yesLabel}\n Enter or n + Enter: ${noLabel}\n`);
67
+ for (;;) {
68
+ const answer = (await ask(' Your choice [y/N]: ')).toLowerCase();
69
+ if (answer === 'y' || answer === 'yes')
70
+ return true;
71
+ if (answer === '' || answer === 'n' || answer === 'no')
72
+ return false;
73
+ write(' Please type y or n, then press Enter.\n');
48
74
  }
49
75
  };
50
76
  let last = 0;
51
77
  try {
52
- write('sketchbook: pick what to do (q quits). Every choice runs a normal sketchbook command, shown before it runs.\n');
78
+ if (ui.enabled)
79
+ write(ui.header('explore'));
80
+ write(`${line(' Explore your design system, one step at a time.')}\n Choose a number and press Enter. Type q and press Enter to quit.\n`);
53
81
  for (;;) {
54
82
  const groups = Object.entries(GROUPS).map(([g, label]) => ({ g, label, list: commands().filter((c) => c.group === g) })).filter((x) => x.list.length);
55
- const group = await choose('Groups:', groups.map((x) => ({ label: `${x.label.padEnd(12)} ${x.list.map((c) => c.name).join(', ')}`, value: x })), 'q) quit');
83
+ const group = await choose('Groups:', groups.map((x) => ({ label: `${x.label.padEnd(12)} ${x.list.length} ${x.list.length === 1 ? 'command' : 'commands'}`, value: x })), 'q) quit');
56
84
  if (group === 'q')
57
85
  break;
58
86
  if (group === 'b')
59
87
  continue;
60
- const cmd = await choose(`${group.label}:`, group.list.map((c) => ({ label: `${c.name.padEnd(9)} ${c.summary}`, value: c })), 'b) back q) quit');
88
+ const cmd = await choose(`${group.label}:`, group.list.map((c) => ({ label: c.name, description: brief(c.summary.split(/(?<=\.)\s/)[0] ?? c.summary), value: c })), 'b) back q) quit');
61
89
  if (cmd === 'q')
62
90
  break;
63
91
  if (cmd === 'b')
64
92
  continue;
93
+ write(`\n${heading(cmd.name)}\n ${line(brief(cmd.summary))}\n ${note(`More: sketchbook help ${cmd.name} --details`)}\n ${note(cmd.mutates ? (cmd.dryRun ? 'Changes files · a preview runs before confirmation' : 'Changes files · confirmation required') : 'Read-only · no files changed')}\n`);
94
+ write(` Documentation: ${DOCS_URL}\n`);
65
95
  const current = await currentValues(root);
66
96
  const argv = [cmd.name];
67
97
  for (const a of cmd.args) {
98
+ const selected = cmd.subcommands?.find((sub) => typeof sub !== 'string' && sub.name === argv[1]);
99
+ const sub = typeof selected === 'object' ? selected : undefined;
100
+ const remainingUsage = sub?.usage.slice(`sketchbook ${cmd.name} ${sub.name}`.length).trim();
101
+ const required = a.required || Boolean(a.variadic && remainingUsage?.startsWith('<'));
102
+ // Only suggest literal examples: quoted arguments and flags need shell parsing, which this prompt does not perform.
103
+ const candidates = [...(sub?.examples ?? []), ...cmd.examples];
104
+ const example = candidates.map((e) => e.split(/\s+/)).find((parts) => parts[0] === 'sketchbook' && parts[1] === cmd.name &&
105
+ argv.slice(1).every((arg, i) => parts[i + 2] === arg) &&
106
+ parts.length > argv.length + 1 && parts.slice(argv.length + 1).every((part) => /^[a-zA-Z0-9_./:=@+-]+$/.test(part)));
107
+ const values = example?.slice(argv.length + 1);
108
+ const hint = values?.length ? (a.variadic ? values.join(' ') : values[0]) : undefined;
68
109
  for (;;) {
69
- const v = await ask(`${a.name}${a.required ? '' : ' (optional)'}: ${a.description}\n> `);
70
- if (!v && a.required) {
110
+ const description = a.variadic && sub && remainingUsage ? `Arguments for ${sub.name}: ${remainingUsage}` : `${a.name}: ${brief(a.description)}`;
111
+ write(`\n${line(` ${description}`)}\n`);
112
+ if (hint)
113
+ write(`${line(` Example to type: ${hint}`)}\n`);
114
+ const v = await ask(` ${required ? 'Type a value and press Enter' : 'Type a value, or press Enter to skip'}: `);
115
+ if (!v && required) {
71
116
  write('Required.\n');
72
117
  continue;
73
118
  }
@@ -76,37 +121,41 @@ export async function interactive({ root = process.cwd(), input = process.stdin,
76
121
  break;
77
122
  }
78
123
  }
79
- for (const [k, o] of Object.entries(cmd.options)) {
80
- const hint = current[k] !== undefined ? ` [current: ${current[k]}; Enter keeps it]` : ' [Enter skips]';
81
- if (o.type === 'boolean') {
82
- if (/^y(es)?$/i.test(await ask(`--${k}: ${o.description}? (y/N)\n> `)))
83
- argv.push(`--${k}`);
84
- continue;
124
+ const configure = Object.keys(cmd.options).length > 0 && await confirm('Configure optional settings?', 'review options', 'use defaults');
125
+ if (configure)
126
+ for (const [k, o] of Object.entries(cmd.options)) {
127
+ const hint = current[k] !== undefined ? ` [current: ${current[k]}; Enter keeps it]` : ' [Enter skips]';
128
+ if (o.type === 'boolean') {
129
+ if (await confirm(`--${k}: ${o.description}`, 'enable', 'leave off'))
130
+ argv.push(`--${k}`);
131
+ continue;
132
+ }
133
+ const example = o.value && /^(?:https?:\/\/\S+|\d+(?:\.\d+)?)$/.test(o.value) ? `\n Example to type: ${o.value}` : '';
134
+ const v = await ask(`\n --${k}: ${brief(o.description)}${hint}${example}\n Value: `);
135
+ if (v)
136
+ argv.push(`--${k}`, v);
85
137
  }
86
- const v = await ask(`--${k}: ${o.description}${hint}\n> `);
87
- if (v)
88
- argv.push(`--${k}`, v);
89
- }
90
- const shown = `sketchbook ${argv.map((x) => (/\s/.test(x) ? JSON.stringify(x) : x)).join(' ')}`;
138
+ // Display a shell-safe command for people who want to repeat it.
139
+ const shown = `sketchbook ${argv.map((x) => (/^[a-zA-Z0-9_./:=@+-]+$/.test(x) ? x : `'${x.replace(/'/g, `'\\''`)}'`)).join(' ')}`;
91
140
  if (cmd.mutates && cmd.dryRun) {
92
- write(`\nDry run: ${shown} --dry-run\n`);
93
- last = await run([...argv, '--dry-run'], { root, stdout: write, stderr: write });
141
+ write(`\n${heading('Preview · no files will be changed')}\n ${shown} --dry-run\n\n`);
142
+ last = await run([...argv, '--dry-run'], { root, stdout: write, stderr: write, human: ui.enabled });
94
143
  if (last === 1) {
95
144
  write('The dry run failed; nothing was changed.\n');
96
145
  continue;
97
146
  }
98
- if (!/^y(es)?$/i.test(await ask('Apply these changes? (y/N)\n> '))) {
99
- write('Not applied.\n');
147
+ if (!await confirm('Apply these changes?', 'apply changes', 'cancel without applying')) {
148
+ write(`\n ${ui.warning('Not applied.')} No files were changed.\n`);
100
149
  continue;
101
150
  }
102
151
  }
103
- else if (cmd.mutates && !/^y(es)?$/i.test(await ask(`Run ${shown}? It changes files. (y/N)\n> `))) {
104
- write('Not run.\n');
152
+ else if (cmd.mutates && !await confirm(`Run ${shown}? This changes files.`, 'run command', 'cancel without running')) {
153
+ write(`\n ${ui.warning('Not run.')} No files were changed.\n`);
105
154
  continue;
106
155
  }
107
- write(`\nRunning: ${shown}\n`);
108
- last = await run(argv, { root, stdout: write, stderr: write });
109
- write(`(exit ${last})\n`);
156
+ write(`\n${heading('Running')}\n Running: ${shown}\n\n`);
157
+ last = await run(argv, { root, stdout: write, stderr: write, human: ui.enabled });
158
+ write(`\n${heading(last === 0 ? ui.success('Done') : ui.warning(last === 2 ? 'Done with notices' : 'Command failed'))} ${note(`exit ${last}`)}\n`);
110
159
  }
111
160
  }
112
161
  catch (e) {
@@ -0,0 +1,13 @@
1
+ export declare const DOCS_URL = "https://sketchbook-docs.vercel.app/";
2
+ export declare function presentation(enabled: boolean, color?: boolean): {
3
+ enabled: boolean;
4
+ accent: (s: string) => string;
5
+ bold: (s: string) => string;
6
+ dim: (s: string) => string;
7
+ success: (s: string) => string;
8
+ warning: (s: string) => string;
9
+ header: (label: string) => string;
10
+ line: (value: string) => string;
11
+ section: (label: string) => string;
12
+ error: (message: string, fix?: string | null) => string;
13
+ };
@@ -0,0 +1,45 @@
1
+ export const DOCS_URL = 'https://sketchbook-docs.vercel.app/';
2
+ // Terminal-only presentation. Commands retain their plain and JSON interfaces for pipes.
3
+ export function presentation(enabled, color = enabled && !('NO_COLOR' in process.env)) {
4
+ const paint = (code, value) => color ? `\u001b[${code}m${value}\u001b[0m` : value;
5
+ const accent = (s) => paint('38;5;208', s);
6
+ const bold = (s) => paint('1', s);
7
+ const dim = (s) => paint('2', s);
8
+ const success = (s) => paint('32', s);
9
+ const warning = (s) => paint('33', s);
10
+ const wrap = (value) => {
11
+ const width = Math.max(20, process.stdout.columns || 80);
12
+ // ANSI control sequences do not occupy terminal columns.
13
+ // eslint-disable-next-line no-control-regex
14
+ const size = (s) => [...s.replace(new RegExp('\\x1b\\[[0-9;]*m', 'g'), '')].length;
15
+ return value.split('\n').flatMap((line) => {
16
+ if (size(line) <= width)
17
+ return [line];
18
+ const indent = line.match(/^\s*/)?.[0] ?? '';
19
+ const parts = line.trim().split(/\s+/);
20
+ const lines = [];
21
+ let current = indent;
22
+ for (const part of parts) {
23
+ const space = current.trim() ? ' ' : '';
24
+ if (current.trim() && size(current + space + part) > width) {
25
+ lines.push(current);
26
+ current = indent + part;
27
+ }
28
+ else
29
+ current += space + part;
30
+ }
31
+ lines.push(current);
32
+ return lines;
33
+ }).join('\n');
34
+ };
35
+ return {
36
+ enabled, accent, bold, dim, success, warning,
37
+ header: (label) => `\n${accent('◆')} ${bold('SKETCHBOOK')} ${dim(' / ' + label)}\n`,
38
+ line: (value) => wrap(value).split('\n').map((line) => {
39
+ const match = /^(\s*)([A-Za-z][A-Za-z ]{1,24}:)(.*)$/.exec(line);
40
+ return match ? `${match[1]}${bold(match[2] ?? '')}${match[3]}` : line;
41
+ }).join('\n'),
42
+ section: (label) => `${accent('▸')} ${bold(label)}`,
43
+ error: (message, fix) => wrap(`${accent('✕')} ${bold('Error')} ${message}${fix ? `\n ${dim('Next')} ${fix}` : ''}`) + '\n',
44
+ };
45
+ }
@@ -12,11 +12,16 @@ export declare const GLOBAL_OPTIONS: {
12
12
  readonly type: "boolean";
13
13
  readonly description: "Show help for the command";
14
14
  };
15
+ readonly details: {
16
+ readonly type: "boolean";
17
+ readonly description: "Show the full human-readable output";
18
+ };
15
19
  };
16
20
  export interface DispatchIO {
17
21
  root?: string;
18
22
  stdout?: (s: string) => unknown;
19
23
  stderr?: (s: string) => unknown;
24
+ human?: boolean;
20
25
  }
21
- export declare function dispatch(argv: string[], { root, stdout, stderr }?: DispatchIO): Promise<number>;
26
+ export declare function dispatch(argv: string[], { root, stdout, stderr, human }?: DispatchIO): Promise<number>;
22
27
  export declare function usage(cmd: Pick<Command, 'name' | 'args' | 'options' | 'dryRun'>): string;
@@ -8,6 +8,7 @@ import { dirname, join, resolve } from 'node:path';
8
8
  import { fileURLToPath } from 'node:url';
9
9
  import { commands, find } from './registry.mjs';
10
10
  import help from './commands/help.mjs';
11
+ import { presentation } from './presentation.mjs';
11
12
  import { runChecks } from '../checks/run.mjs';
12
13
  import { errorMessage, show } from '../lib/files.mjs';
13
14
  const HARNESS = fileURLToPath(new URL('../', import.meta.url));
@@ -15,6 +16,7 @@ export const GLOBAL_OPTIONS = {
15
16
  json: { type: 'boolean', description: 'Print one JSON envelope instead of human output' },
16
17
  'dry-run': { type: 'boolean', description: 'Show what would change without writing (mutating commands that support it)' },
17
18
  help: { type: 'boolean', description: 'Show help for the command' },
19
+ details: { type: 'boolean', description: 'Show the full human-readable output' },
18
20
  };
19
21
  const asError = (e) => ({ file: e.file ?? null, msg: e.msg ?? show(e), fix: e.fix ?? null, ...(e.token ? { token: e.token } : {}), ...(e.id ? { check: e.id } : {}) });
20
22
  // Runs the deterministic checks after a mutating command: in-process for --json, with live output otherwise.
@@ -38,15 +40,19 @@ function ancestorProject(start) {
38
40
  dir = parent;
39
41
  }
40
42
  }
41
- export async function dispatch(argv, { root = process.cwd(), stdout = (s) => process.stdout.write(s), stderr = (s) => process.stderr.write(s) } = {}) {
43
+ export async function dispatch(argv, { root = process.cwd(), stdout = (s) => process.stdout.write(s), stderr = (s) => process.stderr.write(s), human = Boolean(process.stdout.isTTY) } = {}) {
42
44
  let [name, ...rest] = argv;
43
45
  const json = argv.includes('--json');
44
46
  if (!name || name === '--help' || name === '-h' || (name === '--json' && rest.length === 0)) {
45
47
  name = 'help';
46
- rest = json ? ['--json'] : [];
48
+ rest = [...(json ? ['--json'] : []), ...(argv.includes('--details') ? ['--details'] : [])];
47
49
  }
50
+ const ui = presentation(human && !json);
51
+ const errorUi = presentation(ui.enabled, ui.enabled && Boolean(process.stderr.isTTY) && !('NO_COLOR' in process.env));
48
52
  const out = (line = '') => { if (!json)
49
- stdout(line + '\n'); };
53
+ stdout((ui.enabled ? ui.line(line) : line) + '\n'); };
54
+ if (ui.enabled)
55
+ stdout(ui.header(name));
50
56
  const finish = (cmdName, r) => {
51
57
  const errors = (r.errors ?? []).map(asError);
52
58
  const exitCode = r.exitCode ?? (errors.length ? 1 : 0);
@@ -55,13 +61,13 @@ export async function dispatch(argv, { root = process.cwd(), stdout = (s) => pro
55
61
  stdout(JSON.stringify(envelope, null, 2) + '\n');
56
62
  else
57
63
  for (const e of errors)
58
- stderr(`${e.msg}${e.fix ? `\n fix: ${e.fix}` : ''}\n`);
64
+ stderr(ui.enabled ? errorUi.error(e.msg, e.fix) : `${e.msg}${e.fix ? `\n fix: ${e.fix}` : ''}\n`);
59
65
  return exitCode;
60
66
  };
61
67
  const fail = (cmdName, msg, fix, file = null) => finish(cmdName, { errors: [{ file, msg, fix }], exitCode: 1 });
62
68
  const cmd = find(name);
63
69
  if (!cmd)
64
- return fail(name, `Unknown command "${name}". Commands: ${commands().map((c) => c.name).join(', ')}.`, 'Run sketchbook help to list commands.');
70
+ return fail(name, ui.enabled ? `Unknown command "${name}".` : `Unknown command "${name}". Commands: ${commands().map((c) => c.name).join(', ')}.`, 'Run sketchbook help to list commands.');
65
71
  // Commands that take CSS variables as arguments (--sb-color-primary) keep them as positionals, not options.
66
72
  const known = new Set([...Object.keys(GLOBAL_OPTIONS), ...Object.keys(cmd.options)]);
67
73
  const MARK = '\u0000';
@@ -79,7 +85,7 @@ export async function dispatch(argv, { root = process.cwd(), stdout = (s) => pro
79
85
  const values = parsed.values;
80
86
  const positionals = parsed.positionals.map((p) => (p.startsWith(MARK) ? p.slice(1) : p));
81
87
  if (values.help)
82
- return finish(name, help.run({ root, args: [name], options: {}, json, out }));
88
+ return finish(name, help.run({ root, args: [name], options: {}, json, out, human: ui.enabled, details: Boolean(values.details) }));
83
89
  if (cmd.project !== false && !existsSync(join(root, 'harness.config.json'))) {
84
90
  const ancestor = ancestorProject(root);
85
91
  return fail(name, `Not a Sketchbook project (no harness.config.json in ${root}).`, ancestor
@@ -92,7 +98,7 @@ export async function dispatch(argv, { root = process.cwd(), stdout = (s) => pro
92
98
  if (positionals.length < required)
93
99
  return fail(name, `Usage: ${usage(cmd)}`, `Run sketchbook help ${name}.`);
94
100
  try {
95
- const r = await cmd.run({ root, args: positionals, options: values, json, dryRun: Boolean(values['dry-run']), out, checks: () => checks(root, json) });
101
+ const r = await cmd.run({ root, args: positionals, options: values, json, dryRun: Boolean(values['dry-run']), human: ui.enabled, details: Boolean(values.details), out, checks: () => checks(root, json) });
96
102
  return finish(name, r);
97
103
  }
98
104
  catch (e) {
@@ -50,6 +50,8 @@ export interface CommandContext<S extends OptionSpecs = OptionSpecs> {
50
50
  options: OptionValues<S>;
51
51
  json: boolean;
52
52
  dryRun: boolean;
53
+ human?: boolean;
54
+ details?: boolean;
53
55
  out: (line?: string) => void;
54
56
  checks: () => Promise<ChecksSummary>;
55
57
  }
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@usesketchbook/cli",
3
- "version": "0.1.2",
3
+ "version": "0.2.1",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@usesketchbook/cli",
9
- "version": "0.1.2",
9
+ "version": "0.2.1",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "lucide-static": "1.76.0",
@@ -10,6 +10,7 @@ import { Readable } from 'node:stream';
10
10
  import { commands, GROUPS } from '../cli/registry.mjs';
11
11
  import { cliDocs } from '../cli/docs.mjs';
12
12
  import { knownCommands } from '../cli/known.mjs';
13
+ import { dispatch } from '../cli/run.mjs';
13
14
  import { interactive, wantsInteractive } from '../cli/interactive.mjs';
14
15
  import { parseJson } from '../lib/files.mjs';
15
16
  const CLI = join(ROOT, 'harness/cli.mjs');
@@ -129,12 +130,12 @@ test('L8 known-commands.json is generated from the registry plus planned-command
129
130
  await rm(dir, { recursive: true });
130
131
  });
131
132
  // Scripted stdin for the interactive menu; `run` records argv instead of running commands unless real is set.
132
- async function menu(lines, { real = false, root } = {}) {
133
+ async function menu(lines, { real = false, failDryRun = false, root } = {}) {
133
134
  root ??= await reference();
134
135
  const calls = [];
135
136
  let text = '';
136
137
  const output = { write: (s) => { text += s; } };
137
- const run = real ? undefined : (argv, { stdout }) => { calls.push(argv); must(stdout, 'dispatch stdout')(`(ran ${argv.join(' ')})\n`); return Promise.resolve(0); };
138
+ const run = real ? undefined : (argv, { stdout }) => { calls.push(argv); must(stdout, 'dispatch stdout')(`(ran ${argv.join(' ')})\n`); return Promise.resolve(failDryRun && argv.includes('--dry-run') ? 1 : 0); };
138
139
  const code = await interactive({ root, input: Readable.from(lines.map((l) => `${l}\n`)), output, ...(run ? { run } : {}) });
139
140
  return { calls, text, code };
140
141
  }
@@ -153,18 +154,40 @@ test('L9 interactive: groups -> command -> read-only commands run at once', asyn
153
154
  test('L10 interactive: prompts with current values, dry run first, applies only on yes', async () => {
154
155
  const opts = Object.keys(must(commands().find((c) => c.name === 'init'), 'the init command').options);
155
156
  const answers = opts.map((k) => (k === 'font' ? 'Inter' : ''));
156
- const no = await menu([groupIndex('project'), commandIndex('init'), ...answers, 'n', 'q']);
157
+ const no = await menu([groupIndex('project'), commandIndex('init'), 'y', ...answers, 'n', 'q']);
157
158
  assert.deepEqual(no.calls, [['init', '--font', 'Inter', '--dry-run']]);
158
159
  assert.match(no.text, /--primary: .*\[current: /);
159
160
  assert.match(no.text, /Not applied/);
160
- const yes = await menu([groupIndex('design'), commandIndex('sync'), 'tokens', '', 'n', 'n', '', '', '', 'y', 'q']);
161
+ const yes = await menu([groupIndex('design'), commandIndex('sync'), 'tokens', '', '', 'y', 'q']);
161
162
  assert.deepEqual(yes.calls, [['sync', 'tokens', '--dry-run'], ['sync', 'tokens']]);
162
163
  const required = await menu([groupIndex('project'), commandIndex('prefix'), '', 'acme', 'n']);
163
164
  assert.match(required.text, /Required\./);
164
165
  assert.deepEqual(required.calls, [['prefix', 'acme', '--dry-run']]);
166
+ const choices = await menu([groupIndex('tokens'), 'b', 'q']);
167
+ assert.match(choices.text, /1 {2}tokens\n {6}Change foundations/);
168
+ assert.match(choices.text, /2 {2}presets\n {6}List the standards catalog/);
165
169
  const bad = await menu(['9', 'x', 'b', 'q']);
166
170
  assert.match(bad.text, /Type 1-/);
167
171
  assert.deepEqual(bad.calls, []);
172
+ const defaultCancel = await menu([groupIndex('design'), commandIndex('sync'), 'tokens', '', '', 'maybe', '', 'q']);
173
+ assert.deepEqual(defaultCancel.calls, [['sync', 'tokens', '--dry-run']]);
174
+ assert.match(defaultCancel.text, /Please type y or n/);
175
+ assert.match(defaultCancel.text, /Enter or n \+ Enter: cancel without applying/);
176
+ assert.match(defaultCancel.text, /Not applied/);
177
+ const apply = await menu([groupIndex('design'), commandIndex('sync'), 'tokens', '', '', 'y', 'q']);
178
+ assert.deepEqual(apply.calls, [['sync', 'tokens', '--dry-run'], ['sync', 'tokens']]);
179
+ const guided = await menu([groupIndex('tokens'), commandIndex('tokens'), 'set', '', 'typography.family Inter', '', 'n', 'q']);
180
+ assert.match(guided.text, /Arguments for set: <key> <value>/);
181
+ assert.match(guided.text, /Example to type: typography\.family Inter/);
182
+ assert.match(guided.text, /Required\./);
183
+ assert.match(guided.text, /Documentation: https:\/\/sketchbook-docs\.vercel\.app\//);
184
+ assert.deepEqual(guided.calls, [['tokens', 'set', 'typography.family', 'Inter', '--dry-run']]);
185
+ const quoted = await menu([groupIndex('tokens'), commandIndex('tokens'), 'set', 'color.primary #336699', '', '', 'q']);
186
+ assert.match(quoted.text, /sketchbook tokens set color\.primary '#336699' --dry-run/);
187
+ const failed = await menu([groupIndex('design'), commandIndex('sync'), 'tokens', '', '', 'q'], { failDryRun: true });
188
+ assert.deepEqual(failed.calls, [['sync', 'tokens', '--dry-run']]);
189
+ assert.match(failed.text, /dry run failed/);
190
+ assert.doesNotMatch(failed.text, /Apply these changes/);
168
191
  });
169
192
  test('L11 bare sketchbook without a terminal (or with --json) prints help instead of the menu', async () => {
170
193
  assert.equal(wantsInteractive([], { stdin: { isTTY: true }, stdout: { isTTY: true } }), true);
@@ -234,3 +257,28 @@ test('L13 generate rebuilds every generated output from the spec (what a project
234
257
  assert.deepEqual((await runChecks(dir, { only: ['G1'] })).results[0]?.errors, []);
235
258
  await rm(dir, { recursive: true });
236
259
  });
260
+ test('terminal presentation abbreviates lists without changing pipes or JSON', async () => {
261
+ const dir = await reference();
262
+ const run = async (args, human) => {
263
+ let out = '';
264
+ let err = '';
265
+ const code = await dispatch(args, { root: dir, human, stdout: (s) => { out += s; }, stderr: (s) => { err += s; } });
266
+ return { code, out, err };
267
+ };
268
+ const help = await run(['help'], true);
269
+ assert.match(help.out, /SKETCHBOOK/);
270
+ assert.match(help.out, /help --details/);
271
+ const brief = await run(['list'], true);
272
+ const full = await run(['list', '--details'], true);
273
+ assert.match(brief.out, /more\. Use sketchbook list --details/);
274
+ assert.doesNotMatch(full.out, /more\. Use sketchbook list --details/);
275
+ const plain = await run(['list'], false);
276
+ assert.equal(plain.out.includes('\x1b['), false);
277
+ assert.doesNotMatch(plain.out, /SKETCHBOOK/);
278
+ const json = await run(['list', '--json'], true);
279
+ envelope(parseJson(json.out), 'list');
280
+ const error = await run(['not-a-command'], true);
281
+ assert.equal(error.code, 1);
282
+ assert.match(error.err, /Unknown command/);
283
+ assert.match(error.err, /Next/);
284
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@usesketchbook/cli",
3
- "version": "0.1.2",
3
+ "version": "0.2.1",
4
4
  "description": "Provider-neutral harness for building an accessible, white-label Web Components design system from a spec.",
5
5
  "type": "module",
6
6
  "publishConfig": {