#!/usr/bin/env node /** * Generates stub packages for all workspace:* dependencies. * Scans web/src for imports from @szl-holdings/*, @workspace/*, @szl/* * and creates minimal stub packages under stubs/ directory. */ import { readFileSync, writeFileSync, mkdirSync, readdirSync, statSync } from 'fs'; import { join, dirname, resolve } from 'path'; const ROOT = resolve(dirname(new URL(import.meta.url).pathname), '..'); const SRC_DIR = join(ROOT, 'web', 'src'); // Collect all .ts/.tsx files recursively function collectFiles(dir, exts = ['.ts', '.tsx']) { const results = []; for (const entry of readdirSync(dir, { withFileTypes: true })) { const full = join(dir, entry.name); if (entry.isDirectory()) { results.push(...collectFiles(full, exts)); } else if (exts.some(ext => entry.name.endsWith(ext))) { results.push(full); } } return results; } // Also scan index.css for CSS imports const cssFile = join(ROOT, 'web', 'src', 'index.css'); // Parse imports from a TypeScript/TSX file function parseImports(content) { const imports = []; // Match: import { X, Y } from 'pkg'; import X from 'pkg'; import 'pkg'; const importRegex = /import\s+(?:(?:type\s+)?(?:\{([^}]*)\}|(\w+))\s+from\s+)?['"](@szl-holdings\/[^'"]+|@workspace\/[^'"]+|@szl\/[^'"]+)['"]/g; let m; while ((m = importRegex.exec(content)) !== null) { const namedStr = m[1] || ''; const defaultImport = m[2] || null; const modulePath = m[3]; const named = namedStr .split(',') .map(s => s.trim()) .filter(Boolean) .map(s => { // Handle "X as Y" -> extract X const asMatch = s.match(/^(?:type\s+)?(\w+)(?:\s+as\s+\w+)?$/); return asMatch ? asMatch[1] : s.replace(/^type\s+/, ''); }) .filter(s => /^\w+$/.test(s)); imports.push({ modulePath, named, defaultImport }); } return imports; } // Collect all imports const allFiles = collectFiles(SRC_DIR); const importMap = new Map(); // pkgName -> Map> for (const file of allFiles) { const content = readFileSync(file, 'utf-8'); const imports = parseImports(content); for (const { modulePath, named, defaultImport } of imports) { // Split: @szl-holdings/shared-ui/utils -> pkg=@szl-holdings/shared-ui, sub=utils const parts = modulePath.split('/'); let pkgName, subpath; if (parts[0].startsWith('@')) { pkgName = parts.slice(0, 2).join('/'); subpath = parts.slice(2).join('/') || '.'; } else { pkgName = parts[0]; subpath = parts.slice(1).join('/') || '.'; } if (!importMap.has(pkgName)) { importMap.set(pkgName, new Map()); } const subMap = importMap.get(pkgName); if (!subMap.has(subpath)) { subMap.set(subpath, new Set()); } const exports = subMap.get(subpath); for (const n of named) exports.add(n); if (defaultImport) exports.add('__default__:' + defaultImport); } } // Also handle CSS imports try { const cssContent = readFileSync(cssFile, 'utf-8'); const cssImportRegex = /@import\s+['"](@szl-holdings\/[^'"]+|@workspace\/[^'"]+|@szl\/[^'"]+)['"]/g; let m; while ((m = cssImportRegex.exec(cssContent)) !== null) { const modulePath = m[1]; const parts = modulePath.split('/'); let pkgName, subpath; if (parts[0].startsWith('@')) { pkgName = parts.slice(0, 2).join('/'); subpath = parts.slice(2).join('/') || '.'; } else { pkgName = parts[0]; subpath = parts.slice(1).join('/') || '.'; } if (!importMap.has(pkgName)) importMap.set(pkgName, new Map()); const subMap = importMap.get(pkgName); if (!subMap.has(subpath)) subMap.set(subpath, new Set()); subMap.get(subpath).add('__css__'); } } catch (e) { /* ignore */ } // React component stub generator function generateStubCode(exportNames) { const lines = ["import React from 'react';"]; const hasCSS = exportNames.has('__css__'); const jsExports = [...exportNames].filter(n => !n.startsWith('__')); const defaultExports = [...exportNames].filter(n => n.startsWith('__default__:')); // Known type-only exports that should be exported as types const typeOnlyNames = new Set(['AuthTokens', 'CommandModeSignal', 'SidebarNavSection', 'KeyboardShortcut', 'OnboardingConfig', 'CommandItem', 'ActivationStep', 'DataProvenanceInfo', 'StatusVariant', 'AuditTrailEntry', 'PolicyDecisionRecord', 'ProofPanelData', 'RecommendationAction', 'AutonomyMode', 'AmbientSignal', 'DocumentPipelineResult', 'OwnershipNode']); // Generate a React component stub const componentStub = `(props) => React.createElement('div', { 'data-stub': true, ...props }, props?.children || null)`; const fnStub = `(...args) => {}`; for (const name of jsExports) { if (typeOnlyNames.has(name)) { // Skip type-only exports in JS (they're just types) continue; } // Heuristic: PascalCase = React component, camelCase/UPPER = function/constant if (/^[A-Z]/.test(name)) { lines.push(`export const ${name} = ${componentStub};`); } else if (name === 'cn') { lines.push(`export function cn(...args) { return args.filter(Boolean).join(' '); }`); } else if (name === 'toAlpha') { lines.push(`export function toAlpha(hex, alpha) { return hex + Math.round(alpha * 255).toString(16).padStart(2, '0'); }`); } else if (name === 'color') { lines.push(`export const color = new Proxy({}, { get: (t, k) => '#888888' });`); } else if (name === 'toast') { lines.push(`export const toast = Object.assign((...a) => {}, { success: () => {}, error: () => {}, info: () => {}, warning: () => {}, dismiss: () => {} });`); } else if (name === 'analytics') { lines.push(`export const analytics = { track: () => {}, identify: () => {}, page: () => {}, reset: () => {} };`); } else { lines.push(`export const ${name} = ${fnStub};`); } } // Default export if (defaultExports.length > 0) { lines.push(`export default ${componentStub};`); } else if (jsExports.length === 0 && !hasCSS) { lines.push(`export default {};`); } if (hasCSS) { return '/* stub CSS */'; } return lines.join('\n') + '\n'; } // Generate stub packages const STUBS_DIR = join(ROOT, 'stubs'); mkdirSync(STUBS_DIR, { recursive: true }); for (const [pkgName, subMap] of importMap) { const safeDirName = pkgName.replace(/^@/, '').replace(/\//g, '__'); const pkgDir = join(STUBS_DIR, safeDirName); mkdirSync(pkgDir, { recursive: true }); // Build exports map for package.json const exportsMap = {}; const subpaths = [...subMap.keys()]; for (const sub of subpaths) { const exportNames = subMap.get(sub); const hasCSS = exportNames.has('__css__'); const fileName = sub === '.' ? 'index' : sub.replace(/\//g, '__'); const ext = hasCSS ? '.css' : '.js'; const filePath = `./${fileName}${ext}`; // Write the stub file const stubContent = generateStubCode(exportNames); writeFileSync(join(pkgDir, `${fileName}${ext}`), stubContent); // Add to exports map const exportKey = sub === '.' ? '.' : `./${sub}`; if (hasCSS) { exportsMap[exportKey] = filePath; } else { exportsMap[exportKey] = { import: filePath, default: filePath }; } } // Add a wildcard catch-all export exportsMap['./*'] = { import: './catch-all.js', default: './catch-all.js' }; // Write catch-all stub writeFileSync(join(pkgDir, 'catch-all.js'), ` import React from 'react'; const Stub = (props) => React.createElement('div', { 'data-stub': true, ...props }, props?.children || null); export default Stub; export { Stub }; export const noop = () => {}; `); // Write package.json const pkgJson = { name: pkgName, version: '0.0.0-stub', type: 'module', exports: exportsMap, main: './index.js', }; // Write index.js if not already created if (!subMap.has('.')) { writeFileSync(join(pkgDir, 'index.js'), ` import React from 'react'; const Stub = (props) => React.createElement('div', { 'data-stub': true, ...props }, props?.children || null); export default Stub; export { Stub }; `); pkgJson.exports['.'] = { import: './index.js', default: './index.js' }; } writeFileSync(join(pkgDir, 'package.json'), JSON.stringify(pkgJson, null, 2) + '\n'); console.log(`✓ ${pkgName} (${subpaths.length} subpaths)`); } console.log(`\nGenerated ${importMap.size} stub packages in stubs/`);