vouchington-tooling 0.63.0 → 0.65.0

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 (90) hide show
  1. package/README.md +109 -7
  2. package/dist/cli/commands/cloc.d.mts +7 -0
  3. package/dist/cli/commands/cloc.mjs +47 -0
  4. package/dist/cli/commands/storybook-browser-runner.d.mts +7 -0
  5. package/dist/cli/commands/storybook-browser-runner.mjs +29 -0
  6. package/dist/cli/commands/worktree.d.mts +1 -1
  7. package/dist/cli/commands/worktree.mjs +54 -7
  8. package/dist/cli/index.mjs +4 -0
  9. package/dist/cli/parse-forwarded-commands.d.mts +6 -0
  10. package/dist/cli/parse-forwarded-commands.mjs +4 -0
  11. package/dist/cli/parse.d.mts +6 -0
  12. package/dist/cli/usage-text.d.mts +1 -1
  13. package/dist/cli/usage-text.mjs +19 -1
  14. package/dist/cloc/child-process.d.mts +3 -0
  15. package/dist/cloc/child-process.mjs +14 -0
  16. package/dist/cloc/classify.d.mts +8 -0
  17. package/dist/cloc/classify.mjs +20 -0
  18. package/dist/cloc/config-load.d.mts +7 -0
  19. package/dist/cloc/config-load.mjs +26 -0
  20. package/dist/cloc/config.d.mts +55 -0
  21. package/dist/cloc/config.mjs +109 -0
  22. package/dist/cloc/count.d.mts +9 -0
  23. package/dist/cloc/count.mjs +33 -0
  24. package/dist/cloc/index.d.mts +12 -0
  25. package/dist/cloc/index.mjs +7 -0
  26. package/dist/cloc/layout.test-helpers.d.mts +8 -0
  27. package/dist/cloc/layout.test-helpers.mjs +42 -0
  28. package/dist/cloc/paths.d.mts +7 -0
  29. package/dist/cloc/paths.mjs +29 -0
  30. package/dist/cloc/patterns.d.mts +10 -0
  31. package/dist/cloc/patterns.mjs +25 -0
  32. package/dist/cloc/rows.d.mts +13 -0
  33. package/dist/cloc/rows.mjs +42 -0
  34. package/dist/cloc/scc.d.mts +10 -0
  35. package/dist/cloc/scc.mjs +55 -0
  36. package/dist/cloc/tracked.d.mts +4 -0
  37. package/dist/cloc/tracked.mjs +40 -0
  38. package/dist/command-policy/engine.mjs +9 -2
  39. package/dist/command-policy/hook/post-tool-use.mjs +3 -0
  40. package/dist/git-worktrees/assess.d.mts +15 -0
  41. package/dist/git-worktrees/assess.mjs +25 -6
  42. package/dist/git-worktrees/reclaim.d.mts +15 -2
  43. package/dist/git-worktrees/reclaim.mjs +49 -11
  44. package/dist/git-worktrees/reclaim.test-helpers.mjs +11 -5
  45. package/dist/git-worktrees/run.d.mts +2 -0
  46. package/dist/git-worktrees/run.mjs +4 -1
  47. package/dist/shell-parse/shell-heredoc.mjs +9 -1
  48. package/dist/storybook-browser-runner/args.d.mts +8 -0
  49. package/dist/storybook-browser-runner/args.mjs +52 -0
  50. package/dist/storybook-browser-runner/attempt-result.d.mts +41 -0
  51. package/dist/storybook-browser-runner/attempt-result.mjs +108 -0
  52. package/dist/storybook-browser-runner/bootstrap-telemetry.d.mts +35 -0
  53. package/dist/storybook-browser-runner/bootstrap-telemetry.mjs +138 -0
  54. package/dist/storybook-browser-runner/cache-plan.d.mts +22 -0
  55. package/dist/storybook-browser-runner/cache-plan.mjs +53 -0
  56. package/dist/storybook-browser-runner/diagnostics.d.mts +8 -0
  57. package/dist/storybook-browser-runner/diagnostics.mjs +29 -0
  58. package/dist/storybook-browser-runner/env.d.mts +2 -0
  59. package/dist/storybook-browser-runner/env.mjs +59 -0
  60. package/dist/storybook-browser-runner/fixtures.test-helpers.d.mts +49 -0
  61. package/dist/storybook-browser-runner/fixtures.test-helpers.mjs +95 -0
  62. package/dist/storybook-browser-runner/index.d.mts +15 -0
  63. package/dist/storybook-browser-runner/index.mjs +70 -0
  64. package/dist/storybook-browser-runner/observer-state.d.mts +22 -0
  65. package/dist/storybook-browser-runner/observer-state.mjs +21 -0
  66. package/dist/storybook-browser-runner/options.d.mts +18 -0
  67. package/dist/storybook-browser-runner/options.mjs +49 -0
  68. package/dist/storybook-browser-runner/output-observer.d.mts +37 -0
  69. package/dist/storybook-browser-runner/output-observer.mjs +130 -0
  70. package/dist/storybook-browser-runner/output-patterns.d.mts +14 -0
  71. package/dist/storybook-browser-runner/output-patterns.mjs +26 -0
  72. package/dist/storybook-browser-runner/quiet-output.d.mts +16 -0
  73. package/dist/storybook-browser-runner/quiet-output.mjs +79 -0
  74. package/dist/storybook-browser-runner/run-attempt.d.mts +14 -0
  75. package/dist/storybook-browser-runner/run-attempt.mjs +111 -0
  76. package/dist/storybook-browser-runner/runtime-metadata.d.mts +12 -0
  77. package/dist/storybook-browser-runner/runtime-metadata.mjs +50 -0
  78. package/dist/storybook-browser-runner/session-deps.d.mts +11 -0
  79. package/dist/storybook-browser-runner/session-deps.mjs +70 -0
  80. package/dist/storybook-browser-runner/types.d.mts +49 -0
  81. package/dist/storybook-browser-runner/types.mjs +1 -0
  82. package/dist/storybook-browser-runner/vite-detectors.d.mts +6 -0
  83. package/dist/storybook-browser-runner/vite-detectors.mjs +20 -0
  84. package/dist/storybook-browser-runner/watchdog.d.mts +23 -0
  85. package/dist/storybook-browser-runner/watchdog.mjs +55 -0
  86. package/package.json +12 -2
  87. package/scripts/__pycache__/run_bounded_process.cpython-312.pyc +0 -0
  88. package/skills/blackboard/SKILL.md +6 -3
  89. package/skills/manifest.json +20 -20
  90. package/skills/retrospective-distill/SKILL.md +3 -4
@@ -0,0 +1,53 @@
1
+ import { resolve } from 'node:path';
2
+ import { storybookBrowserAttemptCacheDir } from "./env.mjs";
3
+ import { envName } from "./options.mjs";
4
+ export function storybookBrowserPersistentCacheDir(project, env, cwd) {
5
+ if (env[envName(project, 'PERSISTENT_CACHE')] === '0')
6
+ return undefined;
7
+ const configured = env[envName(project, 'PERSISTENT_CACHE_DIR')];
8
+ if (configured)
9
+ return resolve(cwd, configured);
10
+ return env.CI ? resolve(cwd, '.cache/vite/storybook-browser') : undefined;
11
+ }
12
+ export function initialCachePlan(attemptEnv, persistentCacheDir) {
13
+ if (persistentCacheDir) {
14
+ return { dir: persistentCacheDir, persistentDir: persistentCacheDir, role: 'persistent' };
15
+ }
16
+ const dir = attemptEnv.VITEST_STORYBOOK_BROWSER_CACHE_DIR;
17
+ if (!dir)
18
+ throw new Error('makeAttemptEnv did not set Vite cache dir for attempt cache');
19
+ return { dir, persistentDir: persistentCacheDir, role: 'attempt' };
20
+ }
21
+ export function nextCachePlan(input) {
22
+ const { attempt, attemptEnv, cachePlan, deps, persistentCacheDir, result } = input;
23
+ if (!result.optimizerReloadFromNewDeps &&
24
+ (result.isStall ||
25
+ result.runnerMissing ||
26
+ result.viteFetchFailure ||
27
+ (result.hung && !result.viteReady))) {
28
+ if (cachePlan.role === 'persistent')
29
+ clearPersistentCache(cachePlan.dir, deps);
30
+ // The directory is named by attempt number, so an earlier run may have left stale state in it.
31
+ const dir = storybookBrowserAttemptCacheDir(attemptEnv, attempt + 1, deps.cwd);
32
+ deps.rmSync(dir, { force: true, recursive: true });
33
+ return { dir, persistentDir: persistentCacheDir, role: 'attempt' };
34
+ }
35
+ return cachePlan;
36
+ }
37
+ export function clearPersistentCache(cacheDir, deps) {
38
+ deps.stderr.write(`[storybook-browser] clearing persistent cache after failed startup: ${cacheDir}\n`);
39
+ deps.rmSync(cacheDir, { force: true, recursive: true });
40
+ }
41
+ /** Copies a successful attempt's optimizer cache over the persistent cache. */
42
+ export function promoteAttemptCache(cachePlan, deps, result) {
43
+ if (result.code !== 0 || cachePlan.role !== 'attempt' || !cachePlan.persistentDir)
44
+ return;
45
+ if (!deps.existsSync(resolve(cachePlan.dir, 'deps/_metadata.json'))) {
46
+ deps.stderr.write(`[storybook-browser] not promoting attempt cache; optimizer metadata missing in ${cachePlan.dir}\n`);
47
+ return;
48
+ }
49
+ deps.rmSync(cachePlan.persistentDir, { force: true, recursive: true });
50
+ deps.mkdirSync(resolve(cachePlan.persistentDir, '..'), { recursive: true });
51
+ deps.cpSync(cachePlan.dir, cachePlan.persistentDir, { recursive: true });
52
+ deps.stderr.write(`[storybook-browser] promoted attempt cache ${cachePlan.dir} to persistent cache ${cachePlan.persistentDir}\n`);
53
+ }
@@ -0,0 +1,8 @@
1
+ export declare class StorybookBrowserDiagnostics {
2
+ private readonly summaries;
3
+ private outputTail;
4
+ private outputTruncated;
5
+ recordOutput(chunk: string | Buffer): void;
6
+ recordAttempt(summary: string): void;
7
+ render(): Buffer;
8
+ }
@@ -0,0 +1,29 @@
1
+ const MAX_DIAGNOSTIC_BYTES = 1024 * 1024;
2
+ const MAX_OUTPUT_TAIL_BYTES = 960 * 1024;
3
+ const truncatedMarker = Buffer.from('[diagnostic output truncated]\n');
4
+ export class StorybookBrowserDiagnostics {
5
+ summaries = [];
6
+ outputTail = Buffer.alloc(0);
7
+ outputTruncated = false;
8
+ recordOutput(chunk) {
9
+ const next = Buffer.concat([this.outputTail, Buffer.from(chunk)]);
10
+ if (next.byteLength <= MAX_OUTPUT_TAIL_BYTES) {
11
+ this.outputTail = next;
12
+ return;
13
+ }
14
+ this.outputTruncated = true;
15
+ this.outputTail = next.subarray(next.byteLength - MAX_OUTPUT_TAIL_BYTES);
16
+ }
17
+ recordAttempt(summary) {
18
+ this.summaries.push(summary.trimEnd());
19
+ }
20
+ render() {
21
+ const summary = Buffer.from(`${['[storybook-browser-diagnostics]', ...this.summaries, 'output tail:'].join('\n')}\n`);
22
+ const prefix = this.outputTruncated ? Buffer.concat([summary, truncatedMarker]) : summary;
23
+ const available = Math.max(0, MAX_DIAGNOSTIC_BYTES - prefix.byteLength);
24
+ const tail = this.outputTail.byteLength <= available
25
+ ? this.outputTail
26
+ : this.outputTail.subarray(this.outputTail.byteLength - available);
27
+ return Buffer.concat([prefix, tail]).subarray(0, MAX_DIAGNOSTIC_BYTES);
28
+ }
29
+ }
@@ -0,0 +1,2 @@
1
+ export declare function makeAttemptEnv(projectName: string, env: NodeJS.ProcessEnv, attempt: number, cwd: string, priorHang?: boolean): NodeJS.ProcessEnv;
2
+ export declare function storybookBrowserAttemptCacheDir(env: NodeJS.ProcessEnv, attempt: number, cwd: string): string;
@@ -0,0 +1,59 @@
1
+ import { tmpdir } from 'node:os';
2
+ import { resolve } from 'node:path';
3
+ import { parsePositiveInteger } from "./options.mjs";
4
+ const MIN_PORT = 1024;
5
+ const MAX_TCP_PORT = 65_535;
6
+ export function makeAttemptEnv(projectName, env, attempt, cwd, priorHang = false) {
7
+ let debug = removeUnboundedProtocolDebug(env.DEBUG);
8
+ debug = appendDebugNamespace(debug, '-pw:protocol*');
9
+ debug = appendDebugNamespace(debug, 'vitest:browser:playwright');
10
+ debug = appendDebugNamespace(debug, 'vitest:browser:api');
11
+ // Keep only bounded browser lifecycle evidence after a hang. Raw protocol traffic can exceed
12
+ // hundreds of MiB while conveying no semantic test progress.
13
+ if (priorHang)
14
+ debug = appendDebugNamespace(debug, 'pw:browser*');
15
+ return {
16
+ ...env,
17
+ DEBUG: appendDebugNamespace(debug, 'vite:deps'),
18
+ STORYBOOK_DISABLE_TELEMETRY: '1',
19
+ VITEST_COVERAGE_SCOPE: projectName,
20
+ VITEST_PW_DEBUG: '1',
21
+ VITEST_STORYBOOK_BROWSER: '1',
22
+ VITEST_STORYBOOK_BROWSER_API_PORT: String(storybookBrowserApiPort(env, attempt)),
23
+ VITEST_STORYBOOK_BROWSER_CACHE_DIR: storybookBrowserAttemptCacheDir(env, attempt, cwd),
24
+ };
25
+ }
26
+ export function storybookBrowserAttemptCacheDir(env, attempt, cwd) {
27
+ if (!env.CI && !env.RUNNER_TEMP) {
28
+ return resolve(cwd, `node_modules/.vite/storybook-browser-attempt-${attempt}`);
29
+ }
30
+ return resolve(env.RUNNER_TEMP || env.TMPDIR || tmpdir(), `vite-storybook-browser-attempt-${attempt}`);
31
+ }
32
+ function removeUnboundedProtocolDebug(value) {
33
+ if (!value)
34
+ return value;
35
+ const namespaces = value
36
+ .split(',')
37
+ .map((namespace) => namespace.trim())
38
+ .filter((namespace) => namespace && !/^-?pw:protocol\*?$/.test(namespace));
39
+ return namespaces.length > 0 ? namespaces.join(',') : undefined;
40
+ }
41
+ function storybookBrowserApiPort(env, attempt) {
42
+ const parsed = parsePositiveInteger(env.VITEST_STORYBOOK_BROWSER_API_PORT, 0);
43
+ const explicitPort = parsed >= MIN_PORT && parsed <= MAX_TCP_PORT ? parsed : 0;
44
+ const offset = (attempt - 1) * 137;
45
+ // Wrap inside the unprivileged range so a retry offset never produces a port that needs root.
46
+ if (explicitPort)
47
+ return MIN_PORT + ((explicitPort - MIN_PORT + offset) % (MAX_TCP_PORT - MIN_PORT + 1));
48
+ return 45_000 + ((process.pid + offset) % 10_000);
49
+ }
50
+ function appendDebugNamespace(value, namespace) {
51
+ if (!value)
52
+ return namespace;
53
+ return value
54
+ .split(',')
55
+ .map((part) => part.trim())
56
+ .includes(namespace)
57
+ ? value
58
+ : `${value},${namespace}`;
59
+ }
@@ -0,0 +1,49 @@
1
+ import { EventEmitter } from 'node:events';
2
+ import type { StorybookBrowserProject, StorybookBrowserRunnerDeps } from './types.mts';
3
+ export declare const PROJECT_NAME = "browser-suite";
4
+ export declare const PROJECT: StorybookBrowserProject;
5
+ export type Child = EventEmitter & {
6
+ kill: (signal: NodeJS.Signals) => boolean;
7
+ pid: number | undefined;
8
+ stderr: EventEmitter;
9
+ stdout: EventEmitter;
10
+ };
11
+ export declare function makeChild(pid: number | undefined): Child;
12
+ export type FakeOptions = {
13
+ exists?: (path: string) => boolean;
14
+ isProcessGroupAlive?: StorybookBrowserRunnerDeps['isProcessGroupAlive'];
15
+ now?: () => number;
16
+ };
17
+ /** Injected spawn, clock, timers, filesystem and streams: no process or browser is started. */
18
+ export declare function makeDeps(children: Child[], options?: FakeOptions): {
19
+ copied: {
20
+ dest: string;
21
+ src: string;
22
+ }[];
23
+ deps: StorybookBrowserRunnerDeps;
24
+ dirs: string[];
25
+ intervals: {
26
+ callback: () => void;
27
+ }[];
28
+ killed: {
29
+ pid: number;
30
+ signal: NodeJS.Signals;
31
+ }[];
32
+ removed: string[];
33
+ spawnCalls: {
34
+ args: string[];
35
+ command: string;
36
+ env: NodeJS.ProcessEnv;
37
+ }[];
38
+ stderr: string[];
39
+ stdout: string[];
40
+ written: {
41
+ content: string;
42
+ path: string;
43
+ }[];
44
+ };
45
+ export declare function exitChild(child: Child, code: number | null, signal?: NodeJS.Signals | null): void;
46
+ export declare function waitFor(predicate: () => boolean): Promise<void>;
47
+ export declare const fetchFailure = "Failed to fetch dynamically imported module: http://localhost:47711/@id/__x00__virtual:/project-annotations.js";
48
+ export declare const runnerMissing: string;
49
+ export declare const progress: (sequence: number) => string;
@@ -0,0 +1,95 @@
1
+ import { EventEmitter } from 'node:events';
2
+ import { expect } from 'vitest';
3
+ export const PROJECT_NAME = 'browser-suite';
4
+ export const PROJECT = {
5
+ completionFile: '.vitest-reports/browser-suite.json',
6
+ optimizeDepsConfigPath: 'config/optimize-deps.mts',
7
+ projectName: PROJECT_NAME,
8
+ resultFiles: ['.vitest-reports/browser-suite.json', 'coverage/lcov.info'],
9
+ };
10
+ export function makeChild(pid) {
11
+ return Object.assign(new EventEmitter(), {
12
+ kill: () => true,
13
+ pid,
14
+ stderr: new EventEmitter(),
15
+ stdout: new EventEmitter(),
16
+ });
17
+ }
18
+ /** Injected spawn, clock, timers, filesystem and streams: no process or browser is started. */
19
+ export function makeDeps(children, options = {}) {
20
+ const spawnCalls = [];
21
+ const intervals = [];
22
+ const killed = [];
23
+ const copied = [];
24
+ const dirs = [];
25
+ const removed = [];
26
+ const stderr = [];
27
+ const stdout = [];
28
+ const written = [];
29
+ const live = new Set();
30
+ let index = 0;
31
+ const deps = {
32
+ clearInterval: (timer) => {
33
+ const at = intervals.indexOf(timer);
34
+ if (at !== -1)
35
+ intervals.splice(at, 1);
36
+ },
37
+ clearTimeout: () => undefined,
38
+ cpSync: (src, dest) => void copied.push({ dest: String(dest), src: String(src) }),
39
+ cwd: '/repo',
40
+ existsSync: (path) => options.exists?.(String(path)) ?? false,
41
+ isProcessGroupAlive: options.isProcessGroupAlive ?? ((pid) => live.has(pid)),
42
+ killProcessGroup: (pid, signal) => {
43
+ if (signal === 'SIGTERM')
44
+ live.add(pid);
45
+ killed.push({ pid, signal });
46
+ },
47
+ mkdirSync: (path) => (dirs.push(String(path)), undefined),
48
+ now: options.now ?? (() => 0),
49
+ offParentSignal: () => undefined,
50
+ onParentSignal: () => undefined,
51
+ rmSync: (path) => void removed.push(String(path)),
52
+ setInterval: ((callback) => {
53
+ const interval = { callback };
54
+ intervals.push(interval);
55
+ return interval;
56
+ }),
57
+ setTimeout: ((callback, delay = 0) => {
58
+ if (delay <= 5000)
59
+ callback();
60
+ return { delay };
61
+ }),
62
+ spawn: ((command, args, spawnOptions) => {
63
+ const child = children[index++];
64
+ if (!child)
65
+ throw new Error('unexpected spawn');
66
+ spawnCalls.push({ args: [...(args ?? [])], command, env: spawnOptions?.env ?? {} });
67
+ return child;
68
+ }),
69
+ stderr: { write: (chunk) => (stderr.push(String(chunk)), true) },
70
+ stdout: { write: (chunk) => (stdout.push(String(chunk)), true) },
71
+ waitForProcessGroupExit: async (pid) => void live.delete(pid),
72
+ writeFileSync: (path, content) => void written.push({
73
+ content: typeof content === 'string' ? content : Buffer.from(content).toString(),
74
+ path: String(path),
75
+ }),
76
+ };
77
+ return { copied, deps, dirs, intervals, killed, removed, spawnCalls, stderr, stdout, written };
78
+ }
79
+ export function exitChild(child, code, signal = null) {
80
+ child.emit('exit', code, signal);
81
+ child.emit('close', code, signal);
82
+ }
83
+ export async function waitFor(predicate) {
84
+ for (let attempt = 0; attempt < 20; attempt += 1) {
85
+ if (predicate())
86
+ return;
87
+ await Promise.resolve();
88
+ }
89
+ expect(predicate()).toBe(true);
90
+ }
91
+ export const fetchFailure = 'Failed to fetch dynamically imported module: http://localhost:47711/@id/__x00__virtual:/project-annotations.js';
92
+ export const runnerMissing = 'Error: Failed to import test file /repo/node_modules/.pnpm/x/node_modules/@storybook/addon-vitest/dist/vitest-plugin/setup-file.js\n' +
93
+ 'Caused by: Error: Vitest failed to find the runner.\n' +
94
+ 'Test Files 149 failed\n';
95
+ export const progress = (sequence) => `[vitest-browser-progress] seq=${sequence} event=module-start module="a.stories.tsx"\n`;
@@ -0,0 +1,15 @@
1
+ import type { StorybookBrowserProject, StorybookBrowserRunnerDeps } from './types.mts';
2
+ export { makeAttemptEnv, storybookBrowserAttemptCacheDir } from './env.mts';
3
+ export { commandArgs, parsePositiveInteger, resolveProject, resolveRunnerOptions, } from './options.mts';
4
+ export type { StorybookBrowserRunnerOptions } from './options.mts';
5
+ export { parseStorybookBrowserRunnerArgs } from './args.mts';
6
+ export type { ParsedStorybookBrowserRunnerArgs } from './args.mts';
7
+ export type { ResolvedStorybookBrowserProject, StorybookBrowserProject, StorybookBrowserRunnerDeps, } from './types.mts';
8
+ /**
9
+ * Runs the Storybook Vitest browser project under a watchdog with a Vite optimizer cache, retries
10
+ * on known Vite and browser start-up flakes, and a shared session budget. Resolves with the
11
+ * process exit code.
12
+ */
13
+ export declare function runStorybookBrowserTests(project: StorybookBrowserProject, options?: {
14
+ env?: NodeJS.ProcessEnv;
15
+ }, deps?: StorybookBrowserRunnerDeps): Promise<number>;
@@ -0,0 +1,70 @@
1
+ import { dirname, resolve } from 'node:path';
2
+ import { formatAttemptResult } from "./attempt-result.mjs";
3
+ import { initialCachePlan, nextCachePlan, promoteAttemptCache, storybookBrowserPersistentCacheDir, } from "./cache-plan.mjs";
4
+ import { StorybookBrowserDiagnostics } from "./diagnostics.mjs";
5
+ import { makeAttemptEnv } from "./env.mjs";
6
+ import { resolveProject, resolveRunnerOptions } from "./options.mjs";
7
+ import { runUpstreamAttempt } from "./run-attempt.mjs";
8
+ import { storybookBrowserRuntimeMetadata } from "./runtime-metadata.mjs";
9
+ import { defaultRunnerDeps } from "./session-deps.mjs";
10
+ export { makeAttemptEnv, storybookBrowserAttemptCacheDir } from "./env.mjs";
11
+ export { commandArgs, parsePositiveInteger, resolveProject, resolveRunnerOptions, } from "./options.mjs";
12
+ export { parseStorybookBrowserRunnerArgs } from "./args.mjs";
13
+ /**
14
+ * Runs the Storybook Vitest browser project under a watchdog with a Vite optimizer cache, retries
15
+ * on known Vite and browser start-up flakes, and a shared session budget. Resolves with the
16
+ * process exit code.
17
+ */
18
+ export async function runStorybookBrowserTests(project, options = {}, deps = defaultRunnerDeps()) {
19
+ const resolved = resolveProject(project);
20
+ const env = { ...process.env, ...options.env };
21
+ const settings = resolveRunnerOptions(resolved, env);
22
+ const sessionDeadlineAt = deps.now() + settings.sessionBudgetMs;
23
+ const diagnostics = new StorybookBrowserDiagnostics();
24
+ const runtimeSummary = `[storybook-browser] runtime=${JSON.stringify(storybookBrowserRuntimeMetadata(deps.cwd))}\n`;
25
+ deps.stderr.write(runtimeSummary);
26
+ diagnostics.recordAttempt(runtimeSummary);
27
+ const diagnosticsPath = resolve(deps.cwd, settings.diagnosticsFile);
28
+ const persistentCacheDir = storybookBrowserPersistentCacheDir(resolved, env, deps.cwd);
29
+ let cachePlan;
30
+ let priorHang = false;
31
+ for (let attempt = 1;; attempt += 1) {
32
+ for (const path of resolved.resultFiles)
33
+ deps.rmSync(resolve(deps.cwd, path), { force: true });
34
+ const attemptEnv = makeAttemptEnv(resolved.projectName, env, attempt, deps.cwd, priorHang);
35
+ cachePlan ??= initialCachePlan(attemptEnv, persistentCacheDir);
36
+ attemptEnv.VITEST_STORYBOOK_BROWSER_CACHE_DIR = cachePlan.dir;
37
+ if (cachePlan.role === 'persistent')
38
+ deps.mkdirSync(cachePlan.dir, { recursive: true });
39
+ deps.stderr.write(`[storybook-browser] starting attempt ${attempt}/${settings.attempts} with ${cachePlan.role} cache ${cachePlan.dir}; optimizerStallMs=${settings.stallMs}; hangMs=${settings.hangMs}\n`);
40
+ const result = await runUpstreamAttempt({
41
+ deps,
42
+ diagnostics,
43
+ env: attemptEnv,
44
+ options: settings,
45
+ project: resolved,
46
+ sessionDeadlineAt,
47
+ });
48
+ record(deps, diagnostics, formatAttemptResult(attempt, result));
49
+ if (result.optimizerReloadFromNewDeps)
50
+ record(deps, diagnostics, newDepsGuidance(resolved, result.newOptimizeDeps));
51
+ deps.mkdirSync(dirname(diagnosticsPath), { recursive: true });
52
+ deps.writeFileSync(diagnosticsPath, diagnostics.render());
53
+ promoteAttemptCache(cachePlan, deps, result);
54
+ if (result.code === 0)
55
+ return 0;
56
+ if (!result.retryable || attempt === settings.attempts)
57
+ return result.code;
58
+ cachePlan = nextCachePlan({ attempt, attemptEnv, cachePlan, deps, persistentCacheDir, result });
59
+ priorHang = result.hung;
60
+ deps.stderr.write(`[storybook-browser] retrying after retryable Vite/browser failure on attempt ${attempt}\n`);
61
+ }
62
+ }
63
+ function record(deps, diagnostics, message) {
64
+ deps.stderr.write(message);
65
+ diagnostics.recordAttempt(message);
66
+ }
67
+ function newDepsGuidance(project, packages) {
68
+ return (`[storybook-browser] Vite discovered new optimizeDeps during the browser run: ${packages.join(', ') || 'unknown packages'}. ` +
69
+ `${project.optimizeDepsGuidance} This is not a retryable startup flake.\n`);
70
+ }
@@ -0,0 +1,22 @@
1
+ export type OutputObserverSnapshot = {
2
+ anyOutputSeen: boolean;
3
+ browserSessionConnectionTimedOut: boolean;
4
+ firstTestOutputAt: number | null;
5
+ lastHangProgressAt: number;
6
+ lastOutputAt: number;
7
+ lastSemanticProgressAt: number;
8
+ newOptimizeDeps: string[];
9
+ optimizerLastProgressAt: number | null;
10
+ optimizerReadyAt: number | null;
11
+ outputBuffer: string;
12
+ retryableViteFailure: boolean;
13
+ sawAddonVitestSetupFile: boolean;
14
+ sawNewOptimizeDeps: boolean;
15
+ sawOptimizerReload: boolean;
16
+ sawRunnerMissingMessage: boolean;
17
+ semanticProgressSeen: boolean;
18
+ startupComplete: boolean;
19
+ storybookBrowserOutputSeen: boolean;
20
+ };
21
+ export type OutputObserverState = Omit<OutputObserverSnapshot, 'newOptimizeDeps'>;
22
+ export declare function initialObserverState(startedAt: number): OutputObserverState;
@@ -0,0 +1,21 @@
1
+ export function initialObserverState(startedAt) {
2
+ return {
3
+ anyOutputSeen: false,
4
+ browserSessionConnectionTimedOut: false,
5
+ firstTestOutputAt: null,
6
+ lastHangProgressAt: startedAt,
7
+ lastOutputAt: startedAt,
8
+ lastSemanticProgressAt: startedAt,
9
+ optimizerLastProgressAt: null,
10
+ optimizerReadyAt: null,
11
+ outputBuffer: '',
12
+ retryableViteFailure: false,
13
+ sawAddonVitestSetupFile: false,
14
+ sawNewOptimizeDeps: false,
15
+ sawOptimizerReload: false,
16
+ sawRunnerMissingMessage: false,
17
+ semanticProgressSeen: false,
18
+ startupComplete: false,
19
+ storybookBrowserOutputSeen: false,
20
+ };
21
+ }
@@ -0,0 +1,18 @@
1
+ import type { ResolvedStorybookBrowserProject, StorybookBrowserProject } from './types.mts';
2
+ export type StorybookBrowserRunnerOptions = {
3
+ attempts: number;
4
+ diagnosticsFile: string;
5
+ hangMs: number;
6
+ sessionBudgetMs: number;
7
+ stallMs: number;
8
+ terminationGraceMs: number;
9
+ };
10
+ export declare function parsePositiveInteger(value: string | undefined, fallback: number): number;
11
+ export declare function envName(project: {
12
+ envPrefix: string;
13
+ }, suffix: string): string;
14
+ export declare function resolveProject(project: StorybookBrowserProject): ResolvedStorybookBrowserProject;
15
+ /** Positive integers from the environment; invalid values fall back to the defaults. */
16
+ export declare function resolveRunnerOptions(project: ResolvedStorybookBrowserProject, env: NodeJS.ProcessEnv): StorybookBrowserRunnerOptions;
17
+ /** Base argv plus the coverage flags unless `<envPrefix>_COVERAGE` is `0`. */
18
+ export declare function commandArgs(project: ResolvedStorybookBrowserProject, env: NodeJS.ProcessEnv): string[];
@@ -0,0 +1,49 @@
1
+ import { DEFAULT_STORYBOOK_PROGRESS_PREFIX } from "../vitest-diagnostics/index.mjs";
2
+ const MAX_STARTUP_ATTEMPTS = 3;
3
+ const DEFAULT_ENV_PREFIX = 'STORYBOOK_BROWSER';
4
+ export function parsePositiveInteger(value, fallback) {
5
+ const parsed = Number(value);
6
+ return value && Number.isSafeInteger(parsed) && parsed > 0 ? parsed : fallback;
7
+ }
8
+ export function envName(project, suffix) {
9
+ return `${project.envPrefix}_${suffix}`;
10
+ }
11
+ export function resolveProject(project) {
12
+ const projectName = project.projectName.trim();
13
+ if (!projectName)
14
+ throw new Error('projectName must be a non-empty Vitest project name');
15
+ const config = project.optimizeDepsConfigPath;
16
+ return {
17
+ args: project.args ?? ['exec', 'vitest', 'run', '--project', projectName],
18
+ command: project.command ?? 'pnpm',
19
+ completionFile: project.completionFile,
20
+ coverageArgs: project.coverageArgs ?? ['--coverage'],
21
+ envPrefix: project.envPrefix ?? DEFAULT_ENV_PREFIX,
22
+ optimizeDepsGuidance: config
23
+ ? `Add them to the optimizeDeps list in ${config}.`
24
+ : 'Add them to the Storybook Vite optimizeDeps include list.',
25
+ progressPrefix: project.progressPrefix ?? DEFAULT_STORYBOOK_PROGRESS_PREFIX,
26
+ projectName,
27
+ resultFiles: project.resultFiles ?? [],
28
+ };
29
+ }
30
+ /** Positive integers from the environment; invalid values fall back to the defaults. */
31
+ export function resolveRunnerOptions(project, env) {
32
+ const read = (suffix, fallback) => parsePositiveInteger(env[envName(project, suffix)], fallback);
33
+ const sessionBudgetMs = read('SESSION_BUDGET_MS', 300_000);
34
+ return {
35
+ attempts: Math.min(read('STARTUP_ATTEMPTS', MAX_STARTUP_ATTEMPTS), MAX_STARTUP_ATTEMPTS),
36
+ diagnosticsFile: env[envName(project, 'DIAGNOSTICS_FILE')] ?? 'storybook-browser-diagnostics.log',
37
+ hangMs: read('HANG_MS', 120_000),
38
+ sessionBudgetMs,
39
+ stallMs: read('OPTIMIZER_STALL_MS', 30_000),
40
+ // Kept below the budget so termination time never consumes the whole session.
41
+ terminationGraceMs: Math.max(1, Math.min(5000, Math.floor(sessionBudgetMs / 2))),
42
+ };
43
+ }
44
+ /** Base argv plus the coverage flags unless `<envPrefix>_COVERAGE` is `0`. */
45
+ export function commandArgs(project, env) {
46
+ return env[envName(project, 'COVERAGE')] === '0'
47
+ ? [...project.args]
48
+ : [...project.args, ...project.coverageArgs];
49
+ }
@@ -0,0 +1,37 @@
1
+ import type { StorybookBrowserBootstrapTelemetry } from './bootstrap-telemetry.mts';
2
+ import type { StorybookBrowserDiagnostics } from './diagnostics.mts';
3
+ import { type ProjectOutputPatterns } from './output-patterns.mts';
4
+ import { type OutputObserverSnapshot } from './observer-state.mts';
5
+ import type { StorybookQuietOutput } from './quiet-output.mts';
6
+ type Source = 'stderr' | 'stdout';
7
+ type Sink = Pick<NodeJS.WriteStream, 'write'>;
8
+ export type OutputObserverOptions = {
9
+ diagnostics: StorybookBrowserDiagnostics;
10
+ now: () => number;
11
+ patterns: ProjectOutputPatterns;
12
+ progressPrefix: string;
13
+ quietOutput: StorybookQuietOutput;
14
+ startedAt: number;
15
+ stderr: Sink;
16
+ stdout: Sink;
17
+ telemetry: StorybookBrowserBootstrapTelemetry;
18
+ };
19
+ /** Reads child output and latches the startup, progress and failure markers the policy needs. */
20
+ export declare class OutputObserver {
21
+ private readonly newOptimizeDeps;
22
+ private readonly options;
23
+ private lastSemanticSequence;
24
+ private readonly decoders;
25
+ private state;
26
+ constructor(options: OutputObserverOptions);
27
+ snapshot(): OutputObserverSnapshot;
28
+ observe(source: Source, chunk: string | Buffer): void;
29
+ /** Emits any unterminated lines the telemetry still holds, stdout before stderr. */
30
+ flush(): void;
31
+ private emit;
32
+ private observeStartup;
33
+ private observeProgress;
34
+ private recordSemanticProgress;
35
+ private observeFailures;
36
+ }
37
+ export {};