Skip to content

Commit d78b69c

Browse files
committed
fix(cli): preserve concurrent project config creation
1 parent a056db1 commit d78b69c

5 files changed

Lines changed: 123 additions & 49 deletions

File tree

‎packages/cli/src/commands/add.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ import {
2626
loadProjectConfig,
2727
projectConfigPath,
2828
recordProjectRegistryItems,
29-
writeProjectConfig,
29+
createProjectConfig,
3030
} from "../utils/projectConfig.js";
3131
import { copyToClipboard } from "../utils/clipboard.js";
3232
import { trackRegistryItemAdded } from "../telemetry/events.js";
@@ -279,7 +279,7 @@ export async function runAdd(opts: RunAddArgs): Promise<RunAddResult> {
279279
let config = loadProjectConfig(projectDir);
280280
const hasConfig = existsSync(projectConfigPath(projectDir));
281281
if (!hasConfig && existsSync(resolve(projectDir, "index.html"))) {
282-
writeProjectConfig(projectDir, DEFAULT_PROJECT_CONFIG);
282+
createProjectConfig(projectDir, DEFAULT_PROJECT_CONFIG);
283283
config = DEFAULT_PROJECT_CONFIG;
284284
}
285285

@@ -499,7 +499,7 @@ export default defineCommand({
499499
!existsSync(projectConfigPath(projectDir)) &&
500500
existsSync(resolve(projectDir, "index.html"))
501501
) {
502-
writeProjectConfig(projectDir, DEFAULT_PROJECT_CONFIG);
502+
createProjectConfig(projectDir, DEFAULT_PROJECT_CONFIG);
503503
config = DEFAULT_PROJECT_CONFIG;
504504
}
505505

‎packages/cli/src/commands/init.package-race.test.ts‎

Lines changed: 40 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -16,47 +16,46 @@ afterEach(() => {
1616
vi.unstubAllEnvs();
1717
});
1818

19-
describe("init package.json creation", () => {
20-
it.each(["existing", "concurrent", "dangling symlink"])(
21-
"preserves a %s entry while completing initialization",
22-
async (kind) => {
23-
const dir = fs.mkdtempSync(join(tmpdir(), "hf-init-package-"));
24-
const project = join(dir, "project");
25-
const packagePath = join(project, "package.json");
26-
const target = join(dir, "missing-target.json");
27-
const original = await vi.importActual<typeof fs>("node:fs");
28-
let injected = false;
29-
vi.mocked(fs.existsSync).mockImplementation((path) => {
30-
if (path === packagePath && !injected) {
31-
injected = true;
32-
if (kind === "dangling symlink") fs.symlinkSync(target, packagePath);
33-
else fs.writeFileSync(packagePath, '{"name":"preserve-me"}\n');
34-
return kind === "existing";
35-
}
36-
return original.existsSync(path);
19+
describe("init config creation", () => {
20+
it.each(
21+
["package.json", "hyperframes.json"].flatMap((filename) =>
22+
["existing", "concurrent", "dangling symlink"].map((kind) => ({ filename, kind })),
23+
),
24+
)("preserves $kind $filename while completing initialization", async ({ filename, kind }) => {
25+
const dir = fs.mkdtempSync(join(tmpdir(), "hf-init-package-"));
26+
const project = join(dir, "project");
27+
const packagePath = join(project, filename);
28+
const target = join(dir, "missing-target.json");
29+
const original = await vi.importActual<typeof fs>("node:fs");
30+
let injected = false;
31+
vi.mocked(fs.existsSync).mockImplementation((path) => {
32+
if (path === packagePath && !injected) {
33+
injected = true;
34+
if (kind === "dangling symlink") fs.symlinkSync(target, packagePath);
35+
else fs.writeFileSync(packagePath, '{"name":"preserve-me"}\n');
36+
return kind === "existing";
37+
}
38+
return original.existsSync(path);
39+
});
40+
vi.stubEnv("HYPERFRAMES_SKIP_SKILLS", "1");
41+
const log = vi.spyOn(console, "log").mockImplementation(() => {});
42+
try {
43+
await runCommand(init, {
44+
rawArgs: [project, "--example", "blank", "--non-interactive"],
3745
});
38-
vi.stubEnv("HYPERFRAMES_SKIP_SKILLS", "1");
39-
const log = vi.spyOn(console, "log").mockImplementation(() => {});
40-
try {
41-
await runCommand(init, {
42-
rawArgs: [project, "--example", "blank", "--non-interactive"],
43-
});
44-
expect(injected).toBe(true);
45-
if (kind === "dangling symlink") {
46-
expect(fs.lstatSync(packagePath).isSymbolicLink()).toBe(true);
47-
expect(fs.existsSync(target)).toBe(false);
48-
} else {
49-
expect(fs.readFileSync(packagePath, "utf-8")).toBe('{"name":"preserve-me"}\n');
50-
}
51-
expect(fs.existsSync(join(project, "index.html"))).toBe(true);
52-
expect(log.mock.calls.flat().join("\n")).toContain("npm run dev");
53-
expect(fs.readdirSync(project).filter((name) => name.startsWith(".hf-create-"))).toEqual(
54-
[],
55-
);
56-
} finally {
57-
vi.mocked(fs.existsSync).mockImplementation(original.existsSync);
58-
fs.rmSync(dir, { recursive: true, force: true });
46+
expect(injected).toBe(true);
47+
if (kind === "dangling symlink") {
48+
expect(fs.lstatSync(packagePath).isSymbolicLink()).toBe(true);
49+
expect(fs.existsSync(target)).toBe(false);
50+
} else {
51+
expect(fs.readFileSync(packagePath, "utf-8")).toBe('{"name":"preserve-me"}\n');
5952
}
60-
},
61-
);
53+
expect(fs.existsSync(join(project, "index.html"))).toBe(true);
54+
expect(log.mock.calls.flat().join("\n")).toContain("npm run dev");
55+
expect(fs.readdirSync(project).filter((name) => name.startsWith(".hf-create-"))).toEqual([]);
56+
} finally {
57+
vi.mocked(fs.existsSync).mockImplementation(original.existsSync);
58+
fs.rmSync(dir, { recursive: true, force: true });
59+
}
60+
});
6261
});

‎packages/cli/src/commands/init.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -592,11 +592,11 @@ async function scaffoldProject(
592592
// When the scaffolding workflow declared itself via --skill, stamp the owning
593593
// skill here so every later render of this project is attributed to it.
594594
if (!existsSync(resolve(destDir, "hyperframes.json"))) {
595-
const { writeProjectConfig, DEFAULT_PROJECT_CONFIG } =
595+
const { createProjectConfig, DEFAULT_PROJECT_CONFIG } =
596596
await import("../utils/projectConfig.js");
597597
const { normalizeSkillSlug } = await import("../telemetry/skill.js");
598598
const skill = normalizeSkillSlug(authoringSkill);
599-
writeProjectConfig(
599+
createProjectConfig(
600600
destDir,
601601
skill ? { ...DEFAULT_PROJECT_CONFIG, authoringSkill: skill } : DEFAULT_PROJECT_CONFIG,
602602
);
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
import { afterEach, describe, expect, it, vi } from "vitest";
2+
import * as fs from "node:fs";
3+
import { tmpdir } from "node:os";
4+
import { join } from "node:path";
5+
import {
6+
createProjectConfig,
7+
DEFAULT_PROJECT_CONFIG,
8+
projectConfigPath,
9+
seedProjectAuthoringSkill,
10+
writeProjectConfig,
11+
} from "./projectConfig.js";
12+
13+
vi.mock("node:fs", async (importOriginal) => {
14+
const original = await importOriginal<typeof fs>();
15+
return { ...original, readFileSync: vi.fn(original.readFileSync) };
16+
});
17+
18+
const dirs: string[] = [];
19+
function project() {
20+
const dir = fs.mkdtempSync(join(tmpdir(), "hf-config-create-"));
21+
dirs.push(dir);
22+
return dir;
23+
}
24+
afterEach(() => {
25+
for (const dir of dirs.splice(0)) {
26+
expect(fs.readdirSync(dir).filter((name) => name.startsWith(".hf-create-"))).toEqual([]);
27+
fs.rmSync(dir, { recursive: true, force: true });
28+
}
29+
});
30+
31+
describe("project config creation", () => {
32+
it("preserves existing bytes on create and still permits intentional updates", () => {
33+
const dir = project();
34+
const path = projectConfigPath(dir);
35+
createProjectConfig(dir);
36+
expect(fs.readFileSync(path, "utf-8")).toBe(
37+
JSON.stringify(DEFAULT_PROJECT_CONFIG, null, 2) + "\n",
38+
);
39+
const updated = { ...DEFAULT_PROJECT_CONFIG, authoringSkill: "slideshow" };
40+
createProjectConfig(dir, updated);
41+
expect(JSON.parse(fs.readFileSync(path, "utf-8"))).toEqual(DEFAULT_PROJECT_CONFIG);
42+
writeProjectConfig(dir, updated);
43+
expect(JSON.parse(fs.readFileSync(path, "utf-8"))).toEqual(updated);
44+
});
45+
46+
it("preserves a config created after the skill seed reads ENOENT", () => {
47+
const dir = project();
48+
const path = projectConfigPath(dir);
49+
const winner = '{"registry":"https://custom.example","authoringSkill":"slideshow"}\n';
50+
vi.mocked(fs.readFileSync).mockImplementationOnce(() => {
51+
fs.writeFileSync(path, winner);
52+
throw Object.assign(new Error("missing before concurrent creation"), { code: "ENOENT" });
53+
});
54+
seedProjectAuthoringSkill(dir, "product-launch-video");
55+
expect(fs.readFileSync(path, "utf-8")).toBe(winner);
56+
});
57+
58+
it("does not create a dangling symlink target when seeding an absent config", () => {
59+
const dir = project();
60+
const target = join(dir, "missing.json");
61+
fs.symlinkSync(target, projectConfigPath(dir));
62+
seedProjectAuthoringSkill(dir, "slideshow");
63+
expect(fs.existsSync(target)).toBe(false);
64+
expect(fs.lstatSync(projectConfigPath(dir)).isSymbolicLink()).toBe(true);
65+
});
66+
});

‎packages/cli/src/utils/projectConfig.ts‎

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import { readFileSync, writeFileSync } from "node:fs";
1111
import { join, resolve } from "node:path";
1212
import { DEFAULT_REGISTRY_URL } from "../registry/index.js";
1313
import { normalizeSkillSlug } from "../telemetry/skill.js";
14+
import { writeNewFileSync } from "./writeNewFile.js";
1415

1516
export const PROJECT_CONFIG_FILENAME = "hyperframes.json";
1617
const PROJECT_CONFIG_SCHEMA_URL = "https://hyperframes.heygen.com/schema/hyperframes.json";
@@ -187,6 +188,14 @@ export function writeProjectConfig(
187188
writeFileSync(path, JSON.stringify(config, null, 2) + "\n", "utf-8");
188189
}
189190

191+
/** Create `hyperframes.json` without replacing an existing file or following a symlink. */
192+
export function createProjectConfig(
193+
projectDir: string,
194+
config: ProjectConfig = DEFAULT_PROJECT_CONFIG,
195+
): void {
196+
writeNewFileSync(projectConfigPath(projectDir), JSON.stringify(config, null, 2) + "\n");
197+
}
198+
190199
/**
191200
* Load the project config for the given directory, falling back to defaults
192201
* if missing. Mutates nothing on disk. Used by commands that want to operate
@@ -234,8 +243,8 @@ function isFileNotFound(error: unknown): boolean {
234243
* never fails the render it rode in on.
235244
*
236245
* One of two writers that touch an ALREADY EXISTING `hyperframes.json` (the
237-
* other is {@link recordProjectRegistryItems}; every plain `writeProjectConfig`
238-
* call site is guarded to write only when the file is absent), so it must not
246+
* other is {@link recordProjectRegistryItems}; absent-only callers use
247+
* {@link createProjectConfig}), so it must not
239248
* round-trip through {@link normalizeConfig}:
240249
* that rebuilds the object from a field whitelist, which would drop keys it
241250
* does not know about and materialize defaults the user never wrote. The file
@@ -259,7 +268,7 @@ export function seedProjectAuthoringSkill(projectDir: string, rawSkill: unknown)
259268
} catch (error) {
260269
if (isFileNotFound(error)) {
261270
try {
262-
writeProjectConfig(projectDir, { ...DEFAULT_PROJECT_CONFIG, authoringSkill: skill });
271+
createProjectConfig(projectDir, { ...DEFAULT_PROJECT_CONFIG, authoringSkill: skill });
263272
} catch {
264273
// Read-only or missing project directory — best effort.
265274
}

0 commit comments

Comments
 (0)