Skip to content

Commit de9206e

Browse files
fix(cli): detect a missing or stale studio build before it crashes (#4076)
* fix(cli): name the missing or stale workspace package before preview crashes Running hyperframes preview from source with an unbuilt or stale package previously crashed deep inside that package's own import graph with a raw resolver error naming neither the package nor the fix. Add a preflight that runs before the preview command's own module import, so it also catches the crash that happens at CLI load time before the studio dev server ever spawns. * test(cli): cover the preview workspace-build gate wiring Adds a test that exercises the real CLI dispatch path (mocked module loaders, not source-text matching) to prove the preview command's build-check runs before its module loads and that a failure exits non-zero without double-printing. Also guards the exports-map reader against a malformed package.json instead of crashing raw. * fix(cli): correct why the audio-fx generated file is checked The comment claimed core/src/index.ts imports both generated files directly. Only runtime-inline.ts is; audio-fx-runtime-inline.ts is reachable solely via core's own audio-fx-runtime export subpath, which the engine package imports. The check itself was already correct to require both, only the stated reason was wrong.
1 parent e174b17 commit de9206e

6 files changed

Lines changed: 404 additions & 18 deletions

File tree

‎packages/cli/src/cli.lifecycle.test.ts‎

Lines changed: 1 addition & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { afterEach, describe, expect, it, vi } from "vitest";
2+
import { mockTelemetry } from "./cliDispatchTestUtils.js";
23

34
const originalArgv = [...process.argv];
45
const originalExitCode = process.exitCode;
@@ -244,22 +245,6 @@ function mockInitCommand(run: () => void): void {
244245
}));
245246
}
246247

247-
function mockTelemetry(overrides: {
248-
flushSync?: ReturnType<typeof vi.fn>;
249-
trackCommandResult?: ReturnType<typeof vi.fn>;
250-
}): void {
251-
vi.doMock("./telemetry/index.js", () => ({
252-
flush: vi.fn(async () => {}),
253-
flushSync: overrides.flushSync ?? vi.fn(),
254-
incrementCommandCount: vi.fn(),
255-
showTelemetryNotice: vi.fn(),
256-
shouldTrack: () => false,
257-
trackCliError: vi.fn(),
258-
trackCommand: vi.fn(),
259-
trackCommandResult: overrides.trackCommandResult ?? vi.fn(),
260-
}));
261-
}
262-
263248
function emitStreamEpipe(): void {
264249
process.stdout.emit("error", Object.assign(new Error("write EPIPE"), { code: "EPIPE" }));
265250
}

‎packages/cli/src/cli.ts‎

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ for (const stream of [process.stdout, process.stderr]) {
3131
// probe lands in a directory that does not contain the bundled worker.
3232
// We emit the worker entry next to cli.js (see tsup.config.ts) and tell
3333
// the pool where to find it via the published env-var override.
34-
import { dirname, join } from "node:path";
34+
import { dirname, join, resolve } from "node:path";
3535
import { fileURLToPath } from "node:url";
3636
import { existsSync } from "node:fs";
3737

@@ -106,6 +106,7 @@ import { getRunId } from "./telemetry/runId.js";
106106
import { reportCommandFailure, trackCommandFailures } from "./utils/command-failure-tracking.js";
107107
import { isRenderSucceeded } from "./utils/render-success-state.js";
108108
import { resolveCommandUsage } from "./utils/commandUsageResolution.js";
109+
import { isDevMode } from "./utils/env.js";
109110
import {
110111
CliResultSignal,
111112
CliRuntimeError,
@@ -118,6 +119,22 @@ import {
118119

119120
const isHelp = process.argv.includes("--help") || process.argv.includes("-h");
120121

122+
// Runs before commands/preview.js is imported, so a missing or stale
123+
// package is named here instead of crashing deep inside that import.
124+
async function assertStudioWorkspaceBuilt(): Promise<void> {
125+
if (!isDevMode()) return;
126+
const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..", "..", "..");
127+
const { checkStudioWorkspaceBuild, formatWorkspaceBuildProblems } =
128+
await import("./utils/workspaceBuildCheck.js");
129+
const problems = checkStudioWorkspaceBuild(repoRoot);
130+
if (problems.length === 0) return;
131+
console.error(formatWorkspaceBuildProblems(problems));
132+
throw new CliRuntimeError("Studio workspace build check failed", {
133+
exitCode: 1,
134+
presented: true,
135+
});
136+
}
137+
121138
// ---------------------------------------------------------------------------
122139
// CLI definition — all commands are lazy-loaded via dynamic import()
123140
// ---------------------------------------------------------------------------
@@ -128,7 +145,8 @@ const commandLoaders = {
128145
catalog: () => import("./commands/catalog.js").then((m) => m.default),
129146
play: () => import("./commands/play.js").then((m) => m.default),
130147
present: () => import("./commands/present.js").then((m) => m.default),
131-
preview: () => import("./commands/preview.js").then((m) => m.default),
148+
preview: () =>
149+
assertStudioWorkspaceBuilt().then(() => import("./commands/preview.js").then((m) => m.default)),
132150
publish: () => import("./commands/publish.js").then((m) => m.default),
133151
render: () => import("./commands/render.js").then((m) => m.default),
134152
lint: () => import("./commands/lint.js").then((m) => m.default),
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
import { afterEach, describe, expect, it, vi } from "vitest";
2+
import { mockTelemetry } from "./cliDispatchTestUtils.js";
3+
4+
const originalArgv = [...process.argv];
5+
const originalExitCode = process.exitCode;
6+
7+
afterEach(() => {
8+
process.argv = [...originalArgv];
9+
process.exitCode = originalExitCode;
10+
vi.doUnmock("./commands/preview.js");
11+
vi.doUnmock("./utils/env.js");
12+
vi.doUnmock("./utils/workspaceBuildCheck.js");
13+
vi.doUnmock("./telemetry/index.js");
14+
vi.doUnmock("./telemetry/events.js");
15+
vi.resetModules();
16+
});
17+
18+
function mockPreviewGate(problems: Array<Record<string, string>>): () => boolean {
19+
let previewImported = false;
20+
vi.doMock("./commands/preview.js", () => {
21+
previewImported = true;
22+
return { default: { meta: { name: "preview" }, args: {}, run: vi.fn() } };
23+
});
24+
vi.doMock("./utils/env.js", () => ({ isDevMode: () => true }));
25+
vi.doMock("./utils/workspaceBuildCheck.js", () => ({
26+
checkStudioWorkspaceBuild: () => problems,
27+
formatWorkspaceBuildProblems: () =>
28+
problems.map((p) => ` - ${p.package}: ${p.detail}`).join("\n"),
29+
}));
30+
mockTelemetry();
31+
return () => previewImported;
32+
}
33+
34+
describe("CLI preview workspace build gate", () => {
35+
it("blocks the preview command before its module loads, without printing the raw error twice", async () => {
36+
const wasPreviewImported = mockPreviewGate([
37+
{
38+
package: "core",
39+
kind: "missing",
40+
detail: "dist/ is missing or empty",
41+
fix: "bun run build",
42+
},
43+
]);
44+
const errorSpy = vi.spyOn(console, "error").mockImplementation(() => undefined);
45+
46+
process.argv = ["node", "cli.ts", "preview", "--json"];
47+
await import("./cli.js");
48+
49+
expect(wasPreviewImported()).toBe(false);
50+
expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining("dist/ is missing or empty"));
51+
expect(errorSpy).toHaveBeenCalledTimes(1);
52+
expect(process.exitCode).toBe(1);
53+
errorSpy.mockRestore();
54+
});
55+
56+
it("imports the preview module once the workspace build check reports no problems", async () => {
57+
const wasPreviewImported = mockPreviewGate([]);
58+
59+
process.argv = ["node", "cli.ts", "preview", "--json"];
60+
await import("./cli.js");
61+
62+
expect(wasPreviewImported()).toBe(true);
63+
});
64+
});
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import { vi } from "vitest";
2+
3+
// Shared by every test that drives the real `cli.js` dispatch path
4+
// (dynamic import + process.argv) instead of source-text matching.
5+
6+
export function mockTelemetry(
7+
overrides: {
8+
flushSync?: ReturnType<typeof vi.fn>;
9+
trackCommandResult?: ReturnType<typeof vi.fn>;
10+
trackCommandFailure?: ReturnType<typeof vi.fn>;
11+
} = {},
12+
): void {
13+
vi.doMock("./telemetry/index.js", () => ({
14+
flush: vi.fn(async () => {}),
15+
flushSync: overrides.flushSync ?? vi.fn(),
16+
incrementCommandCount: vi.fn(),
17+
showTelemetryNotice: vi.fn(),
18+
shouldTrack: () => false,
19+
trackCliError: vi.fn(),
20+
trackCommand: vi.fn(),
21+
trackCommandResult: overrides.trackCommandResult ?? vi.fn(),
22+
}));
23+
vi.doMock("./telemetry/events.js", () => ({
24+
trackCommandFailure: overrides.trackCommandFailure ?? vi.fn(),
25+
}));
26+
}
Lines changed: 127 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,127 @@
1+
import { afterEach, describe, expect, it } from "vitest";
2+
import { mkdirSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from "node:fs";
3+
import { join } from "node:path";
4+
import { tmpdir } from "node:os";
5+
import {
6+
checkStudioWorkspaceBuild,
7+
SKIP_STALE_CHECK_ENV,
8+
STUDIO_WORKSPACE_BUILD_ORDER,
9+
} from "./workspaceBuildCheck.js";
10+
11+
let dirs: string[] = [];
12+
13+
function tmpRepoRoot(): string {
14+
const dir = mkdtempSync(join(tmpdir(), "hf-workspace-build-check-"));
15+
dirs.push(dir);
16+
return dir;
17+
}
18+
19+
/** A fully built package: dist/index.js exists, no exports gap, dist newer than src. */
20+
function writeBuiltPackage(
21+
repoRoot: string,
22+
pkg: string,
23+
exportsMap: Record<string, unknown> = {
24+
".": { node: "./dist/index.js", import: "./src/index.ts" },
25+
},
26+
): void {
27+
const pkgDir = join(repoRoot, "packages", pkg);
28+
mkdirSync(join(pkgDir, "src"), { recursive: true });
29+
mkdirSync(join(pkgDir, "dist"), { recursive: true });
30+
writeFileSync(join(pkgDir, "package.json"), JSON.stringify({ name: pkg, exports: exportsMap }));
31+
writeFileSync(join(pkgDir, "src", "index.ts"), "export {};");
32+
writeFileSync(join(pkgDir, "dist", "index.js"), "export {};");
33+
const srcFiles = [join(pkgDir, "src", "index.ts")];
34+
if (pkg === "core") {
35+
mkdirSync(join(pkgDir, "src", "generated"), { recursive: true });
36+
writeFileSync(join(pkgDir, "src", "generated", "runtime-inline.ts"), "export {};");
37+
writeFileSync(join(pkgDir, "src", "generated", "audio-fx-runtime-inline.ts"), "export {};");
38+
srcFiles.push(
39+
join(pkgDir, "src", "generated", "runtime-inline.ts"),
40+
join(pkgDir, "src", "generated", "audio-fx-runtime-inline.ts"),
41+
);
42+
}
43+
// dist strictly newer than every src file so a fresh build never reads as
44+
// stale — explicit timestamps, not write order, since two writeFileSync
45+
// calls can land within the same JS Date.now() tick.
46+
const past = new Date(Date.now() - 10_000);
47+
const now = new Date();
48+
for (const file of srcFiles) utimesSync(file, past, past);
49+
utimesSync(join(pkgDir, "dist", "index.js"), now, now);
50+
}
51+
52+
function writeAllBuilt(repoRoot: string): void {
53+
for (const pkg of STUDIO_WORKSPACE_BUILD_ORDER) writeBuiltPackage(repoRoot, pkg);
54+
}
55+
56+
afterEach(() => {
57+
delete process.env[SKIP_STALE_CHECK_ENV];
58+
for (const dir of dirs) rmSync(dir, { recursive: true, force: true });
59+
dirs = [];
60+
});
61+
62+
describe("checkStudioWorkspaceBuild", () => {
63+
it("reports every package as missing on a fresh clone with nothing built", () => {
64+
const repoRoot = tmpRepoRoot();
65+
mkdirSync(join(repoRoot, "packages"), { recursive: true });
66+
67+
const problems = checkStudioWorkspaceBuild(repoRoot);
68+
69+
expect(problems.map((p) => p.package)).toEqual([...STUDIO_WORKSPACE_BUILD_ORDER]);
70+
expect(problems.every((p) => p.kind === "missing")).toBe(true);
71+
});
72+
73+
it("reports only the one package whose src changed after its last build", () => {
74+
const repoRoot = tmpRepoRoot();
75+
writeAllBuilt(repoRoot);
76+
const parsersSrc = join(repoRoot, "packages", "parsers", "src", "index.ts");
77+
utimesSync(parsersSrc, new Date(), new Date());
78+
79+
const problems = checkStudioWorkspaceBuild(repoRoot);
80+
81+
expect(problems).toEqual([expect.objectContaining({ package: "parsers", kind: "stale" })]);
82+
});
83+
84+
it("skips the stale-src check under the escape hatch env var", () => {
85+
const repoRoot = tmpRepoRoot();
86+
writeAllBuilt(repoRoot);
87+
const parsersSrc = join(repoRoot, "packages", "parsers", "src", "index.ts");
88+
utimesSync(parsersSrc, new Date(), new Date());
89+
process.env[SKIP_STALE_CHECK_ENV] = "1";
90+
91+
expect(checkStudioWorkspaceBuild(repoRoot)).toEqual([]);
92+
});
93+
94+
it("reports a new export subpath missing from an otherwise fresh dist", () => {
95+
const repoRoot = tmpRepoRoot();
96+
writeAllBuilt(repoRoot);
97+
// Simulates a merge that added a subpath to package.json and its src file,
98+
// without anyone rebuilding this already-checked-out worktree's dist.
99+
writeBuiltPackage(repoRoot, "core", {
100+
".": { node: "./dist/index.js", import: "./src/index.ts" },
101+
"./new-thing": { node: "./dist/newThing.js", import: "./src/newThing.ts" },
102+
});
103+
104+
const problems = checkStudioWorkspaceBuild(repoRoot);
105+
106+
expect(problems).toEqual([expect.objectContaining({ package: "core", kind: "missing" })]);
107+
expect(problems[0]?.detail).toContain("newThing.js");
108+
});
109+
110+
it("reports nothing for a fully built, fresh workspace", () => {
111+
const repoRoot = tmpRepoRoot();
112+
writeAllBuilt(repoRoot);
113+
114+
expect(checkStudioWorkspaceBuild(repoRoot)).toEqual([]);
115+
});
116+
117+
it("reports a broken package.json instead of throwing", () => {
118+
const repoRoot = tmpRepoRoot();
119+
writeAllBuilt(repoRoot);
120+
writeFileSync(join(repoRoot, "packages", "parsers", "package.json"), "{not json");
121+
122+
const problems = checkStudioWorkspaceBuild(repoRoot);
123+
124+
expect(problems).toEqual([expect.objectContaining({ package: "parsers", kind: "missing" })]);
125+
expect(problems[0]?.detail).toContain("package.json is invalid");
126+
});
127+
});

0 commit comments

Comments
 (0)