Skip to content

Write HTML. Render video. Built for agents.

feat(scripts): typecheck the scripts directory (#3149)

Miguel Ángel79dff2051699
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 6463d8c9e1..d91f5d4e99 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -259,6 +259,7 @@ jobs:
- run: bash scripts/ci/install-workspace-dependencies.sh
- run: bun run build
- run: bun run --filter '*' typecheck
+ - run: bun run typecheck:scripts
test:
name: Test
diff --git a/lefthook.yml b/lefthook.yml
index 3477e0df44..8d42077b37 100644
--- a/lefthook.yml
+++ b/lefthook.yml
@@ -19,7 +19,7 @@ pre-commit:
run: bun packages/cli/scripts/gen-skills-manifest.ts && git add skills-manifest.json
typecheck:
glob: "*.{ts,tsx}"
- run: cd packages/core && bunx tsc --noEmit && cd ../studio && bunx tsc --noEmit
+ run: cd packages/core && bunx tsc --noEmit && cd ../studio && bunx tsc --noEmit && cd ../.. && bunx tsc --noEmit -p scripts/tsconfig.json
# Mirrors the CI gate (same `--base origin/main` so the local hook can't
# pass on a branch CI would fail). Audits the working tree, which means
# unstaged WIP in `packages/**` is part of the diff — stash before
diff --git a/package.json b/package.json
index 46fb3ceb50..390d267104 100644
--- a/package.json
+++ b/package.json
@@ -49,6 +49,7 @@
"format:check": "oxfmt --check .",
"knip": "knip",
"test:scripts": "node --import tsx --test scripts/check-tracked-artifacts.test.mjs scripts/check-docs-snippet-motion.test.mjs scripts/registry-target-paths.test.mjs scripts/check-workspace-contracts.test.mjs scripts/check-package-cycles.test.mjs scripts/check-cli-process-ownership.test.mjs scripts/package-subpaths.test.mjs scripts/validate-release-channel.test.mjs scripts/publish-workflow.test.mjs scripts/install-workspace-dependencies.test.mjs scripts/draft-changelog.test.ts scripts/set-version.test.ts scripts/release-prepare.test.ts scripts/cli-options.test.ts scripts/changelog-weekly.test.ts scripts/claude-plugin-compression.test.ts scripts/studio-runtime-smoke.test.mjs scripts/verify-packed-manifests.test.mjs scripts/lint-skills.test.mjs packages/gcp-cloud-run/check-dockerfile-workspaces.test.mjs",
+ "typecheck:scripts": "tsc --noEmit -p scripts/tsconfig.json",
"test:skills": "node --test 'skills/**/*.test.mjs'",
"generate:previews": "tsx scripts/generate-template-previews.ts",
"generate:catalog-previews": "tsx scripts/generate-catalog-previews.ts",
diff --git a/scripts/backfill-block-previews.ts b/scripts/backfill-block-previews.ts
index 1069c81a3b..c33b89c694 100644
--- a/scripts/backfill-block-previews.ts
+++ b/scripts/backfill-block-previews.ts
@@ -10,7 +10,7 @@
* npx tsx scripts/backfill-block-previews.ts --dry-run # preview changes only
*/
-import { readdirSync, readFileSync, writeFileSync } from "node:fs";
+import { readdirSync, readFileSync, writeFileSync, type Dirent } from "node:fs";
import { join, resolve, dirname } from "node:path";
import { fileURLToPath } from "node:url";
@@ -44,7 +44,7 @@ function writeManifest(manifestPath: string, manifest: Record<string, unknown>):
function backfillBlocks() {
const blocksDir = join(registryDir, "blocks");
- let entries: ReturnType<typeof readdirSync<string>>;
+ let entries: Dirent[];
try {
entries = readdirSync(blocksDir, { withFileTypes: true });
} catch {
@@ -81,7 +81,7 @@ function backfillBlocks() {
function normalizeComponents() {
const componentsDir = join(registryDir, "components");
- let entries: ReturnType<typeof readdirSync<string>>;
+ let entries: Dirent[];
try {
entries = readdirSync(componentsDir, { withFileTypes: true });
} catch {
diff --git a/scripts/changelog-weekly.ts b/scripts/changelog-weekly.ts
index 1c208347ca..dbcc8435a1 100644
--- a/scripts/changelog-weekly.ts
+++ b/scripts/changelog-weekly.ts
@@ -531,7 +531,7 @@ function capitalize(value: string) {
if (!value) {
return value;
}
- return value[0].toUpperCase() + value.slice(1);
+ return value.charAt(0).toUpperCase() + value.slice(1);
}
function git(args: string[]) {
diff --git a/scripts/cli-options.ts b/scripts/cli-options.ts
index 5983cdcda5..0cf95e535c 100644
--- a/scripts/cli-options.ts
+++ b/scripts/cli-options.ts
@@ -27,7 +27,7 @@ export function parseMappedArgument<
parsed: Parsed,
config: ParserConfig<Parsed, ValueKey, BooleanKey>,
) {
- const arg = args[index];
+ const arg = args[index] ?? config.fail(`No argument at index ${index}`);
if (applyInlineValueOption(arg, parsed, config.inlineValueOptions)) {
return index;
diff --git a/scripts/draft-changelog.ts b/scripts/draft-changelog.ts
index a57cccede8..cc902f7349 100644
--- a/scripts/draft-changelog.ts
+++ b/scripts/draft-changelog.ts
@@ -273,12 +273,8 @@ export function parseConventionalSubject(subject: string): ParsedSubject {
};
}
- return {
- type: match[1],
- scope: match[2],
- summary: match[4],
- breaking: match[3] === "!",
- };
+ const [, type = "other", scope, breaking, summary = subject] = match;
+ return { type, scope, summary, breaking: breaking === "!" };
}
function extractPrNumber(subject: string) {
@@ -444,7 +440,7 @@ function capitalize(value: string) {
if (!value) {
return value;
}
- return value[0].toUpperCase() + value.slice(1);
+ return value.charAt(0).toUpperCase() + value.slice(1);
}
function renderTagsLiteral(tags: string[]) {
diff --git a/scripts/generate-catalog-pages.ts b/scripts/generate-catalog-pages.ts
index ef7dac0375..6fd2deea35 100644
--- a/scripts/generate-catalog-pages.ts
+++ b/scripts/generate-catalog-pages.ts
@@ -234,7 +234,7 @@ function textureGroupsFor(manifest: RegistryItem): TextureGroup[] {
if (!group || typeof group !== "object") return false;
if (!("title" in group) || typeof group.title !== "string") return false;
if (!("items" in group) || !Array.isArray(group.items)) return false;
- return group.items.every((item) => typeof item === "string");
+ return group.items.every((item: unknown) => typeof item === "string");
});
}
@@ -403,7 +403,7 @@ function generateTextureAnimationExample(
function generateTexturePreview(manifest: RegistryItem, textureGroups: TextureGroup[]): string[] {
const sampleItems = textureGroups
.map((group) => group.items[0])
- .filter(Boolean)
+ .filter((item): item is string => Boolean(item))
.slice(0, 6);
const lines: string[] = ['<div className="hf-texture-preview-panel">'];
@@ -411,8 +411,8 @@ function generateTexturePreview(manifest: RegistryItem, textureGroups: TextureGr
const maskPath = textureMaskUrlFor(manifest, item);
lines.push(
` <div className="hf-texture-preview-card" style={{ "--mask-url": "url('${maskPath}')" }}>`,
- ` <div className="hf-texture-preview-label">${textureLabel(item!)}</div>`,
- ` <div className="hf-texture-preview-shadow"><div className="hf-texture-preview-word">${textureSampleWord(item!)}</div></div>`,
+ ` <div className="hf-texture-preview-label">${textureLabel(item)}</div>`,
+ ` <div className="hf-texture-preview-shadow"><div className="hf-texture-preview-word">${textureSampleWord(item)}</div></div>`,
" </div>",
);
}
diff --git a/scripts/generate-catalog-previews.ts b/scripts/generate-catalog-previews.ts
index d8a262994b..77cb3f0e20 100644
--- a/scripts/generate-catalog-previews.ts
+++ b/scripts/generate-catalog-previews.ts
@@ -35,17 +35,14 @@ import { tmpdir } from "node:os";
import { fileURLToPath } from "node:url";
// Import from source — bun workspace linking doesn't resolve for scripts outside packages/.
import {
- createFileServer,
- createCaptureSession,
- initializeSession,
captureFrame,
- getCompositionDuration,
closeCaptureSession,
createRenderJob,
executeRenderJob,
} from "../packages/producer/src/index.js";
import { compileForRender } from "../packages/producer/src/services/htmlCompiler.js";
import { resolveContainedCopies } from "./registry-target-paths.mjs";
+import { openOpaqueCapture } from "./preview-capture.js";
const scriptDir = dirname(fileURLToPath(import.meta.url));
const repoRoot = resolve(scriptDir, "..");
@@ -277,52 +274,25 @@ async function prepareProjectDir(item: CatalogItem): Promise<string> {
return tmpDir;
}
+/** Pull a `data-<attr>` pixel value out of the wrapper markup, or fall back. */
+function wrapperDimension(html: string, attr: "width" | "height", fallback: number): number {
+ const match = html.match(new RegExp(`data-${attr}="(\\d+)"`))?.[1];
+ return match ? parseInt(match, 10) : fallback;
+}
+
async function generateThumbnail(item: CatalogItem, projectDir: string): Promise<void> {
const outDir = outputDir(item.kind);
mkdirSync(outDir, { recursive: true });
// Read dimensions from the wrapper index.html (which may differ from native
// dimensions for portrait overlays that are scaled to fit landscape).
- let width = 1920;
- let height = 1080;
- const wrapperPath = join(projectDir, "index.html");
- const wrapperHtml = readFileSync(wrapperPath, "utf-8");
- const wMatch = wrapperHtml.match(/data-width="(\d+)"/);
- const hMatch = wrapperHtml.match(/data-height="(\d+)"/);
- if (wMatch) width = parseInt(wMatch[1], 10);
- if (hMatch) height = parseInt(hMatch[1], 10);
+ const wrapperHtml = readFileSync(join(projectDir, "index.html"), "utf-8");
+ const width = wrapperDimension(wrapperHtml, "width", 1920);
+ const height = wrapperDimension(wrapperHtml, "height", 1080);
const framesDir = join(projectDir, "_thumb_frames");
- mkdirSync(framesDir, { recursive: true });
-
- const fileServer = await createFileServer({
- projectDir,
- port: 0,
- fps: { num: 30, den: 1 },
- });
+ const { fileServer, session, duration } = await openOpaqueCapture({ projectDir, width, height });
try {
- // `format: "png"` is the engine's TRANSPARENT capture mode: it forces
- // `background-image: none !important` on every `[data-composition-id]`, so
- // any block whose scene paints its own backdrop (the VS Code snippets sit
- // on a desktop wallpaper) loses it and the poster comes out empty. These
- // posters are opaque page images, never a compositing layer — capture
- // opaque and transcode to the .png the catalog pages reference.
- const session = await createCaptureSession(fileServer.url, framesDir, {
- width,
- height,
- fps: { num: 30, den: 1 },
- format: "jpeg",
- quality: 95,
- });
- await initializeSession(session);
-
- let duration: number;
- try {
- duration = await getCompositionDuration(session);
- } catch {
- duration = 5;
- }
-
// Capture after the treatment appears, capped for long compositions.
const captureTime = Math.min(3.0, duration * 0.6);
const result = await captureFrame(session, 0, captureTime);
diff --git a/scripts/generate-registry-items.ts b/scripts/generate-registry-items.ts
index d06a4b1c0f..36390d8a71 100644
--- a/scripts/generate-registry-items.ts
+++ b/scripts/generate-registry-items.ts
@@ -24,7 +24,10 @@ import {
type FileType,
type RegistryItem,
type RegistryManifest,
-} from "@hyperframes/core";
+ // Import from source, like every other script here: bun workspace linking
+ // does not resolve for scripts outside packages/, so the package name
+ // typechecks on a machine with a warm node_modules and fails in CI.
+} from "../packages/core/src/index.js";
const scriptDir = dirname(fileURLToPath(import.meta.url));
const repoRoot = resolve(scriptDir, "..");
diff --git a/scripts/generate-template-previews.ts b/scripts/generate-template-previews.ts
index 8dfe334334..b4189109a9 100644
--- a/scripts/generate-template-previews.ts
+++ b/scripts/generate-template-previews.ts
@@ -2,7 +2,7 @@
/**
* Generate Template Preview Images + Videos
*
- * Uses @hyperframes/producer to render PNG thumbnails and short MP4 preview
+ * Uses the producer package to render PNG thumbnails and short MP4 preview
* videos of each built-in template.
*
* Output: docs/images/templates/<id>.png + <id>.mp4
@@ -28,16 +28,14 @@ import { execFileSync } from "node:child_process";
import { join, resolve, dirname } from "node:path";
import { tmpdir } from "node:os";
import { fileURLToPath } from "node:url";
+// Import from source — scripts are typechecked before workspace packages are built.
import {
- createFileServer,
- createCaptureSession,
- initializeSession,
captureFrame,
- getCompositionDuration,
closeCaptureSession,
createRenderJob,
executeRenderJob,
-} from "@hyperframes/producer";
+} from "../packages/producer/src/index.js";
+import { openOpaqueCapture } from "./preview-capture.js";
const scriptDir = dirname(fileURLToPath(import.meta.url));
const repoRoot = resolve(scriptDir, "..");
@@ -59,11 +57,12 @@ const TEMPLATE_CONFIG: Record<string, { width: number; height: number; captureTi
};
function patchTemplateHtml(dir: string, durationSeconds: number): void {
- const htmlFiles = readdirSync(dir, { withFileTypes: true, recursive: true })
- .filter((e) => e.isFile() && e.name.endsWith(".html"))
- .map((e) => join(e.parentPath ?? e.path, e.name));
+ const htmlEntries = readdirSync(dir, { withFileTypes: true, recursive: true }).filter(
+ (e) => e.isFile() && e.name.endsWith(".html"),
+ );
- for (const file of htmlFiles) {
+ for (const entry of htmlEntries) {
+ const file = join(entry.parentPath, entry.name);
let content = readFileSync(file, "utf-8");
content = content.replace(/<video[^>]*src="__VIDEO_SRC__"[^>]*>[\s\S]*?<\/video>/g, "");
content = content.replace(/<video[^>]*src="__VIDEO_SRC__"[^>]*>/g, "");
@@ -140,34 +139,12 @@ async function generateThumbnail(templateId: string, projectDir: string): Promis
const config = TEMPLATE_CONFIG[templateId] ?? DEFAULT_CONFIG;
const framesDir = join(projectDir, "_thumb_frames");
- mkdirSync(framesDir, { recursive: true });
-
- const fileServer = await createFileServer({
+ const { fileServer, session, duration } = await openOpaqueCapture({
projectDir,
- port: 0,
- fps: { num: 30, den: 1 },
+ width: config.width,
+ height: config.height,
});
try {
- // Opaque capture, for the reason spelled out in generate-catalog-previews.ts:
- // `format: "png"` is the engine's TRANSPARENT mode and forces
- // `background-image: none !important` on every composition root, silently
- // dropping any backdrop the template paints for itself.
- const session = await createCaptureSession(fileServer.url, framesDir, {
- width: config.width,
- height: config.height,
- fps: 30,
- format: "jpeg",
- quality: 95,
- });
- await initializeSession(session);
-
- let duration: number;
- try {
- duration = await getCompositionDuration(session);
- } catch {
- duration = 5;
- }
-
const t = Math.min(config.captureTime, duration * 0.8);
const result = await captureFrame(session, 0, t);
execFileSync(
diff --git a/scripts/lint-skills.ts b/scripts/lint-skills.ts
index 8aa912d9da..d03b26b97b 100644
--- a/scripts/lint-skills.ts
+++ b/scripts/lint-skills.ts
@@ -225,7 +225,7 @@ export function lintFrontmatter(content: string): LineViolation[] {
violation(1, `Missing SKILL.md YAML frontmatter (must start with '---').`, "<top of file>"),
];
}
- const parsed = parseFrontmatterYaml(match[1]);
+ const parsed = parseFrontmatterYaml(match[1] ?? "");
const preflightError = parsedDataError(parsed);
if (preflightError) return [preflightError];
return validateShape(parsed.data as Record<string, unknown>);
diff --git a/scripts/preview-capture.ts b/scripts/preview-capture.ts
new file mode 100644
index 0000000000..8557209588
--- /dev/null
+++ b/scripts/preview-capture.ts
@@ -0,0 +1,75 @@
+/**
+ * The capture setup both preview generators need, in one place.
+ *
+ * They diverged only in how they picked width and height, so keeping two copies
+ * meant the opaque-capture rationale below had to be re-derived, and re-read,
+ * every time either script changed.
+ */
+
+import { mkdirSync } from "node:fs";
+import { join } from "node:path";
+// Import from source — bun workspace linking doesn't resolve for scripts outside packages/.
+import {
+ createFileServer,
+ createCaptureSession,
+ initializeSession,
+ getCompositionDuration,
+} from "../packages/producer/src/index.js";
+
+const FPS = { num: 30, den: 1 } as const;
+
+/** Duration to assume when the composition does not report one. */
+const FALLBACK_DURATION_SECONDS = 5;
+
+export interface OpaqueCapture {
+ fileServer: Awaited<ReturnType<typeof createFileServer>>;
+ session: Awaited<ReturnType<typeof createCaptureSession>>;
+ /** Seconds. Falls back to {@link FALLBACK_DURATION_SECONDS}. */
+ duration: number;
+}
+
+/**
+ * Serve `projectDir`, open a capture session over it and read its duration.
+ *
+ * Capture is opaque on purpose. `format: "png"` is the engine's TRANSPARENT
+ * mode: it forces `background-image: none !important` on every
+ * `[data-composition-id]`, so any composition painting its own backdrop (the
+ * VS Code snippets sit on a desktop wallpaper) loses it and the poster comes
+ * out empty. These posters are page images, never a compositing layer, so
+ * capture opaque and transcode to the .png the pages reference.
+ *
+ * The caller owns both handles and must close them.
+ */
+export async function openOpaqueCapture(params: {
+ projectDir: string;
+ width: number;
+ height: number;
+}): Promise<OpaqueCapture> {
+ const framesDir = join(params.projectDir, "_thumb_frames");
+ mkdirSync(framesDir, { recursive: true });
+
+ const fileServer = await createFileServer({ projectDir: params.projectDir, port: 0, fps: FPS });
+ try {
+ const session = await createCaptureSession(fileServer.url, framesDir, {
+ width: params.width,
+ height: params.height,
+ fps: FPS,
+ format: "jpeg",
+ quality: 95,
+ });
+ await initializeSession(session);
+
+ let duration: number;
+ try {
+ duration = await getCompositionDuration(session);
+ } catch {
+ duration = FALLBACK_DURATION_SECONDS;
+ }
+ return { fileServer, session, duration };
+ } catch (error) {
+ // The session never reached the caller, so nothing else will close the
+ // server this function opened.
+ fileServer.close();
+ throw error;
+ }
+}
diff --git a/scripts/set-version.ts b/scripts/set-version.ts
index ce176429f6..150d3e1db7 100644
--- a/scripts/set-version.ts
+++ b/scripts/set-version.ts
@@ -226,7 +226,9 @@ function assertTagMonotonicity(version: string) {
process.exit(1);
}
-export function releaseRequiresChangelog(options: ReleaseOptions) {
+export function releaseRequiresChangelog(
+ options: Pick<ReleaseOptions, "version" | "skipTag" | "skipChangelogCheck">,
+) {
return !options.skipTag && !options.skipChangelogCheck && !isPrerelease(options.version);
}
@@ -267,7 +269,7 @@ export function unreviewedChangelogArtifacts(version: string) {
}
function artifactExists(artifact: string) {
- const [path, marker] = artifact.split("#");
+ const [path = artifact, marker] = artifact.split("#");
const absolutePath = join(ROOT, path);
if (!existsSync(absolutePath)) {
@@ -277,7 +279,7 @@ function artifactExists(artifact: string) {
}
function artifactHasGeneratedTodo(artifact: string) {
- const [path, marker] = artifact.split("#");
+ const [path = artifact, marker] = artifact.split("#");
const content = readFileSync(join(ROOT, path), "utf-8");
if (!marker) {
return hasGeneratedChangelogTodo(content);
diff --git a/scripts/tsconfig.json b/scripts/tsconfig.json
new file mode 100644
index 0000000000..d3044f3b7b
--- /dev/null
+++ b/scripts/tsconfig.json
@@ -0,0 +1,16 @@
+{
+ "compilerOptions": {
+ "target": "ES2022",
+ "module": "ESNext",
+ "moduleResolution": "bundler",
+ "strict": true,
+ "noUncheckedIndexedAccess": true,
+ "esModuleInterop": true,
+ "skipLibCheck": true,
+ "noEmit": true,
+ "allowJs": true,
+ "allowImportingTsExtensions": true
+ },
+ "include": ["**/*.ts"],
+ "exclude": ["node_modules"]
+}