An open source design system that's fully customizable and agent ready
TypeScript
fix(vibe-tests): auto-fix missing XDS imports + surface as quality signal (#1164)
Cindy Zhanga80f6a738a6f
diff --git a/internal/vibe-tests/src/build-previews.ts b/internal/vibe-tests/src/build-previews.tsindex d38e7fe6b8..ea48c11d60 100644--- a/internal/vibe-tests/src/build-previews.ts+++ b/internal/vibe-tests/src/build-previews.ts@@ -36,6 +36,52 @@ const LIGHTNINGCSS_TARGETS_JS = `{safari: (17 << 16) | (5 << 8),}`;++/**+ * Fix missing XDS component imports in AI-generated .tsx files.+ * Scans for XDS* identifiers used in JSX that aren't imported,+ * and prepends the missing import. Returns list of auto-imported components.+ */+function fixMissingXDSImports(filePath: string): string[] {+ const code = fs.readFileSync(filePath, 'utf-8');+ const usedComponents = new Set<string>();+ const jsxPattern = /(?:<|jsxs?\(\s*)(XDS\w+)/g;+ let match;+ while ((match = jsxPattern.exec(code)) !== null) {+ usedComponents.add(match[1]);+ }+ if (usedComponents.size === 0) return [];+ const importedComponents = new Set<string>();+ const importPattern =+ /import\s*\{([^}]+)\}\s*from\s*['"]@xds\/core[^'"]*['"]/g;+ while ((match = importPattern.exec(code)) !== null) {+ for (const specifier of match[1].split(',')) {+ const name = specifier.trim().split(/\s+as\s+/)[0].trim();+ if (name.startsWith('XDS')) importedComponents.add(name);+ }+ }+ const missing = [...usedComponents].filter(c => !importedComponents.has(c));+ if (missing.length === 0) return [];+ const importLine = `import {${missing.sort().join(', ')}} from '@xds/core';\n`;+ fs.writeFileSync(filePath, importLine + code);+ return missing.sort();+}++/**+ * Validate a built preview HTML for unresolved XDS component references.+ * Returns list of unresolved component names (empty if clean).+ */+function validatePreviewHtml(htmlPath: string): string[] {+ const html = fs.readFileSync(htmlPath, 'utf-8');+ const unresolved = new Set<string>();+ const pattern = /\.jsxs?\((XDS[A-Z]\w+)/g;+ let match;+ while ((match = pattern.exec(html)) !== null) {+ unresolved.add(match[1]);+ }+ return [...unresolved].sort();+}+interface PreviewManifest {[promptId: string]: {[target: string]: string; // relative path to preview HTML@@ -611,6 +657,8 @@ async function main() {console.log('='.repeat(40));const manifest: PreviewManifest = {};+ /** Track which prompts needed auto-imported components (quality signal) */+ const importFixes: Record<string, string[]> = {};for (const iterationId of iterations) {const iterDir = path.join(resultsDir, iterationId);@@ -639,12 +687,31 @@ async function main() {console.log(` π ${promptId} (${target})...`);+ // Auto-fix missing XDS imports before building+ if (target === 'xds' || target === 'xds-tailwind') {+ const autoImported = fixMissingXDSImports(componentPath);+ if (autoImported.length > 0) {+ console.log(` β‘ Auto-imported: ${autoImported.join(', ')}`);+ importFixes[promptId] = autoImported;+ }+ }+if (target === 'baseline') {ensureBaselineShims();}const ok = buildPreview(componentPath, target, promptId, previewPath);if (ok) {+ // Post-build validation: ensure no unresolved XDS references+ if (target === 'xds' || target === 'xds-tailwind') {+ const unresolved = validatePreviewHtml(previewPath);+ if (unresolved.length > 0) {+ console.error(+ ` β Unresolved XDS components in ${previewFile}: ${unresolved.join(', ')}`,+ );+ }+ }+if (!manifest[promptId]) manifest[promptId] = {};manifest[promptId][target] = `previews/${previewFile}`;console.log(` β ${previewFile}`);@@ -666,6 +733,18 @@ async function main() {}writeJson(manifestOutPath, manifest);+ // Write import-fixes sidecar so evaluators can penalize missing imports+ if (Object.keys(importFixes).length > 0) {+ const fixesPath = path.join(outDir, 'import-fixes.json');+ writeJson(fixesPath, importFixes);+ console.log(+ `\nβ ${Object.keys(importFixes).length} prompt(s) had missing XDS imports (auto-fixed):`,+ );+ for (const [promptId, components] of Object.entries(importFixes)) {+ console.log(` ${promptId}: ${components.join(', ')}`);+ }+ }+const totalPreviews = Object.values(manifest).reduce((sum, targets) => sum + Object.keys(targets).length,0,diff --git a/internal/vibe-tests/src/fix-imports.ts b/internal/vibe-tests/src/fix-imports.tsnew file mode 100644index 0000000000..bbe6c824a9--- /dev/null+++ b/internal/vibe-tests/src/fix-imports.ts@@ -0,0 +1,135 @@+#!/usr/bin/env node+/**+ * @file Standalone codemod: fix missing XDS imports in vibe test results+ *+ * Scans .tsx files in results directories and adds missing XDS component+ * imports. Use after running vibe tests but before building previews,+ * or as a bulk-fix for existing results.+ *+ * Usage:+ * tsx src/fix-imports.ts --iterations <id1,id2,...>+ * tsx src/fix-imports.ts --iterations <id> --dry-run+ */++import * as fs from 'node:fs';+import * as path from 'node:path';+import {getResultsDir, readJson} from './utils.js';++function fixMissingXDSImports(+ filePath: string,+ dryRun: boolean,+): string[] {+ const code = fs.readFileSync(filePath, 'utf-8');++ // Find all XDS component references used in JSX+ const usedComponents = new Set<string>();+ const jsxPattern = /(?:<|jsxs?\(\s*)(XDS\w+)/g;+ let match;+ while ((match = jsxPattern.exec(code)) !== null) {+ usedComponents.add(match[1]);+ }+ if (usedComponents.size === 0) return [];++ // Find already-imported XDS components+ const importedComponents = new Set<string>();+ const importPattern =+ /import\s*\{([^}]+)\}\s*from\s*['"]@xds\/core[^'"]*['"]/g;+ while ((match = importPattern.exec(code)) !== null) {+ for (const specifier of match[1].split(',')) {+ const name = specifier+ .trim()+ .split(/\s+as\s+/)[0]+ .trim();+ if (name.startsWith('XDS')) importedComponents.add(name);+ }+ }++ const missing = [...usedComponents].filter(c => !importedComponents.has(c));+ if (missing.length === 0) return [];++ if (!dryRun) {+ const importLine = `import {${missing.sort().join(', ')}} from '@xds/core';\n`;+ fs.writeFileSync(filePath, importLine + code);+ }++ return missing.sort();+}++function parseArgs(): {iterations: string[]; dryRun: boolean} {+ const args = process.argv.slice(2);+ let iterations: string[] = [];+ let dryRun = false;++ for (let i = 0; i < args.length; i++) {+ if (args[i] === '--iterations' && args[i + 1]) {+ iterations = args[++i].split(',');+ } else if (args[i] === '--dry-run') {+ dryRun = true;+ }+ }++ if (iterations.length === 0) {+ console.error(+ 'Usage: tsx src/fix-imports.ts --iterations <id1,id2,...> [--dry-run]',+ );+ process.exit(1);+ }++ return {iterations, dryRun};+}++function main() {+ const {iterations, dryRun} = parseArgs();+ const resultsDir = getResultsDir();++ console.log(+ `\nπ§ Fix Missing XDS Imports${dryRun ? ' (dry run)' : ''}`,+ );+ console.log('='.repeat(40));++ let totalFixed = 0;+ let totalFiles = 0;++ for (const iterationId of iterations) {+ const iterDir = path.join(resultsDir, iterationId);+ const manifestPath = path.join(iterDir, 'manifest.json');++ if (!fs.existsSync(manifestPath)) {+ console.error(` β No manifest for ${iterationId}, skipping`);+ continue;+ }++ const iterManifest = readJson<{config?: {target?: string}}>(manifestPath);+ const target = iterManifest.config?.target ?? 'xds';++ // Only XDS targets need import fixing+ if (target !== 'xds' && target !== 'xds-tailwind') {+ console.log(` β ${iterationId} is ${target}, skipping`);+ continue;+ }++ const codeDir = path.join(iterDir, 'results');+ if (!fs.existsSync(codeDir)) continue;++ const files = fs.readdirSync(codeDir).filter(f => f.endsWith('.tsx'));++ for (const file of files) {+ totalFiles++;+ const filePath = path.resolve(codeDir, file);+ const promptId = path.basename(file, '.tsx');+ const fixed = fixMissingXDSImports(filePath, dryRun);++ if (fixed.length > 0) {+ totalFixed++;+ const action = dryRun ? 'would fix' : 'fixed';+ console.log(` β‘ ${promptId}: ${action} ${fixed.join(', ')}`);+ }+ }+ }++ console.log(+ `\nβ ${totalFixed}/${totalFiles} file(s) ${dryRun ? 'would need' : 'needed'} import fixes`,+ );+}++main();diff --git a/internal/vibe-tests/src/validate-previews.ts b/internal/vibe-tests/src/validate-previews.tsnew file mode 100644index 0000000000..125ee2b5b1--- /dev/null+++ b/internal/vibe-tests/src/validate-previews.ts@@ -0,0 +1,112 @@+#!/usr/bin/env node+/**+ * @file Standalone validator: check built preview HTML for unresolved XDS refs+ *+ * Scans built preview HTML files and detects literal XDS component references+ * that survived the bundle β meaning they weren't imported and will crash+ * at runtime with React error #130.+ *+ * Usage:+ * tsx src/validate-previews.ts --iterations <id1,id2,...>+ *+ * Exit code 1 if any unresolved references found.+ */++import * as fs from 'node:fs';+import * as path from 'node:path';+import {getResultsDir} from './utils.js';++function validatePreviewHtml(htmlPath: string): string[] {+ const html = fs.readFileSync(htmlPath, 'utf-8');+ const unresolved = new Set<string>();++ // Match jsx(XDSFoo or jsxs(XDSFoo β literal unresolved references+ const pattern = /\.jsxs?\((XDS[A-Z]\w+)/g;+ let match;+ while ((match = pattern.exec(html)) !== null) {+ unresolved.add(match[1]);+ }++ return [...unresolved].sort();+}++function parseArgs(): {iterations: string[]} {+ const args = process.argv.slice(2);+ let iterations: string[] = [];++ for (let i = 0; i < args.length; i++) {+ if (args[i] === '--iterations' && args[i + 1]) {+ iterations = args[++i].split(',');+ }+ }++ if (iterations.length === 0) {+ console.error(+ 'Usage: tsx src/validate-previews.ts --iterations <id1,id2,...>',+ );+ process.exit(1);+ }++ return {iterations};+}++function main() {+ const {iterations} = parseArgs();+ const resultsDir = getResultsDir();++ console.log('\nπ Validating Preview HTML');+ console.log('='.repeat(40));++ let totalFiles = 0;+ let totalErrors = 0;+ const errors: Array<{file: string; components: string[]}> = [];++ for (const iterationId of iterations) {+ const previewsDir = path.join(resultsDir, iterationId, 'previews');++ if (!fs.existsSync(previewsDir)) {+ console.error(` β No previews dir for ${iterationId}, skipping`);+ continue;+ }++ // Walk preview directories+ const promptDirs = fs.readdirSync(previewsDir).filter(d => {+ const fullPath = path.join(previewsDir, d);+ return fs.statSync(fullPath).isDirectory();+ });++ for (const promptDir of promptDirs) {+ const dirPath = path.join(previewsDir, promptDir);+ const htmlFiles = fs+ .readdirSync(dirPath)+ .filter(f => f.endsWith('.html'));++ for (const htmlFile of htmlFiles) {+ totalFiles++;+ const htmlPath = path.join(dirPath, htmlFile);+ const unresolved = validatePreviewHtml(htmlPath);++ if (unresolved.length > 0) {+ totalErrors++;+ const relPath = `${promptDir}/${htmlFile}`;+ errors.push({file: relPath, components: unresolved});+ console.error(+ ` β ${relPath}: unresolved ${unresolved.join(', ')}`,+ );+ } else {+ console.log(` β ${promptDir}/${htmlFile}`);+ }+ }+ }+ }++ console.log(`\n${totalErrors === 0 ? 'β ' : 'β'} ${totalFiles} file(s) checked, ${totalErrors} error(s)`);++ if (errors.length > 0) {+ console.error('\nUnresolved XDS components will cause React error #130 at runtime.');+ console.error('Run fix-imports.ts then rebuild to fix.');+ process.exit(1);+ }+}++main();