@agent-scope/cli 1.18.1 → 1.20.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/cli.js +907 -292
- package/dist/cli.js.map +1 -1
- package/dist/index.cjs +716 -108
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +30 -1
- package/dist/index.d.ts +30 -1
- package/dist/index.js +716 -110
- package/dist/index.js.map +1 -1
- package/package.json +9 -8
package/dist/index.cjs
CHANGED
|
@@ -191,13 +191,15 @@ function buildTable(headers, rows) {
|
|
|
191
191
|
}
|
|
192
192
|
function formatListTable(rows) {
|
|
193
193
|
if (rows.length === 0) return "No components found.";
|
|
194
|
-
const headers = ["NAME", "FILE", "COMPLEXITY", "HOOKS", "CONTEXTS"];
|
|
194
|
+
const headers = ["NAME", "FILE", "COMPLEXITY", "HOOKS", "CONTEXTS", "COLLECTION", "INTERNAL"];
|
|
195
195
|
const tableRows = rows.map((r) => [
|
|
196
196
|
r.name,
|
|
197
197
|
r.file,
|
|
198
198
|
r.complexityClass,
|
|
199
199
|
String(r.hookCount),
|
|
200
|
-
String(r.contextCount)
|
|
200
|
+
String(r.contextCount),
|
|
201
|
+
r.collection ?? "\u2014",
|
|
202
|
+
r.internal ? "yes" : "no"
|
|
201
203
|
]);
|
|
202
204
|
return buildTable(headers, tableRows);
|
|
203
205
|
}
|
|
@@ -228,6 +230,8 @@ function formatGetTable(name, descriptor) {
|
|
|
228
230
|
` Composes: ${descriptor.composes.join(", ") || "none"}`,
|
|
229
231
|
` Composed By: ${descriptor.composedBy.join(", ") || "none"}`,
|
|
230
232
|
` Side Effects: ${formatSideEffects(descriptor.sideEffects)}`,
|
|
233
|
+
` Collection: ${descriptor.collection ?? "\u2014"}`,
|
|
234
|
+
` Internal: ${descriptor.internal}`,
|
|
231
235
|
"",
|
|
232
236
|
` Props (${propNames.length}):`
|
|
233
237
|
];
|
|
@@ -250,8 +254,16 @@ function formatGetJson(name, descriptor) {
|
|
|
250
254
|
}
|
|
251
255
|
function formatQueryTable(rows, queryDesc) {
|
|
252
256
|
if (rows.length === 0) return `No components match: ${queryDesc}`;
|
|
253
|
-
const headers = ["NAME", "FILE", "COMPLEXITY", "HOOKS", "CONTEXTS"];
|
|
254
|
-
const tableRows = rows.map((r) => [
|
|
257
|
+
const headers = ["NAME", "FILE", "COMPLEXITY", "HOOKS", "CONTEXTS", "COLLECTION", "INTERNAL"];
|
|
258
|
+
const tableRows = rows.map((r) => [
|
|
259
|
+
r.name,
|
|
260
|
+
r.file,
|
|
261
|
+
r.complexityClass,
|
|
262
|
+
r.hooks,
|
|
263
|
+
r.contexts,
|
|
264
|
+
r.collection ?? "\u2014",
|
|
265
|
+
r.internal ? "yes" : "no"
|
|
266
|
+
]);
|
|
255
267
|
return `Query: ${queryDesc}
|
|
256
268
|
|
|
257
269
|
${buildTable(headers, tableRows)}`;
|
|
@@ -541,10 +553,10 @@ async function getCompiledCssForClasses(cwd, classes) {
|
|
|
541
553
|
return build3(deduped);
|
|
542
554
|
}
|
|
543
555
|
async function compileGlobalCssFile(cssFilePath, cwd) {
|
|
544
|
-
const { existsSync:
|
|
556
|
+
const { existsSync: existsSync16, readFileSync: readFileSync14 } = await import('fs');
|
|
545
557
|
const { createRequire: createRequire3 } = await import('module');
|
|
546
|
-
if (!
|
|
547
|
-
const raw =
|
|
558
|
+
if (!existsSync16(cssFilePath)) return null;
|
|
559
|
+
const raw = readFileSync14(cssFilePath, "utf-8");
|
|
548
560
|
const needsCompile = /@tailwind|@import\s+['"]tailwindcss/.test(raw);
|
|
549
561
|
if (!needsCompile) {
|
|
550
562
|
return raw;
|
|
@@ -970,7 +982,7 @@ function parseChecks(raw) {
|
|
|
970
982
|
}
|
|
971
983
|
function createCiCommand() {
|
|
972
984
|
return new commander.Command("ci").description(
|
|
973
|
-
"Run
|
|
985
|
+
"Run the full Scope pipeline non-interactively and exit with a structured code.\n\nPIPELINE STEPS (in order):\n 1. manifest generate scan source, build .reactscope/manifest.json\n 2. render all screenshot every component\n 3. tokens compliance score on-token CSS coverage\n 4. visual regression pixel diff against --baseline (if provided)\n\nCHECKS (--checks flag, comma-separated):\n compliance token coverage below --threshold \u2192 exit 1\n a11y accessibility violations \u2192 exit 2\n console-errors console.error during render \u2192 exit 3\n visual-regression pixel diff against baseline \u2192 exit 4\n (render failures always \u2192 exit 5 regardless of --checks)\n\nEXIT CODES:\n 0 all checks passed\n 1 compliance below threshold\n 2 accessibility violations\n 3 console errors during render\n 4 visual regression detected\n 5 component render failures\n\nExamples:\n scope ci\n scope ci --baseline .reactscope/baseline --threshold 0.95\n scope ci --checks compliance,a11y --json -o ci-result.json\n scope ci --viewport 1280x720"
|
|
974
986
|
).option(
|
|
975
987
|
"-b, --baseline <dir>",
|
|
976
988
|
"Baseline directory for visual regression comparison (omit to skip)"
|
|
@@ -1013,6 +1025,192 @@ function createCiCommand() {
|
|
|
1013
1025
|
}
|
|
1014
1026
|
);
|
|
1015
1027
|
}
|
|
1028
|
+
function collectSourceFiles(dir) {
|
|
1029
|
+
if (!fs.existsSync(dir)) return [];
|
|
1030
|
+
const results = [];
|
|
1031
|
+
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
1032
|
+
const full = path.join(dir, entry.name);
|
|
1033
|
+
if (entry.isDirectory() && entry.name !== "node_modules" && entry.name !== ".reactscope") {
|
|
1034
|
+
results.push(...collectSourceFiles(full));
|
|
1035
|
+
} else if (entry.isFile() && /\.(tsx?|jsx?)$/.test(entry.name)) {
|
|
1036
|
+
results.push(full);
|
|
1037
|
+
}
|
|
1038
|
+
}
|
|
1039
|
+
return results;
|
|
1040
|
+
}
|
|
1041
|
+
function checkConfig(cwd) {
|
|
1042
|
+
const configPath = path.resolve(cwd, "reactscope.config.json");
|
|
1043
|
+
if (!fs.existsSync(configPath)) {
|
|
1044
|
+
return {
|
|
1045
|
+
name: "config",
|
|
1046
|
+
status: "error",
|
|
1047
|
+
message: "reactscope.config.json not found \u2014 run `scope init`"
|
|
1048
|
+
};
|
|
1049
|
+
}
|
|
1050
|
+
try {
|
|
1051
|
+
JSON.parse(fs.readFileSync(configPath, "utf-8"));
|
|
1052
|
+
return { name: "config", status: "ok", message: "reactscope.config.json valid" };
|
|
1053
|
+
} catch {
|
|
1054
|
+
return { name: "config", status: "error", message: "reactscope.config.json is not valid JSON" };
|
|
1055
|
+
}
|
|
1056
|
+
}
|
|
1057
|
+
function checkTokens(cwd) {
|
|
1058
|
+
const configPath = path.resolve(cwd, "reactscope.config.json");
|
|
1059
|
+
let tokensPath = path.resolve(cwd, "reactscope.tokens.json");
|
|
1060
|
+
if (fs.existsSync(configPath)) {
|
|
1061
|
+
try {
|
|
1062
|
+
const cfg = JSON.parse(fs.readFileSync(configPath, "utf-8"));
|
|
1063
|
+
if (cfg.tokens?.file) tokensPath = path.resolve(cwd, cfg.tokens.file);
|
|
1064
|
+
} catch {
|
|
1065
|
+
}
|
|
1066
|
+
}
|
|
1067
|
+
if (!fs.existsSync(tokensPath)) {
|
|
1068
|
+
return {
|
|
1069
|
+
name: "tokens",
|
|
1070
|
+
status: "warn",
|
|
1071
|
+
message: `Token file not found at ${tokensPath} \u2014 run \`scope init\``
|
|
1072
|
+
};
|
|
1073
|
+
}
|
|
1074
|
+
try {
|
|
1075
|
+
const raw = JSON.parse(fs.readFileSync(tokensPath, "utf-8"));
|
|
1076
|
+
if (!raw.version) {
|
|
1077
|
+
return { name: "tokens", status: "warn", message: "Token file is missing a `version` field" };
|
|
1078
|
+
}
|
|
1079
|
+
return { name: "tokens", status: "ok", message: "Token file valid" };
|
|
1080
|
+
} catch {
|
|
1081
|
+
return { name: "tokens", status: "error", message: "Token file is not valid JSON" };
|
|
1082
|
+
}
|
|
1083
|
+
}
|
|
1084
|
+
function checkGlobalCss(cwd) {
|
|
1085
|
+
const configPath = path.resolve(cwd, "reactscope.config.json");
|
|
1086
|
+
let globalCss = [];
|
|
1087
|
+
if (fs.existsSync(configPath)) {
|
|
1088
|
+
try {
|
|
1089
|
+
const cfg = JSON.parse(fs.readFileSync(configPath, "utf-8"));
|
|
1090
|
+
globalCss = cfg.components?.wrappers?.globalCSS ?? [];
|
|
1091
|
+
} catch {
|
|
1092
|
+
}
|
|
1093
|
+
}
|
|
1094
|
+
if (globalCss.length === 0) {
|
|
1095
|
+
return {
|
|
1096
|
+
name: "globalCSS",
|
|
1097
|
+
status: "warn",
|
|
1098
|
+
message: "No globalCSS configured \u2014 Tailwind styles won't apply to renders. Add `components.wrappers.globalCSS` to reactscope.config.json"
|
|
1099
|
+
};
|
|
1100
|
+
}
|
|
1101
|
+
const missing = globalCss.filter((f) => !fs.existsSync(path.resolve(cwd, f)));
|
|
1102
|
+
if (missing.length > 0) {
|
|
1103
|
+
return {
|
|
1104
|
+
name: "globalCSS",
|
|
1105
|
+
status: "error",
|
|
1106
|
+
message: `globalCSS file(s) not found: ${missing.join(", ")}`
|
|
1107
|
+
};
|
|
1108
|
+
}
|
|
1109
|
+
return {
|
|
1110
|
+
name: "globalCSS",
|
|
1111
|
+
status: "ok",
|
|
1112
|
+
message: `${globalCss.length} globalCSS file(s) present`
|
|
1113
|
+
};
|
|
1114
|
+
}
|
|
1115
|
+
function checkManifest(cwd) {
|
|
1116
|
+
const manifestPath = path.resolve(cwd, ".reactscope", "manifest.json");
|
|
1117
|
+
if (!fs.existsSync(manifestPath)) {
|
|
1118
|
+
return {
|
|
1119
|
+
name: "manifest",
|
|
1120
|
+
status: "warn",
|
|
1121
|
+
message: "Manifest not found \u2014 run `scope manifest generate`"
|
|
1122
|
+
};
|
|
1123
|
+
}
|
|
1124
|
+
const manifestMtime = fs.statSync(manifestPath).mtimeMs;
|
|
1125
|
+
const sourceDir = path.resolve(cwd, "src");
|
|
1126
|
+
const sourceFiles = collectSourceFiles(sourceDir);
|
|
1127
|
+
const stale = sourceFiles.filter((f) => fs.statSync(f).mtimeMs > manifestMtime);
|
|
1128
|
+
if (stale.length > 0) {
|
|
1129
|
+
return {
|
|
1130
|
+
name: "manifest",
|
|
1131
|
+
status: "warn",
|
|
1132
|
+
message: `Manifest may be stale \u2014 ${stale.length} source file(s) modified since last generate. Run \`scope manifest generate\``
|
|
1133
|
+
};
|
|
1134
|
+
}
|
|
1135
|
+
return { name: "manifest", status: "ok", message: "Manifest present and up to date" };
|
|
1136
|
+
}
|
|
1137
|
+
var ICONS = { ok: "\u2713", warn: "!", error: "\u2717" };
|
|
1138
|
+
function formatCheck(check) {
|
|
1139
|
+
return ` [${ICONS[check.status]}] ${check.name.padEnd(12)} ${check.message}`;
|
|
1140
|
+
}
|
|
1141
|
+
function createDoctorCommand() {
|
|
1142
|
+
return new commander.Command("doctor").description(
|
|
1143
|
+
`Verify your Scope project setup before running other commands.
|
|
1144
|
+
|
|
1145
|
+
CHECKS PERFORMED:
|
|
1146
|
+
config reactscope.config.json exists and is valid JSON
|
|
1147
|
+
tokens reactscope.tokens.json exists and passes validation
|
|
1148
|
+
css globalCSS files referenced in config actually exist
|
|
1149
|
+
manifest .reactscope/manifest.json exists and is not stale
|
|
1150
|
+
(stale = source files modified after last generate)
|
|
1151
|
+
|
|
1152
|
+
STATUS LEVELS: ok | warn | error
|
|
1153
|
+
|
|
1154
|
+
Run this first whenever renders fail or produce unexpected output.
|
|
1155
|
+
|
|
1156
|
+
Examples:
|
|
1157
|
+
scope doctor
|
|
1158
|
+
scope doctor --json
|
|
1159
|
+
scope doctor --json | jq '.checks[] | select(.status == "error")'`
|
|
1160
|
+
).option("--json", "Emit structured JSON output", false).action((opts) => {
|
|
1161
|
+
const cwd = process.cwd();
|
|
1162
|
+
const checks = [
|
|
1163
|
+
checkConfig(cwd),
|
|
1164
|
+
checkTokens(cwd),
|
|
1165
|
+
checkGlobalCss(cwd),
|
|
1166
|
+
checkManifest(cwd)
|
|
1167
|
+
];
|
|
1168
|
+
const errors = checks.filter((c) => c.status === "error").length;
|
|
1169
|
+
const warnings = checks.filter((c) => c.status === "warn").length;
|
|
1170
|
+
if (opts.json) {
|
|
1171
|
+
process.stdout.write(
|
|
1172
|
+
`${JSON.stringify({ passed: checks.length - errors - warnings, warnings, errors, checks }, null, 2)}
|
|
1173
|
+
`
|
|
1174
|
+
);
|
|
1175
|
+
if (errors > 0) process.exit(1);
|
|
1176
|
+
return;
|
|
1177
|
+
}
|
|
1178
|
+
process.stdout.write("\nScope Doctor\n");
|
|
1179
|
+
process.stdout.write("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n");
|
|
1180
|
+
for (const check of checks) process.stdout.write(`${formatCheck(check)}
|
|
1181
|
+
`);
|
|
1182
|
+
process.stdout.write("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n");
|
|
1183
|
+
if (errors > 0) {
|
|
1184
|
+
process.stdout.write(` ${errors} error(s), ${warnings} warning(s)
|
|
1185
|
+
|
|
1186
|
+
`);
|
|
1187
|
+
process.exit(1);
|
|
1188
|
+
} else if (warnings > 0) {
|
|
1189
|
+
process.stdout.write(` ${warnings} warning(s) \u2014 everything works but could be better
|
|
1190
|
+
|
|
1191
|
+
`);
|
|
1192
|
+
} else {
|
|
1193
|
+
process.stdout.write(" All checks passed!\n\n");
|
|
1194
|
+
}
|
|
1195
|
+
});
|
|
1196
|
+
}
|
|
1197
|
+
|
|
1198
|
+
// src/skill-content.ts
|
|
1199
|
+
var SKILL_CONTENT = '# Scope \u2014 Agent Skill\n\n## TLDR\nScope is a React codebase introspection toolkit. Use it to answer questions about component structure, props, context dependencies, side effects, and visual output \u2014 without running the app.\n\n**When to reach for it:** Any task requiring "which components use X", "what props does Y accept", "render Z for visual verification", "does this component depend on a provider", or "what design tokens are in use".\n\n**3-command workflow:**\n```\nscope init # scaffold config + auto-generate manifest\nscope manifest query --context ThemeContext # ask questions about the codebase\nscope render Button # produce a PNG of a component\n```\n\n---\n\n---\n\n## Mental Model\n\nUnderstanding how Scope\'s data flows is the key to using it effectively as an agent.\n\n```\nSource TypeScript files\n \u2193 (ts-morph AST parse)\n manifest.json \u2190 structural facts: props, hooks, contexts, complexity\n \u2193 (esbuild + Playwright)\n renders/*.json \u2190 visual facts: screenshot, computedStyles, dom, a11y\n \u2193 (token engine)\n compliance-styles.json \u2190 audit facts: which CSS values match tokens, which don\'t\n \u2193 (site generator)\n site/ \u2190 human-readable docs combining all of the above\n```\n\nEach layer depends on the previous. If you\'re getting unexpected results, check whether the earlier layers are stale (run `scope doctor` to diagnose).\n\n---\n\n## The Four Subsystems\n\n### 1. Manifest (`scope manifest *`)\nThe manifest is a static analysis snapshot of your TypeScript source. It tells you:\n- What components exist, where they live, and how they\'re exported\n- What props each component accepts (types, defaults, required/optional)\n- What React hooks they call (`detectedHooks`)\n- What contexts they consume (`requiredContexts`) \u2014 must be provided for a render to succeed\n- Whether they compose other components (`composes` / `composedBy`)\n- Their **complexity class** \u2014 `"simple"` or `"complex"` \u2014 which determines the render engine\n\nThe manifest never runs your code. It only reads TypeScript. This means it\'s fast and safe, but it can\'t know about runtime values.\n\n### 2. Render Engine (`scope render *`)\nThe render engine compiles components with esbuild and renders them in Chromium (Playwright). Two paths exist:\n\n| Path | When | Speed | Capability |\n|------|------|-------|------------|\n| **Satori** | `complexityClass: "simple"` | ~8ms | Flexbox only, no JS, no CSS-in-JS |\n| **BrowserPool** | `complexityClass: "complex"` | ~200\u2013800ms | Full DOM, CSS, Tailwind, animations |\n\nMost real-world components route through BrowserPool. Scope defaults to `"complex"` when uncertain (safe fallback).\n\nEach render produces:\n- `screenshot` \u2014 retina-quality PNG (2\xD7 `deviceScaleFactor`; display at CSS px dimensions)\n- `width` / `height` \u2014 CSS pixel dimensions of the component root\n- `computedStyles` \u2014 per-node computed CSS keyed by `#node-0`, `#node-1`, etc.\n- `dom` \u2014 full DOM tree with bounding boxes (BrowserPool only)\n- `accessibility` \u2014 role, aria-name, violation list (BrowserPool only)\n- `renderTimeMs` \u2014 wall-clock render duration\n\n### 3. Scope Files (`.scope.tsx`)\nScope files let you define **named rendering scenarios** for a component alongside it in the source tree. They are the primary way to ensure `render all` produces meaningful screenshots.\n\n```tsx\n// Button.scope.tsx\nimport type { ScopeFile } from \'@agent-scope/cli\';\nimport { Button } from \'./Button\';\n\nexport default {\n default: { variant: \'primary\', children: \'Click me\' },\n ghost: { variant: \'ghost\', children: \'Cancel\' },\n danger: { variant: \'danger\', children: \'Delete\' },\n disabled: { variant: \'primary\', children: \'Disabled\', disabled: true },\n} satisfies ScopeFile<typeof Button>;\n```\n\nKey rules:\n- The file must be named `<ComponentName>.scope.tsx` in the same directory\n- Export a default object where keys are scenario names and values are props\n- `render all` uses the `default` scenario (or first defined) as the primary screenshot\n- If 2+ scenarios exist, `render all` automatically runs a matrix and merges cells into the component JSON\n- Scenarios also feed the interactive Playground in the docs site\n\nWhen a component renders blank with `{}` props, **the fix is usually to create a `.scope.tsx` file** with real props.\n\n### 4. Token Compliance\nThe compliance pipeline:\n1. `scope render all` captures `computedStyles` for every element in every component\n2. These are written to `.reactscope/compliance-styles.json`\n3. The token engine compares each computed CSS value against your `reactscope.tokens.json`\n4. `scope tokens compliance` reports the aggregate on-system percentage\n5. `scope ci` fails if the percentage is below `complianceThreshold` (default 90%)\n\n**On-system** means the value exactly matches a resolved token value. Off-system means it\'s a hardcoded value with no token backing it.\n\n---\n\n## Complexity Classes \u2014 Practical Guide\n\nThe `complexityClass` field determines which render engine runs. Scope auto-detects it, but agents should understand it:\n\n**`"simple"` components:**\n- Pure presentational, flexbox layout only\n- No CSS grid, no absolute/fixed/sticky positioning\n- No CSS animations, transitions, or transforms\n- No `className` values Scope can\'t statically trace (e.g. dynamic Tailwind classes)\n- Renders in ~8ms via Satori (SVG-based, no browser needed)\n\n**`"complex"` components:**\n- Anything using Tailwind (CSS injection required)\n- CSS grid, positioned elements, overflow, z-index\n- Components that read from context at render time\n- Any component Scope isn\'t sure about (conservative default)\n- Renders in ~200\u2013800ms via Playwright BrowserPool\n\nWhen in doubt: complex is always safe. Simple is an optimization.\n\n---\n\n## Required Contexts \u2014 Why Renders Fail\n\nIf `requiredContexts` is non-empty, the component calls `useContext` on one or more contexts. Without a provider, it will either render broken or throw entirely.\n\nTwo ways to fix:\n1. **Provider presets in config** (recommended): add provider names to `reactscope.config.json \u2192 components.wrappers.providers`\n2. **Scope file with wrapper**: wrap the component in a provider in the scenario itself\n\nBuilt-in mocks (always provided): `ThemeContext \u2192 { theme: \'light\' }`, `LocaleContext \u2192 { locale: \'en-US\' }`.\n\n---\n\n## `scope doctor` \u2014 Always Run This First\n\nBefore debugging any render issue, run:\n```bash\nscope doctor\n```\n\nIt checks:\n- `reactscope.config.json` is valid JSON\n- Token file exists and has a `version` field\n- Every path in `globalCSS` resolves on disk\n- Manifest is present and up to date (not stale relative to source)\n\n**If `globalCSS` is empty or missing**: Tailwind styles won\'t apply to renders. Every component will look unstyled. This is the most common footgun. Fix: add your CSS entry file (the one with `@tailwind base; @tailwind components; @tailwind utilities;`) to `globalCSS` in config.\n\n---\n\n## Agent Decision Tree\n\n**"I want to know what props Component X accepts"**\n\u2192 `scope manifest get X --format json | jq \'.props\'`\n\n**"I want to know which components will break if I change a context"**\n\u2192 `scope manifest query --context MyContext --format json`\n\n**"I want to render a component to verify visual output"**\n\u2192 Create a `.scope.tsx` file with real props first, then `scope render X`\n\n**"I want to render all variants of a component"**\n\u2192 Define all variants in `.scope.tsx`, then `scope render all` (auto-matrix)\n\u2192 Or: `scope render matrix X --axes \'variant:primary,secondary,danger\'`\n\n**"I want to audit token compliance"**\n\u2192 `scope render all` first (populates computedStyles), then `scope tokens compliance`\n\n**"Renders look unstyled / blank"**\n\u2192 Run `scope doctor` \u2014 likely missing `globalCSS`\n\u2192 If props are the issue: create/update the `.scope.tsx` file\n\n**"I want to understand blast radius of a token change"**\n\u2192 `scope tokens impact color.primary.500 --new-value \'#0077dd\'`\n\u2192 `scope tokens preview color.primary.500 --new-value \'#0077dd\'` for visual diff\n\n**"I need to set up Scope in a new project"**\n\u2192 `scope init --yes` (auto-detects Tailwind + CSS, generates manifest automatically)\n\u2192 `scope doctor` to validate\n\u2192 Create `.scope.tsx` files for key components\n\u2192 `scope render all`\n\n**"I want to run Scope in CI"**\n\u2192 `scope ci --json --output ci-result.json`\n\u2192 Exit code 0 = pass, non-zero = specific failure type\n\n---\n\n\n## Installation\n\n```bash\nnpm install -g @agent-scope/cli # global\nnpm install --save-dev @agent-scope/cli # per-project\n```\n\nBinary: `scope`\n\n---\n\n## Core Workflow\n\n```\ninit \u2192 manifest generate \u2192 manifest query/get/list \u2192 render \u2192 (token audit) \u2192 ci\n```\n\n- **init**: Scaffold `reactscope.config.json` + token stub, auto-detect framework/globalCSS, **immediately runs `manifest generate`** so you see results right away.\n- **doctor**: Health-check command \u2014 validates config, token file, globalCSS presence, and manifest staleness.\n- **generate**: Parse TypeScript AST and emit `.reactscope/manifest.json`. Run once per codebase change (or automatically via `scope init`).\n- **query / get / list**: Ask structural questions. No network required. Works from manifest alone. Supports filtering by `--collection` and `--internal`.\n- **render**: Produce PNGs of components via esbuild + Playwright (BrowserPool). Requires manifest for file paths. Auto-injects required prop defaults and globalCSS.\n- **token audit**: Validate design tokens via `@scope/tokens` CLI commands (`tokens list`, `tokens compliance`, `tokens impact`, `tokens preview`, `tokens export`).\n- **ci**: Run compliance checks and exit with code 0/1 for CI pipelines. `report pr-comment` posts results to GitHub PRs.\n\n---\n\n## Full CLI Reference\n\n### `scope init`\nScaffold config, detect framework, extract Tailwind tokens, detect globalCSS files, and **automatically run `scope manifest generate`**.\n\n```bash\nscope init\nscope init --force # overwrite existing config\n```\n\nAfter init completes, the manifest is already written \u2014 no manual `scope manifest generate` step needed.\n\n**Tailwind token extraction**: reads `tailwind.config.js`, extracts colors (with nested scale support), spacing, fontFamily, borderRadius. Stored in `reactscope.tokens.json`.\n\n**globalCSS detection**: checks 9 common patterns (`src/styles.css`, `src/index.css`, `app/globals.css`, etc.). Stored in `components.wrappers.globalCSS` in config.\n\n---\n\n### `scope doctor`\nValidate the Scope setup. Exits non-zero on errors, zero on warnings-only.\n\n```bash\nscope doctor\nscope doctor --json\n```\n\nChecks:\n- `config` \u2014 `reactscope.config.json` is valid JSON with required fields\n- `tokens` \u2014 token file is present and has a valid `version` field\n- `globalCSS` \u2014 globalCSS files listed in config exist on disk\n- `manifest` \u2014 manifest exists and is not stale (compares source file mtimes)\n\n```\n$ scope doctor\nScope Doctor\n\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n [\u2713] config reactscope.config.json valid\n [\u2713] tokens Token file valid\n [\u2713] globalCSS 1 globalCSS file(s) present\n [!] manifest Manifest may be stale \u2014 5 source file(s) modified since last generate\n\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n 1 warning(s) \u2014 everything works but could be better\n```\n\n---\n\n### `scope capture <url>`\nCapture a live React component tree from a running app URL.\n\n```bash\nscope capture http://localhost:3000\nscope capture http://localhost:3000 --output report.json --pretty\nscope capture http://localhost:3000 --timeout 15000 --wait 2000\n```\n\nFlags:\n| Flag | Type | Default | Description |\n|------|------|---------|-------------|\n| `-o, --output <path>` | string | stdout | Write JSON to file |\n| `--pretty` | bool | false | Pretty-print JSON |\n| `--timeout <ms>` | number | 10000 | Max wait for React to mount |\n| `--wait <ms>` | number | 0 | Additional wait after page load |\n\nOutput (stdout): serialized PageReport JSON (or path when `--output` is set)\n\n---\n\n### `scope tree <url>`\nPrint the React component tree from a live URL.\n\n```bash\nscope tree http://localhost:3000\nscope tree http://localhost:3000 --depth 3 --show-props --show-hooks\n```\n\nFlags:\n| Flag | Type | Default | Description |\n|------|------|---------|-------------|\n| `--depth <n>` | number | unlimited | Max depth to display |\n| `--show-props` | bool | false | Include prop names next to components |\n| `--show-hooks` | bool | false | Show hook counts per component |\n| `--timeout <ms>` | number | 10000 | Max wait for React to mount |\n| `--wait <ms>` | number | 0 | Additional wait after page load |\n\n---\n\n### `scope report <url>`\nCapture and print a human-readable summary of a React app.\n\n```bash\nscope report http://localhost:3000\nscope report http://localhost:3000 --json\n```\n\nFlags:\n| Flag | Type | Default | Description |\n|------|------|---------|-------------|\n| `--json` | bool | false | Emit structured JSON instead of text |\n| `--timeout <ms>` | number | 10000 | Max wait for React to mount |\n| `--wait <ms>` | number | 0 | Additional wait after page load |\n\n---\n\n### `scope report baseline`\nSave a baseline snapshot for future diff comparisons.\n\n```bash\nscope report baseline\nscope report baseline --output baselines/my-baseline.json\n```\n\n---\n\n### `scope report diff`\nDiff the current app state against a saved baseline.\n\n```bash\nscope report diff\nscope report diff --baseline baselines/my-baseline.json\nscope report diff --json\n```\n\n---\n\n### `scope report pr-comment`\nPost a Scope CI report as a GitHub PR comment. Used in CI pipelines via the reusable `scope-ci` workflow.\n\n```bash\nscope report pr-comment --report-path scope-ci-report.json\n```\n\nRequires `GITHUB_TOKEN`, `GITHUB_REPOSITORY`, and `GITHUB_PR_NUMBER` in environment.\n\n---\n\n### `scope manifest generate`\nScan source files and write `.reactscope/manifest.json`.\n\n```bash\nscope manifest generate\nscope manifest generate --root ./packages/ui\nscope manifest generate --include "src/**/*.tsx" --exclude "**/*.test.tsx"\nscope manifest generate --output custom/manifest.json\n```\n\nFlags:\n| Flag | Type | Default | Description |\n|------|------|---------|-------------|\n| `--root <path>` | string | cwd | Project root directory |\n| `--output <path>` | string | `.reactscope/manifest.json` | Output path |\n| `--include <globs>` | string | `src/**/*.tsx,src/**/*.ts` | Comma-separated include globs |\n| `--exclude <globs>` | string | `**/node_modules/**,...` | Comma-separated exclude globs |\n\n---\n\n### `scope manifest list`\nList all components in the manifest.\n\n```bash\nscope manifest list\nscope manifest list --filter "Button*"\nscope manifest list --format json\nscope manifest list --collection Forms # filter to named collection\nscope manifest list --internal # only internal components\nscope manifest list --no-internal # hide internal components\n```\n\nFlags:\n| Flag | Type | Default | Description |\n|------|------|---------|-------------|\n| `--format <fmt>` | `json\\|table` | auto (TTY\u2192table, pipe\u2192json) | Output format |\n| `--filter <glob>` | string | \u2014 | Filter component names by glob |\n| `--collection <name>` | string | \u2014 | Filter to named collection |\n| `--internal` | bool | false | Show only internal components |\n| `--no-internal` | bool | false | Hide internal components |\n| `--manifest <path>` | string | `.reactscope/manifest.json` | Manifest path |\n\nTTY table output (includes COLLECTION and INTERNAL columns):\n```\nNAME FILE COMPLEXITY HOOKS CONTEXTS COLLECTION INTERNAL\n------------ --------------------------- ---------- ----- -------- ---------- --------\nButton src/components/Button.tsx simple 1 0 \u2014 no\nThemeToggle src/components/Toggle.tsx complex 3 1 Forms no\n```\n\n---\n\n### `scope manifest get <name>`\nGet full details of a single component.\n\n```bash\nscope manifest get Button\nscope manifest get Button --format json\n```\n\nJSON output includes `collection` and `internal` fields:\n```json\n{\n "name": "Button",\n "filePath": "src/components/Button.tsx",\n "collection": "Primitives",\n "internal": false,\n ...\n}\n```\n\n---\n\n### `scope manifest query`\nQuery components by attributes.\n\n```bash\nscope manifest query --context ThemeContext\nscope manifest query --hook useEffect\nscope manifest query --complexity complex\nscope manifest query --side-effects\nscope manifest query --has-fetch\nscope manifest query --has-prop <propName>\nscope manifest query --composed-by <ComponentName>\nscope manifest query --internal\nscope manifest query --collection Forms\nscope manifest query --context ThemeContext --format json\n```\n\nFlags:\n| Flag | Type | Default | Description |\n|------|------|---------|-------------|\n| `--context <name>` | string | \u2014 | Find components consuming a context by name |\n| `--hook <name>` | string | \u2014 | Find components using a specific hook |\n| `--complexity <class>` | `simple\\|complex` | \u2014 | Filter by complexity class |\n| `--side-effects` | bool | false | Any side effects detected |\n| `--has-fetch` | bool | false | Components with fetch calls specifically |\n| `--has-prop <name>` | string | \u2014 | Components that accept a specific prop |\n| `--composed-by <name>` | string | \u2014 | Components rendered inside a specific parent |\n| `--internal` | bool | false | Only internal components |\n| `--collection <name>` | string | \u2014 | Filter to named collection |\n| `--format <fmt>` | `json\\|table` | auto | Output format |\n| `--manifest <path>` | string | `.reactscope/manifest.json` | Manifest path |\n\n---\n\n### `scope render <component>`\nRender a single component to PNG (TTY) or JSON (pipe).\n\n**Auto prop defaults**: if `--props` is omitted, Scope injects sensible defaults so required props don\'t produce blank renders: strings/nodes \u2192 component name, unions \u2192 first value, booleans \u2192 `false`, numbers \u2192 `0`.\n\n**globalCSS auto-injection**: reads `components.wrappers.globalCSS` from config and compiles/injects CSS (supports Tailwind v3 via PostCSS) into the render harness. A warning is printed to stderr if no globalCSS is configured (common cause of unstyled renders).\n\n```bash\nscope render Button\nscope render Button --props \'{"variant":"primary","children":"Click me"}\'\nscope render Button --viewport 375x812\nscope render Button --output button.png\nscope render Button --format json\n```\n\nFlags:\n| Flag | Type | Default | Description |\n|------|------|---------|-------------|\n| `--props <json>` | string | `{}` | Inline props as JSON string |\n| `--viewport <WxH>` | string | `375x812` | Viewport size |\n| `--theme <name>` | string | \u2014 | Theme name from token system |\n| `-o, --output <path>` | string | \u2014 | Write PNG to specific path |\n| `--format <fmt>` | `png\\|json` | auto (TTY\u2192file, pipe\u2192json) | Output format |\n| `--manifest <path>` | string | `.reactscope/manifest.json` | Manifest path |\n\n---\n\n### `scope render matrix <component>`\nRender across a Cartesian product of prop axes. Accepts both `key:v1,v2` and `{"key":["v1","v2"]}` JSON format for `--axes`.\n\n```bash\nscope render matrix Button --axes \'variant:primary,secondary,danger\'\nscope render matrix Button --axes \'{"variant":["primary","secondary"]}\'\nscope render matrix Button --axes \'variant:primary,secondary size:sm,md,lg\'\nscope render matrix Button --sprite button-matrix.png --format json\n```\n\n---\n\n### `scope render all`\nRender every component in the manifest.\n\n```bash\nscope render all\nscope render all --concurrency 4 --output-dir renders/\n```\n\nHandles imports of CSS files in components (maps to empty loader so styles are injected at page level). SVG and font imports are handled via dataurl loaders.\n\n---\n\n### `scope instrument tree`\nCapture the live React component tree with instrumentation metadata.\n\n```bash\nscope instrument tree http://localhost:3000\nscope instrument tree http://localhost:3000 --depth 5 --show-props\n```\n\n**Implementation note**: uses a fresh `chromium.launch()` + `newContext()` + `newPage()` per call (not BrowserPool), with `addInitScript` called before `setContent` to ensure the Scope runtime is injected at document-start before React loads.\n\n---\n\n### `scope instrument hooks`\nProfile hook execution in live components.\n\n```bash\nscope instrument hooks http://localhost:3000\nscope instrument hooks http://localhost:3000 --component Button\n```\n\n**Implementation note**: requires `addInitScript({ content: getBrowserEntryScript() })` before `setContent` so `__REACT_DEVTOOLS_GLOBAL_HOOK__` is present when React loads its renderer.\n\n---\n\n### `scope instrument profile`\nProfile render performance of live components.\n\n```bash\nscope instrument profile http://localhost:3000\n```\n\n---\n\n### `scope instrument renders`\nRe-render causality analysis \u2014 what triggered each render.\n\n```bash\nscope instrument renders http://localhost:3000\n```\n\n---\n\n### `scope tokens get <name>`\nGet details of a single design token.\n\n### `scope tokens list`\nList all tokens. Token file must have a `version` field (written by `scope init`).\n\n```bash\nscope tokens list\nscope tokens list --type color\nscope tokens list --format json\n```\n\n### `scope tokens search <query>`\nFull-text search across token names/values.\n\n### `scope tokens resolve <value>`\nResolve a CSS value or alias back to its token name.\n\n### `scope tokens validate`\nValidate token file schema.\n\n### `scope tokens compliance`\nCheck rendered components for design token compliance.\n\n```bash\nscope tokens compliance\nscope tokens compliance --threshold 95\n```\n\n### `scope tokens impact <token>`\nAnalyze impact of changing a token \u2014 which components use it.\n\n```bash\nscope tokens impact --token color.primary.500\n```\n\n### `scope tokens preview <token>`\nPreview a token value change visually before committing.\n\n### `scope tokens export`\nExport tokens in multiple formats.\n\n```bash\nscope tokens export --format flat-json\nscope tokens export --format css\nscope tokens export --format scss\nscope tokens export --format ts\nscope tokens export --format tailwind\nscope tokens export --format style-dictionary\n```\n\n**Format aliases** (auto-corrected with "Did you mean?" hint):\n- `json` \u2192 `flat-json`\n- `js` \u2192 `ts`\n- `sass` \u2192 `scss`\n- `tw` \u2192 `tailwind`\n\n---\n\n### `scope ci`\nRun all CI checks (compliance, accessibility, console errors) and exit 0/1.\n\n```bash\nscope ci\nscope ci --json\nscope ci --threshold 90 # compliance threshold (default: 90)\n```\n\n```\n$ scope ci --json\n\u2192 CI passed in 3.2s\n\u2192 Compliance 100.0% >= threshold 90.0% \u2705\n\u2192 Accessibility audit not yet implemented \u2014 skipped \u2705\n\u2192 No console errors detected \u2705\n\u2192 Exit code 0\n```\n\nThe `scope-ci` **reusable GitHub Actions workflow** is available at `.github/workflows/scope-ci.yml` and can be included in any repo\'s CI to run `scope ci` and post results as a PR comment via `scope report pr-comment`.\n\n---\n\n### `scope site build`\nGenerate a static HTML component gallery site from the manifest.\n\n```bash\nscope site build\nscope site build --output ./dist/site\n```\n\n**Collections support**: components are grouped under named collection sections in the sidebar and index grid. Internal components are hidden from the sidebar and card grid but appear in composition detail sections with an `internal` badge.\n\n**Collection display rules**:\n- Sidebar: one section divider per collection + an "Ungrouped" section; internal components excluded\n- Index page: named sections with heading + optional description; internal components excluded\n- Component detail page: Composes/Composed By lists ALL components including internal ones (with subtle badge)\n- Falls back to flat list when no collections configured (backwards-compatible)\n\n### `scope site serve`\nServe the generated site locally.\n\n```bash\nscope site serve\nscope site serve --port 4000\n```\n\n---\n\n## Collections & Internal Components\n\nComponents can be organized into named **collections** and flagged as **internal** (library implementation details not shown in the public gallery).\n\n### Defining collections\n\n**1. TSDoc tag** (highest precedence):\n```tsx\n/**\n * @collection Forms\n */\nexport function Input() { ... }\n```\n\n**2. `.scope.ts` co-located file**:\n```ts\n// Input.scope.ts\nexport const collection = "Forms"\n```\n\n**3. Config-level glob patterns**:\n```json\n// reactscope.config.json\n{\n "collections": [\n { "name": "Forms", "description": "Form inputs and controls", "patterns": ["src/forms/**"] },\n { "name": "Primitives", "patterns": ["src/primitives/**"] }\n ]\n}\n```\n\nResolution precedence: TSDoc `@collection` > `.scope.ts` export > config pattern.\n\n### Flagging internal components\n\n**TSDoc tag**:\n```tsx\n/**\n * @internal\n */\nexport function InternalHelperButton() { ... }\n```\n\n**Config glob patterns**:\n```json\n{\n "internalPatterns": ["src/internal/**", "src/**/*Internal*"]\n}\n```\n\n---\n\n## Manifest Output Schema\n\nFile: `.reactscope/manifest.json`\n\n```typescript\n{\n version: "0.1",\n generatedAt: string, // ISO 8601\n collections: CollectionConfig[], // echoes config.collections, [] when not set\n components: Record<string, ComponentDescriptor>,\n tree: Record<string, { children: string[], parents: string[] }>\n}\n```\n\n### `ComponentDescriptor` fields\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `filePath` | `string` | Relative path from project root to source file |\n| `exportType` | `"named" \\| "default" \\| "none"` | How the component is exported |\n| `displayName` | `string` | `displayName` if set, else function/class name |\n| `collection` | `string?` | Resolved collection name (`undefined` = ungrouped) |\n| `internal` | `boolean` | `true` if flagged as internal (default: `false`) |\n| `props` | `Record<string, PropDescriptor>` | Extracted prop types keyed by prop name |\n| `composes` | `string[]` | Components this one renders in its JSX |\n| `composedBy` | `string[]` | Components that render this one in their JSX |\n| `complexityClass` | `"simple" \\| "complex"` | Render path: simple = Satori-safe, complex = requires BrowserPool |\n| `requiredContexts` | `string[]` | React context names consumed |\n| `detectedHooks` | `string[]` | All hooks called, sorted alphabetically |\n| `sideEffects` | `SideEffects` | Side effect categories detected |\n| `memoized` | `boolean` | Wrapped with `React.memo` |\n| `forwardedRef` | `boolean` | Wrapped with `React.forwardRef` |\n| `hocWrappers` | `string[]` | HOC wrapper names (excluding memo/forwardRef) |\n| `loc` | `{ start: number, end: number }` | Line numbers in source file |\n\n---\n\n## Common Agent Workflows\n\n### Structural queries\n\n```bash\n# Which components use ThemeContext?\nscope manifest query --context ThemeContext\n\n# What props does Button accept?\nscope manifest get Button --format json | jq \'.props\'\n\n# Which components are safe to render without a provider?\nscope manifest query --complexity simple # + check requiredContexts === []\n\n# Show all components with side effects\nscope manifest query --side-effects\n\n# Which components make fetch calls?\nscope manifest query --has-fetch\n\n# Which components use useEffect?\nscope manifest query --hook useEffect\n\n# Which components accept a disabled prop?\nscope manifest query --has-prop disabled\n\n# Which components are composed inside Modal?\nscope manifest query --composed-by Modal\n\n# All components in the Forms collection\nscope manifest list --collection Forms\n\n# All internal components (library implementation details)\nscope manifest list --internal\n\n# Public components only (hide internals)\nscope manifest list --no-internal\n```\n\n### Render workflows\n\n```bash\n# Render Button in all variants (auto-defaults props if not provided)\nscope render matrix Button --axes \'variant:primary,secondary,danger\'\n\n# Render with JSON axes format\nscope render matrix Button --axes \'{"variant":["primary","secondary"]}\'\n\n# Render with explicit props\nscope render Button --props \'{"variant":"primary","disabled":true}\'\n\n# Render all components (handles CSS/SVG/font imports automatically)\nscope render all --concurrency 8\n\n# Get render as JSON\nscope render Button --format json | jq \'.screenshot\' | base64 -d > button.png\n```\n\n### Token workflows\n\n```bash\n# List all tokens\nscope tokens list\n\n# Check compliance\nscope tokens compliance --threshold 95\n\n# See what a token change impacts\nscope tokens impact --token color.primary.500\n\n# Export for Tailwind\nscope tokens export --format tailwind\n```\n\n### CI workflow\n\n```bash\n# Full compliance check\nscope ci --json\n\n# In GitHub Actions \u2014 use the reusable workflow\n# .github/workflows/ci.yml:\n# uses: FlatFilers/Scope/.github/workflows/scope-ci.yml@main\n```\n\n---\n\n## Error Patterns\n\n| Error | Cause | Fix |\n|-------|-------|-----|\n| `"React root not found"` | App not running, wrong URL, or Vite HMR interfering | Use `scope capture --wait 2000` |\n| `"Component not in manifest"` | Manifest is stale | Run `scope manifest generate` first |\n| `"Manifest not found"` | Missing manifest | Run `scope init` or `scope manifest generate` |\n| `"requiredContexts missing"` | Component needs a provider | Add provider presets to `reactscope.config.json` |\n| Blank PNG / 16\xD76px renders | No globalCSS injected (common with Tailwind) | Set `components.wrappers.globalCSS` in config; run `scope doctor` to verify |\n| `"Invalid props JSON"` | Malformed JSON in `--props` | Use single outer quotes: `--props \'{"key":"val"}\'` |\n| `"SCOPE_CAPTURE_JSON not available"` | Scope runtime not injected before React loaded | Fixed in PR #83 \u2014 update CLI |\n| `"No React DevTools hook found"` | Hook instrumentation init order bug | Fixed in PR #83 \u2014 update CLI |\n| `"ERR_MODULE_NOT_FOUND"` after tokens commands | Old Node shebang in CLI binary | Fixed in PR #90 \u2014 CLI now uses `#!/usr/bin/env bun` |\n| `"version" field missing in tokens` | Token stub written by old `scope init` | Re-run `scope init --force` or add `"version": "1"` to token file |\n| `"unknown option --has-prop"` | Old CLI version | Fixed in PR #90 \u2014 update CLI |\n| Format alias error (`json`, `js`, `sass`, `tw`) | Wrong format name for `tokens export` | Use `flat-json`, `ts`, `scss`, `tailwind`; CLI shows "Did you mean?" hint |\n\n---\n\n## `reactscope.config.json`\n\n```json\n{\n "components": {\n "wrappers": {\n "globalCSS": ["src/styles.css"]\n }\n },\n "tokens": {\n "file": "reactscope.tokens.json"\n },\n "collections": [\n { "name": "Forms", "description": "Form inputs and controls", "patterns": ["src/forms/**"] },\n { "name": "Primitives", "patterns": ["src/primitives/**"] }\n ],\n "internalPatterns": ["src/internal/**"],\n "providers": {\n "theme": { "component": "ThemeProvider", "props": { "theme": "light" } },\n "router": { "component": "MemoryRouter", "props": { "initialEntries": ["/"] } }\n }\n}\n```\n\n**Built-in mock providers** (always available, no config needed):\n- `ThemeContext` \u2192 `{ theme: \'light\' }` (or `--theme <name>`)\n- `LocaleContext` \u2192 `{ locale: \'en-US\' }`\n\n---\n\n## What Scope Cannot Do\n\n- **Runtime state**: `useState` values after user interaction\n- **Network requests**: `fetch`, `XHR`, `WebSocket`\n- **User interactions**: click, type, hover, drag\n- **Auth/session-gated components**: components that redirect or throw without a session\n- **Server components (RSC)**: React Server Components\n- **Dynamic CSS**: CSS-in-JS styles computed at runtime from props Scope can\'t infer\n\n---\n\n## Version History\n\n| Version | Date | Summary |\n|---------|------|---------|\n| v1.0 | 2026-03-11 | Initial SKILL.md (PR #36) \u2014 manifest, render, capture, tree, report, tokens, ci commands |\n| v1.1 | 2026-03-11 | Updated through PR #82 \u2014 Phase 2 CLI commands complete |\n| v1.2 | 2026-03-13 | PRs #83\u2013#95: runtime injection fix, dogfooding fixes (12 bugs), `scope doctor`, `scope init` auto-manifest, globalCSS render warning, collections & internal components feature |\n';
|
|
1200
|
+
|
|
1201
|
+
// src/get-skill-command.ts
|
|
1202
|
+
function createGetSkillCommand() {
|
|
1203
|
+
return new commander.Command("get-skill").description(
|
|
1204
|
+
'Print the embedded Scope SKILL.md to stdout.\n\nAgents: pipe this command into your context loader to bootstrap Scope knowledge.\nThe skill covers: when to use each command, config requirements, output format,\nrender engine selection, and common failure modes.\n\nEMBEDDED AT BUILD TIME \u2014 works in any install context (global npm, npx, local).\n\nExamples:\n scope get-skill # raw markdown to stdout\n scope get-skill --json # { "skill": "..." } for structured ingestion\n scope get-skill | head -50 # preview the skill\n scope get-skill > /tmp/SKILL.md # save locally'
|
|
1205
|
+
).option("--json", "Wrap output in JSON { skill: string } instead of raw markdown").action((opts) => {
|
|
1206
|
+
if (opts.json) {
|
|
1207
|
+
process.stdout.write(`${JSON.stringify({ skill: SKILL_CONTENT }, null, 2)}
|
|
1208
|
+
`);
|
|
1209
|
+
} else {
|
|
1210
|
+
process.stdout.write(SKILL_CONTENT);
|
|
1211
|
+
}
|
|
1212
|
+
});
|
|
1213
|
+
}
|
|
1016
1214
|
function hasConfigFile(dir, stem) {
|
|
1017
1215
|
if (!fs.existsSync(dir)) return false;
|
|
1018
1216
|
try {
|
|
@@ -1223,9 +1421,9 @@ function createRL() {
|
|
|
1223
1421
|
});
|
|
1224
1422
|
}
|
|
1225
1423
|
async function ask(rl, question) {
|
|
1226
|
-
return new Promise((
|
|
1424
|
+
return new Promise((resolve19) => {
|
|
1227
1425
|
rl.question(question, (answer) => {
|
|
1228
|
-
|
|
1426
|
+
resolve19(answer.trim());
|
|
1229
1427
|
});
|
|
1230
1428
|
});
|
|
1231
1429
|
}
|
|
@@ -1300,7 +1498,7 @@ function extractTailwindTokens(tokenSources) {
|
|
|
1300
1498
|
}
|
|
1301
1499
|
}
|
|
1302
1500
|
if (Object.keys(colorTokens).length > 0) {
|
|
1303
|
-
tokens
|
|
1501
|
+
tokens.color = colorTokens;
|
|
1304
1502
|
}
|
|
1305
1503
|
}
|
|
1306
1504
|
}
|
|
@@ -1313,7 +1511,7 @@ function extractTailwindTokens(tokenSources) {
|
|
|
1313
1511
|
for (const [key, val] of Object.entries(spacingValues)) {
|
|
1314
1512
|
spacingTokens[key] = { value: val, type: "dimension" };
|
|
1315
1513
|
}
|
|
1316
|
-
tokens
|
|
1514
|
+
tokens.spacing = spacingTokens;
|
|
1317
1515
|
}
|
|
1318
1516
|
}
|
|
1319
1517
|
const fontFamilyMatch = raw.match(/fontFamily\s*:\s*\{([\s\S]*?)\n\s*\}/);
|
|
@@ -1326,7 +1524,7 @@ function extractTailwindTokens(tokenSources) {
|
|
|
1326
1524
|
}
|
|
1327
1525
|
}
|
|
1328
1526
|
if (Object.keys(fontTokens).length > 0) {
|
|
1329
|
-
tokens
|
|
1527
|
+
tokens.font = fontTokens;
|
|
1330
1528
|
}
|
|
1331
1529
|
}
|
|
1332
1530
|
const borderRadiusMatch = raw.match(/borderRadius\s*:\s*\{([\s\S]*?)\n\s*\}/);
|
|
@@ -1337,7 +1535,7 @@ function extractTailwindTokens(tokenSources) {
|
|
|
1337
1535
|
for (const [key, val] of Object.entries(radiusValues)) {
|
|
1338
1536
|
radiusTokens[key] = { value: val, type: "dimension" };
|
|
1339
1537
|
}
|
|
1340
|
-
tokens
|
|
1538
|
+
tokens.radius = radiusTokens;
|
|
1341
1539
|
}
|
|
1342
1540
|
}
|
|
1343
1541
|
return Object.keys(tokens).length > 0 ? tokens : null;
|
|
@@ -1456,7 +1654,28 @@ async function runInit(options) {
|
|
|
1456
1654
|
process.stdout.write(` ${p}
|
|
1457
1655
|
`);
|
|
1458
1656
|
}
|
|
1459
|
-
process.stdout.write("\n
|
|
1657
|
+
process.stdout.write("\n Scanning components...\n");
|
|
1658
|
+
try {
|
|
1659
|
+
const manifestConfig = {
|
|
1660
|
+
include: config.components.include,
|
|
1661
|
+
rootDir
|
|
1662
|
+
};
|
|
1663
|
+
const manifest$1 = await manifest.generateManifest(manifestConfig);
|
|
1664
|
+
const manifestCount = Object.keys(manifest$1.components).length;
|
|
1665
|
+
const manifestOutPath = path.join(rootDir, config.output.dir, "manifest.json");
|
|
1666
|
+
fs.mkdirSync(path.join(rootDir, config.output.dir), { recursive: true });
|
|
1667
|
+
fs.writeFileSync(manifestOutPath, `${JSON.stringify(manifest$1, null, 2)}
|
|
1668
|
+
`);
|
|
1669
|
+
process.stdout.write(
|
|
1670
|
+
` Found ${manifestCount} component(s) \u2014 manifest written to ${manifestOutPath}
|
|
1671
|
+
`
|
|
1672
|
+
);
|
|
1673
|
+
} catch {
|
|
1674
|
+
process.stdout.write(
|
|
1675
|
+
" (manifest generate skipped \u2014 run `scope manifest generate` manually)\n"
|
|
1676
|
+
);
|
|
1677
|
+
}
|
|
1678
|
+
process.stdout.write("\n");
|
|
1460
1679
|
return {
|
|
1461
1680
|
success: true,
|
|
1462
1681
|
message: "Project initialised successfully.",
|
|
@@ -1465,7 +1684,9 @@ async function runInit(options) {
|
|
|
1465
1684
|
};
|
|
1466
1685
|
}
|
|
1467
1686
|
function createInitCommand() {
|
|
1468
|
-
return new commander.Command("init").description(
|
|
1687
|
+
return new commander.Command("init").description(
|
|
1688
|
+
"Auto-detect your project layout and scaffold reactscope.config.json.\n\nWHAT IT DOES:\n - Detects component glob patterns from tsconfig / package.json / directory scan\n - Detects globalCSS files (Tailwind, PostCSS)\n - Writes reactscope.config.json with all detected values\n - Adds .reactscope/ to .gitignore\n - Creates .reactscope/ output directory\n\nCONFIG FIELDS GENERATED:\n components.include glob patterns for component discovery\n components.wrappers providers + globalCSS to inject on every render\n render.viewport default viewport (1280\xD7800)\n tokens.file path to reactscope.tokens.json\n output.dir .reactscope/ (all outputs go here)\n ci.complianceThreshold 0.90 (90% on-token required to pass CI)\n\nSafe to re-run \u2014 will not overwrite existing config unless --force.\n\nExamples:\n scope init\n scope init --yes # accept all detected defaults, no prompts\n scope init --force # overwrite existing config"
|
|
1689
|
+
).option("-y, --yes", "Accept all detected defaults without prompting", false).option("--force", "Overwrite existing reactscope.config.json if present", false).action(async (opts) => {
|
|
1469
1690
|
try {
|
|
1470
1691
|
const result = await runInit({ yes: opts.yes, force: opts.force });
|
|
1471
1692
|
if (!result.success && !result.skipped) {
|
|
@@ -1494,34 +1715,56 @@ function resolveFormat(formatFlag) {
|
|
|
1494
1715
|
return isTTY() ? "table" : "json";
|
|
1495
1716
|
}
|
|
1496
1717
|
function registerList(manifestCmd) {
|
|
1497
|
-
manifestCmd.command("list").description(
|
|
1498
|
-
|
|
1499
|
-
|
|
1500
|
-
|
|
1501
|
-
|
|
1502
|
-
|
|
1503
|
-
|
|
1504
|
-
|
|
1505
|
-
|
|
1506
|
-
|
|
1507
|
-
|
|
1508
|
-
|
|
1509
|
-
|
|
1510
|
-
|
|
1511
|
-
|
|
1512
|
-
|
|
1513
|
-
|
|
1514
|
-
|
|
1718
|
+
manifestCmd.command("list").description(
|
|
1719
|
+
`List all components in the manifest as a table (TTY) or JSON (piped).
|
|
1720
|
+
|
|
1721
|
+
Examples:
|
|
1722
|
+
scope manifest list
|
|
1723
|
+
scope manifest list --format json | jq '.[].name'
|
|
1724
|
+
scope manifest list --filter "Button*"`
|
|
1725
|
+
).option("--format <fmt>", "Output format: json or table (default: auto-detect)").option("--filter <glob>", "Filter components by name glob pattern").option("--collection <name>", "Filter to only components in the named collection").option("--internal", "Show only internal components").option("--no-internal", "Hide internal components from output").option("--manifest <path>", "Path to manifest.json", MANIFEST_PATH).action(
|
|
1726
|
+
(opts) => {
|
|
1727
|
+
try {
|
|
1728
|
+
const manifest = loadManifest(opts.manifest);
|
|
1729
|
+
const format = resolveFormat(opts.format);
|
|
1730
|
+
let entries = Object.entries(manifest.components);
|
|
1731
|
+
if (opts.filter !== void 0) {
|
|
1732
|
+
const filterPattern = opts.filter ?? "";
|
|
1733
|
+
entries = entries.filter(([name]) => matchGlob(filterPattern, name));
|
|
1734
|
+
}
|
|
1735
|
+
if (opts.collection !== void 0) {
|
|
1736
|
+
const col = opts.collection;
|
|
1737
|
+
entries = entries.filter(([, d]) => d.collection === col);
|
|
1738
|
+
}
|
|
1739
|
+
if (opts.internal === true) {
|
|
1740
|
+
entries = entries.filter(([, d]) => d.internal);
|
|
1741
|
+
} else if (opts.internal === false) {
|
|
1742
|
+
entries = entries.filter(([, d]) => !d.internal);
|
|
1743
|
+
}
|
|
1744
|
+
const rows = entries.map(([name, descriptor]) => ({
|
|
1745
|
+
name,
|
|
1746
|
+
file: descriptor.filePath,
|
|
1747
|
+
complexityClass: descriptor.complexityClass,
|
|
1748
|
+
hookCount: descriptor.detectedHooks.length,
|
|
1749
|
+
contextCount: descriptor.requiredContexts.length,
|
|
1750
|
+
collection: descriptor.collection,
|
|
1751
|
+
internal: descriptor.internal
|
|
1752
|
+
}));
|
|
1753
|
+
const output = format === "json" ? formatListJson(rows) : formatListTable(rows);
|
|
1754
|
+
process.stdout.write(`${output}
|
|
1515
1755
|
`);
|
|
1516
|
-
|
|
1517
|
-
|
|
1756
|
+
} catch (err) {
|
|
1757
|
+
process.stderr.write(`Error: ${err instanceof Error ? err.message : String(err)}
|
|
1518
1758
|
`);
|
|
1519
|
-
|
|
1759
|
+
process.exit(1);
|
|
1760
|
+
}
|
|
1520
1761
|
}
|
|
1521
|
-
|
|
1762
|
+
);
|
|
1522
1763
|
}
|
|
1523
1764
|
function registerGet(manifestCmd) {
|
|
1524
|
-
manifestCmd.command("get <name>").description(
|
|
1765
|
+
manifestCmd.command("get <name>").description(
|
|
1766
|
+
"Get full details of a single component: props, hooks, complexity class, file path.\n\nExamples:\n scope manifest get Button\n scope manifest get Button --format json\n scope manifest get Button --format json | jq '.complexity'"
|
|
1767
|
+
).option("--format <fmt>", "Output format: json or table (default: auto-detect)").option("--manifest <path>", "Path to manifest.json", MANIFEST_PATH).action((name, opts) => {
|
|
1525
1768
|
try {
|
|
1526
1769
|
const manifest = loadManifest(opts.manifest);
|
|
1527
1770
|
const format = resolveFormat(opts.format);
|
|
@@ -1545,10 +1788,12 @@ Available: ${available}${hint}`
|
|
|
1545
1788
|
});
|
|
1546
1789
|
}
|
|
1547
1790
|
function registerQuery(manifestCmd) {
|
|
1548
|
-
manifestCmd.command("query").description(
|
|
1791
|
+
manifestCmd.command("query").description(
|
|
1792
|
+
'Filter components by structural attributes. All flags are AND-combined.\n\nCOMPLEXITY CLASSES:\n simple \u2014 pure/presentational, no side effects, Satori-renderable\n complex \u2014 uses context/hooks/effects, requires BrowserPool to render\n\nExamples:\n scope manifest query --complexity simple\n scope manifest query --has-fetch\n scope manifest query --hook useContext --side-effects\n scope manifest query --has-prop "variant:union" --format json\n scope manifest query --composed-by Layout'
|
|
1793
|
+
).option("--context <name>", "Find components consuming a context").option("--hook <name>", "Find components using a specific hook").option("--complexity <class>", "Filter by complexity class: simple or complex").option("--side-effects", "Find components with any side effects", false).option("--has-fetch", "Find components with fetch calls", false).option(
|
|
1549
1794
|
"--has-prop <spec>",
|
|
1550
1795
|
"Find components with a prop matching name or name:type (e.g. 'loading' or 'variant:union')"
|
|
1551
|
-
).option("--composed-by <name>", "Find components that compose the named component").option("--format <fmt>", "Output format: json or table (default: auto-detect)").option("--manifest <path>", "Path to manifest.json", MANIFEST_PATH).action(
|
|
1796
|
+
).option("--composed-by <name>", "Find components that compose the named component").option("--internal", "Find only internal components", false).option("--collection <name>", "Filter to only components in the named collection").option("--format <fmt>", "Output format: json or table (default: auto-detect)").option("--manifest <path>", "Path to manifest.json", MANIFEST_PATH).action(
|
|
1552
1797
|
(opts) => {
|
|
1553
1798
|
try {
|
|
1554
1799
|
const manifest = loadManifest(opts.manifest);
|
|
@@ -1561,9 +1806,11 @@ function registerQuery(manifestCmd) {
|
|
|
1561
1806
|
if (opts.hasFetch) queryParts.push("has-fetch");
|
|
1562
1807
|
if (opts.hasProp !== void 0) queryParts.push(`has-prop=${opts.hasProp}`);
|
|
1563
1808
|
if (opts.composedBy !== void 0) queryParts.push(`composed-by=${opts.composedBy}`);
|
|
1809
|
+
if (opts.internal) queryParts.push("internal");
|
|
1810
|
+
if (opts.collection !== void 0) queryParts.push(`collection=${opts.collection}`);
|
|
1564
1811
|
if (queryParts.length === 0) {
|
|
1565
1812
|
process.stderr.write(
|
|
1566
|
-
"No query flags specified. Use --context, --hook, --complexity, --side-effects, --has-fetch, --has-prop,
|
|
1813
|
+
"No query flags specified. Use --context, --hook, --complexity, --side-effects, --has-fetch, --has-prop, --composed-by, --internal, or --collection.\n"
|
|
1567
1814
|
);
|
|
1568
1815
|
process.exit(1);
|
|
1569
1816
|
}
|
|
@@ -1608,15 +1855,24 @@ function registerQuery(manifestCmd) {
|
|
|
1608
1855
|
const targetName = opts.composedBy;
|
|
1609
1856
|
entries = entries.filter(([, d]) => {
|
|
1610
1857
|
const composedBy = d.composedBy;
|
|
1611
|
-
return composedBy
|
|
1858
|
+
return composedBy?.includes(targetName);
|
|
1612
1859
|
});
|
|
1613
1860
|
}
|
|
1861
|
+
if (opts.internal) {
|
|
1862
|
+
entries = entries.filter(([, d]) => d.internal);
|
|
1863
|
+
}
|
|
1864
|
+
if (opts.collection !== void 0) {
|
|
1865
|
+
const col = opts.collection;
|
|
1866
|
+
entries = entries.filter(([, d]) => d.collection === col);
|
|
1867
|
+
}
|
|
1614
1868
|
const rows = entries.map(([name, d]) => ({
|
|
1615
1869
|
name,
|
|
1616
1870
|
file: d.filePath,
|
|
1617
1871
|
complexityClass: d.complexityClass,
|
|
1618
1872
|
hooks: d.detectedHooks.join(", ") || "\u2014",
|
|
1619
|
-
contexts: d.requiredContexts.join(", ") || "\u2014"
|
|
1873
|
+
contexts: d.requiredContexts.join(", ") || "\u2014",
|
|
1874
|
+
collection: d.collection,
|
|
1875
|
+
internal: d.internal
|
|
1620
1876
|
}));
|
|
1621
1877
|
const output = format === "json" ? formatQueryJson(rows) : formatQueryTable(rows, queryDesc);
|
|
1622
1878
|
process.stdout.write(`${output}
|
|
@@ -1631,7 +1887,7 @@ function registerQuery(manifestCmd) {
|
|
|
1631
1887
|
}
|
|
1632
1888
|
function registerGenerate(manifestCmd) {
|
|
1633
1889
|
manifestCmd.command("generate").description(
|
|
1634
|
-
|
|
1890
|
+
'Scan source files and generate .reactscope/manifest.json.\n\nUses Babel static analysis \u2014 no runtime or bundler required.\nRe-run whenever components are added, removed, or significantly changed.\n\nWHAT IT CAPTURES per component:\n - File path and export name\n - All props with types and default values\n - Hook usage (useState, useEffect, useContext, custom hooks)\n - Side effects (fetch, timers, subscriptions)\n - Complexity class: simple | complex\n - Context dependencies and composed child components\n\nExamples:\n scope manifest generate\n scope manifest generate --root ./packages/ui\n scope manifest generate --include "src/components/**/*.tsx" --exclude "**/*.stories.tsx"\n scope manifest generate --output ./custom-manifest.json'
|
|
1635
1891
|
).option("--root <path>", "Project root directory (default: cwd)").option("--output <path>", "Output path for manifest.json", MANIFEST_PATH).option("--include <globs>", "Comma-separated glob patterns to include").option("--exclude <globs>", "Comma-separated glob patterns to exclude").action(async (opts) => {
|
|
1636
1892
|
try {
|
|
1637
1893
|
const rootDir = path.resolve(process.cwd(), opts.root ?? ".");
|
|
@@ -1666,7 +1922,7 @@ function registerGenerate(manifestCmd) {
|
|
|
1666
1922
|
}
|
|
1667
1923
|
function createManifestCommand() {
|
|
1668
1924
|
const manifestCmd = new commander.Command("manifest").description(
|
|
1669
|
-
"Query and explore the component manifest"
|
|
1925
|
+
"Query and explore the component manifest (.reactscope/manifest.json).\n\nThe manifest is the source-of-truth registry of every React component\nin your codebase \u2014 generated by static analysis (no runtime needed).\n\nRun `scope manifest generate` first, then use list/get/query to explore.\n\nExamples:\n scope manifest generate\n scope manifest list\n scope manifest get Button\n scope manifest query --complexity complex --has-fetch"
|
|
1670
1926
|
);
|
|
1671
1927
|
registerList(manifestCmd);
|
|
1672
1928
|
registerGet(manifestCmd);
|
|
@@ -1982,7 +2238,19 @@ async function runHooksProfiling(componentName, filePath, props) {
|
|
|
1982
2238
|
}
|
|
1983
2239
|
function createInstrumentHooksCommand() {
|
|
1984
2240
|
const cmd = new commander.Command("hooks").description(
|
|
1985
|
-
|
|
2241
|
+
`Profile per-hook-instance data for a component.
|
|
2242
|
+
|
|
2243
|
+
METRICS CAPTURED per hook instance:
|
|
2244
|
+
useState update count, current value
|
|
2245
|
+
useCallback cache hit rate (stable reference %)
|
|
2246
|
+
useMemo cache hit rate (recompute %)
|
|
2247
|
+
useEffect execution count
|
|
2248
|
+
useRef current value snapshot
|
|
2249
|
+
|
|
2250
|
+
Examples:
|
|
2251
|
+
scope instrument hooks SearchInput
|
|
2252
|
+
scope instrument hooks SearchInput --props '{"value":"hello"}' --json
|
|
2253
|
+
scope instrument hooks Dropdown --json | jq '.hooks[] | select(.type == "useMemo")' `
|
|
1986
2254
|
).argument("<component>", "Component name (must exist in the manifest)").option("--props <json>", "Inline props JSON passed to the component", "{}").option("--manifest <path>", "Path to manifest.json", MANIFEST_PATH2).option("--format <fmt>", "Output format: json|text (default: auto)", "json").option("--show-flags", "Show heuristic flags only (useful for CI checks)", false).action(
|
|
1987
2255
|
async (componentName, opts) => {
|
|
1988
2256
|
try {
|
|
@@ -2266,7 +2534,19 @@ async function runInteractionProfile(componentName, filePath, props, interaction
|
|
|
2266
2534
|
}
|
|
2267
2535
|
function createInstrumentProfileCommand() {
|
|
2268
2536
|
const cmd = new commander.Command("profile").description(
|
|
2269
|
-
|
|
2537
|
+
`Capture a full performance profile for an interaction sequence.
|
|
2538
|
+
|
|
2539
|
+
PROFILE INCLUDES:
|
|
2540
|
+
renders total re-renders triggered by the interaction
|
|
2541
|
+
timing interaction start \u2192 paint time (ms)
|
|
2542
|
+
layoutShifts cumulative layout shift (CLS) score
|
|
2543
|
+
scriptTime JS execution time (ms)
|
|
2544
|
+
longTasks count of tasks >50ms
|
|
2545
|
+
|
|
2546
|
+
Examples:
|
|
2547
|
+
scope instrument profile Button --interaction '[{"action":"click","target":"button"}]'
|
|
2548
|
+
scope instrument profile Modal --interaction '[{"action":"click","target":".open-btn"}]' --json
|
|
2549
|
+
scope instrument profile Form --json | jq '.summary.renderCount'`
|
|
2270
2550
|
).argument("<component>", "Component name (must exist in the manifest)").option(
|
|
2271
2551
|
"--interaction <json>",
|
|
2272
2552
|
`Interaction steps JSON, e.g. '[{"action":"click","target":"button.primary"}]'`,
|
|
@@ -2602,7 +2882,21 @@ async function runInstrumentTree(options) {
|
|
|
2602
2882
|
}
|
|
2603
2883
|
}
|
|
2604
2884
|
function createInstrumentTreeCommand() {
|
|
2605
|
-
return new commander.Command("tree").description(
|
|
2885
|
+
return new commander.Command("tree").description(
|
|
2886
|
+
`Render a component and output the full instrumentation tree:
|
|
2887
|
+
DOM structure, computed styles per node, a11y roles, and React fibers.
|
|
2888
|
+
|
|
2889
|
+
OUTPUT STRUCTURE per node:
|
|
2890
|
+
tag / id / className DOM identity
|
|
2891
|
+
computedStyles resolved CSS properties
|
|
2892
|
+
a11y role, name, focusable
|
|
2893
|
+
children nested child nodes
|
|
2894
|
+
|
|
2895
|
+
Examples:
|
|
2896
|
+
scope instrument tree Card
|
|
2897
|
+
scope instrument tree Button --props '{"variant":"primary"}' --json
|
|
2898
|
+
scope instrument tree Input --json | jq '.tree.computedStyles'`
|
|
2899
|
+
).argument("<component>", "Component name to instrument (must exist in the manifest)").option("--sort-by <field>", "Sort nodes by field: renderCount | depth").option("--limit <n>", "Limit output to the first N nodes (depth-first)").option("--uses-context <name>", "Filter to components that use a specific context").option("--provider-depth", "Annotate each node with its context-provider nesting depth", false).option(
|
|
2606
2900
|
"--wasted-renders",
|
|
2607
2901
|
"Filter to components with wasted renders (no prop/state/context changes, not memoized)",
|
|
2608
2902
|
false
|
|
@@ -2996,7 +3290,8 @@ Available: ${available}`
|
|
|
2996
3290
|
}
|
|
2997
3291
|
const rootDir = process.cwd();
|
|
2998
3292
|
const filePath = path.resolve(rootDir, descriptor.filePath);
|
|
2999
|
-
const preScript = playwright.getBrowserEntryScript()
|
|
3293
|
+
const preScript = `${playwright.getBrowserEntryScript()}
|
|
3294
|
+
${buildInstrumentationScript()}`;
|
|
3000
3295
|
const htmlHarness = await buildComponentHarness(
|
|
3001
3296
|
filePath,
|
|
3002
3297
|
options.componentName,
|
|
@@ -3085,7 +3380,24 @@ function formatRendersTable(result) {
|
|
|
3085
3380
|
return lines.join("\n");
|
|
3086
3381
|
}
|
|
3087
3382
|
function createInstrumentRendersCommand() {
|
|
3088
|
-
return new commander.Command("renders").description(
|
|
3383
|
+
return new commander.Command("renders").description(
|
|
3384
|
+
`Trace every re-render triggered by an interaction and identify root causes.
|
|
3385
|
+
|
|
3386
|
+
OUTPUT INCLUDES per render event:
|
|
3387
|
+
component which component re-rendered
|
|
3388
|
+
trigger why it re-rendered: state_change | props_change | context_change |
|
|
3389
|
+
parent_rerender | force_update | hook_dependency
|
|
3390
|
+
wasted true if re-rendered with no changed inputs and not memoized
|
|
3391
|
+
chain full causality chain from root cause to this render
|
|
3392
|
+
|
|
3393
|
+
WASTED RENDERS: propsChanged=false AND stateChanged=false AND contextChanged=false
|
|
3394
|
+
AND memoized=false \u2014 these are optimisation opportunities.
|
|
3395
|
+
|
|
3396
|
+
Examples:
|
|
3397
|
+
scope instrument renders SearchPage --interaction '[{"action":"type","target":"input","text":"hello"}]'
|
|
3398
|
+
scope instrument renders Button --interaction '[{"action":"click","target":"button"}]' --json
|
|
3399
|
+
scope instrument renders Form --json | jq '.events[] | select(.wasted == true)'`
|
|
3400
|
+
).argument("<component>", "Component name to instrument (must be in manifest)").option(
|
|
3089
3401
|
"--interaction <json>",
|
|
3090
3402
|
`Interaction sequence JSON, e.g. '[{"action":"click","target":"button"}]'`,
|
|
3091
3403
|
"[]"
|
|
@@ -3131,7 +3443,28 @@ function createInstrumentRendersCommand() {
|
|
|
3131
3443
|
}
|
|
3132
3444
|
function createInstrumentCommand() {
|
|
3133
3445
|
const instrumentCmd = new commander.Command("instrument").description(
|
|
3134
|
-
|
|
3446
|
+
`Runtime instrumentation for React component behaviour analysis.
|
|
3447
|
+
|
|
3448
|
+
All instrument commands:
|
|
3449
|
+
1. Build an esbuild harness for the component
|
|
3450
|
+
2. Load it in a Playwright browser
|
|
3451
|
+
3. Inject instrumentation hooks into React DevTools fiber
|
|
3452
|
+
4. Execute interactions and collect events
|
|
3453
|
+
|
|
3454
|
+
PREREQUISITES:
|
|
3455
|
+
scope manifest generate (component must be in manifest)
|
|
3456
|
+
reactscope.config.json (for wrappers/globalCSS)
|
|
3457
|
+
|
|
3458
|
+
INTERACTION FORMAT:
|
|
3459
|
+
JSON array of step objects: [{action, target, text?}]
|
|
3460
|
+
Actions: click | type | focus | blur | hover | key
|
|
3461
|
+
Target: CSS selector for the element to interact with
|
|
3462
|
+
|
|
3463
|
+
Examples:
|
|
3464
|
+
scope instrument renders Button --interaction '[{"action":"click","target":"button"}]'
|
|
3465
|
+
scope instrument hooks SearchInput --props '{"value":"hello"}'
|
|
3466
|
+
scope instrument profile Modal --interaction '[{"action":"click","target":".open-btn"}]'
|
|
3467
|
+
scope instrument tree Card`
|
|
3135
3468
|
);
|
|
3136
3469
|
instrumentCmd.addCommand(createInstrumentRendersCommand());
|
|
3137
3470
|
instrumentCmd.addCommand(createInstrumentHooksCommand());
|
|
@@ -3370,7 +3703,7 @@ function buildRenderer(filePath, componentName, viewportWidth, viewportHeight, g
|
|
|
3370
3703
|
}
|
|
3371
3704
|
});
|
|
3372
3705
|
return [...set];
|
|
3373
|
-
});
|
|
3706
|
+
}) ?? [];
|
|
3374
3707
|
const projectCss2 = await getCompiledCssForClasses(rootDir, classes);
|
|
3375
3708
|
if (projectCss2 != null && projectCss2.length > 0) {
|
|
3376
3709
|
await page.addStyleTag({ content: projectCss2 });
|
|
@@ -3383,49 +3716,147 @@ function buildRenderer(filePath, componentName, viewportWidth, viewportHeight, g
|
|
|
3383
3716
|
`Component "${componentName}" rendered with zero bounding box \u2014 it may be invisible or not mounted`
|
|
3384
3717
|
);
|
|
3385
3718
|
}
|
|
3386
|
-
const PAD =
|
|
3387
|
-
const MIN_W = 320;
|
|
3388
|
-
const MIN_H = 200;
|
|
3719
|
+
const PAD = 8;
|
|
3389
3720
|
const clipX = Math.max(0, boundingBox.x - PAD);
|
|
3390
3721
|
const clipY = Math.max(0, boundingBox.y - PAD);
|
|
3391
3722
|
const rawW = boundingBox.width + PAD * 2;
|
|
3392
3723
|
const rawH = boundingBox.height + PAD * 2;
|
|
3393
|
-
const
|
|
3394
|
-
const
|
|
3395
|
-
const safeW = Math.min(clipW, viewportWidth - clipX);
|
|
3396
|
-
const safeH = Math.min(clipH, viewportHeight - clipY);
|
|
3724
|
+
const safeW = Math.min(rawW, viewportWidth - clipX);
|
|
3725
|
+
const safeH = Math.min(rawH, viewportHeight - clipY);
|
|
3397
3726
|
const screenshot = await page.screenshot({
|
|
3398
3727
|
clip: { x: clipX, y: clipY, width: safeW, height: safeH },
|
|
3399
3728
|
type: "png"
|
|
3400
3729
|
});
|
|
3730
|
+
const STYLE_PROPS = [
|
|
3731
|
+
"display",
|
|
3732
|
+
"width",
|
|
3733
|
+
"height",
|
|
3734
|
+
"color",
|
|
3735
|
+
"backgroundColor",
|
|
3736
|
+
"fontSize",
|
|
3737
|
+
"fontFamily",
|
|
3738
|
+
"fontWeight",
|
|
3739
|
+
"lineHeight",
|
|
3740
|
+
"padding",
|
|
3741
|
+
"paddingTop",
|
|
3742
|
+
"paddingRight",
|
|
3743
|
+
"paddingBottom",
|
|
3744
|
+
"paddingLeft",
|
|
3745
|
+
"margin",
|
|
3746
|
+
"marginTop",
|
|
3747
|
+
"marginRight",
|
|
3748
|
+
"marginBottom",
|
|
3749
|
+
"marginLeft",
|
|
3750
|
+
"gap",
|
|
3751
|
+
"borderRadius",
|
|
3752
|
+
"borderWidth",
|
|
3753
|
+
"borderColor",
|
|
3754
|
+
"borderStyle",
|
|
3755
|
+
"boxShadow",
|
|
3756
|
+
"opacity",
|
|
3757
|
+
"position",
|
|
3758
|
+
"flexDirection",
|
|
3759
|
+
"alignItems",
|
|
3760
|
+
"justifyContent",
|
|
3761
|
+
"overflow"
|
|
3762
|
+
];
|
|
3763
|
+
const _domResult = await page.evaluate(
|
|
3764
|
+
(args) => {
|
|
3765
|
+
let count = 0;
|
|
3766
|
+
const styles = {};
|
|
3767
|
+
function captureStyles(el, id, propList) {
|
|
3768
|
+
const computed = window.getComputedStyle(el);
|
|
3769
|
+
const out = {};
|
|
3770
|
+
for (const prop of propList) {
|
|
3771
|
+
const val = computed[prop] ?? "";
|
|
3772
|
+
if (val && val !== "none" && val !== "normal" && val !== "auto") out[prop] = val;
|
|
3773
|
+
}
|
|
3774
|
+
styles[id] = out;
|
|
3775
|
+
}
|
|
3776
|
+
function walk(node) {
|
|
3777
|
+
if (node.nodeType === Node.TEXT_NODE) {
|
|
3778
|
+
return {
|
|
3779
|
+
tag: "#text",
|
|
3780
|
+
attrs: {},
|
|
3781
|
+
text: node.textContent?.trim() ?? "",
|
|
3782
|
+
children: []
|
|
3783
|
+
};
|
|
3784
|
+
}
|
|
3785
|
+
const el = node;
|
|
3786
|
+
const id = count++;
|
|
3787
|
+
captureStyles(el, id, args.props);
|
|
3788
|
+
const attrs = {};
|
|
3789
|
+
for (const attr of Array.from(el.attributes)) {
|
|
3790
|
+
attrs[attr.name] = attr.value;
|
|
3791
|
+
}
|
|
3792
|
+
const children = Array.from(el.childNodes).filter(
|
|
3793
|
+
(n) => n.nodeType === Node.ELEMENT_NODE || n.nodeType === Node.TEXT_NODE && (n.textContent?.trim() ?? "").length > 0
|
|
3794
|
+
).map(walk);
|
|
3795
|
+
return { tag: el.tagName.toLowerCase(), attrs, nodeId: id, children };
|
|
3796
|
+
}
|
|
3797
|
+
const root = document.querySelector(args.sel);
|
|
3798
|
+
if (!root)
|
|
3799
|
+
return {
|
|
3800
|
+
tree: { tag: "div", attrs: {}, children: [] },
|
|
3801
|
+
elementCount: 0,
|
|
3802
|
+
nodeStyles: {}
|
|
3803
|
+
};
|
|
3804
|
+
return { tree: walk(root), elementCount: count, nodeStyles: styles };
|
|
3805
|
+
},
|
|
3806
|
+
{ sel: "[data-reactscope-root] > *", props: STYLE_PROPS }
|
|
3807
|
+
);
|
|
3808
|
+
const domTree = _domResult?.tree ?? { tag: "div", attrs: {}, children: [] };
|
|
3809
|
+
const elementCount = _domResult?.elementCount ?? 0;
|
|
3810
|
+
const nodeStyles = _domResult?.nodeStyles ?? {};
|
|
3401
3811
|
const computedStyles = {};
|
|
3402
|
-
|
|
3403
|
-
|
|
3404
|
-
|
|
3405
|
-
|
|
3406
|
-
|
|
3407
|
-
|
|
3408
|
-
|
|
3409
|
-
|
|
3410
|
-
|
|
3411
|
-
|
|
3412
|
-
|
|
3413
|
-
|
|
3414
|
-
"fontFamily",
|
|
3415
|
-
"padding",
|
|
3416
|
-
"margin"
|
|
3417
|
-
]) {
|
|
3418
|
-
out[prop] = computed.getPropertyValue(prop);
|
|
3812
|
+
if (nodeStyles[0]) computedStyles["[data-reactscope-root] > *"] = nodeStyles[0];
|
|
3813
|
+
for (const [nodeId, styles] of Object.entries(nodeStyles)) {
|
|
3814
|
+
computedStyles[`#node-${nodeId}`] = styles;
|
|
3815
|
+
}
|
|
3816
|
+
const dom = {
|
|
3817
|
+
tree: domTree,
|
|
3818
|
+
elementCount,
|
|
3819
|
+
boundingBox: {
|
|
3820
|
+
x: boundingBox.x,
|
|
3821
|
+
y: boundingBox.y,
|
|
3822
|
+
width: boundingBox.width,
|
|
3823
|
+
height: boundingBox.height
|
|
3419
3824
|
}
|
|
3420
|
-
|
|
3421
|
-
|
|
3422
|
-
|
|
3825
|
+
};
|
|
3826
|
+
const a11yInfo = await page.evaluate((sel) => {
|
|
3827
|
+
const wrapper = document.querySelector(sel);
|
|
3828
|
+
const el = wrapper?.firstElementChild ?? wrapper;
|
|
3829
|
+
if (!el) return { role: "generic", name: "" };
|
|
3830
|
+
return {
|
|
3831
|
+
role: el.getAttribute("role") ?? el.tagName.toLowerCase() ?? "generic",
|
|
3832
|
+
name: el.getAttribute("aria-label") ?? el.getAttribute("aria-labelledby") ?? el.textContent?.trim().slice(0, 100) ?? ""
|
|
3833
|
+
};
|
|
3834
|
+
}, "[data-reactscope-root]") ?? {
|
|
3835
|
+
role: "generic",
|
|
3836
|
+
name: ""
|
|
3837
|
+
};
|
|
3838
|
+
const imgViolations = await page.evaluate((sel) => {
|
|
3839
|
+
const container = document.querySelector(sel);
|
|
3840
|
+
if (!container) return [];
|
|
3841
|
+
const issues = [];
|
|
3842
|
+
container.querySelectorAll("img").forEach((img) => {
|
|
3843
|
+
if (!img.alt) issues.push("Image missing accessible name");
|
|
3844
|
+
});
|
|
3845
|
+
return issues;
|
|
3846
|
+
}, "[data-reactscope-root]") ?? [];
|
|
3847
|
+
const accessibility = {
|
|
3848
|
+
role: a11yInfo.role,
|
|
3849
|
+
name: a11yInfo.name,
|
|
3850
|
+
violations: imgViolations
|
|
3851
|
+
};
|
|
3423
3852
|
return {
|
|
3424
3853
|
screenshot,
|
|
3425
3854
|
width: Math.round(safeW),
|
|
3426
3855
|
height: Math.round(safeH),
|
|
3427
3856
|
renderTimeMs,
|
|
3428
|
-
computedStyles
|
|
3857
|
+
computedStyles,
|
|
3858
|
+
dom,
|
|
3859
|
+
accessibility
|
|
3429
3860
|
};
|
|
3430
3861
|
} finally {
|
|
3431
3862
|
pool.release(slot);
|
|
@@ -3463,7 +3894,27 @@ Available: ${available}`
|
|
|
3463
3894
|
return { __default__: {} };
|
|
3464
3895
|
}
|
|
3465
3896
|
function registerRenderSingle(renderCmd) {
|
|
3466
|
-
renderCmd.command("component <component>", { isDefault: true }).description(
|
|
3897
|
+
renderCmd.command("component <component>", { isDefault: true }).description(
|
|
3898
|
+
`Render one component to a PNG screenshot or JSON data object.
|
|
3899
|
+
|
|
3900
|
+
PROP SOURCES (in priority order):
|
|
3901
|
+
--scenario <name> named scenario from <ComponentName>.scope file
|
|
3902
|
+
--props <json> inline props JSON string
|
|
3903
|
+
(no flag) component rendered with all-default props
|
|
3904
|
+
|
|
3905
|
+
FORMAT DETECTION:
|
|
3906
|
+
--format png always write PNG
|
|
3907
|
+
--format json always write JSON render data
|
|
3908
|
+
auto (default) PNG when -o has .png extension or stdout is file;
|
|
3909
|
+
JSON when stdout is a pipe
|
|
3910
|
+
|
|
3911
|
+
Examples:
|
|
3912
|
+
scope render component Button
|
|
3913
|
+
scope render component Button --props '{"variant":"primary","size":"lg"}'
|
|
3914
|
+
scope render component Button --scenario hover-state -o button-hover.png
|
|
3915
|
+
scope render component Card --viewport 375x812 --theme dark
|
|
3916
|
+
scope render component Badge --format json | jq '.a11y'`
|
|
3917
|
+
).option("--props <json>", `Inline props JSON, e.g. '{"variant":"primary"}'`).option("--scenario <name>", "Run a named scenario from the component's .scope file").option("--viewport <WxH>", "Viewport size e.g. 1280x720", "375x812").option("--theme <name>", "Theme name from the token system").option("-o, --output <path>", "Write PNG to file instead of stdout").option("--format <fmt>", "Output format: png or json (default: auto)").option("--manifest <path>", "Path to manifest.json", MANIFEST_PATH6).action(
|
|
3467
3918
|
async (componentName, opts) => {
|
|
3468
3919
|
try {
|
|
3469
3920
|
const manifest = loadManifest(opts.manifest);
|
|
@@ -3506,6 +3957,11 @@ Available: ${available}`
|
|
|
3506
3957
|
const wrapperScript = scopeData?.hasWrapper === true ? await buildWrapperScript(scopeData.filePath) : void 0;
|
|
3507
3958
|
const scenarios = buildScenarioMap(opts, scopeData);
|
|
3508
3959
|
const globalCssFiles = loadGlobalCssFilesFromConfig(rootDir);
|
|
3960
|
+
if (globalCssFiles.length === 0) {
|
|
3961
|
+
process.stderr.write(
|
|
3962
|
+
"warning: No globalCSS files configured. Tailwind/CSS styles will not be applied to renders.\n Add `components.wrappers.globalCSS` to reactscope.config.json\n"
|
|
3963
|
+
);
|
|
3964
|
+
}
|
|
3509
3965
|
const renderer = buildRenderer(
|
|
3510
3966
|
filePath,
|
|
3511
3967
|
componentName,
|
|
@@ -3583,7 +4039,9 @@ Available: ${available}`
|
|
|
3583
4039
|
);
|
|
3584
4040
|
}
|
|
3585
4041
|
function registerRenderMatrix(renderCmd) {
|
|
3586
|
-
renderCmd.command("matrix <component>").description(
|
|
4042
|
+
renderCmd.command("matrix <component>").description(
|
|
4043
|
+
'Render every combination of values across one or more prop axes.\nProduces a matrix of screenshots \u2014 one cell per combination.\n\nAXES FORMAT (two equivalent forms):\n Short: --axes "variant:primary,ghost size:sm,md,lg"\n JSON: --axes {"variant":["primary","ghost"],"size":["sm","md","lg"]}\n\nCOMPOSITION CONTEXTS (--contexts):\n Test component in different layout environments.\n Available IDs: centered, rtl, sidebar, dark-bg, light-bg\n (Define custom contexts in reactscope.config.json)\n\nSTRESS PRESETS (--stress):\n Inject adversarial content to test edge cases.\n Available IDs: text.long, text.unicode, text.empty\n\nExamples:\n scope render matrix Button --axes "variant:primary,ghost,destructive"\n scope render matrix Button --axes "variant:primary,ghost size:sm,lg" --sprite matrix.png\n scope render matrix Badge --axes "type:info,warn,error" --contexts centered,rtl\n scope render matrix Input --stress text.long,text.unicode --format json'
|
|
4044
|
+
).option(
|
|
3587
4045
|
"--axes <spec>",
|
|
3588
4046
|
`Axis definitions: key:v1,v2 space-separated OR JSON object e.g. 'variant:primary,ghost size:sm,lg' or '{"variant":["primary","ghost"],"size":["sm","lg"]}'`
|
|
3589
4047
|
).option(
|
|
@@ -3742,7 +4200,9 @@ Available: ${available}`
|
|
|
3742
4200
|
);
|
|
3743
4201
|
}
|
|
3744
4202
|
function registerRenderAll(renderCmd) {
|
|
3745
|
-
renderCmd.command("all").description(
|
|
4203
|
+
renderCmd.command("all").description(
|
|
4204
|
+
"Render every component in the manifest and write to .reactscope/renders/.\n\nAlso emits .reactscope/compliance-styles.json (computed CSS class\u2192value map)\nwhich is required by `scope tokens compliance`.\n\nSCENARIO SELECTION:\n Each component is rendered using its default scenario from its .scope file\n if one exists, otherwise with all-default props.\n\nMATRIX AUTO-DETECTION:\n If a component has a .scope file with a matrix block, render all\n will render the matrix cells in addition to the default screenshot.\n\nExamples:\n scope render all\n scope render all --concurrency 8\n scope render all --format json --output-dir .reactscope/renders\n scope render all --manifest ./custom/manifest.json"
|
|
4205
|
+
).option("--concurrency <n>", "Max parallel renders", "4").option("--output-dir <dir>", "Output directory for renders", DEFAULT_OUTPUT_DIR).option("--manifest <path>", "Path to manifest.json", MANIFEST_PATH6).option("--format <fmt>", "Output format: json|png (default: png)", "png").action(
|
|
3746
4206
|
async (opts) => {
|
|
3747
4207
|
try {
|
|
3748
4208
|
const manifest = loadManifest(opts.manifest);
|
|
@@ -3759,17 +4219,31 @@ function registerRenderAll(renderCmd) {
|
|
|
3759
4219
|
process.stderr.write(`Rendering ${total} components (concurrency: ${concurrency})\u2026
|
|
3760
4220
|
`);
|
|
3761
4221
|
const results = [];
|
|
4222
|
+
const complianceStylesMap = {};
|
|
3762
4223
|
let completed = 0;
|
|
3763
4224
|
const renderOne = async (name) => {
|
|
3764
4225
|
const descriptor = manifest.components[name];
|
|
3765
4226
|
if (descriptor === void 0) return;
|
|
3766
4227
|
const filePath = path.resolve(rootDir, descriptor.filePath);
|
|
3767
4228
|
const allCssFiles = loadGlobalCssFilesFromConfig(process.cwd());
|
|
3768
|
-
const
|
|
4229
|
+
const scopeData = await loadScopeFileForComponent(filePath);
|
|
4230
|
+
const scenarioEntries = scopeData !== null ? Object.entries(scopeData.scenarios) : [];
|
|
4231
|
+
const defaultEntry = scenarioEntries.find(([k]) => k === "default") ?? scenarioEntries[0];
|
|
4232
|
+
const renderProps = defaultEntry !== void 0 ? defaultEntry[1] : {};
|
|
4233
|
+
const wrapperScript = scopeData?.hasWrapper === true ? await buildWrapperScript(scopeData.filePath) : void 0;
|
|
4234
|
+
const renderer = buildRenderer(
|
|
4235
|
+
filePath,
|
|
4236
|
+
name,
|
|
4237
|
+
375,
|
|
4238
|
+
812,
|
|
4239
|
+
allCssFiles,
|
|
4240
|
+
process.cwd(),
|
|
4241
|
+
wrapperScript
|
|
4242
|
+
);
|
|
3769
4243
|
const outcome = await render.safeRender(
|
|
3770
|
-
() => renderer.renderCell(
|
|
4244
|
+
() => renderer.renderCell(renderProps, descriptor.complexityClass),
|
|
3771
4245
|
{
|
|
3772
|
-
props:
|
|
4246
|
+
props: renderProps,
|
|
3773
4247
|
sourceLocation: {
|
|
3774
4248
|
file: descriptor.filePath,
|
|
3775
4249
|
line: descriptor.loc.start,
|
|
@@ -3809,6 +4283,77 @@ function registerRenderAll(renderCmd) {
|
|
|
3809
4283
|
fs.writeFileSync(pngPath, result.screenshot);
|
|
3810
4284
|
const jsonPath = path.resolve(outputDir, `${name}.json`);
|
|
3811
4285
|
fs.writeFileSync(jsonPath, JSON.stringify(formatRenderJson(name, {}, result), null, 2));
|
|
4286
|
+
const rawStyles = result.computedStyles["[data-reactscope-root] > *"] ?? {};
|
|
4287
|
+
const compStyles = {
|
|
4288
|
+
colors: {},
|
|
4289
|
+
spacing: {},
|
|
4290
|
+
typography: {},
|
|
4291
|
+
borders: {},
|
|
4292
|
+
shadows: {}
|
|
4293
|
+
};
|
|
4294
|
+
for (const [prop, val] of Object.entries(rawStyles)) {
|
|
4295
|
+
if (!val || val === "none" || val === "") continue;
|
|
4296
|
+
const lower = prop.toLowerCase();
|
|
4297
|
+
if (lower.includes("color") || lower.includes("background")) {
|
|
4298
|
+
compStyles.colors[prop] = val;
|
|
4299
|
+
} else if (lower.includes("padding") || lower.includes("margin") || lower.includes("gap") || lower.includes("width") || lower.includes("height")) {
|
|
4300
|
+
compStyles.spacing[prop] = val;
|
|
4301
|
+
} else if (lower.includes("font") || lower.includes("lineheight") || lower.includes("letterspacing") || lower.includes("texttransform")) {
|
|
4302
|
+
compStyles.typography[prop] = val;
|
|
4303
|
+
} else if (lower.includes("border") || lower.includes("radius") || lower.includes("outline")) {
|
|
4304
|
+
compStyles.borders[prop] = val;
|
|
4305
|
+
} else if (lower.includes("shadow")) {
|
|
4306
|
+
compStyles.shadows[prop] = val;
|
|
4307
|
+
}
|
|
4308
|
+
}
|
|
4309
|
+
complianceStylesMap[name] = compStyles;
|
|
4310
|
+
if (scopeData !== null && Object.keys(scopeData.scenarios).length >= 2) {
|
|
4311
|
+
try {
|
|
4312
|
+
const scenarioEntries2 = Object.entries(scopeData.scenarios);
|
|
4313
|
+
const scenarioAxis = {
|
|
4314
|
+
name: "scenario",
|
|
4315
|
+
values: scenarioEntries2.map(([k]) => k)
|
|
4316
|
+
};
|
|
4317
|
+
const scenarioPropsMap = Object.fromEntries(scenarioEntries2);
|
|
4318
|
+
const matrixRenderer = buildRenderer(
|
|
4319
|
+
filePath,
|
|
4320
|
+
name,
|
|
4321
|
+
375,
|
|
4322
|
+
812,
|
|
4323
|
+
allCssFiles,
|
|
4324
|
+
process.cwd(),
|
|
4325
|
+
wrapperScript
|
|
4326
|
+
);
|
|
4327
|
+
const wrappedRenderer = {
|
|
4328
|
+
_satori: matrixRenderer._satori,
|
|
4329
|
+
async renderCell(props, cc) {
|
|
4330
|
+
const scenarioName = props.scenario;
|
|
4331
|
+
const realProps = scenarioName !== void 0 ? scenarioPropsMap[scenarioName] ?? props : props;
|
|
4332
|
+
return matrixRenderer.renderCell(realProps, cc ?? "simple");
|
|
4333
|
+
}
|
|
4334
|
+
};
|
|
4335
|
+
const matrix = new render.RenderMatrix(wrappedRenderer, [scenarioAxis], {
|
|
4336
|
+
concurrency: 2
|
|
4337
|
+
});
|
|
4338
|
+
const matrixResult = await matrix.render();
|
|
4339
|
+
const matrixCells = matrixResult.cells.map((cell) => ({
|
|
4340
|
+
axisValues: [scenarioEntries2[cell.axisIndices[0] ?? 0]?.[0] ?? ""],
|
|
4341
|
+
screenshot: cell.result.screenshot.toString("base64"),
|
|
4342
|
+
width: cell.result.width,
|
|
4343
|
+
height: cell.result.height,
|
|
4344
|
+
renderTimeMs: cell.result.renderTimeMs
|
|
4345
|
+
}));
|
|
4346
|
+
const existingJson = JSON.parse(fs.readFileSync(jsonPath, "utf-8"));
|
|
4347
|
+
existingJson.cells = matrixCells;
|
|
4348
|
+
existingJson.axisLabels = [scenarioAxis.values];
|
|
4349
|
+
fs.writeFileSync(jsonPath, JSON.stringify(existingJson, null, 2));
|
|
4350
|
+
} catch (matrixErr) {
|
|
4351
|
+
process.stderr.write(
|
|
4352
|
+
` [warn] Matrix render for ${name} failed: ${matrixErr instanceof Error ? matrixErr.message : String(matrixErr)}
|
|
4353
|
+
`
|
|
4354
|
+
);
|
|
4355
|
+
}
|
|
4356
|
+
}
|
|
3812
4357
|
if (isTTY()) {
|
|
3813
4358
|
process.stdout.write(
|
|
3814
4359
|
`\u2713 ${name} \u2192 ${opts.outputDir}/${name}.png (${result.width}\xD7${result.height}, ${result.renderTimeMs.toFixed(0)}ms)
|
|
@@ -3832,6 +4377,14 @@ function registerRenderAll(renderCmd) {
|
|
|
3832
4377
|
}
|
|
3833
4378
|
await Promise.all(workers);
|
|
3834
4379
|
await shutdownPool3();
|
|
4380
|
+
const compStylesPath = path.resolve(
|
|
4381
|
+
path.resolve(process.cwd(), opts.outputDir),
|
|
4382
|
+
"..",
|
|
4383
|
+
"compliance-styles.json"
|
|
4384
|
+
);
|
|
4385
|
+
fs.writeFileSync(compStylesPath, JSON.stringify(complianceStylesMap, null, 2));
|
|
4386
|
+
process.stderr.write(`[scope/render] \u2713 Wrote compliance-styles.json
|
|
4387
|
+
`);
|
|
3835
4388
|
process.stderr.write("\n");
|
|
3836
4389
|
const summary = formatSummaryText(results, outputDir);
|
|
3837
4390
|
process.stderr.write(`${summary}
|
|
@@ -3871,7 +4424,7 @@ function resolveMatrixFormat(formatFlag, spriteAlreadyWritten) {
|
|
|
3871
4424
|
}
|
|
3872
4425
|
function createRenderCommand() {
|
|
3873
4426
|
const renderCmd = new commander.Command("render").description(
|
|
3874
|
-
|
|
4427
|
+
'Render React components to PNG screenshots or JSON render data.\n\nScope uses two render engines depending on component complexity:\n Satori \u2014 fast SVG\u2192PNG renderer for simple/presentational components\n BrowserPool \u2014 Playwright headless browser for complex components\n (context providers, hooks, async, global CSS)\n\nPREREQUISITES:\n 1. reactscope.config.json exists (scope init)\n 2. manifest.json is up to date (scope manifest generate)\n 3. If using globalCSS: Tailwind/PostCSS is configured in the project\n\nOUTPUTS (written to .reactscope/renders/<ComponentName>/):\n screenshot.png retina-quality PNG (2\xD7 physical pixels, displayed at 1\xD7)\n render.json props, dimensions, DOM snapshot, a11y, computed styles\n compliance-styles.json (render all only) \u2014 token matching input\n\nExamples:\n scope render component Button\n scope render matrix Button --axes "variant:primary,ghost size:sm,md,lg"\n scope render all\n scope render all --format json --output-dir ./out'
|
|
3875
4428
|
);
|
|
3876
4429
|
registerRenderSingle(renderCmd);
|
|
3877
4430
|
registerRenderMatrix(renderCmd);
|
|
@@ -4031,12 +4584,12 @@ async function runBaseline(options = {}) {
|
|
|
4031
4584
|
fs.mkdirSync(rendersDir, { recursive: true });
|
|
4032
4585
|
let manifest$1;
|
|
4033
4586
|
if (manifestPath !== void 0) {
|
|
4034
|
-
const { readFileSync:
|
|
4587
|
+
const { readFileSync: readFileSync14 } = await import('fs');
|
|
4035
4588
|
const absPath = path.resolve(rootDir, manifestPath);
|
|
4036
4589
|
if (!fs.existsSync(absPath)) {
|
|
4037
4590
|
throw new Error(`Manifest not found at ${absPath}.`);
|
|
4038
4591
|
}
|
|
4039
|
-
manifest$1 = JSON.parse(
|
|
4592
|
+
manifest$1 = JSON.parse(readFileSync14(absPath, "utf-8"));
|
|
4040
4593
|
process.stderr.write(`Loaded manifest from ${manifestPath}
|
|
4041
4594
|
`);
|
|
4042
4595
|
} else {
|
|
@@ -5089,7 +5642,9 @@ var MIME_TYPES = {
|
|
|
5089
5642
|
".ico": "image/x-icon"
|
|
5090
5643
|
};
|
|
5091
5644
|
function registerBuild(siteCmd) {
|
|
5092
|
-
siteCmd.command("build").description(
|
|
5645
|
+
siteCmd.command("build").description(
|
|
5646
|
+
'Build the static HTML site from manifest + render outputs.\n\nINPUT DIRECTORY (.reactscope/ by default) must contain:\n manifest.json component registry\n renders/ screenshots and render.json files from `scope render all`\n\nOPTIONAL:\n --compliance <path> include token compliance scores on detail pages\n --base-path <path> set if deploying to a subdirectory (e.g. /ui-docs)\n\nExamples:\n scope site build\n scope site build --title "Design System" -o .reactscope/site\n scope site build --compliance .reactscope/compliance-styles.json\n scope site build --base-path /ui'
|
|
5647
|
+
).option("-i, --input <path>", "Path to .reactscope input directory", ".reactscope").option("-o, --output <path>", "Output directory for generated site", ".reactscope/site").option("--base-path <path>", "Base URL path prefix for subdirectory deployment", "/").option("--compliance <path>", "Path to compliance batch report JSON").option("--title <text>", "Site title", "Scope \u2014 Component Gallery").action(
|
|
5093
5648
|
async (opts) => {
|
|
5094
5649
|
try {
|
|
5095
5650
|
const inputDir = path.resolve(process.cwd(), opts.input);
|
|
@@ -5131,7 +5686,9 @@ Run \`scope manifest generate\` first.`
|
|
|
5131
5686
|
);
|
|
5132
5687
|
}
|
|
5133
5688
|
function registerServe(siteCmd) {
|
|
5134
|
-
siteCmd.command("serve").description(
|
|
5689
|
+
siteCmd.command("serve").description(
|
|
5690
|
+
"Start a local HTTP server for the built site directory.\n\nRun `scope site build` first.\nCtrl+C to stop.\n\nExamples:\n scope site serve\n scope site serve --port 8080\n scope site serve --dir ./my-site-output"
|
|
5691
|
+
).option("-p, --port <number>", "Port to listen on", "3000").option("-d, --dir <path>", "Directory to serve", ".reactscope/site").action((opts) => {
|
|
5135
5692
|
try {
|
|
5136
5693
|
const port = Number.parseInt(opts.port, 10);
|
|
5137
5694
|
if (Number.isNaN(port) || port < 1 || port > 65535) {
|
|
@@ -5195,7 +5752,7 @@ Run \`scope site build\` first.`
|
|
|
5195
5752
|
}
|
|
5196
5753
|
function createSiteCommand() {
|
|
5197
5754
|
const siteCmd = new commander.Command("site").description(
|
|
5198
|
-
|
|
5755
|
+
'Build and serve the static HTML component gallery site.\n\nPREREQUISITES:\n scope manifest generate (manifest.json)\n scope render all (renders/ + compliance-styles.json)\n\nSITE CONTENTS:\n /index.html component gallery with screenshots + metadata\n /<component>/index.html detail page: props, renders, matrix, X-Ray, compliance\n\nExamples:\n scope site build && scope site serve\n scope site build --title "Acme UI" --compliance .reactscope/compliance-styles.json\n scope site serve --port 8080'
|
|
5199
5756
|
);
|
|
5200
5757
|
registerBuild(siteCmd);
|
|
5201
5758
|
registerServe(siteCmd);
|
|
@@ -5333,7 +5890,9 @@ function formatComplianceReport(batch, threshold) {
|
|
|
5333
5890
|
return lines.join("\n");
|
|
5334
5891
|
}
|
|
5335
5892
|
function registerCompliance(tokensCmd) {
|
|
5336
|
-
tokensCmd.command("compliance").description(
|
|
5893
|
+
tokensCmd.command("compliance").description(
|
|
5894
|
+
"Compute a token compliance score across all rendered components.\n\nCompares computed CSS values from .reactscope/compliance-styles.json\nagainst the token file \u2014 reports what % of style values are on-token.\n\nPREREQUISITES:\n scope render all must have run first (produces compliance-styles.json)\n\nSCORING:\n compliant value exactly matches a token\n near-match value is within tolerance of a token (e.g. close color)\n off-token value not found in token file\n\nEXIT CODES:\n 0 compliance >= threshold (or no --threshold set)\n 1 compliance < threshold\n\nExamples:\n scope tokens compliance\n scope tokens compliance --threshold 90\n scope tokens compliance --format json | jq '.summary'\n scope tokens compliance --styles ./custom/compliance-styles.json"
|
|
5895
|
+
).option("--file <path>", "Path to token file (overrides config)").option("--styles <path>", `Path to compliance styles JSON (default: ${DEFAULT_STYLES_PATH})`).option("--threshold <n>", "Exit code 1 if compliance score is below this percentage (0-100)").option("--format <fmt>", "Output format: json or text (default: auto-detect)").action((opts) => {
|
|
5337
5896
|
try {
|
|
5338
5897
|
const tokenFilePath = resolveTokenFilePath(opts.file);
|
|
5339
5898
|
const { tokens: tokens$1 } = loadTokens(tokenFilePath);
|
|
@@ -5391,7 +5950,9 @@ function resolveTokenFilePath2(fileFlag) {
|
|
|
5391
5950
|
return path.resolve(process.cwd(), DEFAULT_TOKEN_FILE);
|
|
5392
5951
|
}
|
|
5393
5952
|
function createTokensExportCommand() {
|
|
5394
|
-
return new commander.Command("export").description(
|
|
5953
|
+
return new commander.Command("export").description(
|
|
5954
|
+
'Export design tokens to CSS variables, TypeScript, SCSS, Tailwind config, Figma, or flat JSON.\n\nFORMATS:\n css CSS custom properties (:root { --color-primary-500: #3b82f6; })\n scss SCSS variables ($color-primary-500: #3b82f6;)\n ts TypeScript const export (export const tokens = {...})\n tailwind Tailwind theme.extend block (paste into tailwind.config.js)\n flat-json Flat { path: value } map (useful for tooling integration)\n figma Figma Tokens plugin format\n\nExamples:\n scope tokens export --format css --out src/tokens.css\n scope tokens export --format css --prefix brand --selector ":root, [data-theme]"\n scope tokens export --format tailwind --out tailwind-tokens.js\n scope tokens export --format ts --out src/tokens.ts\n scope tokens export --format css --theme dark --out dark-tokens.css'
|
|
5955
|
+
).requiredOption("--format <fmt>", `Output format: ${SUPPORTED_FORMATS.join(", ")}`).option("--file <path>", "Path to token file (overrides config)").option("--out <path>", "Write output to file instead of stdout").option("--prefix <prefix>", "CSS/SCSS: prefix for variable names (e.g. 'scope')").option("--selector <selector>", "CSS: custom root selector (default: ':root')").option(
|
|
5395
5956
|
"--theme <name>",
|
|
5396
5957
|
"Include theme overrides for the named theme (applies to css, ts, scss, tailwind, figma)"
|
|
5397
5958
|
).action(
|
|
@@ -5531,7 +6092,9 @@ function formatImpactSummary(report) {
|
|
|
5531
6092
|
return `\u2192 ${parts.join(", ")}`;
|
|
5532
6093
|
}
|
|
5533
6094
|
function registerImpact(tokensCmd) {
|
|
5534
|
-
tokensCmd.command("impact <path>").description(
|
|
6095
|
+
tokensCmd.command("impact <path>").description(
|
|
6096
|
+
"List every component and CSS element that uses a given token.\nUse this to understand the blast radius before changing a token value.\n\nPREREQUISITE: scope render all (populates compliance-styles.json)\n\nExamples:\n scope tokens impact color.primary.500\n scope tokens impact spacing.4 --format json\n scope tokens impact font.size.base | grep Button"
|
|
6097
|
+
).option("--file <path>", "Path to token file (overrides config)").option("--styles <path>", `Path to compliance styles JSON (default: ${DEFAULT_STYLES_PATH2})`).option("--new-value <value>", "Proposed new value \u2014 report visual severity of the change").option("--format <fmt>", "Output format: json or text (default: auto-detect)").action(
|
|
5535
6098
|
(tokenPath, opts) => {
|
|
5536
6099
|
try {
|
|
5537
6100
|
const tokenFilePath = resolveTokenFilePath(opts.file);
|
|
@@ -5620,7 +6183,9 @@ async function renderComponentWithCssOverride(filePath, componentName, cssOverri
|
|
|
5620
6183
|
}
|
|
5621
6184
|
}
|
|
5622
6185
|
function registerPreview(tokensCmd) {
|
|
5623
|
-
tokensCmd.command("preview <path>").description(
|
|
6186
|
+
tokensCmd.command("preview <path>").description(
|
|
6187
|
+
'Render before/after screenshots of all components affected by a token change.\nUseful for visual review before committing a token value update.\n\nPREREQUISITE: scope render all (provides baseline renders)\n\nExamples:\n scope tokens preview color.primary.500\n scope tokens preview color.primary.500 --new-value "#2563eb" -o preview.png'
|
|
6188
|
+
).requiredOption("--new-value <value>", "The proposed new resolved value for the token").option("--sprite", "Output a PNG sprite sheet (default when TTY)", false).option("-o, --output <path>", "Output PNG path (default: .reactscope/previews/<token>.png)").option("--file <path>", "Path to token file (overrides config)").option("--styles <path>", `Path to compliance styles JSON (default: ${DEFAULT_STYLES_PATH3})`).option("--manifest <path>", "Path to manifest.json", DEFAULT_MANIFEST_PATH).option("--format <fmt>", "Output format: json or text (default: auto-detect)").option("--timeout <ms>", "Browser timeout per render (ms)", "10000").option("--viewport-width <px>", "Viewport width in pixels", "1280").option("--viewport-height <px>", "Viewport height in pixels", "720").action(
|
|
5624
6189
|
async (tokenPath, opts) => {
|
|
5625
6190
|
try {
|
|
5626
6191
|
const tokenFilePath = resolveTokenFilePath(opts.file);
|
|
@@ -5867,7 +6432,9 @@ function buildResolutionChain(startPath, rawTokens) {
|
|
|
5867
6432
|
return chain;
|
|
5868
6433
|
}
|
|
5869
6434
|
function registerGet2(tokensCmd) {
|
|
5870
|
-
tokensCmd.command("get <path>").description(
|
|
6435
|
+
tokensCmd.command("get <path>").description(
|
|
6436
|
+
"Resolve a token path and print its final computed value.\nFollows all {ref} chains to the raw value.\n\nExamples:\n scope tokens get color.primary.500\n scope tokens get spacing.4 --format json\n scope tokens get font.size.base --file ./tokens/brand.json"
|
|
6437
|
+
).option("--file <path>", "Path to token file (overrides config)").option("--format <fmt>", "Output format: json or text (default: auto-detect)").action((tokenPath, opts) => {
|
|
5871
6438
|
try {
|
|
5872
6439
|
const filePath = resolveTokenFilePath(opts.file);
|
|
5873
6440
|
const { tokens: tokens$1 } = loadTokens(filePath);
|
|
@@ -5892,7 +6459,18 @@ function registerGet2(tokensCmd) {
|
|
|
5892
6459
|
});
|
|
5893
6460
|
}
|
|
5894
6461
|
function registerList2(tokensCmd) {
|
|
5895
|
-
tokensCmd.command("list [category]").description(
|
|
6462
|
+
tokensCmd.command("list [category]").description(
|
|
6463
|
+
`List all tokens, optionally filtered by category prefix or type.
|
|
6464
|
+
|
|
6465
|
+
CATEGORY: top-level token namespace (e.g. "color", "spacing", "typography")
|
|
6466
|
+
TYPE: token value type \u2014 color | spacing | typography | shadow | radius | opacity
|
|
6467
|
+
|
|
6468
|
+
Examples:
|
|
6469
|
+
scope tokens list
|
|
6470
|
+
scope tokens list color
|
|
6471
|
+
scope tokens list --type spacing
|
|
6472
|
+
scope tokens list color --format json | jq '.[].path'`
|
|
6473
|
+
).option("--type <type>", "Filter by token type (color, dimension, fontFamily, etc.)").option("--file <path>", "Path to token file (overrides config)").option("--format <fmt>", "Output format: json or table (default: auto-detect)").action(
|
|
5896
6474
|
(category, opts) => {
|
|
5897
6475
|
try {
|
|
5898
6476
|
const filePath = resolveTokenFilePath(opts.file);
|
|
@@ -5922,7 +6500,9 @@ function registerList2(tokensCmd) {
|
|
|
5922
6500
|
);
|
|
5923
6501
|
}
|
|
5924
6502
|
function registerSearch(tokensCmd) {
|
|
5925
|
-
tokensCmd.command("search <value>").description(
|
|
6503
|
+
tokensCmd.command("search <value>").description(
|
|
6504
|
+
'Find the token(s) whose computed value matches the given raw value.\nSupports fuzzy color matching (hex \u2194 rgb \u2194 hsl equivalence).\n\nExamples:\n scope tokens search "#3b82f6"\n scope tokens search "16px"\n scope tokens search "rgb(59, 130, 246)" # fuzzy-matches #3b82f6'
|
|
6505
|
+
).option("--type <type>", "Restrict search to a specific token type").option("--fuzzy", "Return nearest match even if no exact match exists", false).option("--file <path>", "Path to token file (overrides config)").option("--format <fmt>", "Output format: json or table (default: auto-detect)").action(
|
|
5926
6506
|
(value, opts) => {
|
|
5927
6507
|
try {
|
|
5928
6508
|
const filePath = resolveTokenFilePath(opts.file);
|
|
@@ -6005,7 +6585,9 @@ Tip: use --fuzzy for nearest-match search.
|
|
|
6005
6585
|
);
|
|
6006
6586
|
}
|
|
6007
6587
|
function registerResolve(tokensCmd) {
|
|
6008
|
-
tokensCmd.command("resolve <path>").description(
|
|
6588
|
+
tokensCmd.command("resolve <path>").description(
|
|
6589
|
+
"Print the full reference chain from a token path down to its raw value.\nUseful for debugging circular references or understanding token inheritance.\n\nExamples:\n scope tokens resolve color.primary.500\n scope tokens resolve button.background --format json"
|
|
6590
|
+
).option("--file <path>", "Path to token file (overrides config)").option("--format <fmt>", "Output format: json or text (default: auto-detect)").action((tokenPath, opts) => {
|
|
6009
6591
|
try {
|
|
6010
6592
|
const filePath = resolveTokenFilePath(opts.file);
|
|
6011
6593
|
const absFilePath = filePath;
|
|
@@ -6041,7 +6623,19 @@ function registerResolve(tokensCmd) {
|
|
|
6041
6623
|
}
|
|
6042
6624
|
function registerValidate(tokensCmd) {
|
|
6043
6625
|
tokensCmd.command("validate").description(
|
|
6044
|
-
|
|
6626
|
+
`Validate the token file and report errors.
|
|
6627
|
+
|
|
6628
|
+
CHECKS:
|
|
6629
|
+
- Circular reference chains (A \u2192 B \u2192 A)
|
|
6630
|
+
- Broken references ({path.that.does.not.exist})
|
|
6631
|
+
- Type mismatches (token declared as "color" but value is a number)
|
|
6632
|
+
- Duplicate paths
|
|
6633
|
+
|
|
6634
|
+
Exits 1 if any errors are found (suitable for CI).
|
|
6635
|
+
|
|
6636
|
+
Examples:
|
|
6637
|
+
scope tokens validate
|
|
6638
|
+
scope tokens validate --format json | jq '.errors'`
|
|
6045
6639
|
).option("--file <path>", "Path to token file (overrides config)").option("--format <fmt>", "Output format: json or text (default: auto-detect)").action((opts) => {
|
|
6046
6640
|
try {
|
|
6047
6641
|
const filePath = resolveTokenFilePath(opts.file);
|
|
@@ -6120,7 +6714,7 @@ function outputValidationResult(filePath, errors, useJson) {
|
|
|
6120
6714
|
}
|
|
6121
6715
|
function createTokensCommand() {
|
|
6122
6716
|
const tokensCmd = new commander.Command("tokens").description(
|
|
6123
|
-
|
|
6717
|
+
'Query, validate, and export design tokens from reactscope.tokens.json.\n\nTOKEN FILE RESOLUTION (in priority order):\n 1. --file <path> explicit override\n 2. tokens.file in reactscope.config.json\n 3. reactscope.tokens.json default (project root)\n\nTOKEN FILE FORMAT (reactscope.tokens.json):\n Nested JSON. Each leaf is a token with { value, type } or just a raw value.\n Paths use dot notation: color.primary.500, spacing.4, font.size.base\n References use {path.to.other.token} syntax.\n Themes: top-level "themes" key with named override maps.\n\nTOKEN TYPES: color | spacing | typography | shadow | radius | opacity | other\n\nExamples:\n scope tokens validate\n scope tokens list color\n scope tokens get color.primary.500\n scope tokens compliance\n scope tokens export --format css --out tokens.css'
|
|
6124
6718
|
);
|
|
6125
6719
|
registerGet2(tokensCmd);
|
|
6126
6720
|
registerList2(tokensCmd);
|
|
@@ -6136,8 +6730,12 @@ function createTokensCommand() {
|
|
|
6136
6730
|
|
|
6137
6731
|
// src/program.ts
|
|
6138
6732
|
function createProgram(options = {}) {
|
|
6139
|
-
const program = new commander.Command("scope").version(options.version ?? "0.1.0").description(
|
|
6140
|
-
|
|
6733
|
+
const program = new commander.Command("scope").version(options.version ?? "0.1.0").description(
|
|
6734
|
+
'Scope \u2014 static analysis + visual rendering toolkit for React component libraries.\n\nScope answers questions about React codebases \u2014 structure, props, visual output,\ndesign token compliance \u2014 without running the full application.\n\nQUICKSTART (new project):\n scope init # detect config, scaffold reactscope.config.json\n scope doctor # verify setup before doing anything else\n scope manifest generate # scan source and build component manifest\n scope render all # screenshot every component\n scope site build # build HTML gallery\n scope site serve # open at http://localhost:3000\n\nQUICKSTART (existing project / CI):\n scope ci # manifest \u2192 render \u2192 compliance \u2192 regression in one step\n\nAGENT BOOTSTRAP:\n scope get-skill # print SKILL.md to stdout \u2014 pipe into agent context\n\nCONFIG FILE: reactscope.config.json (created by `scope init`)\n components.include glob patterns for component files (e.g. "src/**/*.tsx")\n components.wrappers providers and globalCSS to wrap every render\n render.viewport default viewport width\xD7height in px\n tokens.file path to reactscope.tokens.json (default)\n output.dir output root (default: .reactscope/)\n ci.complianceThreshold fail threshold for `scope ci` (default: 0.90)\n\nOUTPUT DIRECTORY: .reactscope/\n manifest.json component registry \u2014 updated by `scope manifest generate`\n renders/<Name>/ PNGs + render.json per component\n compliance-styles.json computed-style map for token matching\n site/ static HTML gallery (built by `scope site build`)\n\nRun `scope <command> --help` for detailed flags and examples.'
|
|
6735
|
+
);
|
|
6736
|
+
program.command("capture <url>").description(
|
|
6737
|
+
"Capture the live React component tree from a running app and emit it as JSON.\nRequires a running dev server at the given URL (e.g. http://localhost:5173).\n\nExamples:\n scope capture http://localhost:5173\n scope capture http://localhost:5173 -o report.json --pretty\n scope capture http://localhost:5173 --timeout 15000 --wait 500"
|
|
6738
|
+
).option("-o, --output <path>", "Write JSON to file instead of stdout").option("--pretty", "Pretty-print JSON output (default: minified)", false).option("--timeout <ms>", "Max wait time for React to mount (ms)", "10000").option("--wait <ms>", "Additional wait after page load before capture (ms)", "0").action(
|
|
6141
6739
|
async (url, opts) => {
|
|
6142
6740
|
try {
|
|
6143
6741
|
const { report } = await browserCapture({
|
|
@@ -6161,7 +6759,9 @@ function createProgram(options = {}) {
|
|
|
6161
6759
|
}
|
|
6162
6760
|
}
|
|
6163
6761
|
);
|
|
6164
|
-
program.command("tree <url>").description(
|
|
6762
|
+
program.command("tree <url>").description(
|
|
6763
|
+
"Print a formatted React component tree from a running app.\nUseful for quickly understanding component hierarchy without full capture.\n\nExamples:\n scope tree http://localhost:5173\n scope tree http://localhost:5173 --show-props --show-hooks\n scope tree http://localhost:5173 --depth 4"
|
|
6764
|
+
).option("--depth <n>", "Max depth to display (default: unlimited)").option("--show-props", "Include prop names next to components", false).option("--show-hooks", "Show hook counts per component", false).option("--timeout <ms>", "Max wait time for React to mount (ms)", "10000").option("--wait <ms>", "Additional wait after page load before capture (ms)", "0").action(
|
|
6165
6765
|
async (url, opts) => {
|
|
6166
6766
|
try {
|
|
6167
6767
|
const { report } = await browserCapture({
|
|
@@ -6184,7 +6784,9 @@ function createProgram(options = {}) {
|
|
|
6184
6784
|
}
|
|
6185
6785
|
}
|
|
6186
6786
|
);
|
|
6187
|
-
program.command("report <url>").description(
|
|
6787
|
+
program.command("report <url>").description(
|
|
6788
|
+
"Capture a React app and print a human-readable analysis summary.\nIncludes component count, hook usage, side-effect summary, and more.\n\nExamples:\n scope report http://localhost:5173\n scope report http://localhost:5173 --json\n scope report http://localhost:5173 --json -o report.json"
|
|
6789
|
+
).option("--json", "Output as structured JSON instead of human-readable text", false).option("--timeout <ms>", "Max wait time for React to mount (ms)", "10000").option("--wait <ms>", "Additional wait after page load before capture (ms)", "0").action(
|
|
6188
6790
|
async (url, opts) => {
|
|
6189
6791
|
try {
|
|
6190
6792
|
const { report } = await browserCapture({
|
|
@@ -6208,7 +6810,9 @@ function createProgram(options = {}) {
|
|
|
6208
6810
|
}
|
|
6209
6811
|
}
|
|
6210
6812
|
);
|
|
6211
|
-
program.command("generate").description(
|
|
6813
|
+
program.command("generate").description(
|
|
6814
|
+
'Generate a Playwright test file from a Scope trace (.json).\nTraces are produced by scope instrument renders or scope capture.\n\nExamples:\n scope generate trace.json\n scope generate trace.json -o tests/scope.spec.ts -d "User login flow"'
|
|
6815
|
+
).argument("<trace>", "Path to a serialized Scope trace (.json)").option("-o, --output <path>", "Output file path", "scope.spec.ts").option("-d, --description <text>", "Test description").action((tracePath, opts) => {
|
|
6212
6816
|
const raw = fs.readFileSync(tracePath, "utf-8");
|
|
6213
6817
|
const trace = playwright.loadTrace(raw);
|
|
6214
6818
|
const source = playwright.generateTest(trace, {
|
|
@@ -6224,6 +6828,8 @@ function createProgram(options = {}) {
|
|
|
6224
6828
|
program.addCommand(createInstrumentCommand());
|
|
6225
6829
|
program.addCommand(createInitCommand());
|
|
6226
6830
|
program.addCommand(createCiCommand());
|
|
6831
|
+
program.addCommand(createDoctorCommand());
|
|
6832
|
+
program.addCommand(createGetSkillCommand());
|
|
6227
6833
|
const existingReportCmd = program.commands.find((c) => c.name() === "report");
|
|
6228
6834
|
if (existingReportCmd !== void 0) {
|
|
6229
6835
|
registerBaselineSubCommand(existingReportCmd);
|
|
@@ -6236,6 +6842,8 @@ function createProgram(options = {}) {
|
|
|
6236
6842
|
|
|
6237
6843
|
exports.CI_EXIT = CI_EXIT;
|
|
6238
6844
|
exports.createCiCommand = createCiCommand;
|
|
6845
|
+
exports.createDoctorCommand = createDoctorCommand;
|
|
6846
|
+
exports.createGetSkillCommand = createGetSkillCommand;
|
|
6239
6847
|
exports.createInitCommand = createInitCommand;
|
|
6240
6848
|
exports.createInstrumentCommand = createInstrumentCommand;
|
|
6241
6849
|
exports.createManifestCommand = createManifestCommand;
|