@histoire/cli 0.0.0-stage → 1.0.0-beta.3

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.
Files changed (175) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +8 -2
  3. package/dist/cli.d.ts +9 -0
  4. package/dist/cli.js +88 -0
  5. package/dist/commands/dev.d.ts +44 -0
  6. package/dist/commands/dev.js +117 -0
  7. package/dist/commands/host.d.ts +66 -0
  8. package/dist/commands/host.js +1 -0
  9. package/dist/commands/screenshot-setup-args.d.ts +4 -0
  10. package/dist/commands/screenshot-setup-args.js +35 -0
  11. package/dist/commands/signal-guard.d.ts +29 -0
  12. package/dist/commands/signal-guard.js +52 -0
  13. package/dist/index.d.ts +2 -0
  14. package/dist/index.js +1 -0
  15. package/dist/terminal/actions.d.ts +51 -0
  16. package/dist/terminal/actions.js +60 -0
  17. package/dist/terminal/banner.d.ts +19 -0
  18. package/dist/terminal/banner.js +48 -0
  19. package/dist/terminal/bridge.d.ts +58 -0
  20. package/dist/terminal/bridge.js +103 -0
  21. package/dist/terminal/clipboard.d.ts +46 -0
  22. package/dist/terminal/clipboard.js +85 -0
  23. package/dist/terminal/diagnostics/attach.d.ts +9 -0
  24. package/dist/terminal/diagnostics/attach.js +46 -0
  25. package/dist/terminal/diagnostics/client.d.ts +12 -0
  26. package/dist/terminal/diagnostics/client.js +19 -0
  27. package/dist/terminal/diagnostics/lines.d.ts +17 -0
  28. package/dist/terminal/diagnostics/lines.js +61 -0
  29. package/dist/terminal/dispatch.d.ts +28 -0
  30. package/dist/terminal/dispatch.js +52 -0
  31. package/dist/terminal/feedback.d.ts +14 -0
  32. package/dist/terminal/feedback.js +27 -0
  33. package/dist/terminal/history/bounded.d.ts +37 -0
  34. package/dist/terminal/history/bounded.js +54 -0
  35. package/dist/terminal/host-extras.d.ts +14 -0
  36. package/dist/terminal/host-extras.js +26 -0
  37. package/dist/terminal/info/client.d.ts +20 -0
  38. package/dist/terminal/info/client.js +25 -0
  39. package/dist/terminal/info/generation-client.d.ts +33 -0
  40. package/dist/terminal/info/generation-client.js +32 -0
  41. package/dist/terminal/info/lines.d.ts +19 -0
  42. package/dist/terminal/info/lines.js +33 -0
  43. package/dist/terminal/info/network.d.ts +17 -0
  44. package/dist/terminal/info/network.js +48 -0
  45. package/dist/terminal/info/qr.d.ts +7 -0
  46. package/dist/terminal/info/qr.js +14 -0
  47. package/dist/terminal/keys.d.ts +44 -0
  48. package/dist/terminal/keys.js +60 -0
  49. package/dist/terminal/logs/browser-options.d.ts +9 -0
  50. package/dist/terminal/logs/browser-options.js +19 -0
  51. package/dist/terminal/navigation/browser.d.ts +69 -0
  52. package/dist/terminal/navigation/browser.js +193 -0
  53. package/dist/terminal/navigation/list.d.ts +53 -0
  54. package/dist/terminal/navigation/list.js +104 -0
  55. package/dist/terminal/navigation/search.d.ts +22 -0
  56. package/dist/terminal/navigation/search.js +44 -0
  57. package/dist/terminal/output/decoder.d.ts +24 -0
  58. package/dist/terminal/output/decoder.js +63 -0
  59. package/dist/terminal/output/history.d.ts +43 -0
  60. package/dist/terminal/output/history.js +21 -0
  61. package/dist/terminal/output/pipeline.d.ts +33 -0
  62. package/dist/terminal/output/pipeline.js +59 -0
  63. package/dist/terminal/output/sanitize.d.ts +32 -0
  64. package/dist/terminal/output/sanitize.js +142 -0
  65. package/dist/terminal/panel-model.d.ts +20 -0
  66. package/dist/terminal/panel-model.js +38 -0
  67. package/dist/terminal/panel.d.ts +30 -0
  68. package/dist/terminal/panel.js +53 -0
  69. package/dist/terminal/plain.d.ts +29 -0
  70. package/dist/terminal/plain.js +68 -0
  71. package/dist/terminal/progress/format.d.ts +28 -0
  72. package/dist/terminal/progress/format.js +77 -0
  73. package/dist/terminal/progress/state.d.ts +71 -0
  74. package/dist/terminal/progress/state.js +150 -0
  75. package/dist/terminal/protocol/catalog.d.ts +143 -0
  76. package/dist/terminal/protocol/catalog.js +61 -0
  77. package/dist/terminal/protocol/core.d.ts +117 -0
  78. package/dist/terminal/protocol/core.js +98 -0
  79. package/dist/terminal/protocol/diagnostics.d.ts +79 -0
  80. package/dist/terminal/protocol/diagnostics.js +31 -0
  81. package/dist/terminal/protocol/index.d.ts +22 -0
  82. package/dist/terminal/protocol/index.js +1 -0
  83. package/dist/terminal/protocol/progress.d.ts +67 -0
  84. package/dist/terminal/protocol/progress.js +52 -0
  85. package/dist/terminal/protocol/requests.d.ts +30 -0
  86. package/dist/terminal/protocol/requests.js +13 -0
  87. package/dist/terminal/protocol/session.d.ts +55 -0
  88. package/dist/terminal/protocol/session.js +28 -0
  89. package/dist/terminal/protocol/tests.d.ts +212 -0
  90. package/dist/terminal/protocol/tests.js +87 -0
  91. package/dist/terminal/protocol/watch.d.ts +60 -0
  92. package/dist/terminal/protocol/watch.js +40 -0
  93. package/dist/terminal/requests/browser-options.d.ts +8 -0
  94. package/dist/terminal/requests/browser-options.js +24 -0
  95. package/dist/terminal/requests/history.d.ts +30 -0
  96. package/dist/terminal/requests/history.js +53 -0
  97. package/dist/terminal/retained.d.ts +27 -0
  98. package/dist/terminal/retained.js +21 -0
  99. package/dist/terminal/session-types.d.ts +76 -0
  100. package/dist/terminal/session-types.js +1 -0
  101. package/dist/terminal/session.d.ts +8 -0
  102. package/dist/terminal/session.js +282 -0
  103. package/dist/terminal/shutdown.d.ts +12 -0
  104. package/dist/terminal/shutdown.js +30 -0
  105. package/dist/terminal/stories/client.d.ts +26 -0
  106. package/dist/terminal/stories/client.js +28 -0
  107. package/dist/terminal/stories/handoff.d.ts +39 -0
  108. package/dist/terminal/stories/handoff.js +40 -0
  109. package/dist/terminal/stories/paged.d.ts +70 -0
  110. package/dist/terminal/stories/paged.js +137 -0
  111. package/dist/terminal/stories/render.d.ts +39 -0
  112. package/dist/terminal/stories/render.js +94 -0
  113. package/dist/terminal/stories/state.d.ts +93 -0
  114. package/dist/terminal/stories/state.js +191 -0
  115. package/dist/terminal/stories/target.d.ts +24 -0
  116. package/dist/terminal/stories/target.js +29 -0
  117. package/dist/terminal/style.d.ts +45 -0
  118. package/dist/terminal/style.js +82 -0
  119. package/dist/terminal/support.d.ts +53 -0
  120. package/dist/terminal/support.js +66 -0
  121. package/dist/terminal/surface.d.ts +41 -0
  122. package/dist/terminal/surface.js +200 -0
  123. package/dist/terminal/tests/client.d.ts +21 -0
  124. package/dist/terminal/tests/client.js +12 -0
  125. package/dist/terminal/tests/console.d.ts +95 -0
  126. package/dist/terminal/tests/console.js +202 -0
  127. package/dist/terminal/tests/format.d.ts +18 -0
  128. package/dist/terminal/tests/format.js +55 -0
  129. package/dist/terminal/tests/header.d.ts +16 -0
  130. package/dist/terminal/tests/header.js +90 -0
  131. package/dist/terminal/tests/reporter.d.ts +17 -0
  132. package/dist/terminal/tests/reporter.js +99 -0
  133. package/dist/terminal/tests/results.d.ts +44 -0
  134. package/dist/terminal/tests/results.js +104 -0
  135. package/dist/terminal/tests/scope.d.ts +25 -0
  136. package/dist/terminal/tests/scope.js +25 -0
  137. package/dist/terminal/tests/session.d.ts +11 -0
  138. package/dist/terminal/tests/session.js +24 -0
  139. package/dist/terminal/tests/state.d.ts +57 -0
  140. package/dist/terminal/tests/state.js +134 -0
  141. package/dist/terminal/views/clear-history.d.ts +6 -0
  142. package/dist/terminal/views/clear-history.js +10 -0
  143. package/dist/terminal/views/error.d.ts +8 -0
  144. package/dist/terminal/views/error.js +24 -0
  145. package/dist/terminal/views/frame.d.ts +20 -0
  146. package/dist/terminal/views/frame.js +23 -0
  147. package/dist/terminal/views/help.d.ts +3 -0
  148. package/dist/terminal/views/help.js +32 -0
  149. package/dist/terminal/views/index.d.ts +6 -0
  150. package/dist/terminal/views/index.js +13 -0
  151. package/dist/terminal/views/logs.d.ts +3 -0
  152. package/dist/terminal/views/logs.js +7 -0
  153. package/dist/terminal/views/registry.d.ts +114 -0
  154. package/dist/terminal/views/registry.js +40 -0
  155. package/dist/terminal/views/requests.d.ts +8 -0
  156. package/dist/terminal/views/requests.js +15 -0
  157. package/dist/terminal/views/session.d.ts +9 -0
  158. package/dist/terminal/views/session.js +133 -0
  159. package/dist/terminal/views/stories.d.ts +9 -0
  160. package/dist/terminal/views/stories.js +172 -0
  161. package/dist/terminal/views/tests.d.ts +9 -0
  162. package/dist/terminal/views/tests.js +105 -0
  163. package/dist/terminal/watch/client.d.ts +12 -0
  164. package/dist/terminal/watch/client.js +7 -0
  165. package/dist/terminal/watch/controller.d.ts +30 -0
  166. package/dist/terminal/watch/controller.js +157 -0
  167. package/dist/terminal/watch/format.d.ts +15 -0
  168. package/dist/terminal/watch/format.js +37 -0
  169. package/dist/terminal/watch/session.d.ts +17 -0
  170. package/dist/terminal/watch/session.js +12 -0
  171. package/dist/terminal/width.d.ts +24 -0
  172. package/dist/terminal/width.js +171 -0
  173. package/dist/workbench-url.d.ts +30 -0
  174. package/dist/workbench-url.js +55 -0
  175. package/package.json +54 -3
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022 Guillaume Chau
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,9 @@
1
- # Temporary Holding Version
1
+ # @histoire/cli
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Command line for Histoire: Sade command definitions, the `histoire dev` parent process and its interactive terminal.
4
+
5
+ - `runCli(host)` defines `dev`, `mcp`, `build`, `preview`, `test`, `screenshot-setup` and `visual`. Command implementations and the dev parent's Histoire-specific inputs are injected by `histoire` as lazy loaders, so `--help` and the dev parent never load project, Vite or test graphs. This package never imports `histoire`.
6
+ - The dev parent owns the public proxy (`@histoire/dev-proxy`) and the terminal (panel, plain output, views, key handling). It talks to the runtime child over the private terminal protocol.
7
+ - Subpath exports: `@histoire/cli/protocol/*` and `@histoire/cli/sanitize` (dependency-light modules also loaded by the child), and `@histoire/cli/workbench-url` (story route helpers; the dev parent loads them only on first use).
8
+
9
+ Tests: `pnpm --filter @histoire/cli test`. Workspace dependencies (`@histoire/dev-proxy`, `@histoire/protocol`, `@histoire/vendors`) resolve to their built output, so build them first (`pnpm run build` at the root).
package/dist/cli.d.ts ADDED
@@ -0,0 +1,9 @@
1
+ import type { CliHost } from './commands/host.js';
2
+ /**
3
+ * Defines every Histoire command and runs the one named on the command line.
4
+ * Command implementations are injected as lazy loaders so `--help` and the dev
5
+ * parent never load project, Vite or test graphs.
6
+ * @param host Version, command loaders and dev parent injection provided by histoire.
7
+ * @returns What the selected command's action returned (a promise for every command), or undefined when no action ran.
8
+ */
9
+ export declare function runCli(host: CliHost): unknown;
package/dist/cli.js ADDED
@@ -0,0 +1,88 @@
1
+ import sade from 'sade';
2
+ import { reportInvalidScreenshotSetupArguments, validateScreenshotSetupArguments } from './commands/screenshot-setup-args.js';
3
+ /**
4
+ * Defines every Histoire command and runs the one named on the command line.
5
+ * Command implementations are injected as lazy loaders so `--help` and the dev
6
+ * parent never load project, Vite or test graphs.
7
+ * @param host Version, command loaders and dev parent injection provided by histoire.
8
+ * @returns What the selected command's action returned (a promise for every command), or undefined when no action ran.
9
+ */
10
+ export function runCli(host) {
11
+ const argv = host.argv ?? process.argv;
12
+ const program = sade('histoire');
13
+ program.version(host.version);
14
+ program.command('dev')
15
+ .describe('open the stories in your browser for development')
16
+ .option('-p, --port <port>', 'Listening port of the server')
17
+ .option('-c, --config <file>', `[string] use specified config file`)
18
+ .option('--open', 'Open in your default browser')
19
+ .option('--host <host>', '[string] specify hostname')
20
+ .option('--mcp', 'Enable MCP, overriding project config')
21
+ .option('--no-mcp', 'Disable default-on dev MCP')
22
+ .option('--mcp-port <port>', 'MCP loopback port (default 6007; 0 selects an ephemeral port)')
23
+ .option('--tui', 'Use the interactive terminal panel, overriding CI and inspector detection')
24
+ .option('--no-tui', 'Use plain terminal output')
25
+ .option('--test-watch', 'Run browser tests for affected stories on every change, starting with the whole book')
26
+ .action(async (options) => {
27
+ const argumentsBeforeSeparator = argv.slice(2, !argv.includes('--') ? undefined : argv.indexOf('--'));
28
+ if (argumentsBeforeSeparator.includes('--mcp') && argumentsBeforeSeparator.includes('--no-mcp'))
29
+ throw new Error('--mcp and --no-mcp cannot be combined');
30
+ const injection = await host.dev();
31
+ const { devCommand } = await import('./commands/dev.js');
32
+ // Sade keeps the option under its CLI spelling.
33
+ const { 'test-watch': testWatch, ...rest } = options;
34
+ return devCommand({ ...rest, testWatch: testWatch === true }, { ...injection, version: host.version });
35
+ });
36
+ program.command('mcp')
37
+ .describe('serve Model Context Protocol over stdio')
38
+ .option('--root <directory>', 'Existing project directory (default current directory)')
39
+ .option('-c, --config <file>', '[string] use specified config file relative to project root')
40
+ .action(async (options) => (await host.commands.mcp())(options));
41
+ program.command('build')
42
+ .describe('build the histoire final app you can deploy')
43
+ .option('-c, --config <file>', `[string] use specified config file`)
44
+ .option('--target <target>', 'Deployment output: static (default) or node')
45
+ .action(async (options) => (await host.commands.build())(options));
46
+ program.command('preview')
47
+ .describe('preview the built directory')
48
+ .option('-p, --port <port>', 'Listening port of the server')
49
+ .action(async (options) => (await host.commands.preview())(options));
50
+ program.command('test')
51
+ .describe('run histoire story tests in Vitest browser mode')
52
+ .option('-c, --config <file>', `[string] use specified config file`)
53
+ .action(async (options) => {
54
+ const separatorIndex = argv.indexOf('--');
55
+ const rawVitestArgs = separatorIndex === -1 ? [] : argv.slice(separatorIndex + 1);
56
+ return (await host.commands.test())(options, rawVitestArgs);
57
+ });
58
+ program.command('screenshot-setup')
59
+ .describe('inspect or explicitly check screenshot browser setup')
60
+ .option('--root <directory>', 'Existing project directory (default current directory)')
61
+ .option('-c, --config <file>', 'Histoire config file relative to project root')
62
+ .option('--check', 'Launch and release one finite screenshot setup probe')
63
+ .option('--json', 'Print one JSON snapshot or error object')
64
+ .action(async (options) => (await host.commands.screenshotSetup())(options));
65
+ program.command('visual')
66
+ .describe('compare story images and review visual regressions')
67
+ .option('-c, --config <file>', 'Use specified Histoire config file')
68
+ .option('--story <id>', 'Exact story ID')
69
+ .option('--variant <id>', 'Exact variant ID, requires --story')
70
+ .option('--case <id>', 'Exact saved or canonical case ID')
71
+ .option('--profile <id>', 'Exact capture profile ID')
72
+ .option('--baseline-ref <ref>', 'Read baselines from this Git ref')
73
+ .option('--incremental', 'Capture only comparisons without valid retained evidence')
74
+ .option('--update', 'Approve successful selected captures')
75
+ .option('--all', 'Explicitly allow whole-project baseline update')
76
+ .action(async (options) => (await host.commands.visual())(options));
77
+ // Sade exits with status 1 for malformed arguments, so preserve the command's
78
+ // documented status 2 for invalid screenshot setup input.
79
+ const screenshotSetupInvalid = argv[2] === 'screenshot-setup'
80
+ ? validateScreenshotSetupArguments(argv.slice(3))
81
+ : undefined;
82
+ if (screenshotSetupInvalid) {
83
+ reportInvalidScreenshotSetupArguments(argv.slice(3).includes('--json'));
84
+ process.exitCode = 2;
85
+ return undefined;
86
+ }
87
+ return program.parse(argv);
88
+ }
@@ -0,0 +1,44 @@
1
+ import type { DevHost, DevOptions } from './host.js';
2
+ /** CLI parent owns public proxy and its process signal registrations. */
3
+ export declare function devCommand(options: DevOptions, host: DevHost): Promise<{
4
+ ready: Promise<void>;
5
+ restart: (request?: import("@histoire/dev-proxy/protocol").RestartRequest) => Promise<void>;
6
+ openBrowser(target: string): Promise<void>;
7
+ sendRuntimeCommand(command: Omit<import("@histoire/dev-proxy/protocol").RuntimeCommand, 'type' | 'generation'>): Promise<import("@histoire/dev-proxy/protocol").RuntimeSendResult>;
8
+ logs: import("../terminal/output/history.js").LogHistory;
9
+ requests: import("../terminal/requests/history.js").RequestHistory;
10
+ bridge: import("../terminal/bridge.js").TerminalBridge<{
11
+ 'catalog.list': import("../terminal/protocol/core.js").TerminalOperationDefinition<import("../terminal/protocol/catalog.js").CatalogListArgs, import("../terminal/protocol/catalog.js").CatalogListPage>;
12
+ 'catalog.variants': import("../terminal/protocol/core.js").TerminalOperationDefinition<import("../terminal/protocol/catalog.js").CatalogVariantsArgs, import("../terminal/protocol/catalog.js").CatalogVariantsPage>;
13
+ 'diagnostics.get': {
14
+ args: Record<string, never>;
15
+ result: import("../terminal/protocol/diagnostics.js").DiagnosticsDto;
16
+ };
17
+ 'session.get': {
18
+ args: Record<string, never>;
19
+ result: import("../terminal/protocol/session.js").SessionInfoDto;
20
+ };
21
+ 'tests.run': import("../terminal/protocol/core.js").TerminalOperationDefinition<import("../terminal/protocol/tests.js").TestRunArgs, import("../terminal/protocol/tests.js").TestOperationDto>;
22
+ 'tests.get': import("../terminal/protocol/core.js").TerminalOperationDefinition<import("../terminal/protocol/tests.js").TestOperationArgs, import("../terminal/protocol/tests.js").TestOperationDto>;
23
+ 'tests.results': import("../terminal/protocol/core.js").TerminalOperationDefinition<import("../terminal/protocol/tests.js").TestResultsArgs, import("../terminal/protocol/tests.js").TestResultsPage>;
24
+ 'tests.cancel': import("../terminal/protocol/core.js").TerminalOperationDefinition<import("../terminal/protocol/tests.js").TestOperationArgs, import("../terminal/protocol/tests.js").TestOperationDto>;
25
+ 'watch.set': import("../terminal/protocol/core.js").TerminalOperationDefinition<import("../terminal/protocol/watch.js").WatchSetArgs, import("../terminal/protocol/watch.js").WatchStateDto>;
26
+ }, import("../terminal/protocol/index.js").TerminalEvents>;
27
+ progress: import("../terminal/progress/state.js").ProgressState;
28
+ retained: import("../terminal/retained.js").RetainedHistories;
29
+ tests: {
30
+ onEvent(generation: string, event: string, data: unknown): void;
31
+ attach: (bridge: Pick<import("../terminal/bridge.js").TerminalBridge, 'subscribe'>) => () => void;
32
+ onRetired(generation: string): void;
33
+ results(operationId: string, page?: {
34
+ cursor?: string;
35
+ failedOnly?: boolean;
36
+ }): Promise<import("../terminal/protocol/tests.js").TestResultsPage>;
37
+ snapshot: () => import("../terminal/tests/state.js").TestEntry[];
38
+ get: (operationId: string) => import("../terminal/tests/state.js").TestEntry | undefined;
39
+ subscribe(listener: () => void): () => boolean;
40
+ };
41
+ url: string;
42
+ status: import("@histoire/dev-proxy/protocol").RuntimeStatus;
43
+ close: () => Promise<void>;
44
+ }>;
@@ -0,0 +1,117 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { startDevProxy } from '@histoire/dev-proxy';
3
+ import { renderBanner } from '../terminal/banner.js';
4
+ import { createTerminalBridge } from '../terminal/bridge.js';
5
+ import { createClipboardWriter } from '../terminal/clipboard.js';
6
+ import { createLogHistory } from '../terminal/output/history.js';
7
+ import { createOutputPipeline } from '../terminal/output/pipeline.js';
8
+ import { describeRestartCause } from '../terminal/progress/format.js';
9
+ import { createProgressState } from '../terminal/progress/state.js';
10
+ import { isProgressEvent } from '../terminal/protocol/progress.js';
11
+ import { createRequestHistory } from '../terminal/requests/history.js';
12
+ import { createRetainedHistories } from '../terminal/retained.js';
13
+ import { createTerminalSession } from '../terminal/session.js';
14
+ import { detectColorLevel } from '../terminal/style.js';
15
+ import { createTestsClient } from '../terminal/tests/client.js';
16
+ import { createTestsState } from '../terminal/tests/state.js';
17
+ import { createSignalGuard } from './signal-guard.js';
18
+ /** CLI parent owns public proxy and its process signal registrations. */
19
+ export async function devCommand(options, host) {
20
+ host.resolveDevMcpOptions(undefined, options);
21
+ if (typeof options.port === 'string' && !/^\d+$/.test(options.port))
22
+ throw new Error('Port must be an integer from 0 to 65535');
23
+ const token = host.captureMcpToken();
24
+ // Terminal-only inputs never reach the runtime child.
25
+ const { tui, testWatch, ...runtimeCliOptions } = options;
26
+ let publicUrl = '';
27
+ let started;
28
+ const bridge = createTerminalBridge({ transport: { send: async (command) => started ? started.sendRuntimeCommand(command) : { ok: false, reason: 'starting' } } });
29
+ // Session-lifetime mirror of startup progress and restart causes, fed only by observed events.
30
+ const secrets = token ? [token] : [];
31
+ const progress = createProgressState({ secrets });
32
+ const logs = createLogHistory();
33
+ // Public HTTP exchanges seen by the proxy; paths are redacted with the credential.
34
+ const requests = createRequestHistory({ secrets });
35
+ // Created before the proxy binds and before any project code loads; an invalid HISTOIRE_TUI fails here.
36
+ // Histories `x` deletes; later slices register theirs (requests) here.
37
+ const retained = createRetainedHistories();
38
+ // Terminal-owned test operations survive restarts as labelled history; the generation retirement below marks unfinished ones lost.
39
+ const tests = createTestsState({ client: createTestsClient(bridge) });
40
+ tests.attach(bridge);
41
+ const terminal = createTerminalSession({ flag: tui, testWatch, version: host.version, logs, progress, bridge, retained, requests, tests, host: options.host, clipboard: createClipboardWriter() });
42
+ // Installed while the terminal is attached, not after startup: a signal or crash in between must still restore it.
43
+ const guard = createSignalGuard({
44
+ process,
45
+ stdout: process.stdout,
46
+ release: terminal.release,
47
+ shutdown: () => terminal.shutdown(),
48
+ setExitCode: (code) => {
49
+ process.exitCode = code;
50
+ },
51
+ exit: code => process.exit(code),
52
+ report: error => console.error(error),
53
+ });
54
+ // Zap banner once, above the first log line; styled only on a color-capable terminal.
55
+ for (const row of renderBanner({ version: host.version, columns: process.stdout.columns ?? 80, color: detectColorLevel(process.env, process.stdout.isTTY === true) }))
56
+ terminal.line(row);
57
+ // One decoder/sanitizer owns every output source; the terminal session decides where visible bytes go.
58
+ const output = createOutputPipeline({ history: logs, secrets, passthrough: terminal.passthrough });
59
+ bridge.subscribe(({ event, data, generation }) => {
60
+ if (event === 'log')
61
+ output.onLog(data, generation);
62
+ else if (event === 'progress' && isProgressEvent(data))
63
+ progress.onProgress(generation, data);
64
+ });
65
+ try {
66
+ started = await startDevProxy({ ...runtimeCliOptions, port: options.port === undefined ? undefined : Number(options.port), token, runtime: host.runtime, runtimeOptions: { ...runtimeCliOptions, projectId: randomUUID(), terminalLogs: true }, onOutput: output.onOutput, onRequest: requests.onEvent, onRuntimeMessage: bridge.receive, onRuntimeRetired: (generation) => {
67
+ bridge.retire(generation);
68
+ tests.onRetired(generation);
69
+ progress.onRetired(generation);
70
+ }, onRuntimeStart: progress.onRuntimeStart, onRestart(cause) {
71
+ progress.onRestart(cause);
72
+ // One notice per restart transition, naming its cause.
73
+ terminal.line(describeRestartCause(cause, secrets));
74
+ }, onDiagnostic: output.onDiagnostic, onListening(url) {
75
+ publicUrl = url;
76
+ terminal.onListening(url);
77
+ terminal.line(` Histoire: ${url}`);
78
+ }, onStatus(state) {
79
+ progress.onStatus(state);
80
+ if (state.status !== 'ready')
81
+ return;
82
+ terminal.onReady(state.base);
83
+ terminal.line(` Local: ${new URL(state.base, publicUrl).href}`);
84
+ } });
85
+ }
86
+ catch (error) {
87
+ // Startup failed before the session was usable: give the terminal back.
88
+ guard.dispose();
89
+ terminal.release();
90
+ throw error;
91
+ }
92
+ const proxy = started;
93
+ /** Closes proxy and runtime; the terminal session runs this after restoring input and screen. */
94
+ async function closeRuntime() {
95
+ guard.dispose();
96
+ try {
97
+ await proxy.close();
98
+ }
99
+ finally {
100
+ bridge.close();
101
+ output.flush();
102
+ }
103
+ }
104
+ /** Same graceful path for signals, `q`, and programmatic close; teardown failures stay a nonzero status. */
105
+ function close() {
106
+ return terminal.shutdown();
107
+ }
108
+ // Bound last: a shutdown requested during startup closes the host right here, after the handlers exist for `closeRuntime` to remove.
109
+ terminal.bind({ restart: request => proxy.restart(request), openBrowser: target => proxy.openBrowser(target), close: closeRuntime });
110
+ // Failed config keeps parent/watcher available for correction and automatic retry.
111
+ void proxy.ready.catch(error => output.onDiagnostic(String(error)));
112
+ return { ...proxy, logs, requests, bridge, progress, retained, tests, get url() {
113
+ return proxy.url;
114
+ }, get status() {
115
+ return proxy.status;
116
+ }, close };
117
+ }
@@ -0,0 +1,66 @@
1
+ /** CLI fields selecting the dev MCP listener; histoire resolves them into a listener policy. */
2
+ export interface DevMcpCliOptions {
3
+ /** Explicit enable, or false from Sade's --no-mcp handling. */
4
+ 'mcp'?: boolean;
5
+ /** Explicit disable, preserved separately to detect conflicting CLI flags. */
6
+ 'no-mcp'?: boolean;
7
+ /** Explicit listening port; zero requests an ephemeral port. */
8
+ 'mcp-port'?: string | number;
9
+ }
10
+ /** Options accepted by `histoire dev`. */
11
+ export interface DevOptions extends DevMcpCliOptions {
12
+ /** Public proxy port; defaults to 6006. */
13
+ port?: number | string;
14
+ /** Public binding independent of private Vite listener. */
15
+ host?: string | boolean;
16
+ /** Explicit project directory. */
17
+ root?: string;
18
+ /** Explicit configuration path. */
19
+ config?: string;
20
+ /** Open public URL before runtime becomes ready. */
21
+ open?: boolean;
22
+ /** Explicit terminal panel choice: `--tui` (true) or `--no-tui` (false); undefined follows `HISTOIRE_TUI` and automatic detection. */
23
+ tui?: boolean;
24
+ /** `--test-watch`: watch the whole book and rerun affected stories on every change. Default off. */
25
+ testWatch?: boolean;
26
+ }
27
+ /**
28
+ * Histoire-specific inputs of the dev parent. The module providing them must stay
29
+ * light (no Vite, runtime or project graph): the parent loads it before the public port binds.
30
+ */
31
+ export interface DevInjection {
32
+ /** Entry of the runtime child process the proxy spawns. */
33
+ runtime: URL;
34
+ /** Removes the MCP credential from the environment and returns it, before project code can read it. */
35
+ captureMcpToken: () => string | undefined;
36
+ /** Validates MCP flags; throws on conflicting or malformed values. */
37
+ resolveDevMcpOptions: (config: undefined, cli: DevMcpCliOptions) => unknown;
38
+ }
39
+ /** Dev parent inputs: histoire's injection plus the version shown in the banner. */
40
+ export interface DevHost extends DevInjection {
41
+ /** Histoire version; empty when unknown. */
42
+ version: string;
43
+ }
44
+ /** Command implementation receiving Sade's parsed options. */
45
+ export type CommandHandler = (options: any) => unknown;
46
+ /** Lazy loader of one command implementation, so unused commands never load. */
47
+ export type CommandLoader<Handler = CommandHandler> = () => Promise<Handler>;
48
+ /** Everything histoire provides to the CLI: version, lazy command implementations and the dev parent injection. */
49
+ export interface CliHost {
50
+ /** Histoire version printed by `--version`. */
51
+ version: string;
52
+ /** Loads the light inputs of the dev parent. */
53
+ dev: () => Promise<DevInjection>;
54
+ /** Lazy implementations of the commands run inside the histoire package. */
55
+ commands: {
56
+ mcp: CommandLoader;
57
+ build: CommandLoader;
58
+ preview: CommandLoader;
59
+ /** Receives the raw arguments after `--`, forwarded to Vitest. */
60
+ test: CommandLoader<(options: any, rawVitestArgs: string[]) => unknown>;
61
+ screenshotSetup: CommandLoader;
62
+ visual: CommandLoader;
63
+ };
64
+ /** Command line, defaults to `process.argv`. */
65
+ argv?: string[];
66
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,4 @@
1
+ /** Validate setup-specific arguments before Sade can choose its generic exit code. */
2
+ export declare function validateScreenshotSetupArguments(args: readonly string[]): string | undefined;
3
+ /** Emit one fixed invalid-argument message on the contract-selected stream. */
4
+ export declare function reportInvalidScreenshotSetupArguments(json: boolean): void;
@@ -0,0 +1,35 @@
1
+ /** Validate setup-specific arguments before Sade can choose its generic exit code. */
2
+ export function validateScreenshotSetupArguments(args) {
3
+ if (args.includes('--help') || args.includes('-h')) {
4
+ return args.every(argument => argument === '--help' || argument === '-h')
5
+ ? undefined
6
+ : 'Help cannot be combined with screenshot setup options';
7
+ }
8
+ for (let index = 0; index < args.length; index++) {
9
+ const argument = args[index];
10
+ if (argument === '--')
11
+ return 'Browser arguments are not accepted by screenshot-setup';
12
+ if (argument === '--check' || argument === '--json')
13
+ continue;
14
+ if (argument === '--root' || argument === '--config' || argument === '-c') {
15
+ const value = args[++index];
16
+ if (!value || value.startsWith('-'))
17
+ return `Missing value for ${argument}`;
18
+ continue;
19
+ }
20
+ if (argument.startsWith('--root=') || argument.startsWith('--config=')) {
21
+ if (!argument.slice(argument.indexOf('=') + 1))
22
+ return `Missing value for ${argument.split('=')[0]}`;
23
+ continue;
24
+ }
25
+ return `Unknown screenshot-setup option: ${argument}`;
26
+ }
27
+ return undefined;
28
+ }
29
+ /** Emit one fixed invalid-argument message on the contract-selected stream. */
30
+ export function reportInvalidScreenshotSetupArguments(json) {
31
+ if (json)
32
+ process.stdout.write(`${JSON.stringify({ error: { code: 'invalid', message: 'Invalid screenshot-setup arguments.' } })}\n`);
33
+ else
34
+ process.stderr.write('Invalid screenshot-setup arguments.\n');
35
+ }
@@ -0,0 +1,29 @@
1
+ import type { EventEmitter } from 'node:events';
2
+ /** Inputs of {@link createSignalGuard}; every side effect is injectable. */
3
+ export interface SignalGuardOptions {
4
+ /** Emitter of signals and fatal errors (the `process` object). */
5
+ process: EventEmitter;
6
+ /** Emitter whose `error` events (EPIPE) must not crash the process (`process.stdout`). */
7
+ stdout: EventEmitter;
8
+ /** Synchronously gives the terminal back; idempotent. */
9
+ release: () => void;
10
+ /** Graceful shutdown shared by signals, `q` and programmatic close. */
11
+ shutdown: () => Promise<void>;
12
+ /** Sets the status the process ends with when the graceful shutdown failed. */
13
+ setExitCode: (code: number) => void;
14
+ /** Ends the process immediately. */
15
+ exit: (code: number) => void;
16
+ /** Reports an error on stderr. */
17
+ report: (error: unknown) => void;
18
+ }
19
+ /**
20
+ * Installs process-level lifecycle handlers for the dev parent: termination signals,
21
+ * fatal errors and a closed stdout. Install as soon as the terminal is attached,
22
+ * so no window leaves raw mode or the alternate screen behind.
23
+ * @param options Injected process and terminal hooks.
24
+ * @returns `dispose` removes the signal and fatal-error handlers; the stdout handler stays so late writes cannot crash.
25
+ */
26
+ export declare function createSignalGuard(options: SignalGuardOptions): {
27
+ /** Removes signal and fatal-error handlers. */
28
+ dispose(): void;
29
+ };
@@ -0,0 +1,52 @@
1
+ /** Termination signals that start the graceful shutdown (a clean shutdown keeps status 0). */
2
+ const SIGNALS = ['SIGINT', 'SIGTERM', 'SIGHUP'];
3
+ /**
4
+ * Installs process-level lifecycle handlers for the dev parent: termination signals,
5
+ * fatal errors and a closed stdout. Install as soon as the terminal is attached,
6
+ * so no window leaves raw mode or the alternate screen behind.
7
+ * @param options Injected process and terminal hooks.
8
+ * @returns `dispose` removes the signal and fatal-error handlers; the stdout handler stays so late writes cannot crash.
9
+ */
10
+ export function createSignalGuard(options) {
11
+ const { process: emitter, stdout } = options;
12
+ /** Graceful path; only a teardown failure makes the status nonzero. */
13
+ function shutdown() {
14
+ void options.shutdown().catch((error) => {
15
+ options.report(error);
16
+ options.setExitCode(1);
17
+ });
18
+ }
19
+ const handlers = SIGNALS.map(signal => [signal, shutdown]);
20
+ /** Restores the terminal before anything is printed, then exits: the process state is unknown. */
21
+ function fatal(error) {
22
+ try {
23
+ options.release();
24
+ }
25
+ catch { }
26
+ options.report(error);
27
+ options.exit(1);
28
+ }
29
+ let stdoutFailed = false;
30
+ /** The reader went away: shut down once and ignore every later stream error. */
31
+ function onStdoutError(error) {
32
+ if (stdoutFailed)
33
+ return;
34
+ stdoutFailed = true;
35
+ if (error.code === 'EPIPE')
36
+ shutdown();
37
+ }
38
+ for (const [signal, handler] of handlers)
39
+ emitter.on(signal, handler);
40
+ emitter.once('uncaughtException', fatal);
41
+ emitter.once('unhandledRejection', fatal);
42
+ stdout.on('error', onStdoutError);
43
+ return {
44
+ /** Removes signal and fatal-error handlers. */
45
+ dispose() {
46
+ for (const [signal, handler] of handlers)
47
+ emitter.off(signal, handler);
48
+ emitter.off('uncaughtException', fatal);
49
+ emitter.off('unhandledRejection', fatal);
50
+ },
51
+ };
52
+ }
@@ -0,0 +1,2 @@
1
+ export { runCli } from './cli.js';
2
+ export type { CliHost, CommandHandler, CommandLoader, DevHost, DevInjection, DevMcpCliOptions, DevOptions } from './commands/host.js';
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ export { runCli } from './cli.js';
@@ -0,0 +1,51 @@
1
+ import type { ClipboardWriter } from './clipboard.js';
2
+ import type { TestsConsole } from './tests/console.js';
3
+ /** Capabilities the main actions use; implemented by the session for both TUI and plain modes. */
4
+ export interface ActionHost {
5
+ /** Starts a replacement runtime; resolves when the proxy accepted the request. */
6
+ restart: (request: {
7
+ fresh: boolean;
8
+ }) => Promise<void>;
9
+ /** Opens the workbench URL in the default browser. */
10
+ openBrowser: () => Promise<void>;
11
+ /** Workbench URL when known. */
12
+ url: () => string | undefined;
13
+ /** Writes to the system clipboard. */
14
+ copy: ClipboardWriter;
15
+ /** Empties the visible output; retained history stays. */
16
+ clearScreen: () => void;
17
+ /** Starts graceful shutdown. */
18
+ quit: () => void;
19
+ /** Manual test controller; absent in doubles that never run tests. */
20
+ tests?: TestsConsole;
21
+ /** Shows one feedback message (transient panel line, or a printed line in plain mode). */
22
+ report: (text: string) => void;
23
+ }
24
+ /** One main-screen action. */
25
+ export interface MainAction {
26
+ key: string;
27
+ label: string;
28
+ description: string;
29
+ run: (host: ActionHost) => void | Promise<void>;
30
+ }
31
+ /**
32
+ * Runs an action body; failures become feedback instead of unhandled rejections.
33
+ * @param host Action host receiving the feedback.
34
+ * @param work Work to run.
35
+ */
36
+ export declare function guarded(host: ActionHost, work: () => void | Promise<void>): Promise<void>;
37
+ /**
38
+ * Requests a runtime replacement; the lifecycle notice names the cause.
39
+ * @param host Action host.
40
+ * @param fresh Skip cached catalog and force dependency optimization.
41
+ */
42
+ export declare function restartRuntime(host: ActionHost, fresh: boolean): Promise<void>;
43
+ /**
44
+ * Opens the workbench in the browser.
45
+ * @param host Action host.
46
+ */
47
+ export declare function openWorkbench(host: ActionHost): Promise<void>;
48
+ /** Keys handled by the main screen itself, in help order. */
49
+ export declare const MAIN_ACTIONS: readonly MainAction[];
50
+ /** Keys main actions own; views may not take them. */
51
+ export declare const RESERVED_SHORTCUTS: readonly string[];
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Runs an action body; failures become feedback instead of unhandled rejections.
3
+ * @param host Action host receiving the feedback.
4
+ * @param work Work to run.
5
+ */
6
+ export async function guarded(host, work) {
7
+ try {
8
+ await work();
9
+ }
10
+ catch (error) {
11
+ host.report(`Failed: ${error instanceof Error ? error.message : String(error)}`);
12
+ }
13
+ }
14
+ /**
15
+ * Requests a runtime replacement; the lifecycle notice names the cause.
16
+ * @param host Action host.
17
+ * @param fresh Skip cached catalog and force dependency optimization.
18
+ */
19
+ export function restartRuntime(host, fresh) {
20
+ host.report(fresh ? 'Fresh restart requested' : 'Restart requested');
21
+ // Not awaited by callers' keypress path: the proxy serializes and coalesces requests.
22
+ return guarded(host, () => host.restart({ fresh }));
23
+ }
24
+ /**
25
+ * Opens the workbench in the browser.
26
+ * @param host Action host.
27
+ */
28
+ export function openWorkbench(host) {
29
+ return guarded(host, async () => {
30
+ const url = host.url();
31
+ if (!url)
32
+ return host.report('Workbench address is not known yet');
33
+ host.report('Opening workbench');
34
+ await host.openBrowser();
35
+ });
36
+ }
37
+ /**
38
+ * Copies the workbench URL, reporting plainly when the clipboard is unavailable.
39
+ * @param host Action host.
40
+ */
41
+ function copyUrl(host) {
42
+ return guarded(host, async () => {
43
+ const url = host.url();
44
+ if (!url)
45
+ return host.report('Workbench address is not known yet');
46
+ const result = await host.copy(url);
47
+ host.report(result.ok ? `Copied address${result.note ? ` (${result.note})` : ''}` : `Copy unavailable: ${result.reason}`);
48
+ });
49
+ }
50
+ /** Keys handled by the main screen itself, in help order. */
51
+ export const MAIN_ACTIONS = [
52
+ { key: 'r', label: 'Restart', description: 'Restart the runtime', run: host => restartRuntime(host, false) },
53
+ { key: 'R', label: 'Fresh restart', description: 'Restart without cached catalog or dependencies', run: host => restartRuntime(host, true) },
54
+ { key: 'o', label: 'Open', description: 'Open the workbench in the browser', run: openWorkbench },
55
+ { key: 'y', label: 'Copy', description: 'Copy the workbench address', run: copyUrl },
56
+ { key: 'c', label: 'Clear', description: 'Clear the visible output', run: (host) => { host.clearScreen(); } },
57
+ { key: 'q', label: 'Quit', description: 'Stop and exit', run: (host) => { host.quit(); } },
58
+ ];
59
+ /** Keys main actions own; views may not take them. */
60
+ export const RESERVED_SHORTCUTS = MAIN_ACTIONS.map(action => action.key);
@@ -0,0 +1,19 @@
1
+ import type { ColorLevel } from './style.js';
2
+ /** Options of {@link renderBanner}. */
3
+ export interface BannerOptions {
4
+ /** Histoire version, without the leading `v`. */
5
+ version: string;
6
+ /** Terminal width. */
7
+ columns: number;
8
+ /** `false` or level 0 disables styling; `true` detects the capability (basic at minimum). */
9
+ color: boolean | ColorLevel;
10
+ /** Workbench address when already known; without it only the version sits beside the art. */
11
+ url?: string;
12
+ }
13
+ /**
14
+ * Startup banner: a small zap beside the version and address. Lines are at most `columns`
15
+ * cells. A terminal too narrow for the art gets the version line only; with color off the
16
+ * output has no escape sequences at all.
17
+ * @param options Version, width, color decision and optional address.
18
+ */
19
+ export declare function renderBanner(options: BannerOptions): string[];