@agent-scope/cli 1.9.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.js CHANGED
@@ -1,4 +1,4 @@
1
- import { existsSync, readFileSync, writeFileSync, mkdirSync, appendFileSync, readdirSync } from 'fs';
1
+ import { existsSync, readFileSync, writeFileSync, mkdirSync, appendFileSync, readdirSync, rmSync } from 'fs';
2
2
  import { join, resolve, dirname } from 'path';
3
3
  import * as readline from 'readline';
4
4
  import { Command } from 'commander';
@@ -8,7 +8,7 @@ import { chromium } from 'playwright';
8
8
  import { safeRender, ALL_CONTEXT_IDS, contextAxis, stressAxis, ALL_STRESS_IDS, RenderMatrix, SatoriRenderer, BrowserPool } from '@agent-scope/render';
9
9
  import * as esbuild from 'esbuild';
10
10
  import { createRequire } from 'module';
11
- import { TokenResolver, validateTokenFile, TokenValidationError, parseTokenFileSync, TokenParseError } from '@agent-scope/tokens';
11
+ import { TokenResolver, validateTokenFile, TokenValidationError, parseTokenFileSync, TokenParseError, ComplianceEngine } from '@agent-scope/tokens';
12
12
 
13
13
  // src/init/index.ts
14
14
  function hasConfigFile(dir, stem) {
@@ -205,9 +205,9 @@ function createRL() {
205
205
  });
206
206
  }
207
207
  async function ask(rl, question) {
208
- return new Promise((resolve6) => {
208
+ return new Promise((resolve7) => {
209
209
  rl.question(question, (answer) => {
210
- resolve6(answer.trim());
210
+ resolve7(answer.trim());
211
211
  });
212
212
  });
213
213
  }
@@ -1997,6 +1997,325 @@ function createRenderCommand() {
1997
1997
  registerRenderAll(renderCmd);
1998
1998
  return renderCmd;
1999
1999
  }
2000
+ var DEFAULT_BASELINE_DIR = ".reactscope/baseline";
2001
+ var _pool3 = null;
2002
+ async function getPool3(viewportWidth, viewportHeight) {
2003
+ if (_pool3 === null) {
2004
+ _pool3 = new BrowserPool({
2005
+ size: { browsers: 1, pagesPerBrowser: 4 },
2006
+ viewportWidth,
2007
+ viewportHeight
2008
+ });
2009
+ await _pool3.init();
2010
+ }
2011
+ return _pool3;
2012
+ }
2013
+ async function shutdownPool3() {
2014
+ if (_pool3 !== null) {
2015
+ await _pool3.close();
2016
+ _pool3 = null;
2017
+ }
2018
+ }
2019
+ async function renderComponent(filePath, componentName, props, viewportWidth, viewportHeight) {
2020
+ const pool = await getPool3(viewportWidth, viewportHeight);
2021
+ const htmlHarness = await buildComponentHarness(filePath, componentName, props, viewportWidth);
2022
+ const slot = await pool.acquire();
2023
+ const { page } = slot;
2024
+ try {
2025
+ await page.setContent(htmlHarness, { waitUntil: "load" });
2026
+ await page.waitForFunction(
2027
+ () => {
2028
+ const w = window;
2029
+ return w.__SCOPE_RENDER_COMPLETE__ === true;
2030
+ },
2031
+ { timeout: 15e3 }
2032
+ );
2033
+ const renderError = await page.evaluate(() => {
2034
+ return window.__SCOPE_RENDER_ERROR__ ?? null;
2035
+ });
2036
+ if (renderError !== null) {
2037
+ throw new Error(`Component render error: ${renderError}`);
2038
+ }
2039
+ const rootDir = process.cwd();
2040
+ const classes = await page.evaluate(() => {
2041
+ const set = /* @__PURE__ */ new Set();
2042
+ document.querySelectorAll("[class]").forEach((el) => {
2043
+ for (const c of el.className.split(/\s+/)) {
2044
+ if (c) set.add(c);
2045
+ }
2046
+ });
2047
+ return [...set];
2048
+ });
2049
+ const projectCss = await getCompiledCssForClasses(rootDir, classes);
2050
+ if (projectCss != null && projectCss.length > 0) {
2051
+ await page.addStyleTag({ content: projectCss });
2052
+ }
2053
+ const startMs = performance.now();
2054
+ const rootLocator = page.locator("[data-reactscope-root]");
2055
+ const boundingBox = await rootLocator.boundingBox();
2056
+ if (boundingBox === null || boundingBox.width === 0 || boundingBox.height === 0) {
2057
+ throw new Error(
2058
+ `Component "${componentName}" rendered with zero bounding box \u2014 it may be invisible or not mounted`
2059
+ );
2060
+ }
2061
+ const PAD = 24;
2062
+ const MIN_W = 320;
2063
+ const MIN_H = 200;
2064
+ const clipX = Math.max(0, boundingBox.x - PAD);
2065
+ const clipY = Math.max(0, boundingBox.y - PAD);
2066
+ const rawW = boundingBox.width + PAD * 2;
2067
+ const rawH = boundingBox.height + PAD * 2;
2068
+ const clipW = Math.max(rawW, MIN_W);
2069
+ const clipH = Math.max(rawH, MIN_H);
2070
+ const safeW = Math.min(clipW, viewportWidth - clipX);
2071
+ const safeH = Math.min(clipH, viewportHeight - clipY);
2072
+ const screenshot = await page.screenshot({
2073
+ clip: { x: clipX, y: clipY, width: safeW, height: safeH },
2074
+ type: "png"
2075
+ });
2076
+ const computedStylesRaw = {};
2077
+ const styles = await page.evaluate((sel) => {
2078
+ const el = document.querySelector(sel);
2079
+ if (el === null) return {};
2080
+ const computed = window.getComputedStyle(el);
2081
+ const out = {};
2082
+ for (const prop of [
2083
+ "display",
2084
+ "width",
2085
+ "height",
2086
+ "color",
2087
+ "backgroundColor",
2088
+ "fontSize",
2089
+ "fontFamily",
2090
+ "padding",
2091
+ "margin"
2092
+ ]) {
2093
+ out[prop] = computed.getPropertyValue(prop);
2094
+ }
2095
+ return out;
2096
+ }, "[data-reactscope-root] > *");
2097
+ computedStylesRaw["[data-reactscope-root] > *"] = styles;
2098
+ const renderTimeMs = performance.now() - startMs;
2099
+ return {
2100
+ screenshot,
2101
+ width: Math.round(safeW),
2102
+ height: Math.round(safeH),
2103
+ renderTimeMs,
2104
+ computedStyles: computedStylesRaw
2105
+ };
2106
+ } finally {
2107
+ pool.release(slot);
2108
+ }
2109
+ }
2110
+ function extractComputedStyles(computedStylesRaw) {
2111
+ const flat = {};
2112
+ for (const styles of Object.values(computedStylesRaw)) {
2113
+ Object.assign(flat, styles);
2114
+ }
2115
+ const colors = {};
2116
+ const spacing = {};
2117
+ const typography = {};
2118
+ const borders = {};
2119
+ const shadows = {};
2120
+ for (const [prop, value] of Object.entries(flat)) {
2121
+ if (prop === "color" || prop === "backgroundColor") {
2122
+ colors[prop] = value;
2123
+ } else if (prop === "padding" || prop === "margin") {
2124
+ spacing[prop] = value;
2125
+ } else if (prop === "fontSize" || prop === "fontFamily" || prop === "fontWeight" || prop === "lineHeight") {
2126
+ typography[prop] = value;
2127
+ } else if (prop === "borderRadius" || prop === "borderWidth") {
2128
+ borders[prop] = value;
2129
+ } else if (prop === "boxShadow") {
2130
+ shadows[prop] = value;
2131
+ }
2132
+ }
2133
+ return { colors, spacing, typography, borders, shadows };
2134
+ }
2135
+ async function runBaseline(options = {}) {
2136
+ const {
2137
+ outputDir = DEFAULT_BASELINE_DIR,
2138
+ componentsGlob,
2139
+ manifestPath,
2140
+ viewportWidth = 375,
2141
+ viewportHeight = 812
2142
+ } = options;
2143
+ const startTime = performance.now();
2144
+ const rootDir = process.cwd();
2145
+ const baselineDir = resolve(rootDir, outputDir);
2146
+ const rendersDir = resolve(baselineDir, "renders");
2147
+ if (existsSync(baselineDir)) {
2148
+ rmSync(baselineDir, { recursive: true, force: true });
2149
+ }
2150
+ mkdirSync(rendersDir, { recursive: true });
2151
+ let manifest;
2152
+ if (manifestPath !== void 0) {
2153
+ const { readFileSync: readFileSync7 } = await import('fs');
2154
+ const absPath = resolve(rootDir, manifestPath);
2155
+ if (!existsSync(absPath)) {
2156
+ throw new Error(`Manifest not found at ${absPath}.`);
2157
+ }
2158
+ manifest = JSON.parse(readFileSync7(absPath, "utf-8"));
2159
+ process.stderr.write(`Loaded manifest from ${manifestPath}
2160
+ `);
2161
+ } else {
2162
+ process.stderr.write("Scanning for React components\u2026\n");
2163
+ manifest = await generateManifest({ rootDir });
2164
+ const count = Object.keys(manifest.components).length;
2165
+ process.stderr.write(`Found ${count} components.
2166
+ `);
2167
+ }
2168
+ writeFileSync(resolve(baselineDir, "manifest.json"), JSON.stringify(manifest, null, 2), "utf-8");
2169
+ let componentNames = Object.keys(manifest.components);
2170
+ if (componentsGlob !== void 0) {
2171
+ componentNames = componentNames.filter((name) => matchGlob(componentsGlob, name));
2172
+ process.stderr.write(
2173
+ `Filtered to ${componentNames.length} components matching "${componentsGlob}".
2174
+ `
2175
+ );
2176
+ }
2177
+ const total = componentNames.length;
2178
+ if (total === 0) {
2179
+ process.stderr.write("No components to baseline.\n");
2180
+ const emptyReport = {
2181
+ components: {},
2182
+ totalProperties: 0,
2183
+ totalOnSystem: 0,
2184
+ totalOffSystem: 0,
2185
+ aggregateCompliance: 1,
2186
+ auditedAt: (/* @__PURE__ */ new Date()).toISOString()
2187
+ };
2188
+ writeFileSync(
2189
+ resolve(baselineDir, "compliance.json"),
2190
+ JSON.stringify(emptyReport, null, 2),
2191
+ "utf-8"
2192
+ );
2193
+ return {
2194
+ baselineDir,
2195
+ componentCount: 0,
2196
+ failureCount: 0,
2197
+ wallClockMs: performance.now() - startTime
2198
+ };
2199
+ }
2200
+ process.stderr.write(`Rendering ${total} components\u2026
2201
+ `);
2202
+ const computedStylesMap = /* @__PURE__ */ new Map();
2203
+ let completed = 0;
2204
+ let failureCount = 0;
2205
+ const CONCURRENCY = 4;
2206
+ let nextIdx = 0;
2207
+ const renderOne = async (name) => {
2208
+ const descriptor = manifest.components[name];
2209
+ if (descriptor === void 0) return;
2210
+ const filePath = resolve(rootDir, descriptor.filePath);
2211
+ const outcome = await safeRender(
2212
+ () => renderComponent(filePath, name, {}, viewportWidth, viewportHeight),
2213
+ {
2214
+ props: {},
2215
+ sourceLocation: {
2216
+ file: descriptor.filePath,
2217
+ line: descriptor.loc.start,
2218
+ column: 0
2219
+ }
2220
+ }
2221
+ );
2222
+ completed++;
2223
+ const pct = Math.round(completed / total * 100);
2224
+ if (isTTY()) {
2225
+ process.stderr.write(`${renderProgressBar(completed, total, name, pct)}\r`);
2226
+ }
2227
+ if (outcome.crashed) {
2228
+ failureCount++;
2229
+ const errPath = resolve(rendersDir, `${name}.error.json`);
2230
+ writeFileSync(
2231
+ errPath,
2232
+ JSON.stringify(
2233
+ {
2234
+ component: name,
2235
+ errorMessage: outcome.error.message,
2236
+ heuristicFlags: outcome.error.heuristicFlags,
2237
+ propsAtCrash: outcome.error.propsAtCrash
2238
+ },
2239
+ null,
2240
+ 2
2241
+ ),
2242
+ "utf-8"
2243
+ );
2244
+ return;
2245
+ }
2246
+ const result = outcome.result;
2247
+ writeFileSync(resolve(rendersDir, `${name}.png`), result.screenshot);
2248
+ const jsonOutput = formatRenderJson(name, {}, result);
2249
+ writeFileSync(
2250
+ resolve(rendersDir, `${name}.json`),
2251
+ JSON.stringify(jsonOutput, null, 2),
2252
+ "utf-8"
2253
+ );
2254
+ computedStylesMap.set(name, extractComputedStyles(result.computedStyles));
2255
+ };
2256
+ const worker = async () => {
2257
+ while (nextIdx < componentNames.length) {
2258
+ const i = nextIdx++;
2259
+ const name = componentNames[i];
2260
+ if (name !== void 0) {
2261
+ await renderOne(name);
2262
+ }
2263
+ }
2264
+ };
2265
+ const workers = [];
2266
+ for (let w = 0; w < Math.min(CONCURRENCY, total); w++) {
2267
+ workers.push(worker());
2268
+ }
2269
+ await Promise.all(workers);
2270
+ await shutdownPool3();
2271
+ if (isTTY()) {
2272
+ process.stderr.write("\n");
2273
+ }
2274
+ const resolver = new TokenResolver([]);
2275
+ const engine = new ComplianceEngine(resolver);
2276
+ const batchReport = engine.auditBatch(computedStylesMap);
2277
+ writeFileSync(
2278
+ resolve(baselineDir, "compliance.json"),
2279
+ JSON.stringify(batchReport, null, 2),
2280
+ "utf-8"
2281
+ );
2282
+ const wallClockMs = performance.now() - startTime;
2283
+ const successCount = total - failureCount;
2284
+ process.stderr.write(
2285
+ `
2286
+ Baseline complete: ${successCount}/${total} components rendered` + (failureCount > 0 ? ` (${failureCount} failed)` : "") + ` in ${(wallClockMs / 1e3).toFixed(1)}s
2287
+ `
2288
+ );
2289
+ process.stderr.write(`Snapshot saved to ${baselineDir}
2290
+ `);
2291
+ return { baselineDir, componentCount: total, failureCount, wallClockMs };
2292
+ }
2293
+ function registerBaselineSubCommand(reportCmd) {
2294
+ reportCmd.command("baseline").description("Capture a baseline snapshot (manifest + renders + compliance) for later diffing").option(
2295
+ "-o, --output <dir>",
2296
+ "Output directory for the baseline snapshot",
2297
+ DEFAULT_BASELINE_DIR
2298
+ ).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(
2299
+ async (opts) => {
2300
+ try {
2301
+ const [wStr, hStr] = opts.viewport.split("x");
2302
+ const viewportWidth = Number.parseInt(wStr ?? "375", 10);
2303
+ const viewportHeight = Number.parseInt(hStr ?? "812", 10);
2304
+ await runBaseline({
2305
+ outputDir: opts.output,
2306
+ componentsGlob: opts.components,
2307
+ manifestPath: opts.manifest,
2308
+ viewportWidth,
2309
+ viewportHeight
2310
+ });
2311
+ } catch (err) {
2312
+ process.stderr.write(`Error: ${err instanceof Error ? err.message : String(err)}
2313
+ `);
2314
+ process.exit(1);
2315
+ }
2316
+ }
2317
+ );
2318
+ }
2000
2319
 
2001
2320
  // src/tree-formatter.ts
2002
2321
  var BRANCH = "\u251C\u2500\u2500 ";
@@ -2707,6 +3026,10 @@ function createProgram(options = {}) {
2707
3026
  program.addCommand(createTokensCommand());
2708
3027
  program.addCommand(createInstrumentCommand());
2709
3028
  program.addCommand(createInitCommand());
3029
+ const existingReportCmd = program.commands.find((c) => c.name() === "report");
3030
+ if (existingReportCmd !== void 0) {
3031
+ registerBaselineSubCommand(existingReportCmd);
3032
+ }
2710
3033
  return program;
2711
3034
  }
2712
3035