@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
@@ -0,0 +1,150 @@
1
+ import { performance } from 'node:perf_hooks';
2
+ import { sanitizeLine } from '../output/sanitize.js';
3
+ /** Retired generations remembered so late frames are fenced; far above any restart burst. */
4
+ const RETIRED_MEMORY = 64;
5
+ /**
6
+ * Creates the progress mirror. Pure state: no I/O, no runtime imports.
7
+ * Child-provided text (labels, failure lines, restart sources) is made terminal-safe on ingestion.
8
+ * @param options Optional injected monotonic clock (`now`, milliseconds; tests only) and credentials to redact.
9
+ * @param options.now Monotonic clock in milliseconds.
10
+ * @param options.secrets Configured credentials removed from child text.
11
+ */
12
+ export function createProgressState(options = {}) {
13
+ const now = options.now ?? (() => performance.now());
14
+ const clean = (text) => sanitizeLine(text, options.secrets);
15
+ const listeners = new Set();
16
+ const retired = new Set();
17
+ let status = 'starting';
18
+ let current;
19
+ /** Cause of the latest restart transition; every generation it spawns shares it. */
20
+ let transitionCause;
21
+ let transitionStartedAt = now();
22
+ let endedAt;
23
+ let readyAfterMs;
24
+ /** Notifies listeners; one faulty listener never affects the others. */
25
+ function changed() {
26
+ if (!listeners.size)
27
+ return;
28
+ const snapshot = view();
29
+ for (const listener of [...listeners]) {
30
+ try {
31
+ listener(snapshot);
32
+ }
33
+ catch { }
34
+ }
35
+ }
36
+ /** Converts a record into its public form with a live elapsed value. */
37
+ function toSnapshot(record) {
38
+ const { startedAt, durationMs, ...rest } = record;
39
+ return { ...rest, elapsedMs: record.status === 'running' ? Math.max(0, now() - startedAt) : durationMs ?? 0 };
40
+ }
41
+ /** Builds the snapshot. */
42
+ function view() {
43
+ const phases = [...current?.phases.values() ?? []].map(toSnapshot);
44
+ return {
45
+ status,
46
+ generation: current?.generation,
47
+ fresh: current?.fresh ?? false,
48
+ cause: current?.cause ?? (status === 'restarting' ? transitionCause : undefined),
49
+ elapsedMs: Math.max(0, (endedAt ?? now()) - transitionStartedAt),
50
+ ...(readyAfterMs === undefined ? {} : { readyAfterMs }),
51
+ phases,
52
+ active: phases.filter(phase => phase.status === 'running'),
53
+ failed: phases.find(phase => phase.status === 'failed'),
54
+ };
55
+ }
56
+ /** Marks running phases of a record as no longer progressing. */
57
+ function interrupt(record) {
58
+ record.retired = true;
59
+ for (const phase of record.phases.values()) {
60
+ if (phase.status === 'running') {
61
+ phase.status = 'interrupted';
62
+ phase.durationMs = Math.max(0, now() - phase.startedAt);
63
+ }
64
+ }
65
+ }
66
+ return {
67
+ onStatus(next) {
68
+ if (next.status === status)
69
+ return;
70
+ const previous = status;
71
+ status = next.status;
72
+ if (status === 'restarting' || (status === 'starting' && previous !== 'restarting')) {
73
+ transitionStartedAt = now();
74
+ endedAt = undefined;
75
+ readyAfterMs = undefined;
76
+ }
77
+ // The retiring generation's phases no longer describe the transition.
78
+ if (status === 'restarting') {
79
+ if (current && !current.retired)
80
+ interrupt(current);
81
+ current = undefined;
82
+ }
83
+ else if (status === 'ready' || status === 'failed' || status === 'closed') {
84
+ endedAt = now();
85
+ if (status === 'ready')
86
+ readyAfterMs = endedAt - transitionStartedAt;
87
+ }
88
+ changed();
89
+ },
90
+ onRuntimeStart({ generation, fresh }) {
91
+ if (current && !current.retired)
92
+ interrupt(current);
93
+ current = { generation, fresh, cause: transitionCause, phases: new Map(), retired: false };
94
+ changed();
95
+ },
96
+ onRestart(cause) {
97
+ transitionCause = cause.source === undefined ? cause : { ...cause, source: clean(cause.source) };
98
+ changed();
99
+ },
100
+ onProgress(generation, rawEvent) {
101
+ if (!current || current.generation !== generation || current.retired || retired.has(generation))
102
+ return;
103
+ const event = {
104
+ ...rawEvent,
105
+ ...(rawEvent.label === undefined ? {} : { label: clean(rawEvent.label) }),
106
+ ...(rawEvent.error === undefined ? {} : { error: clean(rawEvent.error) }),
107
+ };
108
+ const phases = current.phases;
109
+ const existing = phases.get(event.phase);
110
+ if (event.status === 'started') {
111
+ phases.set(event.phase, { phase: event.phase, status: 'running', background: event.background === true, startedAt: now(), ...(event.label ? { label: event.label } : {}) });
112
+ }
113
+ else if (event.status === 'skipped') {
114
+ phases.set(event.phase, { phase: event.phase, status: 'skipped', background: false, startedAt: now(), durationMs: 0, ...(event.label ? { label: event.label } : {}) });
115
+ }
116
+ else if (existing?.status === 'running') {
117
+ if (event.label !== undefined)
118
+ existing.label = event.label;
119
+ if (event.current !== undefined && event.total !== undefined) {
120
+ existing.current = event.current;
121
+ existing.total = event.total;
122
+ }
123
+ if (event.status !== 'updated') {
124
+ existing.status = event.status;
125
+ existing.durationMs = event.durationMs ?? Math.max(0, now() - existing.startedAt);
126
+ if (event.error)
127
+ existing.error = event.error;
128
+ }
129
+ }
130
+ else {
131
+ return;
132
+ }
133
+ changed();
134
+ },
135
+ onRetired(generation) {
136
+ retired.add(generation);
137
+ if (retired.size > RETIRED_MEMORY)
138
+ retired.delete(retired.values().next().value);
139
+ if (current?.generation === generation && !current.retired) {
140
+ interrupt(current);
141
+ changed();
142
+ }
143
+ },
144
+ snapshot: view,
145
+ subscribe(listener) {
146
+ listeners.add(listener);
147
+ return () => listeners.delete(listener);
148
+ },
149
+ };
150
+ }
@@ -0,0 +1,143 @@
1
+ /**
2
+ * Story and variant catalog DTOs (slice 05). Type-and-constant only (plus argument
3
+ * validators), so the parent can load it before binding its listener. Carries display
4
+ * metadata only: no source, content, configuration objects or absolute paths.
5
+ */
6
+ import type { TerminalOperationDefinition } from './core.js';
7
+ /** Largest page of stories or variants by serialized UTF-8 bytes, below the frame bound. */
8
+ export declare const CATALOG_PAGE_BYTES: number;
9
+ /** Longest story ID (matches the catalog `validId` byte bound; IDs are never shortened). */
10
+ export declare const CATALOG_ID_MAX = 1024;
11
+ /** Longest search text. */
12
+ export declare const CATALOG_QUERY_MAX = 256;
13
+ /** Longest retained display text (title, file label); longer values are cut with an ellipsis. */
14
+ export declare const CATALOG_TEXT_MAX = 200;
15
+ /** Message of the failure raised when an expected revision is no longer current. */
16
+ export declare const CATALOG_STALE_MESSAGE = "Catalog revision changed";
17
+ /** Router mode and base needed to build workbench routes against the parent's public origin. */
18
+ export interface CatalogWorkbenchDto {
19
+ /** Normalized deployment base (leading and trailing slash). */
20
+ base: string;
21
+ /** Actual UI router mode. */
22
+ routerMode: 'hash' | 'history';
23
+ }
24
+ /** Catalog lifecycle summary; sent with every page and as the `catalog.state` event. */
25
+ export interface CatalogStateDto {
26
+ /** Revision of the last completed catalog; absent before the first completion. */
27
+ revision?: string;
28
+ /** A new collection is running: the revision stays readable but is about to change. */
29
+ updating: boolean;
30
+ /** Registered stories. */
31
+ stories: number;
32
+ /** Variants across those stories. */
33
+ variants: number;
34
+ /** Completed collection category. */
35
+ outcome?: 'success' | 'partial' | 'failed';
36
+ /** Safe collection issues. */
37
+ diagnostics: number;
38
+ }
39
+ /** Story row. */
40
+ export interface CatalogStoryDto {
41
+ /** Exact registered story ID. */
42
+ id: string;
43
+ /** Display title (bounded). */
44
+ title: string;
45
+ /** Project-relative file label (bounded). */
46
+ filePath: string;
47
+ /** Documentation-only story: it has no executable variant. */
48
+ docsOnly: boolean;
49
+ /** Variants of the story. */
50
+ variantCount: number;
51
+ /** Several stories share this ID: no exact target can be resolved. */
52
+ ambiguous?: true;
53
+ /** Variants matching the search text (only when searching). */
54
+ matchedVariants?: number;
55
+ }
56
+ /** Variant row. */
57
+ export interface CatalogVariantDto {
58
+ /** Exact variant ID within its story. */
59
+ id: string;
60
+ /** Display title (bounded). */
61
+ title: string;
62
+ /** The ID is used by several variants of the story. */
63
+ ambiguous?: true;
64
+ /** Variant text matches the search text (only when searching). */
65
+ matched?: true;
66
+ }
67
+ /** Arguments of `catalog.list`. */
68
+ export interface CatalogListArgs {
69
+ /** Case-insensitive text matched against title, ID, file label and variant ID/title. */
70
+ query?: string;
71
+ /** Opaque cursor of the previous page; absent for the first. Requires `expectedRevision`. */
72
+ cursor?: string;
73
+ /** Refuse to continue when the catalog moved past this revision. */
74
+ expectedRevision?: string;
75
+ /** Stories per page, 1..100 (default 100); also byte-bounded. */
76
+ limit?: number;
77
+ }
78
+ /** Result of `catalog.list`. */
79
+ export interface CatalogListPage {
80
+ /** Revision every row of this page belongs to. */
81
+ revision: string;
82
+ /** Lifecycle and counts of the whole catalog. */
83
+ state: CatalogStateDto;
84
+ /** Routing facts; absent when the base is unusable (nothing can be opened). */
85
+ workbench?: CatalogWorkbenchDto;
86
+ /** Stories matching the query across the whole catalog. */
87
+ total: number;
88
+ /** Stories of this page. */
89
+ stories: CatalogStoryDto[];
90
+ /** Cursor of the next page, absent at the end. */
91
+ next?: string;
92
+ }
93
+ /** Arguments of `catalog.variants`. */
94
+ export interface CatalogVariantsArgs {
95
+ /** Exact story ID. */
96
+ storyId: string;
97
+ /** Marks variants matching this text. */
98
+ query?: string;
99
+ /** Opaque cursor of the previous page. Requires `expectedRevision`. */
100
+ cursor?: string;
101
+ /** Refuse when the catalog moved past this revision. */
102
+ expectedRevision?: string;
103
+ /** Variants per page, 1..100 (default 100); also byte-bounded. */
104
+ limit?: number;
105
+ }
106
+ /** Result of `catalog.variants`. */
107
+ export interface CatalogVariantsPage {
108
+ /** Revision every row of this page belongs to. */
109
+ revision: string;
110
+ /** Exact story ID. */
111
+ storyId: string;
112
+ /** Variants of the story. */
113
+ total: number;
114
+ /** Variants of this page. */
115
+ variants: CatalogVariantDto[];
116
+ /** Cursor of the next page, absent at the end. */
117
+ next?: string;
118
+ }
119
+ /** Operation map merged into `TerminalOperations`. */
120
+ export interface CatalogOperations {
121
+ 'catalog.list': TerminalOperationDefinition<CatalogListArgs, CatalogListPage>;
122
+ 'catalog.variants': TerminalOperationDefinition<CatalogVariantsArgs, CatalogVariantsPage>;
123
+ }
124
+ /** Events merged into `TerminalEvents`. */
125
+ export interface CatalogEvents {
126
+ /** Catalog revision or `updating` state changed. */
127
+ 'catalog.state': CatalogStateDto;
128
+ }
129
+ /**
130
+ * Validates untrusted `catalog.list` arguments.
131
+ * @param value Detached JSON from the parent.
132
+ */
133
+ export declare function parseCatalogListArgs(value: unknown): CatalogListArgs;
134
+ /**
135
+ * Validates untrusted `catalog.variants` arguments.
136
+ * @param value Detached JSON from the parent.
137
+ */
138
+ export declare function parseCatalogVariantsArgs(value: unknown): CatalogVariantsArgs;
139
+ /**
140
+ * Shape check for a catalog state arriving from the child (events and replies).
141
+ * @param value Candidate payload.
142
+ */
143
+ export declare function isCatalogState(value: unknown): value is CatalogStateDto;
@@ -0,0 +1,61 @@
1
+ import { invalidArgument, rejectUnknownKeys, requireRecord, TERMINAL_BOUNDS } from './core.js';
2
+ /** Largest page of stories or variants by serialized UTF-8 bytes, below the frame bound. */
3
+ export const CATALOG_PAGE_BYTES = 160 * 1024;
4
+ /** Longest story ID (matches the catalog `validId` byte bound; IDs are never shortened). */
5
+ export const CATALOG_ID_MAX = 1024;
6
+ /** Longest search text. */
7
+ export const CATALOG_QUERY_MAX = 256;
8
+ /** Longest retained display text (title, file label); longer values are cut with an ellipsis. */
9
+ export const CATALOG_TEXT_MAX = 200;
10
+ /** Message of the failure raised when an expected revision is no longer current. */
11
+ export const CATALOG_STALE_MESSAGE = 'Catalog revision changed';
12
+ /** Validates an optional string argument. */
13
+ function optionalText(value, name, max) {
14
+ if (value === undefined)
15
+ return undefined;
16
+ if (typeof value !== 'string' || value.length > max || !value.isWellFormed())
17
+ invalidArgument(`${name} must be a string of at most ${max} characters`);
18
+ return value;
19
+ }
20
+ /** Validates the paging fields shared by both operations. */
21
+ function pagingArgs(args) {
22
+ const cursor = optionalText(args.cursor, 'cursor', TERMINAL_BOUNDS.idLength);
23
+ const expectedRevision = optionalText(args.expectedRevision, 'expectedRevision', TERMINAL_BOUNDS.idLength * 2);
24
+ // Continuing without the revision the cursor belongs to could silently mix revisions.
25
+ if (cursor !== undefined && expectedRevision === undefined)
26
+ invalidArgument('cursor requires expectedRevision');
27
+ if (args.limit !== undefined && (!Number.isInteger(args.limit) || args.limit < 1 || args.limit > TERMINAL_BOUNDS.pageItems))
28
+ invalidArgument(`limit must be 1..${TERMINAL_BOUNDS.pageItems}`);
29
+ return { query: optionalText(args.query, 'query', CATALOG_QUERY_MAX), cursor, expectedRevision, limit: args.limit };
30
+ }
31
+ /**
32
+ * Validates untrusted `catalog.list` arguments.
33
+ * @param value Detached JSON from the parent.
34
+ */
35
+ export function parseCatalogListArgs(value) {
36
+ const args = requireRecord(value);
37
+ rejectUnknownKeys(args, ['query', 'cursor', 'expectedRevision', 'limit']);
38
+ return pagingArgs(args);
39
+ }
40
+ /**
41
+ * Validates untrusted `catalog.variants` arguments.
42
+ * @param value Detached JSON from the parent.
43
+ */
44
+ export function parseCatalogVariantsArgs(value) {
45
+ const args = requireRecord(value);
46
+ rejectUnknownKeys(args, ['storyId', 'query', 'cursor', 'expectedRevision', 'limit']);
47
+ if (typeof args.storyId !== 'string' || !args.storyId.length || args.storyId.length > CATALOG_ID_MAX || !args.storyId.isWellFormed())
48
+ invalidArgument('storyId must be a non-empty string');
49
+ return { storyId: args.storyId, ...pagingArgs(args) };
50
+ }
51
+ /**
52
+ * Shape check for a catalog state arriving from the child (events and replies).
53
+ * @param value Candidate payload.
54
+ */
55
+ export function isCatalogState(value) {
56
+ if (!value || typeof value !== 'object')
57
+ return false;
58
+ const state = value;
59
+ return typeof state.updating === 'boolean' && Number.isFinite(state.stories) && Number.isFinite(state.variants) && Number.isFinite(state.diagnostics)
60
+ && (state.revision === undefined || typeof state.revision === 'string');
61
+ }
@@ -0,0 +1,117 @@
1
+ /**
2
+ * Shared terminal protocol primitives. Constants and tiny helpers only, so the
3
+ * parent can load this module before binding its listener.
4
+ */
5
+ /** Frozen numeric bounds; later slices must not exceed them. */
6
+ export declare const TERMINAL_BOUNDS: {
7
+ /** Largest serialized `runtime-*` frame. */
8
+ readonly frameBytes: number;
9
+ /** Longest correlation, operation or target identifier. */
10
+ readonly idLength: 100;
11
+ /** Pending parent reads per generation before immediate `busy` rejection. */
12
+ readonly pendingReads: 32;
13
+ /** Default read timeout. */
14
+ readonly readTimeoutMs: 10000;
15
+ /** Longest text (UTF-16 units) of one structured log event or retained line. */
16
+ readonly logTextLength: number;
17
+ /** Retained log entries. */
18
+ readonly logEntries: 2000;
19
+ /** Retained sanitized log text in UTF-8 bytes. */
20
+ readonly logBytes: number;
21
+ /** Retained HTTP request records. */
22
+ readonly requestEntries: 500;
23
+ /** Completed test runs retained per owner. */
24
+ readonly testRuns: 20;
25
+ /** Retained test summaries and fetched result data per owner, in bytes. */
26
+ readonly testBytes: number;
27
+ /** Largest page of catalog items or test cases. */
28
+ readonly pageItems: 100;
29
+ };
30
+ /** Stable failure codes shared by bridge and handlers. */
31
+ export type TerminalErrorCode =
32
+ /** Operation name is not registered in the child. */
33
+ 'unsupported'
34
+ /** Arguments or frame violate contract bounds. */
35
+ | 'invalid'
36
+ /** Too many reads pending for the generation. */
37
+ | 'busy'
38
+ /** Read exceeded its deadline; admitted work is not cancelled. */
39
+ | 'timeout'
40
+ /** Generation retired (restart, exit, shutdown) before an answer. */
41
+ | 'retired'
42
+ /** No ready runtime currently accepts commands. */
43
+ | 'unavailable'
44
+ /** Bridge was closed. */
45
+ | 'closed'
46
+ /** Handler failed. */
47
+ | 'failed';
48
+ /** Error carrying a stable code across the private channel. */
49
+ export declare class TerminalError extends Error {
50
+ readonly code: TerminalErrorCode;
51
+ /**
52
+ * Creates a coded failure.
53
+ * @param code Stable machine-readable code.
54
+ * @param message Short human-readable detail.
55
+ */
56
+ constructor(code: TerminalErrorCode, message: string);
57
+ }
58
+ /** Level of a structured log record. */
59
+ export type TerminalLogLevel = 'log' | 'info' | 'debug' | 'warn' | 'error';
60
+ /** Payload of the `log` runtime event: one intercepted console emission. */
61
+ export interface TerminalLogEvent {
62
+ /** Console level; stream-only emissions fall back to `log` or `error`. */
63
+ level: TerminalLogLevel;
64
+ /** Formatted, possibly multiline text without trailing newline. */
65
+ text: string;
66
+ /** Characters removed by the 16 KiB event bound, when truncated. */
67
+ truncated?: number;
68
+ }
69
+ /** Definition of one request/response operation. */
70
+ export interface TerminalOperationDefinition<Args = unknown, Result = unknown> {
71
+ args: Args;
72
+ result: Result;
73
+ }
74
+ /** Operation-name to definition map; every domain declares its own. */
75
+ export type TerminalOperationMap = Record<string, TerminalOperationDefinition>;
76
+ /** Event-name to payload map; every domain declares its own. */
77
+ export type TerminalEventMap = object;
78
+ /** Operations owned by the core protocol (none yet). */
79
+ export type CoreOperations = Record<never, TerminalOperationDefinition>;
80
+ /** Events owned by the core protocol. */
81
+ export interface CoreEvents {
82
+ /** Intercepted child console emission. */
83
+ log: TerminalLogEvent;
84
+ }
85
+ /** Whether a value is a valid operation/correlation/target identifier; the bound is the transport's. */
86
+ export declare const isTerminalId: (value: unknown) => value is string;
87
+ /**
88
+ * Cuts text to a character bound without splitting a surrogate pair.
89
+ * @param text Text to bound.
90
+ * @param max Maximum retained UTF-16 units.
91
+ * @returns Retained text and number of removed units (0 when untouched).
92
+ */
93
+ export declare function truncateText(text: string, max: number): {
94
+ text: string;
95
+ truncated: number;
96
+ };
97
+ /**
98
+ * Validates an untrusted `log` event payload from the child.
99
+ * @param value Candidate payload.
100
+ */
101
+ export declare function isTerminalLogEvent(value: unknown): value is TerminalLogEvent;
102
+ /**
103
+ * Throws the contracted invalid-argument error.
104
+ * @param message Short human-readable detail.
105
+ */
106
+ export declare function invalidArgument(message: string): never;
107
+ /**
108
+ * Requires untrusted arguments to be a plain object.
109
+ * @param value Detached JSON from the parent.
110
+ */
111
+ export declare function requireRecord(value: unknown): Record<string, unknown>;
112
+ /**
113
+ * Rejects unknown keys so typos cannot silently widen a request.
114
+ * @param value Validated argument object.
115
+ * @param allowed Accepted key names.
116
+ */
117
+ export declare function rejectUnknownKeys(value: Record<string, unknown>, allowed: readonly string[]): void;
@@ -0,0 +1,98 @@
1
+ import { isIdentifier, RUNTIME_FRAME_MAX_BYTES, RUNTIME_ID_MAX_LENGTH } from '@histoire/dev-proxy/protocol';
2
+ /**
3
+ * Shared terminal protocol primitives. Constants and tiny helpers only, so the
4
+ * parent can load this module before binding its listener.
5
+ */
6
+ /** Frozen numeric bounds; later slices must not exceed them. */
7
+ export const TERMINAL_BOUNDS = {
8
+ /** Largest serialized `runtime-*` frame. */
9
+ frameBytes: RUNTIME_FRAME_MAX_BYTES,
10
+ /** Longest correlation, operation or target identifier. */
11
+ idLength: RUNTIME_ID_MAX_LENGTH,
12
+ /** Pending parent reads per generation before immediate `busy` rejection. */
13
+ pendingReads: 32,
14
+ /** Default read timeout. */
15
+ readTimeoutMs: 10_000,
16
+ /** Longest text (UTF-16 units) of one structured log event or retained line. */
17
+ logTextLength: 16 * 1024,
18
+ /** Retained log entries. */
19
+ logEntries: 2000,
20
+ /** Retained sanitized log text in UTF-8 bytes. */
21
+ logBytes: 2 * 1024 * 1024,
22
+ /** Retained HTTP request records. */
23
+ requestEntries: 500,
24
+ /** Completed test runs retained per owner. */
25
+ testRuns: 20,
26
+ /** Retained test summaries and fetched result data per owner, in bytes. */
27
+ testBytes: 8 * 1024 * 1024,
28
+ /** Largest page of catalog items or test cases. */
29
+ pageItems: 100,
30
+ };
31
+ /** Error carrying a stable code across the private channel. */
32
+ export class TerminalError extends Error {
33
+ code;
34
+ /**
35
+ * Creates a coded failure.
36
+ * @param code Stable machine-readable code.
37
+ * @param message Short human-readable detail.
38
+ */
39
+ constructor(code, message) {
40
+ super(message);
41
+ this.code = code;
42
+ this.name = 'TerminalError';
43
+ }
44
+ }
45
+ /** Whether a value is a valid operation/correlation/target identifier; the bound is the transport's. */
46
+ export const isTerminalId = isIdentifier;
47
+ /**
48
+ * Cuts text to a character bound without splitting a surrogate pair.
49
+ * @param text Text to bound.
50
+ * @param max Maximum retained UTF-16 units.
51
+ * @returns Retained text and number of removed units (0 when untouched).
52
+ */
53
+ export function truncateText(text, max) {
54
+ if (text.length <= max)
55
+ return { text, truncated: 0 };
56
+ let end = max;
57
+ const last = text.charCodeAt(end - 1);
58
+ if (last >= 0xD800 && last <= 0xDBFF)
59
+ end--;
60
+ return { text: text.slice(0, end), truncated: text.length - end };
61
+ }
62
+ /**
63
+ * Validates an untrusted `log` event payload from the child.
64
+ * @param value Candidate payload.
65
+ */
66
+ export function isTerminalLogEvent(value) {
67
+ if (!value || typeof value !== 'object')
68
+ return false;
69
+ const event = value;
70
+ return typeof event.text === 'string' && ['log', 'info', 'debug', 'warn', 'error'].includes(event.level) && (event.truncated === undefined || typeof event.truncated === 'number');
71
+ }
72
+ /**
73
+ * Throws the contracted invalid-argument error.
74
+ * @param message Short human-readable detail.
75
+ */
76
+ export function invalidArgument(message) {
77
+ throw new TerminalError('invalid', message);
78
+ }
79
+ /**
80
+ * Requires untrusted arguments to be a plain object.
81
+ * @param value Detached JSON from the parent.
82
+ */
83
+ export function requireRecord(value) {
84
+ if (!value || typeof value !== 'object' || Array.isArray(value))
85
+ invalidArgument('Arguments must be an object');
86
+ return value;
87
+ }
88
+ /**
89
+ * Rejects unknown keys so typos cannot silently widen a request.
90
+ * @param value Validated argument object.
91
+ * @param allowed Accepted key names.
92
+ */
93
+ export function rejectUnknownKeys(value, allowed) {
94
+ for (const key of Object.keys(value)) {
95
+ if (!allowed.includes(key))
96
+ invalidArgument(`Unknown argument: ${key.slice(0, 40)}`);
97
+ }
98
+ }
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Runtime diagnostics DTOs (slice 06). Type-and-constant only, so the parent can load it
3
+ * before binding its listener. Holds no credential, no MCP protocol arguments and no client
4
+ * envelope beyond a sanitized display name.
5
+ */
6
+ /** Bounds of the diagnostics reply. */
7
+ export declare const DIAGNOSTICS_BOUNDS: {
8
+ /** Collection issues listed. */
9
+ readonly issues: 20;
10
+ /** Longest issue message and client name (UTF-16 units). */
11
+ readonly text: 512;
12
+ /** Connected MCP clients named. */
13
+ readonly clients: 10;
14
+ };
15
+ /** One safe collection issue. */
16
+ export interface DiagnosticIssueDto {
17
+ /** Stable machine category, e.g. `COLLECTION_FAILED`. */
18
+ code: string;
19
+ /** Sanitized explanation (project root and credential already removed by the catalog). */
20
+ message: string;
21
+ /** Related project-relative file. */
22
+ file?: string;
23
+ /** Related story. */
24
+ storyId?: string;
25
+ }
26
+ /** Collection diagnostics of the current generation's catalog. */
27
+ export interface DiagnosticsCollectionDto {
28
+ /** Completed collection category. */
29
+ outcome: 'success' | 'partial' | 'failed';
30
+ stories: number;
31
+ variants: number;
32
+ /** Issues retained by the catalog (the listed ones are at most {@link DIAGNOSTICS_BOUNDS.issues}). */
33
+ issues: number;
34
+ /** The catalog itself omitted further issues. */
35
+ truncated: boolean;
36
+ /** First issues, bounded. */
37
+ items: DiagnosticIssueDto[];
38
+ }
39
+ /** Safe MCP summary: availability, endpoint and who is connected. */
40
+ export interface DiagnosticsMcpDto {
41
+ status: 'enabled' | 'disabled' | 'unavailable';
42
+ /** Actual bound endpoint, without credentials. */
43
+ endpoint?: string;
44
+ /** Clients must present a bearer token (the token itself is never included). */
45
+ tokenRequired?: boolean;
46
+ /** Connected clients (display name and transport), at most {@link DIAGNOSTICS_BOUNDS.clients}. */
47
+ clients: {
48
+ name: string;
49
+ transport: 'stdio' | 'http';
50
+ }[];
51
+ /** Connected clients beyond the named ones. */
52
+ clientsOmitted: number;
53
+ /** Queued or running MCP operations. */
54
+ activeOperations: number;
55
+ }
56
+ /** Result of `diagnostics.get`; each section fails independently. */
57
+ export interface DiagnosticsDto {
58
+ /** Absent until a collection completed, or when `problems.collection` is set. */
59
+ collection?: DiagnosticsCollectionDto;
60
+ /** Absent only when `problems.mcp` is set. */
61
+ mcp?: DiagnosticsMcpDto;
62
+ /** Sections that could not be read, with a one-line reason. */
63
+ problems: {
64
+ collection?: string;
65
+ mcp?: string;
66
+ };
67
+ }
68
+ /** Operations added by the diagnostics domain. */
69
+ export interface DiagnosticsOperations {
70
+ 'diagnostics.get': {
71
+ args: Record<string, never>;
72
+ result: DiagnosticsDto;
73
+ };
74
+ }
75
+ /**
76
+ * Validates an untrusted `diagnostics.get` result in the parent; anything else is discarded.
77
+ * @param value Candidate payload.
78
+ */
79
+ export declare function isDiagnostics(value: unknown): value is DiagnosticsDto;
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Runtime diagnostics DTOs (slice 06). Type-and-constant only, so the parent can load it
3
+ * before binding its listener. Holds no credential, no MCP protocol arguments and no client
4
+ * envelope beyond a sanitized display name.
5
+ */
6
+ /** Bounds of the diagnostics reply. */
7
+ export const DIAGNOSTICS_BOUNDS = {
8
+ /** Collection issues listed. */
9
+ issues: 20,
10
+ /** Longest issue message and client name (UTF-16 units). */
11
+ text: 512,
12
+ /** Connected MCP clients named. */
13
+ clients: 10,
14
+ };
15
+ /**
16
+ * Validates an untrusted `diagnostics.get` result in the parent; anything else is discarded.
17
+ * @param value Candidate payload.
18
+ */
19
+ export function isDiagnostics(value) {
20
+ if (!value || typeof value !== 'object')
21
+ return false;
22
+ const dto = value;
23
+ const problems = dto.problems;
24
+ if (!problems || typeof problems !== 'object')
25
+ return false;
26
+ const collection = dto.collection;
27
+ if (collection !== undefined && (typeof collection !== 'object' || !['success', 'partial', 'failed'].includes(collection.outcome) || !Array.isArray(collection.items) || typeof collection.issues !== 'number'))
28
+ return false;
29
+ const mcp = dto.mcp;
30
+ return mcp === undefined || (typeof mcp === 'object' && ['enabled', 'disabled', 'unavailable'].includes(mcp.status) && Array.isArray(mcp.clients));
31
+ }