@agent-scope/cli 1.8.0 → 1.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -2,8 +2,9 @@
2
2
 
3
3
  var fs = require('fs');
4
4
  var path = require('path');
5
- var manifest = require('@agent-scope/manifest');
5
+ var readline = require('readline');
6
6
  var commander = require('commander');
7
+ var manifest = require('@agent-scope/manifest');
7
8
  var playwright = require('@agent-scope/playwright');
8
9
  var playwright$1 = require('playwright');
9
10
  var render = require('@agent-scope/render');
@@ -29,9 +30,353 @@ function _interopNamespace(e) {
29
30
  return Object.freeze(n);
30
31
  }
31
32
 
33
+ var readline__namespace = /*#__PURE__*/_interopNamespace(readline);
32
34
  var esbuild__namespace = /*#__PURE__*/_interopNamespace(esbuild);
33
35
 
34
- // src/manifest-commands.ts
36
+ // src/init/index.ts
37
+ function hasConfigFile(dir, stem) {
38
+ if (!fs.existsSync(dir)) return false;
39
+ try {
40
+ const entries = fs.readdirSync(dir);
41
+ return entries.some((f) => f === stem || f.startsWith(`${stem}.`));
42
+ } catch {
43
+ return false;
44
+ }
45
+ }
46
+ function readSafe(path) {
47
+ try {
48
+ return fs.readFileSync(path, "utf-8");
49
+ } catch {
50
+ return null;
51
+ }
52
+ }
53
+ function detectFramework(rootDir, packageDeps) {
54
+ if (hasConfigFile(rootDir, "next.config")) return "next";
55
+ if (hasConfigFile(rootDir, "vite.config")) return "vite";
56
+ if (hasConfigFile(rootDir, "remix.config")) return "remix";
57
+ if ("react-scripts" in packageDeps) return "cra";
58
+ return "unknown";
59
+ }
60
+ function detectPackageManager(rootDir) {
61
+ if (fs.existsSync(path.join(rootDir, "bun.lock"))) return "bun";
62
+ if (fs.existsSync(path.join(rootDir, "yarn.lock"))) return "yarn";
63
+ if (fs.existsSync(path.join(rootDir, "pnpm-lock.yaml"))) return "pnpm";
64
+ if (fs.existsSync(path.join(rootDir, "package-lock.json"))) return "npm";
65
+ return "npm";
66
+ }
67
+ function detectTypeScript(rootDir) {
68
+ const candidate = path.join(rootDir, "tsconfig.json");
69
+ if (fs.existsSync(candidate)) {
70
+ return { typescript: true, tsconfigPath: candidate };
71
+ }
72
+ return { typescript: false, tsconfigPath: null };
73
+ }
74
+ var COMPONENT_DIRS = ["src/components", "src/app", "src/pages", "src/ui", "src/features", "src"];
75
+ var COMPONENT_EXTS = [".tsx", ".jsx"];
76
+ function detectComponentPatterns(rootDir, typescript) {
77
+ const patterns = [];
78
+ const ext = typescript ? "tsx" : "jsx";
79
+ const altExt = typescript ? "jsx" : "jsx";
80
+ for (const dir of COMPONENT_DIRS) {
81
+ const absDir = path.join(rootDir, dir);
82
+ if (!fs.existsSync(absDir)) continue;
83
+ let hasComponents = false;
84
+ try {
85
+ const entries = fs.readdirSync(absDir, { withFileTypes: true });
86
+ hasComponents = entries.some(
87
+ (e) => e.isFile() && COMPONENT_EXTS.some((x) => e.name.endsWith(x))
88
+ );
89
+ if (!hasComponents) {
90
+ hasComponents = entries.some(
91
+ (e) => e.isDirectory() && (() => {
92
+ try {
93
+ return fs.readdirSync(path.join(absDir, e.name)).some(
94
+ (f) => COMPONENT_EXTS.some((x) => f.endsWith(x))
95
+ );
96
+ } catch {
97
+ return false;
98
+ }
99
+ })()
100
+ );
101
+ }
102
+ } catch {
103
+ continue;
104
+ }
105
+ if (hasComponents) {
106
+ patterns.push(`${dir}/**/*.${ext}`);
107
+ if (altExt !== ext) {
108
+ patterns.push(`${dir}/**/*.${altExt}`);
109
+ }
110
+ }
111
+ }
112
+ const unique = [...new Set(patterns)];
113
+ if (unique.length === 0) {
114
+ return [`**/*.${ext}`];
115
+ }
116
+ return unique;
117
+ }
118
+ var TAILWIND_STEMS = ["tailwind.config"];
119
+ var CSS_EXTS = [".css", ".scss", ".sass", ".less"];
120
+ var THEME_SUFFIXES = [".theme.ts", ".theme.js", ".theme.tsx"];
121
+ var CSS_CUSTOM_PROPS_RE = /:root\s*\{[^}]*--[a-zA-Z]/;
122
+ function detectTokenSources(rootDir) {
123
+ const sources = [];
124
+ for (const stem of TAILWIND_STEMS) {
125
+ if (hasConfigFile(rootDir, stem)) {
126
+ try {
127
+ const entries = fs.readdirSync(rootDir);
128
+ const match = entries.find((f) => f === stem || f.startsWith(`${stem}.`));
129
+ if (match) {
130
+ sources.push({ kind: "tailwind-config", path: path.join(rootDir, match) });
131
+ }
132
+ } catch {
133
+ }
134
+ }
135
+ }
136
+ const srcDir = path.join(rootDir, "src");
137
+ const dirsToScan = fs.existsSync(srcDir) ? [srcDir] : [];
138
+ for (const scanDir of dirsToScan) {
139
+ try {
140
+ const entries = fs.readdirSync(scanDir, { withFileTypes: true });
141
+ for (const entry of entries) {
142
+ if (entry.isFile() && CSS_EXTS.some((x) => entry.name.endsWith(x))) {
143
+ const filePath = path.join(scanDir, entry.name);
144
+ const content = readSafe(filePath);
145
+ if (content !== null && CSS_CUSTOM_PROPS_RE.test(content)) {
146
+ sources.push({ kind: "css-custom-properties", path: filePath });
147
+ }
148
+ }
149
+ }
150
+ } catch {
151
+ }
152
+ }
153
+ if (fs.existsSync(srcDir)) {
154
+ try {
155
+ const entries = fs.readdirSync(srcDir);
156
+ for (const entry of entries) {
157
+ if (THEME_SUFFIXES.some((s) => entry.endsWith(s))) {
158
+ sources.push({ kind: "theme-file", path: path.join(srcDir, entry) });
159
+ }
160
+ }
161
+ } catch {
162
+ }
163
+ }
164
+ return sources;
165
+ }
166
+ function detectProject(rootDir) {
167
+ const pkgPath = path.join(rootDir, "package.json");
168
+ let packageDeps = {};
169
+ const pkgContent = readSafe(pkgPath);
170
+ if (pkgContent !== null) {
171
+ try {
172
+ const pkg = JSON.parse(pkgContent);
173
+ packageDeps = {
174
+ ...pkg.dependencies,
175
+ ...pkg.devDependencies
176
+ };
177
+ } catch {
178
+ }
179
+ }
180
+ const framework = detectFramework(rootDir, packageDeps);
181
+ const { typescript, tsconfigPath } = detectTypeScript(rootDir);
182
+ const packageManager = detectPackageManager(rootDir);
183
+ const componentPatterns = detectComponentPatterns(rootDir, typescript);
184
+ const tokenSources = detectTokenSources(rootDir);
185
+ return {
186
+ framework,
187
+ typescript,
188
+ tsconfigPath,
189
+ componentPatterns,
190
+ tokenSources,
191
+ packageManager
192
+ };
193
+ }
194
+ function buildDefaultConfig(detected, tokenFile, outputDir) {
195
+ const include = detected.componentPatterns.length > 0 ? detected.componentPatterns : ["src/**/*.tsx"];
196
+ return {
197
+ components: {
198
+ include,
199
+ exclude: ["**/*.test.tsx", "**/*.stories.tsx"],
200
+ wrappers: { providers: [], globalCSS: [] }
201
+ },
202
+ render: {
203
+ viewport: { default: { width: 1280, height: 800 } },
204
+ theme: "light",
205
+ warmBrowser: true
206
+ },
207
+ tokens: {
208
+ file: tokenFile,
209
+ compliance: { threshold: 90 }
210
+ },
211
+ output: {
212
+ dir: outputDir,
213
+ sprites: { format: "png", cellPadding: 8, labelAxes: true },
214
+ json: { pretty: true }
215
+ },
216
+ ci: {
217
+ complianceThreshold: 90,
218
+ failOnA11yViolations: true,
219
+ failOnConsoleErrors: false,
220
+ baselinePath: `${outputDir}baseline/`
221
+ }
222
+ };
223
+ }
224
+ function createRL() {
225
+ return readline__namespace.createInterface({
226
+ input: process.stdin,
227
+ output: process.stdout
228
+ });
229
+ }
230
+ async function ask(rl, question) {
231
+ return new Promise((resolve7) => {
232
+ rl.question(question, (answer) => {
233
+ resolve7(answer.trim());
234
+ });
235
+ });
236
+ }
237
+ async function askWithDefault(rl, label, defaultValue) {
238
+ const answer = await ask(rl, ` ${label} [${defaultValue}]: `);
239
+ return answer.length > 0 ? answer : defaultValue;
240
+ }
241
+ function ensureGitignoreEntry(rootDir, entry) {
242
+ const gitignorePath = path.join(rootDir, ".gitignore");
243
+ if (fs.existsSync(gitignorePath)) {
244
+ const content = fs.readFileSync(gitignorePath, "utf-8");
245
+ const normalised = entry.replace(/\/$/, "");
246
+ const lines = content.split("\n").map((l) => l.trim());
247
+ if (lines.includes(entry) || lines.includes(normalised)) {
248
+ return;
249
+ }
250
+ const suffix = content.endsWith("\n") ? "" : "\n";
251
+ fs.appendFileSync(gitignorePath, `${suffix}${entry}
252
+ `);
253
+ } else {
254
+ fs.writeFileSync(gitignorePath, `${entry}
255
+ `);
256
+ }
257
+ }
258
+ function scaffoldConfig(rootDir, config) {
259
+ const path$1 = path.join(rootDir, "reactscope.config.json");
260
+ fs.writeFileSync(path$1, `${JSON.stringify(config, null, 2)}
261
+ `);
262
+ return path$1;
263
+ }
264
+ function scaffoldTokenFile(rootDir, tokenFile) {
265
+ const path$1 = path.join(rootDir, tokenFile);
266
+ if (!fs.existsSync(path$1)) {
267
+ const stub = {
268
+ $schema: "https://raw.githubusercontent.com/FlatFilers/Scope/main/packages/tokens/schema.json",
269
+ tokens: {}
270
+ };
271
+ fs.writeFileSync(path$1, `${JSON.stringify(stub, null, 2)}
272
+ `);
273
+ }
274
+ return path$1;
275
+ }
276
+ function scaffoldOutputDir(rootDir, outputDir) {
277
+ const dirPath = path.join(rootDir, outputDir);
278
+ fs.mkdirSync(dirPath, { recursive: true });
279
+ const keepPath = path.join(dirPath, ".gitkeep");
280
+ if (!fs.existsSync(keepPath)) {
281
+ fs.writeFileSync(keepPath, "");
282
+ }
283
+ return dirPath;
284
+ }
285
+ async function runInit(options) {
286
+ const rootDir = options.cwd ?? process.cwd();
287
+ const configPath = path.join(rootDir, "reactscope.config.json");
288
+ const created = [];
289
+ if (fs.existsSync(configPath) && !options.force) {
290
+ const msg = "reactscope.config.json already exists. Run with --force to overwrite.";
291
+ process.stderr.write(`\u26A0\uFE0F ${msg}
292
+ `);
293
+ return { success: false, message: msg, created: [], skipped: true };
294
+ }
295
+ const detected = detectProject(rootDir);
296
+ const defaultTokenFile = "reactscope.tokens.json";
297
+ const defaultOutputDir = ".reactscope/";
298
+ let config = buildDefaultConfig(detected, defaultTokenFile, defaultOutputDir);
299
+ if (options.yes) {
300
+ process.stdout.write("\n\u{1F50D} Detected project settings:\n");
301
+ process.stdout.write(` Framework : ${detected.framework}
302
+ `);
303
+ process.stdout.write(` TypeScript : ${detected.typescript}
304
+ `);
305
+ process.stdout.write(` Include globs : ${config.components.include.join(", ")}
306
+ `);
307
+ process.stdout.write(` Token file : ${config.tokens.file}
308
+ `);
309
+ process.stdout.write(` Output dir : ${config.output.dir}
310
+
311
+ `);
312
+ } else {
313
+ const rl = createRL();
314
+ process.stdout.write("\n\u{1F680} scope init \u2014 project configuration\n");
315
+ process.stdout.write(" Press Enter to accept the detected value shown in brackets.\n\n");
316
+ try {
317
+ process.stdout.write(` Detected framework: ${detected.framework}
318
+ `);
319
+ const includeRaw = await askWithDefault(
320
+ rl,
321
+ "Component include patterns (comma-separated)",
322
+ config.components.include.join(", ")
323
+ );
324
+ config.components.include = includeRaw.split(",").map((s) => s.trim()).filter(Boolean);
325
+ const excludeRaw = await askWithDefault(
326
+ rl,
327
+ "Component exclude patterns (comma-separated)",
328
+ config.components.exclude.join(", ")
329
+ );
330
+ config.components.exclude = excludeRaw.split(",").map((s) => s.trim()).filter(Boolean);
331
+ const tokenFile = await askWithDefault(rl, "Token file location", config.tokens.file);
332
+ config.tokens.file = tokenFile;
333
+ config.ci.baselinePath = `${config.output.dir}baseline/`;
334
+ const outputDir = await askWithDefault(rl, "Output directory", config.output.dir);
335
+ config.output.dir = outputDir.endsWith("/") ? outputDir : `${outputDir}/`;
336
+ config.ci.baselinePath = `${config.output.dir}baseline/`;
337
+ config = buildDefaultConfig(detected, config.tokens.file, config.output.dir);
338
+ config.components.include = includeRaw.split(",").map((s) => s.trim()).filter(Boolean);
339
+ config.components.exclude = excludeRaw.split(",").map((s) => s.trim()).filter(Boolean);
340
+ } finally {
341
+ rl.close();
342
+ }
343
+ process.stdout.write("\n");
344
+ }
345
+ const cfgPath = scaffoldConfig(rootDir, config);
346
+ created.push(cfgPath);
347
+ const tokPath = scaffoldTokenFile(rootDir, config.tokens.file);
348
+ created.push(tokPath);
349
+ const outDirPath = scaffoldOutputDir(rootDir, config.output.dir);
350
+ created.push(outDirPath);
351
+ ensureGitignoreEntry(rootDir, config.output.dir);
352
+ process.stdout.write("\u2705 Scope project initialised!\n\n");
353
+ process.stdout.write(" Created files:\n");
354
+ for (const p of created) {
355
+ process.stdout.write(` ${p}
356
+ `);
357
+ }
358
+ process.stdout.write("\n Next steps: run `scope manifest` to scan your components.\n\n");
359
+ return {
360
+ success: true,
361
+ message: "Project initialised successfully.",
362
+ created,
363
+ skipped: false
364
+ };
365
+ }
366
+ function createInitCommand() {
367
+ return new commander.Command("init").description("Initialise a Scope project \u2014 scaffold reactscope.config.json and friends").option("-y, --yes", "Accept all detected defaults without prompting", false).option("--force", "Overwrite existing reactscope.config.json if present", false).action(async (opts) => {
368
+ try {
369
+ const result = await runInit({ yes: opts.yes, force: opts.force });
370
+ if (!result.success && !result.skipped) {
371
+ process.exit(1);
372
+ }
373
+ } catch (err) {
374
+ process.stderr.write(`Error: ${err instanceof Error ? err.message : String(err)}
375
+ `);
376
+ process.exit(1);
377
+ }
378
+ });
379
+ }
35
380
 
36
381
  // src/manifest-formatter.ts
37
382
  function isTTY() {
@@ -1675,6 +2020,325 @@ function createRenderCommand() {
1675
2020
  registerRenderAll(renderCmd);
1676
2021
  return renderCmd;
1677
2022
  }
2023
+ var DEFAULT_BASELINE_DIR = ".reactscope/baseline";
2024
+ var _pool3 = null;
2025
+ async function getPool3(viewportWidth, viewportHeight) {
2026
+ if (_pool3 === null) {
2027
+ _pool3 = new render.BrowserPool({
2028
+ size: { browsers: 1, pagesPerBrowser: 4 },
2029
+ viewportWidth,
2030
+ viewportHeight
2031
+ });
2032
+ await _pool3.init();
2033
+ }
2034
+ return _pool3;
2035
+ }
2036
+ async function shutdownPool3() {
2037
+ if (_pool3 !== null) {
2038
+ await _pool3.close();
2039
+ _pool3 = null;
2040
+ }
2041
+ }
2042
+ async function renderComponent(filePath, componentName, props, viewportWidth, viewportHeight) {
2043
+ const pool = await getPool3(viewportWidth, viewportHeight);
2044
+ const htmlHarness = await buildComponentHarness(filePath, componentName, props, viewportWidth);
2045
+ const slot = await pool.acquire();
2046
+ const { page } = slot;
2047
+ try {
2048
+ await page.setContent(htmlHarness, { waitUntil: "load" });
2049
+ await page.waitForFunction(
2050
+ () => {
2051
+ const w = window;
2052
+ return w.__SCOPE_RENDER_COMPLETE__ === true;
2053
+ },
2054
+ { timeout: 15e3 }
2055
+ );
2056
+ const renderError = await page.evaluate(() => {
2057
+ return window.__SCOPE_RENDER_ERROR__ ?? null;
2058
+ });
2059
+ if (renderError !== null) {
2060
+ throw new Error(`Component render error: ${renderError}`);
2061
+ }
2062
+ const rootDir = process.cwd();
2063
+ const classes = await page.evaluate(() => {
2064
+ const set = /* @__PURE__ */ new Set();
2065
+ document.querySelectorAll("[class]").forEach((el) => {
2066
+ for (const c of el.className.split(/\s+/)) {
2067
+ if (c) set.add(c);
2068
+ }
2069
+ });
2070
+ return [...set];
2071
+ });
2072
+ const projectCss = await getCompiledCssForClasses(rootDir, classes);
2073
+ if (projectCss != null && projectCss.length > 0) {
2074
+ await page.addStyleTag({ content: projectCss });
2075
+ }
2076
+ const startMs = performance.now();
2077
+ const rootLocator = page.locator("[data-reactscope-root]");
2078
+ const boundingBox = await rootLocator.boundingBox();
2079
+ if (boundingBox === null || boundingBox.width === 0 || boundingBox.height === 0) {
2080
+ throw new Error(
2081
+ `Component "${componentName}" rendered with zero bounding box \u2014 it may be invisible or not mounted`
2082
+ );
2083
+ }
2084
+ const PAD = 24;
2085
+ const MIN_W = 320;
2086
+ const MIN_H = 200;
2087
+ const clipX = Math.max(0, boundingBox.x - PAD);
2088
+ const clipY = Math.max(0, boundingBox.y - PAD);
2089
+ const rawW = boundingBox.width + PAD * 2;
2090
+ const rawH = boundingBox.height + PAD * 2;
2091
+ const clipW = Math.max(rawW, MIN_W);
2092
+ const clipH = Math.max(rawH, MIN_H);
2093
+ const safeW = Math.min(clipW, viewportWidth - clipX);
2094
+ const safeH = Math.min(clipH, viewportHeight - clipY);
2095
+ const screenshot = await page.screenshot({
2096
+ clip: { x: clipX, y: clipY, width: safeW, height: safeH },
2097
+ type: "png"
2098
+ });
2099
+ const computedStylesRaw = {};
2100
+ const styles = await page.evaluate((sel) => {
2101
+ const el = document.querySelector(sel);
2102
+ if (el === null) return {};
2103
+ const computed = window.getComputedStyle(el);
2104
+ const out = {};
2105
+ for (const prop of [
2106
+ "display",
2107
+ "width",
2108
+ "height",
2109
+ "color",
2110
+ "backgroundColor",
2111
+ "fontSize",
2112
+ "fontFamily",
2113
+ "padding",
2114
+ "margin"
2115
+ ]) {
2116
+ out[prop] = computed.getPropertyValue(prop);
2117
+ }
2118
+ return out;
2119
+ }, "[data-reactscope-root] > *");
2120
+ computedStylesRaw["[data-reactscope-root] > *"] = styles;
2121
+ const renderTimeMs = performance.now() - startMs;
2122
+ return {
2123
+ screenshot,
2124
+ width: Math.round(safeW),
2125
+ height: Math.round(safeH),
2126
+ renderTimeMs,
2127
+ computedStyles: computedStylesRaw
2128
+ };
2129
+ } finally {
2130
+ pool.release(slot);
2131
+ }
2132
+ }
2133
+ function extractComputedStyles(computedStylesRaw) {
2134
+ const flat = {};
2135
+ for (const styles of Object.values(computedStylesRaw)) {
2136
+ Object.assign(flat, styles);
2137
+ }
2138
+ const colors = {};
2139
+ const spacing = {};
2140
+ const typography = {};
2141
+ const borders = {};
2142
+ const shadows = {};
2143
+ for (const [prop, value] of Object.entries(flat)) {
2144
+ if (prop === "color" || prop === "backgroundColor") {
2145
+ colors[prop] = value;
2146
+ } else if (prop === "padding" || prop === "margin") {
2147
+ spacing[prop] = value;
2148
+ } else if (prop === "fontSize" || prop === "fontFamily" || prop === "fontWeight" || prop === "lineHeight") {
2149
+ typography[prop] = value;
2150
+ } else if (prop === "borderRadius" || prop === "borderWidth") {
2151
+ borders[prop] = value;
2152
+ } else if (prop === "boxShadow") {
2153
+ shadows[prop] = value;
2154
+ }
2155
+ }
2156
+ return { colors, spacing, typography, borders, shadows };
2157
+ }
2158
+ async function runBaseline(options = {}) {
2159
+ const {
2160
+ outputDir = DEFAULT_BASELINE_DIR,
2161
+ componentsGlob,
2162
+ manifestPath,
2163
+ viewportWidth = 375,
2164
+ viewportHeight = 812
2165
+ } = options;
2166
+ const startTime = performance.now();
2167
+ const rootDir = process.cwd();
2168
+ const baselineDir = path.resolve(rootDir, outputDir);
2169
+ const rendersDir = path.resolve(baselineDir, "renders");
2170
+ if (fs.existsSync(baselineDir)) {
2171
+ fs.rmSync(baselineDir, { recursive: true, force: true });
2172
+ }
2173
+ fs.mkdirSync(rendersDir, { recursive: true });
2174
+ let manifest$1;
2175
+ if (manifestPath !== void 0) {
2176
+ const { readFileSync: readFileSync7 } = await import('fs');
2177
+ const absPath = path.resolve(rootDir, manifestPath);
2178
+ if (!fs.existsSync(absPath)) {
2179
+ throw new Error(`Manifest not found at ${absPath}.`);
2180
+ }
2181
+ manifest$1 = JSON.parse(readFileSync7(absPath, "utf-8"));
2182
+ process.stderr.write(`Loaded manifest from ${manifestPath}
2183
+ `);
2184
+ } else {
2185
+ process.stderr.write("Scanning for React components\u2026\n");
2186
+ manifest$1 = await manifest.generateManifest({ rootDir });
2187
+ const count = Object.keys(manifest$1.components).length;
2188
+ process.stderr.write(`Found ${count} components.
2189
+ `);
2190
+ }
2191
+ fs.writeFileSync(path.resolve(baselineDir, "manifest.json"), JSON.stringify(manifest$1, null, 2), "utf-8");
2192
+ let componentNames = Object.keys(manifest$1.components);
2193
+ if (componentsGlob !== void 0) {
2194
+ componentNames = componentNames.filter((name) => matchGlob(componentsGlob, name));
2195
+ process.stderr.write(
2196
+ `Filtered to ${componentNames.length} components matching "${componentsGlob}".
2197
+ `
2198
+ );
2199
+ }
2200
+ const total = componentNames.length;
2201
+ if (total === 0) {
2202
+ process.stderr.write("No components to baseline.\n");
2203
+ const emptyReport = {
2204
+ components: {},
2205
+ totalProperties: 0,
2206
+ totalOnSystem: 0,
2207
+ totalOffSystem: 0,
2208
+ aggregateCompliance: 1,
2209
+ auditedAt: (/* @__PURE__ */ new Date()).toISOString()
2210
+ };
2211
+ fs.writeFileSync(
2212
+ path.resolve(baselineDir, "compliance.json"),
2213
+ JSON.stringify(emptyReport, null, 2),
2214
+ "utf-8"
2215
+ );
2216
+ return {
2217
+ baselineDir,
2218
+ componentCount: 0,
2219
+ failureCount: 0,
2220
+ wallClockMs: performance.now() - startTime
2221
+ };
2222
+ }
2223
+ process.stderr.write(`Rendering ${total} components\u2026
2224
+ `);
2225
+ const computedStylesMap = /* @__PURE__ */ new Map();
2226
+ let completed = 0;
2227
+ let failureCount = 0;
2228
+ const CONCURRENCY = 4;
2229
+ let nextIdx = 0;
2230
+ const renderOne = async (name) => {
2231
+ const descriptor = manifest$1.components[name];
2232
+ if (descriptor === void 0) return;
2233
+ const filePath = path.resolve(rootDir, descriptor.filePath);
2234
+ const outcome = await render.safeRender(
2235
+ () => renderComponent(filePath, name, {}, viewportWidth, viewportHeight),
2236
+ {
2237
+ props: {},
2238
+ sourceLocation: {
2239
+ file: descriptor.filePath,
2240
+ line: descriptor.loc.start,
2241
+ column: 0
2242
+ }
2243
+ }
2244
+ );
2245
+ completed++;
2246
+ const pct = Math.round(completed / total * 100);
2247
+ if (isTTY()) {
2248
+ process.stderr.write(`${renderProgressBar(completed, total, name, pct)}\r`);
2249
+ }
2250
+ if (outcome.crashed) {
2251
+ failureCount++;
2252
+ const errPath = path.resolve(rendersDir, `${name}.error.json`);
2253
+ fs.writeFileSync(
2254
+ errPath,
2255
+ JSON.stringify(
2256
+ {
2257
+ component: name,
2258
+ errorMessage: outcome.error.message,
2259
+ heuristicFlags: outcome.error.heuristicFlags,
2260
+ propsAtCrash: outcome.error.propsAtCrash
2261
+ },
2262
+ null,
2263
+ 2
2264
+ ),
2265
+ "utf-8"
2266
+ );
2267
+ return;
2268
+ }
2269
+ const result = outcome.result;
2270
+ fs.writeFileSync(path.resolve(rendersDir, `${name}.png`), result.screenshot);
2271
+ const jsonOutput = formatRenderJson(name, {}, result);
2272
+ fs.writeFileSync(
2273
+ path.resolve(rendersDir, `${name}.json`),
2274
+ JSON.stringify(jsonOutput, null, 2),
2275
+ "utf-8"
2276
+ );
2277
+ computedStylesMap.set(name, extractComputedStyles(result.computedStyles));
2278
+ };
2279
+ const worker = async () => {
2280
+ while (nextIdx < componentNames.length) {
2281
+ const i = nextIdx++;
2282
+ const name = componentNames[i];
2283
+ if (name !== void 0) {
2284
+ await renderOne(name);
2285
+ }
2286
+ }
2287
+ };
2288
+ const workers = [];
2289
+ for (let w = 0; w < Math.min(CONCURRENCY, total); w++) {
2290
+ workers.push(worker());
2291
+ }
2292
+ await Promise.all(workers);
2293
+ await shutdownPool3();
2294
+ if (isTTY()) {
2295
+ process.stderr.write("\n");
2296
+ }
2297
+ const resolver = new tokens.TokenResolver([]);
2298
+ const engine = new tokens.ComplianceEngine(resolver);
2299
+ const batchReport = engine.auditBatch(computedStylesMap);
2300
+ fs.writeFileSync(
2301
+ path.resolve(baselineDir, "compliance.json"),
2302
+ JSON.stringify(batchReport, null, 2),
2303
+ "utf-8"
2304
+ );
2305
+ const wallClockMs = performance.now() - startTime;
2306
+ const successCount = total - failureCount;
2307
+ process.stderr.write(
2308
+ `
2309
+ Baseline complete: ${successCount}/${total} components rendered` + (failureCount > 0 ? ` (${failureCount} failed)` : "") + ` in ${(wallClockMs / 1e3).toFixed(1)}s
2310
+ `
2311
+ );
2312
+ process.stderr.write(`Snapshot saved to ${baselineDir}
2313
+ `);
2314
+ return { baselineDir, componentCount: total, failureCount, wallClockMs };
2315
+ }
2316
+ function registerBaselineSubCommand(reportCmd) {
2317
+ reportCmd.command("baseline").description("Capture a baseline snapshot (manifest + renders + compliance) for later diffing").option(
2318
+ "-o, --output <dir>",
2319
+ "Output directory for the baseline snapshot",
2320
+ DEFAULT_BASELINE_DIR
2321
+ ).option("--components <glob>", "Glob pattern to baseline a subset of components").option("--manifest <path>", "Path to an existing manifest.json to use instead of regenerating").option("--viewport <WxH>", "Viewport size, e.g. 1280x720", "375x812").action(
2322
+ async (opts) => {
2323
+ try {
2324
+ const [wStr, hStr] = opts.viewport.split("x");
2325
+ const viewportWidth = Number.parseInt(wStr ?? "375", 10);
2326
+ const viewportHeight = Number.parseInt(hStr ?? "812", 10);
2327
+ await runBaseline({
2328
+ outputDir: opts.output,
2329
+ componentsGlob: opts.components,
2330
+ manifestPath: opts.manifest,
2331
+ viewportWidth,
2332
+ viewportHeight
2333
+ });
2334
+ } catch (err) {
2335
+ process.stderr.write(`Error: ${err instanceof Error ? err.message : String(err)}
2336
+ `);
2337
+ process.exit(1);
2338
+ }
2339
+ }
2340
+ );
2341
+ }
1678
2342
 
1679
2343
  // src/tree-formatter.ts
1680
2344
  var BRANCH = "\u251C\u2500\u2500 ";
@@ -2384,13 +3048,20 @@ function createProgram(options = {}) {
2384
3048
  program.addCommand(createRenderCommand());
2385
3049
  program.addCommand(createTokensCommand());
2386
3050
  program.addCommand(createInstrumentCommand());
3051
+ program.addCommand(createInitCommand());
3052
+ const existingReportCmd = program.commands.find((c) => c.name() === "report");
3053
+ if (existingReportCmd !== void 0) {
3054
+ registerBaselineSubCommand(existingReportCmd);
3055
+ }
2387
3056
  return program;
2388
3057
  }
2389
3058
 
3059
+ exports.createInitCommand = createInitCommand;
2390
3060
  exports.createManifestCommand = createManifestCommand;
2391
3061
  exports.createProgram = createProgram;
2392
3062
  exports.createTokensCommand = createTokensCommand;
2393
3063
  exports.isTTY = isTTY;
2394
3064
  exports.matchGlob = matchGlob;
3065
+ exports.runInit = runInit;
2395
3066
  //# sourceMappingURL=index.cjs.map
2396
3067
  //# sourceMappingURL=index.cjs.map