Skip to content

Production-ready animations, transitions, backgrounds, and scenes for Remotion

perf(dev): build the preview registry outside Turbopack

kapishdima598c2878b80c
diff --git a/.dockerignore b/.dockerignore
index 6fdbedd5..730d36d6 100644
--- a/.dockerignore
+++ b/.dockerignore
@@ -12,3 +12,4 @@ node_modules
coverage
.vercel
.source
+public/_previews
diff --git a/.gitignore b/.gitignore
index 062f06f5..8a14807d 100644
--- a/.gitignore
+++ b/.gitignore
@@ -43,6 +43,9 @@ next-env.d.ts
# fumadocs generated source
.source/
+# preview bundle (scripts/previews/build.mts)
+/public/_previews/
+
.omc
articles
diff --git a/CLAUDE.md b/CLAUDE.md
index 282bbd7d..275cbcce 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -18,6 +18,7 @@ Solo builders и маленькие команды (1-2 чел), фронтен
- `content/docs/` — MDX документации (fumadocs collection `docs`), `content/changelog/` — записи ченджлога (flat collection `changelog`)
- `registry/` — исходники компонентов: `remocn/` (анимации, переходы, backgrounds), `remocn-ui/` (UI-примитивы), `remocn-icons/` (иконки), `remocn-templates/` (готовые видео). У каждого неймспейса свой `registry.json`; `registry/__index__.tsx` — отдельный реестр превью для сайта
- `registry-artifacts/` — собранный shadcn-registry (`bun run registry:build`), коммитится в репозиторий
+- `public/_previews/` — собранный реестр превью, в git не попадает. См. «Превью собираются отдельно»
- `components/`, `lib/`, `config/`, `hooks/` — код сайта
## Уровни компонентов
@@ -48,6 +49,17 @@ Solo builders и маленькие команды (1-2 чел), фронтен
- `bun test lib/docs-meta.test.ts` — блокирующий шаг CI, отдельный от основного прогона тестов (тот пока `continue-on-error`)
- Агентские артефакты генерируются из этого frontmatter: `/llms-components.txt` (роутер по всем компонентам) и `/docs/**.md` (страница как чистый markdown, см. `lib/mdx-to-markdown.ts`)
+## Превью собираются отдельно
+
+`registry/__index__.tsx` перечисляет ~900 превью, у каждого ленивый импорт компонента и конфига. Turbopack компилирует ленивые импорты сразу, поэтому с этим индексом в графе сайта первый запрос любой страницы с превью компилировал все превью. Теперь индекс собирает Bun, а сайт загружает результат по URL.
+
+- `scripts/previews/build.mts` собирает индекс в `public/_previews/` за ~0,3 с: dev-сборка лежит в `dev/`, production — в `prod/`, друг друга они не затирают. Один набор файлов читают и браузер (`/_previews/…`), и сервер (с диска). Все скрипты названы по хешу содержимого. `react` и `remotion` в сборку не входят: превью берут их у страницы, список общих модулей — `lib/previews/shared-modules.ts`
+- Код сайта импортирует `@/lib/previews` и никогда `@/registry/__index__`: экспорты те же. Тест в `lib/docs-meta.test.ts` это проверяет. Скрипты и Remotion Studio по-прежнему импортируют сам индекс
+- `bun dev` (`scripts/dev.mts`) собирает превью, запускает `next dev` и пересобирает превью при сохранении их исходников. Открытая страница получает сборку по WebSocket и подменяет изменённые превью на месте, без перезагрузки (`lib/previews/hot.ts`). Ошибка сборки печатается в терминале `bun dev`, страница остаётся на последней удачной сборке
+- `bun run build` сначала собирает превью (`bun run previews:build`), затем сайт. `next build` без собранных превью падает на пререндере с подсказкой. Пересобрать превью после `next build` и не пересобрать сайт нельзя: страницы ссылаются на прежний входной файл
+- `registry/__names__.ts` — сгенерированный список имён превью, коммитится. Его переписывает любая сборка превью, когда меняются ключи `registry/__index__.tsx`; тест проверяет, что он не отстал
+- Сервер загружает только конфиги. `load()` на сервере отклоняется: плеер с `lazyComponent={load}` монтируется после гидрации
+
## Changelog
Любая ветка, которая добавляет или заметно меняет компоненты registry, обязана содержать запись ченджлога — в том же PR, что и сама фича.
@@ -76,8 +88,9 @@ Open core. Free примитивы и базовые compositions (MIT). В бу
```bash
bun install # установка зависимостей
-bun dev # dev-сервер Next.js
-bun run build # production-сборка сайта
+bun dev # dev-сервер Next.js и пересборка превью при сохранении
+bun run build # production-сборка превью и сайта
+bun run previews:build # только превью, в public/_previews
bun run typecheck # tsc --noEmit
bun run lint # biome check
bun run registry:build # пересборка registry-artifacts из registry/
diff --git a/app/(home)/changelog/components/changelog-preview.tsx b/app/(home)/changelog/components/changelog-preview.tsx
index c6e77565..f5245f1d 100644
--- a/app/(home)/changelog/components/changelog-preview.tsx
+++ b/app/(home)/changelog/components/changelog-preview.tsx
@@ -1,7 +1,7 @@
"use client";
+import registry from "@/lib/previews";
import { PreviewStage } from "@/lib/ui-preview-internals";
-import registry from "@/registry/__index__";
import { previewManifest } from "@/registry/__manifest__";
export function ChangelogPreview({ name }: { name: string }) {
diff --git a/app/(home)/components/landing/sections/hero/tiles/clips.tsx b/app/(home)/components/landing/sections/hero/tiles/clips.tsx
index 141c352c..48bc6e30 100644
--- a/app/(home)/components/landing/sections/hero/tiles/clips.tsx
+++ b/app/(home)/components/landing/sections/hero/tiles/clips.tsx
@@ -7,8 +7,8 @@ import {
Suspense,
} from "react";
import { AbsoluteFill, Freeze, Sequence, useCurrentFrame } from "remotion";
+import registry from "@/lib/previews";
import { cn } from "@/lib/utils";
-import registry from "@/registry/__index__";
import { previewManifest } from "@/registry/__manifest__";
import { LANDING_SCENES } from "../../../scenes";
import { type ClipEnd, type ClipSpec, TILE_SIZE } from "./config";
diff --git a/app/(home)/components/mega-menu-preview.tsx b/app/(home)/components/mega-menu-preview.tsx
index f13dacbb..c53992bf 100644
--- a/app/(home)/components/mega-menu-preview.tsx
+++ b/app/(home)/components/mega-menu-preview.tsx
@@ -2,7 +2,7 @@
import { Player, type PlayerRef } from "@remotion/player";
import { useRef } from "react";
-import registry from "@/registry/__index__";
+import registry from "@/lib/previews";
import { previewManifest } from "@/registry/__manifest__";
import { useAutoplay } from "./use-autoplay";
diff --git a/app/embed/[name]/embed-player.tsx b/app/embed/[name]/embed-player.tsx
index 9df4c0b8..c1ef096d 100644
--- a/app/embed/[name]/embed-player.tsx
+++ b/app/embed/[name]/embed-player.tsx
@@ -1,7 +1,7 @@
"use client";
+import registry from "@/lib/previews";
import { PreviewStage } from "@/lib/ui-preview-internals";
-import registry from "@/registry/__index__";
import type { BackdropFill } from "@/registry/remocn/backdrop";
export function EmbedPlayer({
diff --git a/app/studio/captions/caption-picker.tsx b/app/studio/captions/caption-picker.tsx
index deb360af..beb23bab 100644
--- a/app/studio/captions/caption-picker.tsx
+++ b/app/studio/captions/caption-picker.tsx
@@ -12,13 +12,13 @@ import { useEffect, useLayoutEffect, useRef, useState } from "react";
import { useAutoplay } from "@/app/(home)/components/use-autoplay";
import { ComponentPreview } from "@/components/docs/component-preview";
import captionsMeta from "@/content/docs/captions/components/meta.json";
+import components from "@/lib/previews";
import {
getCachedStudioElement,
loadStudioElement,
} from "@/lib/studio-element";
import { usePrefersReducedMotion } from "@/lib/use-prefers-reduced-motion";
import { cn } from "@/lib/utils";
-import components from "@/registry/__index__";
import { previewManifest } from "@/registry/__manifest__";
import registry from "@/registry/remocn/registry.json";
diff --git a/components/docs/component-card.tsx b/components/docs/component-card.tsx
index af5280bd..ec064374 100644
--- a/components/docs/component-card.tsx
+++ b/components/docs/component-card.tsx
@@ -5,9 +5,9 @@ import { useIntersectionObserver } from "@uidotdev/usehooks";
import Link from "next/link";
import { useEffect, useRef, useState } from "react";
import { useAutoplay } from "@/app/(home)/components/use-autoplay";
+import registry from "@/lib/previews";
import { usePrefersReducedMotion } from "@/lib/use-prefers-reduced-motion";
import { cn } from "@/lib/utils";
-import registry from "@/registry/__index__";
import { previewManifest } from "@/registry/__manifest__";
import type { CardItem } from "./component-card-grid";
diff --git a/components/docs/component-preview.tsx b/components/docs/component-preview.tsx
index fcd5dd3d..ebbc6e3a 100644
--- a/components/docs/component-preview.tsx
+++ b/components/docs/component-preview.tsx
@@ -6,7 +6,6 @@ import { RotateCcwIcon } from "lucide-react";
import {
type ReactNode,
Suspense,
- use,
useCallback,
useMemo,
useRef,
@@ -17,8 +16,9 @@ import type {
ControlConfig,
ResolvedComponentConfig,
} from "@/lib/customizer-config";
+import registry from "@/lib/previews";
+import { useComponentConfig } from "@/lib/previews/use-component-config";
import { cn } from "@/lib/utils";
-import registry, { loadComponentConfig } from "@/registry/__index__";
import { CustomizePanel } from "./blocks/customize-panel";
import { DocsPlayer } from "./blocks/player/docs-player";
import { PlayerFallback, UnknownBlock } from "./blocks/player/player-fallback";
@@ -103,7 +103,7 @@ function Preview({
}) {
// Suspends until this component's config chunk resolves, then returns
// synchronously from the cached promise. No other config is fetched.
- const config = use(loadComponentConfig(name));
+ const config = useComponentConfig(name);
const { values, isDefault, change, reset } = useCustomizer(
name,
config.controls,
diff --git a/components/docs/icons-gallery.tsx b/components/docs/icons-gallery.tsx
index dc945078..2fc0a798 100644
--- a/components/docs/icons-gallery.tsx
+++ b/components/docs/icons-gallery.tsx
@@ -14,13 +14,13 @@ import {
type IconEntry,
} from "@/components/docs/index/icons/icons";
import { Remotion } from "@/components/ui/svgs/remotion";
+import registry, { type RegistryEntry } from "@/lib/previews";
import {
getCachedStudioElement,
loadStudioElement,
} from "@/lib/studio-element";
import { usePrefersReducedMotion } from "@/lib/use-prefers-reduced-motion";
import { cn } from "@/lib/utils";
-import registry, { type RegistryEntry } from "@/registry/__index__";
import {
type PreviewManifestEntry,
previewManifest,
diff --git a/components/docs/index/libraries/caption-hero.tsx b/components/docs/index/libraries/caption-hero.tsx
index 194d6cd8..65db71e9 100644
--- a/components/docs/index/libraries/caption-hero.tsx
+++ b/components/docs/index/libraries/caption-hero.tsx
@@ -2,8 +2,8 @@
import { memo, useCallback, useState } from "react";
import { previewCaptions } from "@/components/docs/examples/caption-fixture";
+import registry from "@/lib/previews";
import { cn } from "@/lib/utils";
-import registry from "@/registry/__index__";
import { previewManifest } from "@/registry/__manifest__";
import { HeroTag } from "./hero-pill";
import { HeroPlayer } from "./hero-player";
diff --git a/components/docs/index/libraries/registry-hero-player.tsx b/components/docs/index/libraries/registry-hero-player.tsx
index 2e0e94a4..5635e4a9 100644
--- a/components/docs/index/libraries/registry-hero-player.tsx
+++ b/components/docs/index/libraries/registry-hero-player.tsx
@@ -1,6 +1,6 @@
"use client";
-import registry from "@/registry/__index__";
+import registry from "@/lib/previews";
import { previewManifest } from "@/registry/__manifest__";
import { HeroPlayer } from "./hero-player";
diff --git a/components/docs/index/libraries/tile-preview.tsx b/components/docs/index/libraries/tile-preview.tsx
index 139d5361..60649eb9 100644
--- a/components/docs/index/libraries/tile-preview.tsx
+++ b/components/docs/index/libraries/tile-preview.tsx
@@ -2,8 +2,8 @@
import { Player, type PlayerRef } from "@remotion/player";
import { useEffect, useRef } from "react";
+import registry from "@/lib/previews";
import { usePrefersReducedMotion } from "@/lib/use-prefers-reduced-motion";
-import registry from "@/registry/__index__";
import { previewManifest } from "@/registry/__manifest__";
import { FILTER_PHOTO_LOADERS } from "./filter-photo-scenes";
import { useInView } from "./use-in-view";
diff --git a/components/docs/index/templates/template-poster.tsx b/components/docs/index/templates/template-poster.tsx
index 96750527..f2cb53f2 100644
--- a/components/docs/index/templates/template-poster.tsx
+++ b/components/docs/index/templates/template-poster.tsx
@@ -2,7 +2,7 @@
import { Player, type PlayerRef } from "@remotion/player";
import { useEffect, useRef, useState } from "react";
-import registry from "@/registry/__index__";
+import registry from "@/lib/previews";
import { previewManifest } from "@/registry/__manifest__";
/**
diff --git a/components/docs/shader-preset-card.tsx b/components/docs/shader-preset-card.tsx
index 41256131..36294351 100644
--- a/components/docs/shader-preset-card.tsx
+++ b/components/docs/shader-preset-card.tsx
@@ -4,8 +4,8 @@ import { Player, type PlayerRef } from "@remotion/player";
import Link from "next/link";
import { useEffect, useRef, useState } from "react";
import { useAutoplay } from "@/app/(home)/components/use-autoplay";
+import registry from "@/lib/previews";
import type { ShaderPresetItem } from "@/lib/shader-presets";
-import registry from "@/registry/__index__";
import { previewManifest } from "@/registry/__manifest__";
import { CopyButton } from "./copy-button";
@@ -15,8 +15,8 @@ export function ShaderPresetCard({ item }: { item: ShaderPresetItem }) {
const playerRef = useRef<PlayerRef>(null);
const { containerRef } = useAutoplay(playerRef);
// The Player mounts after hydration: on the server its lazyComponent would
- // load the shader there, and the server build strips preview loads
- // (lib/build/strip-server-preview-loads.cjs).
+ // load the shader there, and previews load in the browser only
+ // (lib/previews/index.ts).
const [mounted, setMounted] = useState(false);
useEffect(() => setMounted(true), []);
const command = `npx shadcn@latest add @remocn/${item.name}`;
diff --git a/components/docs/ui-component-preview.tsx b/components/docs/ui-component-preview.tsx
index 513973e7..7fad4b77 100644
--- a/components/docs/ui-component-preview.tsx
+++ b/components/docs/ui-component-preview.tsx
@@ -2,8 +2,9 @@
import { Suspense, use, useMemo } from "react";
import type { ControlConfig } from "@/lib/customizer-config";
+import registry from "@/lib/previews";
+import { useComponentConfig } from "@/lib/previews/use-component-config";
import { cn } from "@/lib/utils";
-import registry, { loadComponentConfig } from "@/registry/__index__";
import { CustomizePanel } from "./blocks/customize-panel";
import { DocsPlayer } from "./blocks/player/docs-player";
import { PlayerFallback, UnknownBlock } from "./blocks/player/player-fallback";
@@ -46,7 +47,7 @@ function UiPreview({
// Suspends on first render until this component's scene chunk resolves:
// the scene component, its honored-control list and its code template.
const scene = use(loadUiScene(name));
- const controls: ControlConfig = use(loadComponentConfig(name)).controls;
+ const controls: ControlConfig = useComponentConfig(name).controls;
const honored = scene.controls;
// config.controls ∩ honored: drops state/speed and every structural knob
diff --git a/lib/build/strip-server-preview-loads.cjs b/lib/build/strip-server-preview-loads.cjs
deleted file mode 100644
index 811f5df2..00000000
--- a/lib/build/strip-server-preview-loads.cjs
+++ /dev/null
@@ -1,40 +0,0 @@
-// Turbopack loader for `registry/__index__.tsx`, applied to server builds only
-// (see `turbopack.rules` in next.config.ts).
-//
-// Every registry entry has `load: () => import(<component>)`. Previews only
-// ever call it in the browser: the Player mounts the composition client-side,
-// and SSR renders the stage around it. But the bundler can't know that, so it
-// compiled all ~900 components a second time for the server graph on the
-// first request to any page that imports the index. Here each server-side
-// `load` becomes a stub, which keeps every component out of the server graph.
-// `loadConfig` is left alone: SSR does read configs.
-//
-// The stub rejects, so a server call fails loudly (the prerender errors) rather
-// than rendering an empty frame. A Remotion <Player lazyComponent={load}>
-// rendered during SSR calls `load` there: mount such a Player after hydration,
-// as the docs stage, component cards and shader preset cards do.
-//
-// lib/build/strip-server-preview-loads.test.ts checks that this still matches
-// every entry of the real index.
-
-const LOAD_ENTRY =
- /^([ \t]+)load: \(\) =>\s+import\([\s\S]*?(?=^\1loadConfig:)/gm;
-
-function stripServerPreviewLoads(source) {
- const out = source.replace(
- LOAD_ENTRY,
- (_match, indent) => `${indent}load: serverPreviewLoad,\n`,
- );
- return `${out}
-function serverPreviewLoad() {
- return Promise.reject(
- new Error(
- "registry/__index__: load() is browser-only, the server build strips it (lib/build/strip-server-preview-loads.cjs)",
- ),
- );
-}
-`;
-}
-
-module.exports = stripServerPreviewLoads;
-module.exports.LOAD_ENTRY = LOAD_ENTRY;
diff --git a/lib/build/strip-server-preview-loads.test.ts b/lib/build/strip-server-preview-loads.test.ts
deleted file mode 100644
index 14e4542b..00000000
--- a/lib/build/strip-server-preview-loads.test.ts
+++ /dev/null
@@ -1,37 +0,0 @@
-import { describe, expect, it } from "bun:test";
-import { readFileSync } from "node:fs";
-import { join } from "node:path";
-import registry from "@/registry/__index__";
-import stripServerPreviewLoads from "./strip-server-preview-loads.cjs";
-
-const source = readFileSync(
- join(import.meta.dir, "../../registry/__index__.tsx"),
- "utf8",
-);
-const stripped = stripServerPreviewLoads(source);
-const entryCount = Object.keys(registry).length;
-
-const count = (text: string, pattern: RegExp) =>
- text.match(pattern)?.length ?? 0;
-
-describe("strip-server-preview-loads", () => {
- it("replaces the load of every registry entry", () => {
- // A new entry written in a shape the loader doesn't match would put its
- // component back into the server graph without failing anywhere else.
- expect(count(stripped, /^\s+load: serverPreviewLoad,$/gm)).toBe(entryCount);
- });
-
- it("leaves no component import behind a load", () => {
- expect(stripped).not.toMatch(/load: \(\) =>\s+import\(/);
- });
-
- it("keeps every loadConfig", () => {
- expect(count(stripped, /loadConfig: \(\) =>\s+import\(/g)).toBe(entryCount);
- });
-
- it("keeps the RegistryEntry type intact", () => {
- expect(stripped).toContain(
- "load: () => Promise<{ default: React.ComponentType<any> }>;",
- );
- });
-});
diff --git a/lib/docs-meta.test.ts b/lib/docs-meta.test.ts
index f4835595..6ad190e0 100644
--- a/lib/docs-meta.test.ts
+++ b/lib/docs-meta.test.ts
@@ -300,6 +300,63 @@ describe("docs pages compile at runtime", () => {
});
});
+describe("previews are built outside the site's bundler", () => {
+ // registry/__index__.tsx lazily imports ~900 previews, and Turbopack
+ // compiles lazy imports up front: in the site's module graph the index
+ // made the first request of any page with a preview compile them all. The
+ // site loads the index as a separate bundle instead (lib/previews/index.ts).
+ it("no site code imports the registry index", () => {
+ const files = [
+ ...new Glob("*.{ts,tsx}").scanSync("."),
+ ...["app", "components", "config", "hooks", "lib"].flatMap((folder) => [
+ ...new Glob(`${folder}/**/*.{ts,tsx}`).scanSync("."),
+ ]),
+ // Blog and changelog pages go through the bundler and may import.
+ ...new Glob("content/{blog,changelog}/**/*.mdx").scanSync("."),
+ ];
+ const offenders = files.filter((file) => {
+ // Tests run under Bun, not in the site's bundle.
+ if (/\.test\.tsx?$/.test(file)) return false;
+ let source = readFileSync(file, "utf8");
+ source = file.endsWith(".mdx")
+ ? // Prose may name the file; only its import lines count.
+ source
+ .split("\n")
+ .filter((line) => /^(import|export)\s/.test(line))
+ .join(";\n")
+ : // Comments may name it too.
+ source
+ .replace(/\/\*[\s\S]*?\*\//g, "")
+ .replace(/(^|[^:"'`\\])\/\/.*$/gm, "$1");
+ // A module specifier that ends at the index, in whatever statement
+ // holds it: import, export … from, import(), require().
+ const specifier = /["'`][^"'`\n]*registry\/__index__(\.tsx?)?["'`]/g;
+ for (const match of source.matchAll(specifier)) {
+ const before = source.slice(0, match.index);
+ const statement = before.slice(before.lastIndexOf(";") + 1);
+ // Type-only forms are erased, so they stay allowed.
+ const typeOnly =
+ /^\s*((import|export) )?type\b/.test(statement) ||
+ /typeof import\(\s*$/.test(before);
+ if (!typeOnly) return true;
+ }
+ return false;
+ });
+
+ expect(offenders).toEqual([]);
+ });
+
+ // The site tells a known preview from an unknown one by this list, without
+ // loading the bundle. Any previews build rewrites it (`bun dev`,
+ // `bun run build`, `bun run previews:build`); commit the result.
+ it("registry/__names__.ts lists the keys of the registry index", async () => {
+ const { default: registry } = await import("@/registry/__index__");
+ const { previewNames } = await import("@/registry/__names__");
+
+ expect<string[]>([...previewNames]).toEqual(Object.keys(registry));
+ });
+});
+
describe("the transitions library page stays complete", () => {
// /docs/transitions answers "is there a transitions library for Remotion?"
// with a count and a table of every transition. A new transition page has
diff --git a/lib/previews/hot.ts b/lib/previews/hot.ts
new file mode 100644
index 00000000..bcb473f9
--- /dev/null
+++ b/lib/previews/hot.ts
@@ -0,0 +1,221 @@
+"use client";
+
+// Dev only: keeps the previews on an open page in step with their sources.
+//
+// The dev launcher (scripts/dev.mts) rebuilds the preview bundle when a
+// source file is saved and announces the build over a WebSocket. Turbopack's
+// Fast Refresh never sees these files, so this module does its job: each
+// loaded preview is rendered through a stand-in component that switches to
+// the rebuilt one. The Player around it stays mounted and keeps its frame,
+// and the customizer keeps its values; a composition holds no state of its
+// own, so nothing else is lost.
+//
+// lib/previews/index.ts imports this module only in development.
+
+import {
+ Component,
+ type ComponentType,
+ createElement,
+ type ReactNode,
+ useSyncExternalStore,
+} from "react";
+import {
+ onPreviewsUpdate,
+ type PreviewBundle,
+ previewsRevision,
+} from "./index";
+
+// biome-ignore lint/suspicious/noExplicitAny: dynamically-loaded Remotion composition, props shape varies per component
+type AnyComponent = ComponentType<any>;
+
+type Manifest = { version: string; port?: number };
+
+const MANIFEST = "/_previews/dev/manifest.json";
+
+async function readManifest(): Promise<Manifest> {
+ const response = await fetch(MANIFEST, { cache: "no-store" });
+ if (!response.ok) {
+ throw new Error(
+ "The preview bundle is missing. Start the site with `bun dev`: it builds the previews into public/_previews.",
+ );
+ }
+ return response.json();
+}
+
+/**
+ * Resolves to the version of the bundle on disk, then calls `onBuilt` with
+ * the version of every later build.
+ */
+export async function connect(
+ onBuilt: (version: string) => void,
+): Promise<string> {
+ const manifest = await readManifest();
+ if (manifest.port) {
+ listen(manifest.port, onBuilt);
+ } else {
+ console.warn(
+ "[previews] No live channel: previews won't update when their source is saved. Start the site with `bun dev`.",
+ );
+ }
+ return manifest.version;
+}
+
+function listen(port: number, onBuilt: (version: string) => void, wait = 3000) {
+ // The launcher writes its port to the manifest and takes it out when it
+ // exits. So: no port means nobody to call, and a port means try again,
+ // whether the launcher was restarted or the connection just dropped. A
+ // port nobody answers on is tried less and less often.
+ let next = Math.min(wait * 2, 30000);
+ const again = () =>
+ setTimeout(() => {
+ readManifest()
+ .then((manifest) => {
+ if (manifest.port) listen(manifest.port, onBuilt, next);
+ else again();
+ })
+ .catch(again);
+ }, wait);
+
+ let socket: WebSocket;
+ try {
+ socket = new WebSocket(`ws://${location.hostname}:${port}`);
+ } catch (error) {
+ // An https page may not open ws:// at all. Previews still load.
+ console.warn("[previews] No live channel:", error);
+ return;
+ }
+ socket.onopen = () => {
+ next = 3000;
+ };
+ socket.onmessage = (event) => {
+ const message: { type: string; version?: string } = JSON.parse(event.data);
+ if (message.version) onBuilt(message.version);
+ if (message.type === "failed") {
+ console.error(
+ "[previews] The rebuild failed: see the terminal running `bun dev`. The page keeps the last good previews.",
+ );
+ }
+ };
+ socket.onclose = again;
+}
+
+const sameProps = (a: Record<string, unknown>, b: Record<string, unknown>) =>
+ a === b ||
+ (Object.keys(a).length === Object.keys(b).length &&
+ Object.keys(a).every((key) => Object.is(a[key], b[key])));
+
+type BoundaryProps = {
+ component: AnyComponent;
+ revision: number;
+ // biome-ignore lint/suspicious/noExplicitAny: the preview's own props
+ props: Record<string, any>;
+ children?: ReactNode;
+};
+
+/**
+ * A preview that threw while rendering. It gets another go whenever
+ * something it renders from changes: the component, any rebuild (a fixed
+ * config or helper keeps the component as it is), or its props. The Player's
+ * own error boundary would stay tripped until a page reload.
+ */
+class Boundary extends Component<
+ BoundaryProps,
+ { error: unknown; seen: BoundaryProps }
+> {
+ state = { error: null as unknown, seen: this.props };
+
+ static getDerivedStateFromError(error: unknown) {
+ return { error };
+ }
+
+ static getDerivedStateFromProps(
+ props: BoundaryProps,
+ state: { error: unknown; seen: BoundaryProps },
+ ) {
+ const { seen } = state;
+ if (
+ props.component === seen.component &&
+ props.revision === seen.revision &&
+ sameProps(props.props, seen.props)
+ ) {
+ return null;
+ }
+ return { error: null, seen: props };
+ }
+
+ render() {
+ const { error } = this.state;
+ if (error === null) return this.props.children;
+ return createElement(
+ "pre",
+ {
+ style: {
+ position: "absolute",
+ inset: 0,
+ margin: 0,
+ padding: 40,
+ overflow: "auto",
+ whiteSpace: "pre-wrap",
+ font: "28px/1.4 ui-monospace, monospace",
+ color: "#fff",
+ background: "#7f1d1d",
+ },
+ },
+ error instanceof Error ? (error.stack ?? error.message) : String(error),
+ );
+ }
+}
+
+type Slot = { current: AnyComponent; StandIn: AnyComponent };
+
+const slots = new Map<string, Slot>();
+
+/**
+ * The stand-in for the preview `name`: one component for the life of the
+ * page, rendering `component` now and its rebuilt versions later.
+ */
+export function hotComponent(
+ name: string,
+ component: AnyComponent,
+): AnyComponent {
+ // Once a stand-in exists, only `reload` moves it on: a second load of the
+ // same preview may still be holding a component from an older bundle.
+ const existing = slots.get(name);
+ if (existing) return existing.StandIn;
+ const slot: Slot = {
+ current: component,
+ StandIn: (props) => {
+ // Every rebuild renders the stand-in again, changed component or not.
+ const revision = useSyncExternalStore(
+ onPreviewsUpdate,
+ previewsRevision,
+ previewsRevision,
+ );
+ const Current = slot.current;
+ return createElement(
+ Boundary,
+ { component: Current, revision, props },
+ createElement(Current, props),
+ );
+ },
+ };
+ slot.StandIn.displayName = `Preview(${name})`;
+ slots.set(name, slot);
+ return slot.StandIn;
+}
+
+/** Points every stand-in at its component in the rebuilt bundle. */
+export async function reload(bundle: PreviewBundle) {
+ await Promise.all(
+ [...slots].map(async ([name, slot]) => {
+ try {
+ const entry = bundle.default[name];
+ // Unchanged chunks keep their URL, so the same component comes back.
+ if (entry) slot.current = (await entry.load()).default;
+ } catch (error) {
+ // One broken preview doesn't hold the others back.
+ console.error(`[previews] "${name}" failed to load`, error);
+ }
+ }),
+ );
+}
diff --git a/lib/previews/index.ts b/lib/previews/index.ts
new file mode 100644
index 00000000..a3969cd1
--- /dev/null
+++ b/lib/previews/index.ts
@@ -0,0 +1,285 @@
+// The site's handle on the preview registry.
+//
+// registry/__index__.tsx lists ~900 previews, each a lazy import of a
+// component and of its config. Turbopack compiles lazy imports up front, so
+// with that index in the site's module graph the first request to any page
+// with a preview compiled every preview. The index is built on its own
+// instead (scripts/previews/build.mts, into public/_previews) and this module
+// loads the result by URL at runtime: the browser from /_previews/, the
+// server from the same files on disk.
+//
+// Site code imports this module and never registry/__index__ itself;
+// lib/docs-meta.test.ts enforces it. It has the same exports.
+
+import { preloadModule } from "react-dom";
+import type { ResolvedComponentConfig } from "@/lib/customizer-config";
+import type { RegistryEntry } from "@/registry/__index__";
+import { previewNames } from "@/registry/__names__";
+import { registerShared } from "./shared";
+
+export type { RegistryEntry };
+
+/** What registry/__index__.tsx exports, as built into public/_previews. */
+export type PreviewBundle = typeof import("@/registry/__index__");
+
+const SERVER = typeof window === "undefined";
+
+// Development and production bundles are separate folders, so `bun dev` and
+// `bun run build` don't overwrite each other's files.
+const MODE = process.env.NODE_ENV === "development" ? "dev" : "prod";
+const BASE = `/_previews/${MODE}`;
+
+/** The bundle `next build` ran against (next.config.ts). Unused in dev. */
+const BUILD_VERSION = process.env.REMOCN_PREVIEWS_VERSION ?? "";
+
+const MISSING =
+ "The preview bundle is missing or stale. `bun dev` and `bun run build` build it into public/_previews; `bun run previews:build` does only that.";
+
+/** The bundle's entry file. Its name carries the hash of its content. */
+const entryFile = (version: string) => `entries-${version}.js`;
+
+let active: { version: string; bundle: Promise<PreviewBundle> } | undefined;
+let verified = false;
+
+if (process.env.NODE_ENV === "development" && !SERVER) {
+ // Fast Refresh ran this module again: the list of previews changed, or this
+ // file did. The previews on the page hang off the state of the first run,
+ // which a second run can't take over, so start the page afresh.
+ const page = globalThis as { __remocnPreviewsLoaded?: boolean };
+ if (page.__remocnPreviewsLoaded) location.reload();
+ page.__remocnPreviewsLoaded = true;
+}
+
+/** Server: where the bundle is on disk. */
+function bundlePath(file: string): string {
+ const { join } = process.getBuiltinModule("node:path");
+ return join(process.cwd(), "public", "_previews", MODE, file);
+}
+
+/** Server: the version of the bundle on disk. */
+function serverVersion(): string {
+ if (verified) return BUILD_VERSION;
+ const { readFileSync } = process.getBuiltinModule("node:fs");
+ let manifest: { version: string };
+ try {
+ manifest = JSON.parse(readFileSync(bundlePath("manifest.json"), "utf8"));
+ } catch (cause) {
+ throw new Error(MISSING, { cause });
+ }
+ // The dev launcher rebuilds the bundle while the server runs.
+ if (process.env.NODE_ENV === "development") return manifest.version;
+ if (manifest.version !== BUILD_VERSION) {
+ throw new Error(
+ "public/_previews/prod is not the bundle this build of the site was made with: it was rebuilt after `next build`. Run `bun run build`.",
+ );
+ }
+ verified = true;
+ return BUILD_VERSION;
+}
+
+function importBundle(version: string): Promise<PreviewBundle> {
+ registerShared();
+ const url = SERVER
+ ? process
+ .getBuiltinModule("node:url")
+ .pathToFileURL(bundlePath(entryFile(version))).href
+ : `${BASE}/${entryFile(version)}`;
+ return import(/* turbopackIgnore: true */ url).catch((cause) => {
+ throw new Error(MISSING, { cause });
+ });
+}
+
+function activate(version: string): Promise<PreviewBundle> {
+ if (active?.version !== version) {
+ const bundle = importBundle(version);
+ active = { version, bundle };
+ // In dev the server outlives a rebuild: its cached configs are old now.
+ if (SERVER) configs.clear();
+ // A bundle that failed to load is asked for again, not remembered.
+ bundle.catch(() => {
+ if (active?.bundle === bundle) active = undefined;
+ });
+ }
+ return active.bundle;
+}
+
+let hot: typeof import("./hot") | undefined;
+let starting: Promise<void> | undefined;
+let swapping: Promise<void> = Promise.resolve();
+
+function loadBundle(): Promise<PreviewBundle> {
+ if (SERVER) return activate(serverVersion());
+ if (process.env.NODE_ENV === "development") {
+ // The dev launcher (scripts/dev.mts) rebuilds the bundle on every save,
+ // so the page asks which one is current and listens for the next.
+ starting ??= import("./hot")
+ .then(async (module) => {
+ hot = module;
+ activate(await module.connect(swap));
+ })
+ .catch((error) => {
+ // Not for good: the next preview to load asks again.
+ starting = undefined;
+ throw error;
+ });
+ return (
+ starting
+ // A rebuild being applied right now: hand out the bundle it brings.
+ .then(() => swapping)
+ .then(() => (active as NonNullable<typeof active>).bundle)
+ );
+ }
+ return activate(BUILD_VERSION);
+}
+
+function entryOf(bundle: PreviewBundle, name: string): RegistryEntry {
+ const entry = bundle.default[name];
+ if (!entry) {
+ throw new Error(`Preview "${name}" is not in the built bundle. ${MISSING}`);
+ }
+ return entry;
+}
+
+function serverLoad(): Promise<never> {
+ return Promise.reject(
+ new Error(
+ "previews: load() is browser-only. A Remotion <Player lazyComponent={load}> rendered on the server calls it there: mount such a Player after hydration, as the docs stage and the component cards do.",
+ ),
+ );
+}
+
+async function browserLoad(name: string) {
+ for (;;) {
+ const bundle = await loadBundle();
+ const version = active?.version;
+ const module = await entryOf(bundle, name).load();
+ if (!hot) return module;
+ // Dev: a rebuild landed while the component was loading. This one is
+ // already old, and the swap has passed over a preview it didn't know yet.
+ if (active?.version !== version) continue;
+ // A stand-in that renders whatever the latest rebuild holds.
+ return { default: hot.hotComponent(name, module.default) };
+ }
+}
+
+const registry: Record<string, RegistryEntry> = Object.fromEntries(
+ previewNames.map((name): [string, RegistryEntry] => [
+ name,
+ {
+ // Previews only mount in the browser. Rejecting on the server keeps a
+ // misplaced Player loud (the prerender fails) instead of an empty frame.
+ load: SERVER ? serverLoad : () => browserLoad(name),
+ loadConfig: async () => entryOf(await loadBundle(), name).loadConfig(),
+ },
+ ]),
+);
+
+const configs = new Map<string, Promise<ResolvedComponentConfig>>();
+/** Dev: each loaded config as its module exports it, to tell which ones a rebuild changed. */
+const rawConfigs = new Map<string, unknown>();
+
+export function loadComponentConfig(
+ slug: string,
+): Promise<ResolvedComponentConfig> {
+ if (!registry[slug]) throw new Error(`Unknown registry entry: ${slug}`);
+ // Before the cache: on the server this is what notices a rebuilt bundle.
+ const bundle = loadBundle();
+ if (SERVER && active) hintPreview(slug, active.version);
+ let promise = configs.get(slug);
+ if (!promise) {
+ promise = bundle.then((loaded) => {
+ if (hot) {
+ entryOf(loaded, slug)
+ .loadConfig()
+ .then((raw) => rawConfigs.set(slug, raw));
+ }
+ return loaded.loadComponentConfig(slug);
+ });
+ configs.set(slug, promise);
+ // The same for a config: a later render gets a fresh attempt.
+ const attempt = promise;
+ attempt.catch(() => {
+ if (configs.get(slug) === attempt) configs.delete(slug);
+ });
+ }
+ return promise;
+}
+
+let preloads:
+ | { version: string; files: string[]; previews: Record<string, number[]> }
+ | undefined;
+
+/**
+ * Server: names the files of a preview in the page's HTML as
+ * `<link rel="modulepreload">`. The browser then fetches them together while
+ * it parses the page. Without the hints it would start after hydration and
+ * find the chunks one import level at a time.
+ */
+function hintPreview(slug: string, version: string) {
+ if (preloads?.version !== version) {
+ const { readFileSync } = process.getBuiltinModule("node:fs");
+ try {
+ preloads = JSON.parse(readFileSync(bundlePath("preload.json"), "utf8"));
+ } catch {
+ // Hints only: the preview loads without them.
+ }
+ if (preloads?.version !== version) {
+ preloads = { version, files: [], previews: {} };
+ }
+ }
+ preloadModule(`${BASE}/${entryFile(version)}`, { as: "script" });
+ for (const index of preloads.previews[slug] ?? []) {
+ preloadModule(`${BASE}/${preloads.files[index]}`, { as: "script" });
+ }
+}
+
+const listeners = new Set<() => void>();
+let revision = 0;
+
+/**
+ * Calls `listener` after a rebuilt bundle replaced what the page had loaded.
+ * Only ever fires in dev.
+ */
+export function onPreviewsUpdate(listener: () => void): () => void {
+ listeners.add(listener);
+ return () => {
+ listeners.delete(listener);
+ };
+}
+
+/** How many rebuilt bundles the page has taken in. Stays 0 outside dev. */
+export function previewsRevision(): number {
+ return revision;
+}
+
+/** Dev: a rebuilt bundle is out. Replace what the page loaded from the old one. */
+function swap(version: string) {
+ swapping = swapping
+ .then(async () => {
+ if (!hot || !active || active.version === version) return;
+ const bundle = await importBundle(version);
+ // From here on a preview that loads gets the new bundle; one that is
+ // loading from the old bundle sees the version move and loads again.
+ active = { version, bundle: Promise.resolve(bundle) };
+ await hot.reload(bundle);
+ for (const slug of [...configs.keys()]) {
+ try {
+ const fresh = await bundle.default[slug]?.loadConfig();
+ // Unchanged chunks keep their URL, so an unchanged config is the
+ // same object and its consumers are left alone.
+ if (fresh === undefined || fresh === rawConfigs.get(slug)) continue;
+ rawConfigs.set(slug, fresh);
+ configs.set(slug, bundle.loadComponentConfig(slug));
+ } catch (error) {
+ console.error(`[previews] config of "${slug}" failed to load`, error);
+ }
+ }
+ revision++;
+ for (const listener of listeners) listener();
+ })
+ .catch((error) => {
+ console.error("[previews] could not apply the rebuilt bundle", error);
+ });
+}
+
+export default registry;
diff --git a/lib/previews/shared-modules.ts b/lib/previews/shared-modules.ts
new file mode 100644
index 00000000..e8c1a4e1
--- /dev/null
+++ b/lib/previews/shared-modules.ts
@@ -0,0 +1,23 @@
+/**
+ * Modules the preview bundle takes from the page instead of bundling its own
+ * copy. A second React or Remotion would not see the contexts of the Player
+ * that renders the preview.
+ *
+ * scripts/previews/build.mts leaves every import of `react`, `react-dom` and
+ * `remotion` (and their subpaths) out of the bundle and fails when the
+ * previews import a subpath missing here. lib/previews/shared.ts hands the
+ * listed modules over at runtime.
+ */
+export const SHARED_MODULES = [
+ "react",
+ "react-dom",
+ "react/jsx-runtime",
+ "react/jsx-dev-runtime",
+ "remotion",
+ "remotion/no-react",
+] as const;
+
+export type SharedModule = (typeof SHARED_MODULES)[number];
+
+/** The global the page fills and the preview bundle reads. */
+export const SHARED_GLOBAL = "__remocnShared";
diff --git a/lib/previews/shared.ts b/lib/previews/shared.ts
new file mode 100644
index 00000000..64785802
--- /dev/null
+++ b/lib/previews/shared.ts
@@ -0,0 +1,24 @@
+import * as React from "react";
+import * as ReactJsxDevRuntime from "react/jsx-dev-runtime";
+import * as ReactJsxRuntime from "react/jsx-runtime";
+import * as ReactDOM from "react-dom";
+import * as Remotion from "remotion";
+import * as RemotionNoReact from "remotion/no-react";
+import { SHARED_GLOBAL, type SharedModule } from "./shared-modules";
+
+const shared: Record<SharedModule, unknown> = {
+ react: React,
+ "react-dom": ReactDOM,
+ "react/jsx-runtime": ReactJsxRuntime,
+ "react/jsx-dev-runtime": ReactJsxDevRuntime,
+ remotion: Remotion,
+ "remotion/no-react": RemotionNoReact,
+};
+
+/**
+ * Gives the preview bundle this page's React and Remotion (see
+ * shared-modules.ts). Call it before the bundle is imported.
+ */
+export function registerShared() {
+ (globalThis as Record<string, unknown>)[SHARED_GLOBAL] = shared;
+}
diff --git a/lib/previews/use-component-config.ts b/lib/previews/use-component-config.ts
new file mode 100644
index 00000000..5c470c56
--- /dev/null
+++ b/lib/previews/use-component-config.ts
@@ -0,0 +1,23 @@
+"use client";
+
+import { startTransition, use, useEffect, useState } from "react";
+import type { ResolvedComponentConfig } from "@/lib/customizer-config";
+import { loadComponentConfig, onPreviewsUpdate } from "./index";
+
+/**
+ * The resolved config of a preview. Suspends until the config's chunk has
+ * loaded, then reads the cached promise synchronously; no other config is
+ * fetched.
+ *
+ * In dev it renders again when a saved config is rebuilt. The update is a
+ * transition, so the preview stays on screen while the new config loads
+ * instead of falling back to its Suspense placeholder.
+ */
+export function useComponentConfig(slug: string): ResolvedComponentConfig {
+ const [, refresh] = useState(0);
+ useEffect(
+ () => onPreviewsUpdate(() => startTransition(() => refresh((n) => n + 1))),
+ [],
+ );
+ return use(loadComponentConfig(slug));
+}
diff --git a/next.config.ts b/next.config.ts
index 813f5de3..6fe7e186 100644
--- a/next.config.ts
+++ b/next.config.ts
@@ -1,3 +1,5 @@
+import { readFileSync } from "node:fs";
+import { join } from "node:path";
import { createMDX } from "fumadocs-mdx/next";
import type { NextConfig } from "next";
import {
@@ -8,6 +10,42 @@ import {
const withMDX = createMDX();
+/**
+ * The version of the production preview bundle, which `bun run build` writes
+ * (scripts/previews/build.mts) before it runs `next build`. Constant in dev:
+ * there the page reads the manifest itself, and a value that changed on each
+ * start would only invalidate Turbopack's cache.
+ */
+function previewsVersion(): string {
+ if (process.env.NODE_ENV === "development") return "";
+ try {
+ const manifest = readFileSync(
+ join(__dirname, "public/_previews/prod/manifest.json"),
+ "utf8",
+ );
+ return JSON.parse(manifest).version;
+ } catch {
+ // lib/previews/index.ts reports the missing bundle where it is needed.
+ return "";
+ }
+}
+
+/**
+ * Every script and font of the preview bundle is named by the hash of its
+ * content, so none of them changes under its URL. The manifest, the preload
+ * map and the source maps are not, and keep the default headers.
+ */
+function previewsHeaders() {
+ const headers = [
+ { key: "Cache-Control", value: "public, max-age=31536000, immutable" },
+ ];
+ return [
+ "/_previews/:mode(dev|prod)/chunks/:file([^/]+\\.js)",
+ "/_previews/:mode(dev|prod)/assets/:file*",
+ "/_previews/:mode(dev|prod)/:entry(entries-[0-9a-f]+\\.js)",
+ ].map((source) => ({ source, headers }));
+}
+
const DOCS_FOLDER_REDIRECTS: Record<string, string> = {
"/docs/getting-started": "/docs/getting-started/introduction",
"/docs/icons": "/docs/icons/gallery",
@@ -44,20 +82,14 @@ const nextConfig: NextConfig = {
outputFileTracingIncludes: {
"/mcp": ["./plugins/remocn/skills/remocn/references/**/*.md"],
},
+ // The preview bundle in public/_previews that lib/previews/index.ts loads
+ // by URL: the version names its entry file, and the server refuses a bundle
+ // other than the one the site was built against.
+ env: {
+ REMOCN_PREVIEWS_VERSION: previewsVersion(),
+ },
turbopack: {
root: __dirname,
- rules: {
- // Previews load their component in the browser only, so the server
- // build drops those imports from the preview index instead of compiling
- // ~900 components a second time. A `path` condition rather than a
- // path-glob key: Turbopack didn't apply the rule under a glob key.
- "*": {
- condition: {
- all: [{ not: "browser" }, { path: /^registry\/__index__\.tsx$/ }],
- },
- loaders: ["./lib/build/strip-server-preview-loads.cjs"],
- },
- },
},
async rewrites() {
// Agents get Markdown at the same URLs; see lib/agent-routing.ts.
@@ -68,7 +100,7 @@ const nextConfig: NextConfig = {
};
},
async headers() {
- return agentHeaders();
+ return [...agentHeaders(), ...previewsHeaders()];
},
async redirects() {
// Collapse the www host into the canonical apex so Google indexes a single
diff --git a/package.json b/package.json
index c26ec093..b8fb97b7 100644
--- a/package.json
+++ b/package.json
@@ -18,10 +18,11 @@
"studio:launch-anything": "remotion studio src/remotion/launch-anything-root.tsx",
"render:launch-anything": "bun scripts/render-launch-anything.mts",
"review:launch-anything": "bun scripts/review-launch-anything.mts",
- "dev": "bun scripts/low-priority.mts next dev",
- "dev:clean": "rm -rf .next && bun scripts/low-priority.mts next dev",
+ "dev": "bun scripts/dev.mts",
+ "dev:clean": "rm -rf .next && bun scripts/dev.mts",
"clean": "rm -rf .next",
- "build": "NODE_OPTIONS=--max-old-space-size=8192 bun scripts/low-priority.mts next build",
+ "build": "bun run previews:build && NODE_OPTIONS=--max-old-space-size=8192 bun scripts/low-priority.mts next build",
+ "previews:build": "bun scripts/previews/build.mts --production --prune",
"start": "next start",
"test": "bun test",
"typecheck": "tsc --noEmit",
diff --git a/proxy.ts b/proxy.ts
index 6fe16d93..538e9355 100644
--- a/proxy.ts
+++ b/proxy.ts
@@ -69,7 +69,8 @@ function tagVariant(request: NextRequest, variant: string) {
export const config = {
matcher: [
- // Everything but build assets, the JSON API, MCP, registry and images.
- "/((?!_next/|api/|mcp|r/|og/|embed/|favicon\\.ico).*)",
+ // Everything but build assets, the preview bundle, the JSON API, MCP,
+ // registry and images.
+ "/((?!_next/|_previews/|api/|mcp|r/|og/|embed/|favicon\\.ico).*)",
],
};
diff --git a/registry/__names__.ts b/registry/__names__.ts
new file mode 100644
index 00000000..029cfc41
--- /dev/null
+++ b/registry/__names__.ts
@@ -0,0 +1,925 @@
+// GENERATED FILE — do not edit by hand.
+// Written by scripts/previews/build.mts (`bun dev`, `bun run build`,
+// `bun run previews:build`) from the keys of registry/__index__.tsx.
+
+export const previewNames = [
+ "release-teaser",
+ "brand-guidelines",
+ "workflow-console",
+ "launch-anything",
+ "fomo-limit-orders",
+ "shader-spiral-pass",
+ "shader-light-tunnel",
+ "inline-word-roll",
+ "shader-text-reveal",
+ "shader-seam",
+ "search-reveal",
+ "type-fossil",
+ "soft-blur-in",
+ "word-stream",
+ "word-push",
+ "sheen-slide-in",
+ "squeeze-in",
+ "fog-rise",
+ "caret-swap",
+ "zoom-words",
+ "centered-word-build",
+ "inline-pill-takeover",
+ "typed-split-wipe",
+ "shadow-sweep-text",
+ "outline-fill-track-text",
+ "gradient-scale-cut-text",
+ "rush-type",
+ "per-character-rise",
+ "bottom-up-letters",
+ "top-down-letters",
+ "spring-scale-in",
+ "micro-scale-fade",
+ "scale-down-fade",
+ "blur-out-up",
+ "focus-blur-resolve",
+ "line-by-line-slide",
+ "per-word-crossfade",
+ "fade-through",
+ "shared-axis-y",
+ "shared-axis-z",
+ "short-slide-right",
+ "kinetic-center-build",
+ "short-slide-down",
+ "typewriter",
+ "hand-count",
+ "handwrite",
+ "inline-highlight",
+ "strikethrough-replace",
+ "staggered-fade-up",
+ "mask-reveal-up",
+ "tracking-in",
+ "shimmer-sweep",
+ "marker-highlight",
+ "ink-underline",
+ "slot-machine-roll",
+ "matrix-decode",
+ "gooey-morph",
+ "stretch-in",
+ "selection-snap",
+ "echo-stack",
+ "type-wall",
+ "ring-text",
+ "period-drop",
+ "outline-trace",
+ "glyph-anatomy",
+ "stripe-type",
+ "path-ride",
+ "type-repeater",
+ "chromatic-wave",
+ "extrude-pop",
+ "perspective-squeeze",
+ "kinetic-morph-text",
+ "kinetic-warp",
+ "rgb-glitch-text",
+ "infinite-marquee",
+ "perspective-marquee",
+ "glass-code-block",
+ "glass-code-walk",
+ "code-morph",
+ "shader-mesh-gradient",
+ "shader-mesh-gradient-dusk",
+ "shader-mesh-gradient-lagoon",
+ "shader-mesh-gradient-peach",
+ "shader-mesh-gradient-aurora",
+ "shader-mesh-gradient-lavender",
+ "shader-mesh-gradient-ember",
+ "shader-mesh-gradient-mint",
+ "shader-mesh-gradient-synthwave",
+ "shader-mesh-gradient-ink",
+ "shader-grain-gradient",
+ "shader-grain-gradient-sunrise",
+ "shader-grain-gradient-nebula",
+ "shader-grain-gradient-orb",
+ "shader-grain-gradient-horizon",
+ "shader-grain-gradient-blush",
+ "shader-grain-gradient-tide",
+ "shader-grain-gradient-arcade",
+ "shader-grain-gradient-dune",
+ "shader-grain-gradient-ultraviolet",
+ "shader-warp",
+ "shader-warp-silk",
+ "shader-warp-sunset",
+ "shader-warp-ocean",
+ "shader-warp-marble",
+ "shader-warp-acid",
+ "shader-warp-cream",
+ "shader-warp-deep-sea",
+ "shader-warp-rose-gold",
+ "shader-warp-storm",
+ "shader-swirl",
+ "shader-swirl-candy",
+ "shader-swirl-sunburst",
+ "shader-swirl-hypno",
+ "shader-swirl-neon",
+ "shader-swirl-tide",
+ "shader-swirl-citrus",
+ "shader-swirl-ember",
+ "shader-swirl-lilac",
+ "shader-swirl-retro",
+ "shader-water",
+ "shader-spiral",
+ "shader-liquid-metal",
+ "shader-color-panels",
+ "shader-neuro-noise",
+ "shader-perlin-noise",
+ "shader-simplex-noise",
+ "shader-voronoi",
+ "shader-dot-orbit",
+ "shader-dithering",
+ "shader-god-rays",
+ "shader-smoke-ring",
+ "shader-metaballs",
+ "shader-pulsing-border",
+ "simulated-cursor",
+ "keystroke",
+ "swirl-dissolve",
+ "dither-dissolve",
+ "perlin-dissolve",
+ "smoke-dissolve",
+ "grain-dissolve",
+ "icon-activity",
+ "icon-alert-triangle",
+ "icon-arrow-down",
+ "icon-arrow-left",
+ "icon-arrow-right",
+ "icon-arrow-up",
+ "icon-at-sign",
+ "icon-award",
+ "icon-bar-chart-3",
+ "icon-bell",
+ "icon-bookmark",
+ "icon-calendar",
+ "icon-camera",
+ "icon-check",
+ "icon-chevron-down",
+ "icon-chevron-left",
+ "icon-chevron-right",
+ "icon-chevron-up",
+ "icon-clock",
+ "icon-cloud",
+ "icon-code",
+ "icon-copy",
+ "icon-credit-card",
+ "icon-crown",
+ "icon-database",
+ "icon-dollar-sign",
+ "icon-download",
+ "icon-external-link",
+ "icon-eye-off",
+ "icon-eye",
+ "icon-file-text",
+ "icon-filter",
+ "icon-flame",
+ "icon-folder",
+ "icon-gem",
+ "icon-gift",
+ "icon-globe",
+ "icon-heart",
+ "icon-help-circle",
+ "icon-home",
+ "icon-image",
+ "icon-inbox",
+ "icon-info",
+ "icon-key",
+ "icon-layout-grid",
+ "icon-link",
+ "icon-loader",
+ "icon-lock",
+ "icon-log-out",
+ "icon-mail",
+ "icon-maximize",
+ "icon-menu",
+ "icon-message-circle",
+ "icon-mic",
+ "icon-monitor",
+ "icon-moon",
+ "icon-more-horizontal",
+ "icon-package",
+ "icon-party-popper",
+ "icon-pause",
+ "icon-pencil",
+ "icon-phone",
+ "icon-play",
+ "icon-plus",
+ "icon-plus-circle",
+ "icon-refresh-cw",
+ "icon-rocket",
+ "icon-save",
+ "icon-search",
+ "icon-send",
+ "icon-settings",
+ "icon-share-2",
+ "icon-shield",
+ "icon-shopping-cart",
+ "icon-skip-forward",
+ "icon-smartphone",
+ "icon-sparkles",
+ "icon-star",
+ "icon-sun",
+ "icon-tag",
+ "icon-target",
+ "icon-terminal",
+ "icon-thumbs-up",
+ "icon-timer",
+ "icon-trash",
+ "icon-trending-down",
+ "icon-trending-up",
+ "icon-trophy",
+ "icon-upload",
+ "icon-user-plus",
+ "icon-user",
+ "icon-users",
+ "icon-video",
+ "icon-volume-2",
+ "icon-volume-x",
+ "icon-wallet",
+ "icon-check-circle",
+ "icon-x",
+ "icon-x-circle",
+ "icon-zap",
+ "wave-wipe",
+ "ripple-zoom",
+ "whip-pan",
+ "push-through",
+ "focus-pull",
+ "zoom-blur",
+ "lens-zoom",
+ "glitch-cut",
+ "ember-burn",
+ "particle-dissolve",
+ "grid-wave",
+ "displacement",
+ "vhs-filter",
+ "crt-screen",
+ "sustained-glitch",
+ "pixelate-region",
+ "ascii-render",
+ "halftone-print",
+ "underwater-ripple",
+ "camera-lens",
+ "security-cam",
+ "hologram",
+ "tv-power-off",
+ "slide-swap",
+ "spring-settle",
+ "warp-dissolve",
+ "chat-to-preview-layout",
+ "animated-line-chart",
+ "animated-bar-chart",
+ "terminal-simulator",
+ "terminal-cursor-zoom",
+ "ecosystem-constellation",
+ "live-code-compilation",
+ "infinite-bento-pan",
+ "github-sponsors",
+ "github-stars",
+ "logo-enter",
+ "number-wheel",
+ "rolling-number",
+ "rolodex-flip",
+ "value-swap",
+ "x-follow-card",
+ "x-followers-overview",
+ "cursor-gravity",
+ "radial-burst",
+ "bauhaus-build",
+ "mondrian-split",
+ "truchet-flip",
+ "trim-burst",
+ "speed-lines",
+ "squiggle",
+ "confetti",
+ "paper-wobble",
+ "paper-sticker",
+ "polaroid",
+ "check-list",
+ "crumple-toss",
+ "scribble-circle",
+ "page-turn",
+ "ink-arrow",
+ "backdrop",
+ "drift",
+ "stage",
+ "claude-chat",
+ "chat-gpt",
+ "v0",
+ "claude-code",
+ "opencode",
+ "agent-run",
+ "button",
+ "accordion",
+ "alert-dialog",
+ "dialog",
+ "sheet",
+ "drawer",
+ "checkbox",
+ "input",
+ "blur-in",
+ "radio",
+ "switch",
+ "select",
+ "select-item",
+ "select-menu",
+ "dropdown-menu",
+ "dropdown-menu-item",
+ "tabs",
+ "cursor",
+ "toast",
+ "message-bubble",
+ "typing-indicator",
+ "command-menu-item",
+ "command-menu",
+ "tooltip",
+ "progress",
+ "skeleton-block",
+ "skeleton",
+ "slider",
+ "combobox",
+ "popover",
+ "context-menu",
+ "toggle-group",
+ "stepper",
+ "resizable",
+ "spinner",
+ "caret",
+ "ascii-dissolve",
+ "caret-wipe",
+ "icon-scatter",
+ "shader-caustics",
+ "shader-gem-smoke",
+ "shader-strata",
+ "shader-weave",
+ "reel",
+ "caption-karaoke",
+ "caption-highlight-box",
+ "caption-active-pop",
+ "caption-word-pop",
+ "caption-bounce-in",
+ "caption-blur-in",
+ "caption-rise",
+ "caption-typewriter",
+ "caption-slot",
+ "caption-subtitle",
+ "caption-dim-progress",
+ "caption-underline",
+ "caption-scramble",
+ "caption-weight",
+ "caption-emoji",
+ "caption-speaker",
+ "caption-stack",
+ "caption-outline",
+ "caption-marker",
+ "caption-stamp",
+ "caption-handwrite",
+ "caption-redact",
+ "caption-prosody",
+ "caption-timeline",
+ "caption-teleprompter",
+ "caption-knockout",
+ "caption-slice",
+ "caption-cube",
+ "caption-split-flap",
+ "caption-label-maker",
+ "caption-drop",
+ "iris-wipe",
+ "venetian-blinds",
+ "paper-tear",
+ "pixel-sort",
+ "light-leak",
+ "hyperspace",
+ "orbit-lock",
+ "puzzle-snap",
+ "spotlight",
+ "neon-sign",
+ "inflate",
+ "liquid-fill",
+ "accordion-unfold",
+ "anamorphic-flare",
+ "pendulum-wave",
+ "flow-field",
+ "isometric-build",
+ "life-grid",
+ "string-art",
+ "topo-lines",
+ "phyllotaxis",
+ "parallax-depth",
+ "dolly-zoom",
+ "turntable",
+ "tiny-planet",
+ "exploded-view",
+ "gravity-pile",
+ "cloth-reveal",
+ "impact-shake",
+ "riso-print",
+ "line-boil",
+ "blueprint",
+ "duotone-beat",
+ "comic-panels",
+ "long-shadow",
+ "synthwave",
+ "brick-mosaic",
+ "x-ray-scan",
+ "toolbar-unfurl",
+ "glyph-relay",
+ "press-warp-dive",
+ "giant-mark-backdrop",
+ "macro-tab-name",
+ "cta-collapse-mark",
+ "node-trail",
+ "graph-relayout",
+ "letter-gate",
+ "device-grows-around",
+ "send-fountain",
+ "glow-born-card",
+ "multi-file-drop",
+ "rim-draw-card",
+ "heat-drain-reveal",
+ "tile-snake-loader",
+ "photo-caret",
+ "flank-roll-swap",
+ "light-burn-to-line",
+ "hot-slab-morph",
+ "noise-forge-sting",
+ "glyph-block-decode",
+ "word-burst-cards",
+ "cooling-type",
+ "focus-front-swap",
+ "macro-letter-pan",
+ "focus-pan-text",
+ "card-swipe-cover",
+ "caret-collapse",
+ "bloom-ring",
+ "beam-sweep",
+ "disc-pop",
+ "strobe-montage",
+ "band-open",
+ "headline-to-line",
+ "word-gap-media",
+ "caret-dolly",
+ "card-push-line",
+ "phrase-list-bridge",
+ "word-pullback",
+ "figure-reels",
+ "figure-to-label",
+ "drop-upload",
+ "macro-click",
+ "calendar-pick",
+ "button-to-card",
+ "prompt-swell",
+ "grid-to-app",
+ "leaderboard-climb",
+ "phone-trio",
+ "photo-halo",
+ "cover-ring",
+ "card-fan",
+ "tilt-settle-list",
+ "shards-to-grid",
+ "stat-rail",
+ "panel-split",
+ "flood-sting",
+ "riddle-clues",
+ "coy-denial",
+ "peek-shut",
+ "no-buts",
+ "in-proportion",
+ "exactly",
+ "which-means",
+ "chore-fold",
+ "name-gloss",
+ "price-page",
+ "free-as-in",
+ "the-tab",
+ "not-yet",
+ "moves-up",
+ "half-built",
+ "what-sticks",
+ "tldr-on-top",
+ "factor-out",
+ "post-script",
+ "rsvp",
+ "your-name-here",
+ "verbed",
+ "pitch-blanks",
+ "we-call-it",
+ "crunch",
+ "overnight",
+ "story-dip",
+ "out-of-context",
+ "answer-first",
+ "double-take",
+ "turnabout",
+ "run-on",
+ "loop-break",
+ "crew-of-one",
+ "they-are-you",
+ "and-you",
+ "edit-ripple",
+ "script-cut",
+ "known-terms",
+ "changed-mind",
+ "said-who",
+ "overheard",
+ "baton-word",
+ "cue-word",
+ "cut-off",
+ "beta-thanks",
+ "embargo-lift",
+ "plain-license",
+ "keep-words",
+ "whole-page",
+ "fine-print-up",
+ "looks-like-this",
+ "shot-answers",
+ "up-close",
+ "yes-run",
+ "week-shipped",
+ "a-to-z",
+ "carry-count",
+ "chunk-stack",
+ "spell-out",
+ "feather-settle",
+ "churn-count",
+ "bug-dock",
+ "two-hit",
+ "absorb-stack",
+ "layover",
+ "nonstop",
+ "on-approach",
+ "negation-drop",
+ "weight-cut",
+ "hook-uncurl",
+ "diminuendo",
+ "core-sum",
+ "cool-down",
+ "idea-set",
+ "row-count",
+ "spine-turn",
+ "packed-count",
+ "less-more",
+ "times-turn",
+ "stripe-count",
+ "window-trail",
+ "fuchidori-count",
+ "ruby-press",
+ "tategaki-turn",
+ "pitch-over",
+ "hot-stage",
+ "first-light",
+ "flash-count",
+ "pull-in",
+ "gear-shift",
+ "slide-doors",
+ "lean-count",
+ "shed-weight",
+ "serif-rise",
+ "module-count",
+ "roman-edition",
+ "single-stroke",
+ "slim-count",
+ "squeeze-out",
+ "edge-fit",
+ "smash-count",
+ "sequel-numeral",
+ "menu-pick",
+ "press-stat",
+ "unmask-line",
+ "point-hop",
+ "mono-settle",
+ "uncomment-line",
+ "enhance-count",
+ "mono-voice",
+ "beat-count",
+ "magnitude-push",
+ "prompt-restyle",
+ "block-swap",
+ "rewrite-bars",
+ "long-vowel",
+ "compact-stat",
+ "plus-open",
+ "res-climb",
+ "filler-cut",
+ "stem-stretch",
+ "pulse-line",
+ "lumen-count",
+ "width-lock",
+ "tall-count",
+ "pinned-word",
+ "zero-stretch",
+ "wake-wipe",
+ "comet-headline",
+ "indent-steps",
+ "point-expand",
+ "layout-swap",
+ "acronym-expand",
+ "diff-swap",
+ "heat-trace",
+ "thin-slab",
+ "stat-inline",
+ "launch-days",
+ "cut-stat",
+ "slash-wipe",
+ "light-signature",
+ "studio-reflection",
+ "flick-swap",
+ "introducing",
+ "feature-headline",
+ "before-after",
+ "feature-trio",
+ "magnet-letters",
+ "ruler-align",
+ "scissors-cut",
+ "tittle-drop",
+ "cursor-frame",
+ "caret-letter",
+ "point-intro",
+ "grid-cell",
+ "spotlight-text",
+ "border-beam",
+ "walkout-name",
+ "ko-count",
+ "play-of-the-game",
+ "t-minus",
+ "max-q",
+ "landing-confirmed",
+ "drop-timer",
+ "sold-out",
+ "got-em",
+ "ipo-open",
+ "candle-rally",
+ "chevron-run",
+ "high-score",
+ "boss-bar",
+ "achievement-pop",
+ "kill-feed",
+ "mvp-card",
+ "bracket-win",
+ "timing-tower",
+ "shot-clock",
+ "speed-trap",
+ "crash-zoom",
+ "pov-setup",
+ "speedrun-timer",
+ "round-slam",
+ "level-up",
+ "combo-counter",
+ "hook-punch",
+ "milestone-roll",
+ "duet-split",
+ "intelligence-glow",
+ "ghost-complete",
+ "query-cascade",
+ "liquid-word",
+ "oval-type",
+ "live-ticker",
+ "ticker-tape",
+ "price-slate",
+ "score-bug",
+ "versus-split",
+ "replay-wipe",
+ "bass-drop",
+ "escalate-cards",
+ "flip-sting",
+ "lights-out",
+ "italic-speed",
+ "split-flash",
+ "dynamic-letter",
+ "snap-click",
+ "scrub-reveal",
+ "aspect-slit",
+ "parallax-lockup",
+ "deadpan-box",
+ "stripe-mask",
+ "full-bleed-type",
+ "rep-stack",
+ "title-converge",
+ "macro-pan",
+ "split-match",
+ "bounce-logo",
+ "glyph-matrix",
+ "ndot-resolve",
+ "shape-morph-o",
+ "axis-flex",
+ "blink-cut",
+ "word-acts",
+ "depth-headline",
+ "speed-ramp-word",
+ "pass-swap",
+ "photo-fill-type",
+ "bracket-index",
+ "select-replace",
+ "wrapped-squash",
+ "rubberband-word",
+ "story-text",
+ "anagram-shuffle",
+ "word-ladder",
+ "hidden-word",
+ "column-reflow",
+ "word-insert",
+ "typo-fix",
+ "font-cycle",
+ "case-flip",
+ "path-text",
+ "ellipsis-resolve",
+ "letter-relay",
+ "stack-letters",
+ "weight-wave",
+ "kerning-snap",
+ "baseline-drop",
+ "scan-reveal",
+ "beam-split",
+ "strobe-words",
+ "torn-edge",
+ "squircle-wave",
+ "ring-burst",
+ "band-shift",
+ "tile-wave",
+ "glass-capsule",
+ "dot-type",
+ "flock-form",
+ "ring-align",
+ "word-stack",
+ "split-word",
+ "counter-reveal",
+ "slit-scan",
+ "moire-reveal",
+ "thread-weave",
+ "fourier-sum",
+ "cell-divide",
+ "hex-fill",
+ "log-rescale",
+ "off-the-charts",
+ "shape-pack",
+ "pattern-tile",
+ "line-cascade",
+ "hatch-shade",
+ "path-search",
+ "transit-lines",
+ "slope-chart",
+ "ridgeline",
+ "beeswarm",
+ "chart-morph",
+ "dumbbell-shift",
+ "stacked-shift",
+ "tally-marks",
+ "abacus-count",
+ "fraction-split",
+ "balance-beam",
+ "domino-run",
+ "spring-bars",
+ "dot-sort",
+ "flow-arrow",
+ "dot-map",
+ "sankey-flow",
+ "branch-tree",
+ "chord-ring",
+ "waterfall-chart",
+ "galton-stack",
+ "bubble-pack",
+ "treemap-split",
+ "venn-merge",
+ "fluted-glass",
+ "frosted-clear",
+ "embossed-mark",
+ "halftone-cut",
+ "column-slide",
+ "ring-cut",
+ "quadtree-mark",
+ "raster-paint",
+ "pixel-bars",
+ "bracket-focus",
+ "crosshair-lock",
+ "measure-dim",
+ "three-steps",
+ "number-split",
+ "radial-bars",
+ "radar-compare",
+ "concentric-scale",
+ "changelog-scroll",
+ "waveform-title",
+ "line-relief",
+ "sparkline-thread",
+ "area-compare",
+ "rank-climb",
+ "time-breakdown",
+ "index-list",
+ "grid-snap-poster",
+ "spec-sheet",
+ "toggle-on",
+ "rotary-dial",
+ "uptime-strip",
+ "quadrant-plot",
+ "streamgraph",
+ "clock-sweep",
+ "ruler-scrub",
+ "timer-duel",
+ "contribution-heatmap",
+ "distribution-shift",
+ "share-donut",
+ "unit-grid",
+ "led-ticker",
+ "ripple-mark",
+ "poster-crop",
+ "collab-lockup",
+ "tagline-justify",
+ "shape-cut",
+ "hairline-open",
+ "diagonal-split",
+ "slit-reveal",
+ "wireframe-to-final",
+ "dot-field-morph",
+ "feature-chips-flow",
+ "version-hero",
+ "benchmark-race",
+ "dot-globe",
+ "waitlist-swarm",
+ "signal-resolve",
+ "keycap-press",
+ "launch-date",
+ "light-trail-write",
+ "color-bars",
+ "grid-montage",
+ "stat-sequence",
+ "quote-hero",
+ "activity-rings",
+ "glass-lens",
+ "pill-morph",
+ "layered-cutout",
+ "neural-pulse",
+ "bokeh-title",
+ "block-city",
+ "flash-sweep",
+ "logo-construct",
+ "ink-bloom",
+ "gravity-grid",
+ "number-mosaic",
+ "growth-line",
+ "countdown",
+ "paper-plane",
+ "chaos-to-order",
+ "notification-avalanche",
+ "phone-scroll",
+ "screenshot-tour",
+ "ui-callout",
+ "theme-flip",
+ "testimonial-stack",
+ "upvote-burst",
+ "bento-build",
+ "pricing-reveal",
+ "url-bar-cta",
+ "table-filter",
+ "flow-builder",
+ "multiplayer-cursors",
+ "channel-reactions",
+ "deploy-pipeline",
+ "live-dashboard",
+ "file-dropzone",
+ "calendar-booking",
+ "ai-image-grid",
+ "device-morph",
+ "pr-merge",
+ "status-page",
+ "video-call",
+ "invite-team",
+ "timeline-editor",
+ "ride-tracking",
+ "mobile-paywall",
+ "sheet-formula",
+ "whats-new-modal",
+ "money-send",
+ "stock-scrub",
+ "card-create",
+ "reels-feed",
+ "swipe-deck",
+ "streak-reward",
+ "rating-laurel",
+ "ai-answer-sources",
+ "now-playing",
+ "year-in-review",
+ "video-watch-page",
+ "voice-agent",
+ "prompt-to-app",
+ "browser-extension",
+ "app-store-listing",
+ "live-activity",
+ "home-widget",
+ "cart-add",
+ "coupon-apply",
+ "invoice-paid",
+ "roadmap-timeline",
+ "analytics-funnel",
+ "world-signups",
+ "social-scheduler",
+ "feature-flag-rollout",
+ "redline-measure",
+ "audit-boxes",
+ "scan-fix",
+ "token-tags",
+ "layout-guides",
+ "design-audit",
+] as const;
diff --git a/scripts/dev.mts b/scripts/dev.mts
new file mode 100644
index 00000000..38a5cd4a
--- /dev/null
+++ b/scripts/dev.mts
@@ -0,0 +1,205 @@
+// `bun dev`: the Next.js dev server plus the preview bundle it loads.
+//
+// The previews are built outside Turbopack (scripts/previews/build.mts). This
+// launcher builds them once, starts `next dev`, and from then on rebuilds
+// them when one of their source files is saved. Open pages hear about a new
+// build over a WebSocket and swap the changed previews in place
+// (lib/previews/hot.ts), so an edit shows up without a page reload.
+//
+// Each rebuild is a separate short process: the bundler takes ~0.3 s and
+// ~2.4 GB while it runs, and kept in this process it never gave that back.
+//
+// bun scripts/dev.mts [...next dev args]
+import { spawn } from "node:child_process";
+import {
+ existsSync,
+ type FSWatcher,
+ readFileSync,
+ watch,
+ writeFileSync,
+} from "node:fs";
+import { join, resolve } from "node:path";
+
+const ROOT = resolve(import.meta.dir, "..");
+const MANIFEST = join(ROOT, "public/_previews/dev/manifest.json");
+const NICE = process.platform === "win32" ? [] : ["nice", "-n", "10"];
+const CHANNEL = "previews";
+/** Where the previews' sources live. A build adds any folder it finds more in. */
+const FOLDERS = ["registry", "components", "lib", "hooks", "config", "app"];
+const SOURCE = /\.(tsx?|jsx?|mjs|css|json)$/;
+
+type BuildResult = { version: string; elapsed: number; inputs: string[] };
+
+let version = "";
+
+const server = Bun.serve({
+ port: 0,
+ fetch(request, server) {
+ if (server.upgrade(request)) return;
+ return new Response("remocn previews live channel", { status: 426 });
+ },
+ websocket: {
+ open(socket) {
+ socket.subscribe(CHANNEL);
+ socket.send(JSON.stringify({ type: "hello", version }));
+ },
+ message() {},
+ },
+});
+
+function build(prune: boolean): Promise<BuildResult | null> {
+ return new Promise((done) => {
+ const [bin, ...args] = [
+ ...NICE,
+ "bun",
+ "scripts/previews/build.mts",
+ "--json",
+ "--port",
+ String(server.port),
+ ...(prune ? ["--prune"] : []),
+ ];
+ const child = spawn(bin, args, {
+ cwd: ROOT,
+ stdio: ["ignore", "pipe", "inherit"],
+ });
+ let stdout = "";
+ child.stdout.on("data", (chunk) => {
+ stdout += chunk;
+ });
+ child.on("error", (error) => {
+ console.error("previews: could not start the build:", error.message);
+ done(null);
+ });
+ child.on("close", (code) => {
+ if (code !== 0) return done(null);
+ try {
+ done(JSON.parse(stdout.trim().split("\n").at(-1) ?? ""));
+ } catch {
+ done(null);
+ }
+ });
+ });
+}
+
+// Rebuild when a source of the bundle is saved. A save of another file in
+// the same folders is the site's business, not the previews'.
+let inputs = new Set<string>();
+// After a failed build the list of sources is out of date: the file that
+// fixes it may be one the bundle has never seen. Then any source counts.
+let failed = false;
+const watchers = new Map<string, FSWatcher>();
+
+function watchFolder(folder: string) {
+ if (watchers.has(folder) || !existsSync(join(ROOT, folder))) return;
+ const watcher = watch(
+ join(ROOT, folder),
+ { recursive: true },
+ (_event, file) => {
+ if (!file) return;
+ const path = `${folder}/${file.toString().replaceAll("\\", "/")}`;
+ if (inputs.has(path) || (failed && SOURCE.test(path))) schedule();
+ },
+ );
+ watcher.on("error", (error) => {
+ console.error(`previews: stopped watching ${folder}/:`, error.message);
+ watchers.delete(folder);
+ });
+ watchers.set(folder, watcher);
+}
+
+function took(result: BuildResult) {
+ failed = false;
+ inputs = new Set(result.inputs);
+ for (const file of result.inputs) watchFolder(file.split("/")[0]);
+}
+
+let timer: ReturnType<typeof setTimeout> | undefined;
+let building = false;
+let again = false;
+
+function schedule() {
+ clearTimeout(timer);
+ // An editor's save is often several events in a row.
+ timer = setTimeout(rebuild, 25);
+}
+
+async function rebuild() {
+ if (building) {
+ again = true;
+ return;
+ }
+ building = true;
+ const result = await build(false);
+ building = false;
+ if (result) {
+ took(result);
+ if (result.version !== version) {
+ version = result.version;
+ server.publish(CHANNEL, JSON.stringify({ type: "built", version }));
+ console.log(` ✓ Previews rebuilt in ${result.elapsed}ms`);
+ }
+ } else {
+ // The build printed what is wrong; pages keep the last good bundle.
+ failed = true;
+ server.publish(CHANNEL, JSON.stringify({ type: "failed" }));
+ }
+ if (again) {
+ again = false;
+ schedule();
+ }
+}
+
+for (const folder of FOLDERS) watchFolder(folder);
+const first = await build(true);
+if (first) {
+ took(first);
+ version = first.version;
+ console.log(` ✓ Previews built in ${first.elapsed}ms`);
+} else {
+ // Start the site anyway: the build runs again on the save that fixes it.
+ failed = true;
+ // No build, no new manifest. Put the port into the one left from the last
+ // run, so the pages that open now hear about the build that works.
+ try {
+ const manifest = JSON.parse(readFileSync(MANIFEST, "utf8"));
+ writeFileSync(
+ MANIFEST,
+ `${JSON.stringify({ ...manifest, port: server.port })}\n`,
+ );
+ } catch {}
+ console.error(
+ " ⨯ Previews did not build. The site runs with the previews it had; fix the error above and save.",
+ );
+}
+
+const next = spawn(
+ "bun",
+ ["scripts/low-priority.mts", "next", "dev", ...process.argv.slice(2)],
+ { cwd: ROOT, stdio: "inherit" },
+);
+
+// Ctrl+C already reaches `next dev` through the terminal's process group;
+// forward the rest so `kill` on this launcher stops the server too.
+for (const signal of ["SIGTERM", "SIGHUP"] as const) {
+ process.on(signal, () => next.kill(signal));
+}
+process.on("SIGINT", () => {});
+
+// The manifest names this launcher's port. Once it is gone, a page loaded by
+// a bare `next dev` should not keep dialling it.
+process.on("exit", () => {
+ try {
+ const { port, ...rest } = JSON.parse(readFileSync(MANIFEST, "utf8"));
+ if (port === server.port) {
+ writeFileSync(MANIFEST, `${JSON.stringify(rest)}\n`);
+ }
+ } catch {}
+});
+
+next.on("error", (error) => {
+ console.error("could not start next dev:", error.message);
+ process.exit(1);
+});
+next.on("exit", (code, signal) => {
+ process.exit(code ?? (signal ? 1 : 0));
+});
diff --git a/scripts/previews/build.mts b/scripts/previews/build.mts
new file mode 100644
index 00000000..9d71686f
--- /dev/null
+++ b/scripts/previews/build.mts
@@ -0,0 +1,373 @@
+// Builds the preview registry into public/_previews, outside Turbopack.
+//
+// registry/__index__.tsx lists ~900 previews, each a lazy import of a
+// component and of its config. Turbopack compiles lazy imports up front, so
+// with the index in the site's module graph the first request to any page
+// with a preview compiled every preview. Bun bundles the same index in about
+// 0.3 s, and the site loads the result by URL (lib/previews/index.ts): the
+// browser from /_previews/, the server from the same files on disk.
+//
+// Development and production builds live in separate folders
+// (public/_previews/dev and public/_previews/prod), so a running `bun dev`
+// and a `bun run build` never overwrite each other's files.
+//
+// bun scripts/previews/build.mts development
+// bun scripts/previews/build.mts --production minified
+// --prune delete files left over from earlier builds
+// --port <n> put the dev launcher's live channel port in the manifest
+// --json print { version, elapsed, inputs } as one JSON line on stdout
+//
+// `bun dev` and `bun run build` run this for you.
+import { createHash } from "node:crypto";
+import { existsSync, statSync } from "node:fs";
+import {
+ copyFile,
+ mkdir,
+ readdir,
+ readFile,
+ rename,
+ rm,
+ writeFile,
+} from "node:fs/promises";
+import { basename, dirname, extname, join, relative, resolve } from "node:path";
+import type { BunPlugin } from "bun";
+import {
+ SHARED_GLOBAL,
+ SHARED_MODULES,
+} from "../../lib/previews/shared-modules";
+
+const args = process.argv.slice(2);
+const PRODUCTION = args.includes("--production");
+const PRUNE = args.includes("--prune");
+const JSON_OUTPUT = args.includes("--json");
+const portArg = args.indexOf("--port");
+const PORT = portArg === -1 ? undefined : Number(args[portArg + 1]);
+
+const ROOT = resolve(import.meta.dir, "../..");
+const MODE = PRODUCTION ? "prod" : "dev";
+const OUT = join(ROOT, "public/_previews", MODE);
+const PUBLIC_PATH = `/_previews/${MODE}/`;
+const NAMES_FILE = join(ROOT, "registry/__names__.ts");
+
+process.chdir(ROOT);
+
+// A file appears under its name only once it is whole. The names are content
+// hashes and "it exists" means "it is up to date", so a build cut short must
+// not leave a half-written file behind under one.
+const TMP = `.tmp-${process.pid}`;
+
+const hash = (data: string | Uint8Array, length: number) =>
+ createHash("sha256").update(data).digest("hex").slice(0, length);
+
+const posix = (path: string) => path.replaceAll("\\", "/");
+
+const sharedSeen = new Set<string>();
+
+/** `react` and `remotion` come from the page, not from the bundle. */
+const sharedPlugin: BunPlugin = {
+ name: "remocn-shared",
+ setup(build) {
+ build.onResolve(
+ { filter: /^(react|react-dom|remotion)(\/.*)?$/ },
+ (args) => {
+ sharedSeen.add(args.path);
+ return { path: args.path, namespace: "remocn-shared" };
+ },
+ );
+ build.onLoad({ filter: /.*/, namespace: "remocn-shared" }, (args) => ({
+ contents: `module.exports = globalThis.${SHARED_GLOBAL}[${JSON.stringify(args.path)}];`,
+ loader: "js",
+ }));
+ },
+};
+
+/** Files of this build, relative to OUT. Everything else there is left over. */
+const current = new Set<string>();
+
+/**
+ * A CSS import (the templates' @fontsource files) becomes a module that adds
+ * a <style> to the page. The files its `url()`s point at are copied next to
+ * the bundle. On the server the module does nothing.
+ */
+const cssPlugin: BunPlugin = {
+ name: "remocn-css",
+ setup(build) {
+ build.onLoad({ filter: /\.css$/ }, async (args) => {
+ let css = await readFile(args.path, "utf8");
+ for (const [whole, , url] of css.matchAll(
+ /url\((['"]?)(\.[^'")]+)\1\)/g,
+ )) {
+ const file = resolve(dirname(args.path), url);
+ const ext = extname(file);
+ const asset = `assets/${basename(file, ext)}-${hash(await readFile(file), 8)}${ext}`;
+ const target = join(OUT, asset);
+ current.add(asset);
+ if (!existsSync(target)) {
+ await mkdir(dirname(target), { recursive: true });
+ await copyFile(file, `${target}${TMP}`);
+ await rename(`${target}${TMP}`, target);
+ }
+ css = css.replace(whole, `url(${PUBLIC_PATH}${asset})`);
+ }
+ const id = hash(css, 10);
+ return {
+ contents: `if (typeof document !== "undefined" && !document.querySelector('style[data-remocn-preview="${id}"]')) {
+ const style = document.createElement("style");
+ style.dataset.remocnPreview = "${id}";
+ style.textContent = ${JSON.stringify(css)};
+ document.head.appendChild(style);
+}`,
+ loader: "js",
+ };
+ });
+ },
+};
+
+const started = performance.now();
+
+const result = await Bun.build({
+ entrypoints: ["registry/__index__.tsx"],
+ // One bundle for both sides. Node loads the browser build as it is: the
+ // registry code has no server variant, and the shared modules come from
+ // whichever side imports the bundle.
+ target: "browser",
+ format: "esm",
+ splitting: true,
+ minify: PRODUCTION,
+ sourcemap: PRODUCTION ? "none" : "linked",
+ metafile: true,
+ naming: {
+ entry: "entries.js",
+ // Chunk names are content hashes: an unchanged chunk keeps its URL, so
+ // the browser keeps the module, and a rebuild rewrites only what changed.
+ chunk: PRODUCTION ? "chunks/[hash].js" : "chunks/[name]-[hash].js",
+ },
+ jsx: { runtime: "automatic", development: !PRODUCTION },
+ define: {
+ "process.env.NODE_ENV": JSON.stringify(
+ PRODUCTION ? "production" : "development",
+ ),
+ },
+ plugins: [sharedPlugin, cssPlugin],
+ throw: false,
+});
+
+// A failed build leaves the folder as it was: pages keep the last good bundle.
+if (!result.success) {
+ for (const log of result.logs) console.error(log);
+ console.error("previews: build failed");
+ process.exit(1);
+}
+
+const unknownShared = [...sharedSeen].filter(
+ (id) => !(SHARED_MODULES as readonly string[]).includes(id),
+);
+if (unknownShared.length > 0) {
+ console.error(
+ `previews: the registry imports ${unknownShared.join(", ")}, which the page does not share with the preview bundle. Add it to lib/previews/shared-modules.ts and lib/previews/shared.ts.`,
+ );
+ process.exit(1);
+}
+
+// The entry is the one output Bun doesn't name by content. It gets its hash
+// here, so that no file of the bundle ever changes under its URL.
+const outputOf = (path: string) =>
+ result.outputs.find((output) => posix(output.path) === `./${path}`);
+const entrySource = (await outputOf("entries.js")?.text()) ?? "";
+const version = hash(entrySource, 12);
+const entry = `entries-${version}.js`;
+
+// Renaming the entry is safe only while no chunk imports it back.
+const importsEntry = Object.entries(result.metafile?.outputs ?? {}).find(
+ ([, output]) =>
+ output.imports.some((imported) => /(^|\/)entries\.js$/.test(imported.path)),
+);
+if (importsEntry) {
+ console.error(
+ `previews: ${importsEntry[0]} imports the entry file, which this script renames. Give shared code a module of its own, or stop renaming the entry.`,
+ );
+ process.exit(1);
+}
+
+let written = 0;
+async function write(path: string, text: string) {
+ const target = join(OUT, path);
+ await mkdir(dirname(target), { recursive: true });
+ await writeFile(`${target}${TMP}`, text);
+ await rename(`${target}${TMP}`, target);
+ written++;
+}
+
+await Promise.all(
+ result.outputs.map(async (output) => {
+ const path = posix(output.path).replace(/^\.\//, "");
+ if (path === "entries.js") {
+ current.add(entry);
+ if (existsSync(join(OUT, entry))) return;
+ return write(
+ entry,
+ entrySource.replace(
+ "sourceMappingURL=entries.js.map",
+ `sourceMappingURL=${entry}.map`,
+ ),
+ );
+ }
+ if (path === "entries.js.map") {
+ current.add(`${entry}.map`);
+ if (existsSync(join(OUT, `${entry}.map`))) return;
+ return write(`${entry}.map`, await output.text());
+ }
+ current.add(path);
+ const target = join(OUT, path);
+ if (existsSync(target)) {
+ // A chunk's name is its content hash: a file that exists is up to date.
+ if (!path.endsWith(".map")) return;
+ // Its source map is not part of that hash: an edit to a comment moves
+ // the mappings and keeps the chunk.
+ if (statSync(target).size === output.size) return;
+ }
+ return write(path, await output.text());
+ }),
+);
+
+const { default: registry } = await import("../../registry/__index__");
+
+// The chunks behind each preview: its config, its component and everything
+// those import. The server names them in the page's HTML, so the browser
+// fetches them together and early instead of one import level at a time.
+const outputs = result.metafile?.outputs ?? {};
+const chunkOf = new Map(
+ Object.entries(outputs).flatMap(([path, output]) =>
+ output.entryPoint ? [[posix(output.entryPoint), path] as const] : [],
+ ),
+);
+const files: string[] = [];
+const fileIndex = new Map<string, number>();
+const previews: Record<string, number[]> = {};
+const unmapped = new Set<string>();
+for (const [name, loaders] of Object.entries(registry)) {
+ const needed = new Set<string>();
+ for (const loader of [loaders.loadConfig, loaders.load]) {
+ // Each loader is `() => import("<module>").then(…)`.
+ const specifier = /import\(\s*["']([^"']+)["']\s*\)/.exec(`${loader}`)?.[1];
+ const chunk =
+ specifier &&
+ chunkOf.get(
+ posix(
+ relative(ROOT, Bun.resolveSync(specifier, join(ROOT, "registry"))),
+ ),
+ );
+ if (!chunk) {
+ unmapped.add(name);
+ continue;
+ }
+ const queue = [chunk];
+ for (const path of queue) {
+ if (needed.has(path)) continue;
+ needed.add(path);
+ for (const imported of outputs[path]?.imports ?? []) {
+ if (imported.kind === "import-statement") queue.push(imported.path);
+ }
+ }
+ }
+ previews[name] = [...needed].map((path) => {
+ const file = posix(path).replace(/^\.\//, "");
+ let index = fileIndex.get(file);
+ if (index === undefined) {
+ index = files.push(file) - 1;
+ fileIndex.set(file, index);
+ }
+ return index;
+ });
+}
+if (unmapped.size > 0) {
+ console.error(
+ `previews: could not tell which module these entries of registry/__index__.tsx import, so their pages won't preload them: ${[...unmapped].join(", ")}`,
+ );
+}
+
+// The site reads the manifest first and everything else by the names in it,
+// so it goes last and in one step: a reader never sees a manifest whose
+// files are still being written.
+const previous = await readFile(join(OUT, "manifest.json"), "utf8")
+ .then((text): { entry?: string } => JSON.parse(text))
+ .catch(() => ({ entry: undefined }));
+await Promise.all([
+ // Node imports these files too, and the repo's package.json is not ESM.
+ writeFile(join(OUT, "package.json"), '{ "type": "module" }\n'),
+ writeFile(
+ join(OUT, "preload.json"),
+ `${JSON.stringify({ version, files, previews })}\n`,
+ ),
+]);
+await writeFile(
+ join(OUT, `manifest.json${TMP}`),
+ `${JSON.stringify({ version, entry, ...(PORT ? { port: PORT } : {}) })}\n`,
+);
+await rename(join(OUT, `manifest.json${TMP}`), join(OUT, "manifest.json"));
+
+// Left-overs. Always: entries older than the previous one, which a page that
+// is loading right now may still ask for. With --prune: every file this
+// build did not produce. The bundle is already published, so a failure here
+// is not a failed build.
+const keep = new Set([
+ ...current,
+ "manifest.json",
+ "preload.json",
+ "package.json",
+]);
+// Under --prune the previous entry's chunks go, so the entry goes with them.
+if (previous.entry && !PRUNE) {
+ keep.add(previous.entry).add(`${previous.entry}.map`);
+}
+let removed = 0;
+try {
+ const stale = (await readdir(OUT, { recursive: true }))
+ .map(posix)
+ .filter((path) => {
+ if (extname(path) === "" || keep.has(path)) return false;
+ // Another build's file in the making, unless it was abandoned.
+ if (/\.tmp-\d+$/.test(path)) {
+ return Date.now() - statSync(join(OUT, path)).mtimeMs > 60_000;
+ }
+ return PRUNE || path.startsWith("entries-");
+ });
+ await Promise.all(stale.map((path) => rm(join(OUT, path), { force: true })));
+ removed = stale.length;
+} catch (error) {
+ console.error("previews: could not remove left-over files:", error);
+}
+
+// The site needs the names without loading the bundle: to tell an unknown
+// preview from a known one while rendering on the server.
+const names = `// GENERATED FILE — do not edit by hand.
+// Written by scripts/previews/build.mts (\`bun dev\`, \`bun run build\`,
+// \`bun run previews:build\`) from the keys of registry/__index__.tsx.
+
+export const previewNames = [
+${Object.keys(registry)
+ .map((name) => ` ${JSON.stringify(name)},`)
+ .join("\n")}
+] as const;
+`;
+if (!existsSync(NAMES_FILE) || (await readFile(NAMES_FILE, "utf8")) !== names) {
+ await writeFile(NAMES_FILE, names);
+}
+
+const inputs = Object.keys(result.metafile?.inputs ?? {})
+ .map((path) => posix(relative(ROOT, resolve(ROOT, path))))
+ .filter(
+ (path) =>
+ !path.startsWith("..") &&
+ !path.includes("node_modules") &&
+ !path.includes(":"),
+ );
+
+const elapsed = Math.round(performance.now() - started);
+if (JSON_OUTPUT) {
+ console.log(JSON.stringify({ version, written, elapsed, inputs }));
+} else {
+ console.log(
+ `previews: ${Object.keys(registry).length} entries, ${written} files written, ${removed} removed, ${elapsed} ms (${PRODUCTION ? "production" : "development"}, version ${version})`,
+ );
+}