Files
heygen-com__hyperframes/packages/core/scripts/buildInjectedArtifact.ts
Miguel Ángel db51d5479d fix(ci): generated files never read half-written, lint scaling test runner-proof, probe cache test off disk (#3834)
* fix(build): stop generated files from being read half-written during the build

Two unrelated pull requests kept failing CI for reasons that had nothing to do
with their changes.

Typecheck failed with "TS1002: Unterminated string literal" pointing at a
generated file. The root build compiles several packages at the same time, and
more than one of them regenerates files under a package's src/generated while a
sibling's tsc is already reading them. A plain write empties the file and then
refills it, so for a few milliseconds what is on disk is the first half of the
new file. Whichever build read it in that gap saw a truncated file and stopped.
It never happened locally because locally nothing else is reading.

Every generator now writes the new version under a temporary name and then
renames it over the target, which the filesystem does in one step. A reader
either gets the whole previous version or the whole new one; there is no moment
where it can see half of either. Content that has not changed is not rewritten
at all, so repeat builds no longer touch these files. Four generators were
affected and all four now go through one shared helper, which is where the rule
lives from now on.

The build also rebuilt the core package a second time, in parallel with the
packages that read it. That second rebuild was already redundant, and removing
it takes the writers out of the window entirely. Renaming is what makes the file
safe; dropping the duplicate build makes the build shorter as well.

Separately, a linter performance test failed on four of the last ten failed runs
on main. It timed a scan with a stopwatch and demanded the result come in under
two seconds; one run took 3.7s. That is a statement about how busy the shared
runner was, not about the code, because a stopwatch also counts the time the
machine spent running someone else's job. The test now counts only the processor
time this process actually used, and checks that the cost grows in step with the
input rather than against a fixed number of milliseconds. Measured on a machine
under load, the stopwatch ratio for the same input reached 45x while the
processor-time ratio stayed at 20x.

Both fixes come with a check that fails if the fix is removed.

* fix(build): keep the shared write helper inside the core package

The helper the generators call had been placed in the repo-root scripts folder.
Every container image that builds a package copies the packages folders whole
but cherry-picks root scripts one file at a time, so the image builds failed on
a missing module. The repo already shows both halves of that convention: the one
root script a package build imports has a matching copy line in the image, and
cross-package imports into the core package need none.

The helper now lives with the core package's other build scripts, and the one
generator outside that package reaches it the way the engine package already
reaches core.

* test(engine): keep the probe cache bound test off the filesystem

The eviction test wrote, stat'ed and deleted 129 temp files to exercise an
in-memory LRU rule. Its runtime tracked filesystem contention rather than
the code under test, and on a busy Windows runner the file churn alone
pushed a ~300ms test past the 5s timeout, failing unrelated pull requests.

Cache identity comes from stat, so the test now synthesises stat results
and never touches disk. While here, the test also asserts the LRU touch:
re-probing an entry before the bound is hit must keep it resident and
evict the next-oldest one instead. The previous shape never hit the cache
during the fill, so that branch was untested.

* test(lint): keep the scaling check inside the scanner's linear range

The CPU-ratio version sampled 320k characters, where the output string's
own growth dominates and the whole test cost seconds of CPU; on a shared
runner that tripped the default test timeout, the failure this change
exists to remove. Sample 10k and 80k characters instead, where 8x input
measures ~8x and a quadratic scan still measures 60x or more, and give
the test an explicit timeout so a slow runner reports the ratio.

* test(core): snapshot file identity through a descriptor

The before/after inode and mtime checks read the file through a path stat
and then exercised the writer on the same path, which reads as a
check-then-use race to static analysis. Snapshot through an open
descriptor instead; the assertions are unchanged.
2026-09-10 03:08:58 +00:00

69 lines
2.5 KiB
TypeScript

/**
* Bundle a stub entry into an injectable IIFE, wrapped as a TypeScript constant.
*
* Two artifacts are built this way — the audio-FX runtime and the position-edits
* render — and the engine injects both into the headless browser as a script tag.
* They were two copies of this file differing in five names, which is a poor
* place for a divergence to hide: whichever copy stopped being edited would go on
* producing a subtly different artifact with nothing to say so.
*/
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { buildSync } from "esbuild";
import { formatGeneratedSource, writeGeneratedFile } from "./writeGeneratedFile.js";
export interface InjectedArtifact {
/** The build script's own `import.meta.url`, so paths resolve beside it. */
scriptUrl: string;
/** Entry stub, relative to the package root. */
entry: string;
/** Output file name inside `src/generated`. */
out: string;
/** SCREAMING_CASE name for the string constant holding the IIFE. */
constName: string;
/** The accessor the rest of the codebase imports. */
fnName: string;
/** What that accessor returns, for its doc comment: "the pre-built X". */
what: string;
/** Structured log event name. */
event: string;
}
export function buildInjectedArtifact(spec: InjectedArtifact): void {
const scriptDir = dirname(fileURLToPath(spec.scriptUrl));
const scriptName = spec.scriptUrl.split("/").pop() ?? "";
const repoRoot = resolve(scriptDir, "..");
const entry = resolve(repoRoot, spec.entry);
const generatedDir = resolve(repoRoot, "src/generated");
const outPath = resolve(generatedDir, spec.out);
const result = buildSync({
entryPoints: [entry],
bundle: true,
write: false,
platform: "browser",
format: "iife",
target: ["es2020"],
minify: true,
legalComments: "none",
});
const iife = result.outputFiles[0]?.text ?? "";
if (!iife) throw new Error(`esbuild produced no output for ${spec.entry.split("/").pop()}`);
const source = [
`// AUTO-GENERATED by scripts/${scriptName} - do not edit`,
`const ${spec.constName}: string = ${JSON.stringify(iife)};`,
"",
`/** Returns the pre-built ${spec.what} as a string constant. */`,
`export function ${spec.fnName}(): string {`,
` return ${spec.constName};`,
"}",
"",
].join("\n");
writeGeneratedFile(outPath, formatGeneratedSource(source, outPath));
console.log(JSON.stringify({ event: spec.event, outPath, bytes: iife.length }));
}