import { execFileSync } from "node:child_process"; import { globSync } from "tinyglobby"; import * as fs from "node:fs"; import * as path from "node:path"; import { fileURLToPath } from "node:url"; const dir = path.parse(fileURLToPath(import.meta.url)).dir; const workspaceRoot = path.resolve(dir, "../../.."); /** * Writes a generated file, creating parent directories as needed, and records * the absolute path in `written` so it can be formatted afterwards. */ export function writeGeneratedFile( target: string, content: string, written: string[], ) { const absolute = path.resolve(target); fs.mkdirSync(path.dirname(absolute), { recursive: true }); fs.writeFileSync(absolute, content); written.push(absolute); } /** * Atomically writes a file by writing to a unique temp file in the same * directory and renaming it into place (rename is atomic on POSIX). This * prevents readers from ever observing a truncated/empty file, which matters * for shared files (e.g. docs/package.json) that may be read and written by * concurrent `gen:docs` processes. Skips the write entirely when the on-disk * content already matches, avoiding an unnecessary truncation window. */ export function writeFileAtomic(absolute: string, content: string) { try { if (fs.readFileSync(absolute, "utf-8") === content) { return; } } catch { // File does not exist yet (or could not be read) — fall through to write. } fs.mkdirSync(path.dirname(absolute), { recursive: true }); const tmp = `${absolute}.${process.pid}.${Date.now()}.${Math.random() .toString(36) .slice(2)}.tmp`; fs.writeFileSync(tmp, content); fs.renameSync(tmp, absolute); } /** * Formats the given files in-place using `vp fmt`. Files that are excluded by * oxfmt ignore rules (e.g. *.mdx) are tolerated. Runs in chunks to avoid argv * length limits. */ export function formatFiles(files: string[]) { const unique = [...new Set(files.map((file) => path.resolve(file)))]; if (unique.length === 0) { return; } const chunkSize = 200; for (let i = 0; i < unique.length; i += chunkSize) { const chunk = unique.slice(i, i + chunkSize); try { execFileSync("vp", ["fmt", ...chunk, "--write"], { encoding: "utf-8", cwd: workspaceRoot, }); } catch (err: any) { const output = `${err?.stdout ?? ""}${err?.stderr ?? ""}`; if (output.includes("Expected at least one target file")) { // All files in this chunk were excluded by oxfmt ignore rules. continue; } // eslint-disable-next-line no-console console.error(output); throw err; } } } export type Project = { /** * The title of the example, from README.md */ title: string; /** * e.g.: examples/01-basic/01-minimal */ pathFromRoot: string; /** * e.g.: minimal */ projectSlug: string; /** * e.g.: basic/minimal */ fullSlug: string; group: { /** * e.g.: examples/01-basic */ pathFromRoot: string; /** * e.g.: basic */ slug: string; }; /** * contents from .bnexample.json */ config: { playground: boolean; docs: boolean; dependencies?: any; devDependencies?: any; shortTitle?: string; author: string; pro?: boolean; tailwind?: boolean; stackBlitz?: boolean; /** * When true, the example generator emits the shared `testDocumentBlocks.ts` * into the example (copied verbatim from `tests/src/fixtures/exporters/testDocumentBlocks.ts`) so * the example can use it as editor `initialContent` while staying * self-contained. */ sharedTestDocument?: boolean; }; readme: string; }; /** * Reads a version specifier from the `catalog:` section of the workspace's * `pnpm-workspace.yaml`. The `catalog:` protocol is pnpm-specific, so generated * example `package.json` files (which are meant to run standalone, e.g. in * StackBlitz via `npm install`) must inline a concrete version instead. Keeping * the catalog as the single source of truth avoids drift when the version bumps. */ export function getCatalogVersion(name: string): string { const workspaceFile = path.join(workspaceRoot, "pnpm-workspace.yaml"); const lines = fs.readFileSync(workspaceFile, "utf-8").split("\n"); let inCatalog = false; for (const line of lines) { if (/^catalog:\s*$/.test(line)) { inCatalog = true; continue; } if (inCatalog) { // A non-indented, non-empty line ends the catalog block. if (line.trim() !== "" && !/^\s/.test(line)) { break; } const match = line.match(/^\s+(\S+):\s*(\S+)\s*$/); if (match && match[1].replace(/^["']|["']$/g, "") === name) { return match[2].replace(/^["']|["']$/g, ""); } } } throw new Error( `Could not find "${name}" in the catalog of ${workspaceFile}`, ); } function groupBy(arr: T[], key: (el: T) => string) { const groups: Record = {}; arr.forEach((val) => { const k = key(val); if (!groups[k]) { groups[k] = []; } groups[k].push(val); }); return groups; } export function groupProjects(projects: Project[]) { const grouped = groupBy(projects, (p) => p.group.slug); return Object.fromEntries( Object.entries(grouped).map(([key, projects]) => { const group = projects[0].group; return [ key, { ...group, projects, }, ]; }), ); } export function addTitleToGroups(grouped: ReturnType) { // read group titles from /pages/examples/_meta.json const meta = { index: "Overview", basic: "Basic", backend: "Backend", "ui-components": "UI Components", theming: "Theming", interoperability: "Interoperability", "custom-schema": "Custom Schemas", collaboration: "Collaboration", extensions: "Extensions", ai: "AI", "vanilla-js": "Vanilla JS", }; const groupsWithTitles = Object.fromEntries( Object.entries(grouped).map(([key, group]) => { if (!(key in meta)) { throw new Error( `Missing group title for ${key}, add to docs/content/examples/meta.json?`, ); } const title = meta[key as keyof typeof meta]; return [ key, { ...group, title, }, ]; }), ); return groupsWithTitles; } // Example files copied into generated trees verbatim (fonts, images, ...) - // reading these as UTF-8 text would corrupt every byte >= 0x80 (each becomes // the U+FFFD replacement character). const BINARY_EXTENSIONS = new Set([ ".gif", ".ico", ".jpeg", ".jpg", ".otf", ".pdf", ".png", ".ttf", ".wasm", ".webp", ".woff", ".woff2", ]); type ProjectFile = | { filename: string; kind: "text"; code: string } | { filename: string; kind: "binary"; sourcePath: string }; export type Files = ProjectFile[]; export function getProjectFiles(project: Project): Files { const dir = path.resolve("../..", project.pathFromRoot, "src"); const files = globSync(["**/*"], { absolute: true, cwd: dir, }); return files.map((fullPath) => { const filename = fullPath.substring(dir.length); if (BINARY_EXTENSIONS.has(path.extname(fullPath).toLowerCase())) { return { filename, kind: "binary" as const, sourcePath: fullPath }; } return { filename, kind: "text" as const, code: fs.readFileSync(fullPath, "utf-8"), }; }); } /** * Get the list of example Projects based on the /examples folder */ export function getExampleProjects(): Project[] { const examples: Project[] = globSync("*", { cwd: path.join(dir, "../../../examples/"), ignore: ["node_modules/**/*", "dist/**/*"], absolute: true, onlyDirectories: true, }) .flatMap((dir) => { return globSync("*", { ignore: ["node_modules/**/*", "dist/**/*"], onlyDirectories: true, absolute: true, cwd: dir, }); }) .flatMap((dir) => { const file = path.join(dir, ".bnexample.json"); if (fs.existsSync(file)) { return [file]; } return []; }) .map((configPath) => { const config = JSON.parse(fs.readFileSync(configPath, "utf-8")); const directory = path.dirname(configPath); const readmePath = path.join(directory, "README.md"); if (!fs.existsSync(readmePath)) { throw new Error(`Missing README.md for ${directory}`); } const md = fs.readFileSync(readmePath, "utf-8"); const [mdTitle, ...rest] = md.split("\n"); const title = mdTitle.match(/# (.*)/)?.[1]; if (!title?.length) { throw new Error(`Missing title in README.md for ${directory}`); } const [groupDir, exampleDir] = path .relative(path.join(workspaceRoot, "examples"), directory) .split(path.sep); const group = { pathFromRoot: replacePathSepToSlash( path.relative(workspaceRoot, path.join(directory, "..")), ), // remove optional 01- prefix slug: groupDir.replace(/^\d{2}-/, ""), }; const projectSlug = exampleDir.replace(/^\d{2}-/, ""); const project = { projectSlug, fullSlug: `${group.slug}/${projectSlug}`, pathFromRoot: replacePathSepToSlash( path.relative(workspaceRoot, directory), ), config, title, group, readme: rest.join("\n").trim(), }; return project; }); // examples.sort((a, b) => { // if (a.config?.order && b.config?.order) { // return a.config.order - b.config.order; // } // if (a.config?.order) { // return -1; // } // if (b.config?.order) { // return 1; // } // return 0; // }); return examples; } export function replacePathSepToSlash(path: string) { const isExtendedLengthPath = path.startsWith("\\\\?\\"); if (isExtendedLengthPath) { return path; } return path.replace(/\\/g, "/"); }