@scrymore/scry-deployer 0.13.1-nightly.20261104035911 → 0.14.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/README.md +93 -6
- package/bin/cli.js +61 -7
- package/lib/capture/web/affected.js +159 -0
- package/lib/capture/web/cores.js +52 -0
- package/lib/capture/web/csf-meta.js +161 -0
- package/lib/capture/web/driver.js +495 -0
- package/lib/capture/web/harness/dom-tree.js +110 -0
- package/lib/capture/web/harness/harness.mjs +343 -0
- package/lib/capture/web/index.js +277 -0
- package/lib/capture/web/options.js +106 -0
- package/lib/capture/web/qualify.js +177 -0
- package/lib/capture/web/scf-writer.js +288 -0
- package/lib/capture/web/signals.js +41 -0
- package/lib/capture/web/storybook-config.js +213 -0
- package/lib/capture/web/vite-server.js +325 -0
- package/lib/init.js +35 -11
- package/lib/templates.js +243 -3
- package/lib/update-workflows.js +172 -5
- package/lib/uploadCommand.js +8 -1
- package/package.json +1 -1
- package/scripts/regenerate-workflow-templates.js +3 -1
package/README.md
CHANGED
|
@@ -33,6 +33,19 @@ npx skills add epinnock/scry-node --skill ss
|
|
|
33
33
|
|
|
34
34
|
It needs the Scry MCP connection that `scry-setup` configures.
|
|
35
35
|
|
|
36
|
+
### Use your shared Scry clipboard
|
|
37
|
+
|
|
38
|
+
If you copy with Scry Copy in Scry Sync, install the `sc` skill and type `/sc`
|
|
39
|
+
(or `/sc turn this into a table`) to hand the newest item on your shared
|
|
40
|
+
clipboard (a copy, or your newest snip) to the assistant:
|
|
41
|
+
|
|
42
|
+
```bash
|
|
43
|
+
npx skills add epinnock/scry-node --skill sc
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
It also needs the Scry MCP connection. Clipboard content is treated as
|
|
47
|
+
untrusted data.
|
|
48
|
+
|
|
36
49
|
## Set up directly with the CLI
|
|
37
50
|
|
|
38
51
|
`init` writes configuration and workflows, configures GitHub secrets, then
|
|
@@ -48,7 +61,7 @@ Visit the [Scry Dashboard](https://dashboard.scrymore.com) and:
|
|
|
48
61
|
### 2. Run the setup command
|
|
49
62
|
|
|
50
63
|
```bash
|
|
51
|
-
npx @scrymore/scry-deployer init --
|
|
64
|
+
npx @scrymore/scry-deployer init --project-id YOUR_PROJECT_ID --api-key YOUR_API_KEY
|
|
52
65
|
```
|
|
53
66
|
|
|
54
67
|
**That's it!** 🎉
|
|
@@ -112,10 +125,10 @@ Requires Node.js 20.9 or newer (Node 18 is end of life; use `@scrymore/scry-depl
|
|
|
112
125
|
|
|
113
126
|
```bash
|
|
114
127
|
# From npm (recommended)
|
|
115
|
-
npx @scrymore/scry-deployer init --
|
|
128
|
+
npx @scrymore/scry-deployer init --project-id xxx --api-key yyy
|
|
116
129
|
|
|
117
130
|
# From GitHub (latest from main branch)
|
|
118
|
-
npx github:scryorg/scry-node init --
|
|
131
|
+
npx github:scryorg/scry-node init --project-id xxx --api-key yyy
|
|
119
132
|
```
|
|
120
133
|
|
|
121
134
|
### Installing as a Dependency
|
|
@@ -138,10 +151,10 @@ After installation, you can run commands using:
|
|
|
138
151
|
|
|
139
152
|
```bash
|
|
140
153
|
# Using the scry-deployer binary
|
|
141
|
-
npm exec -- scry-deployer init --
|
|
154
|
+
npm exec -- scry-deployer init --project-id xxx --api-key yyy
|
|
142
155
|
|
|
143
156
|
# Using the scry alias
|
|
144
|
-
npx scry init --
|
|
157
|
+
npx scry init --project-id xxx --api-key yyy
|
|
145
158
|
|
|
146
159
|
# Using the storybook-deploy alias (for deploy commands)
|
|
147
160
|
npx storybook-deploy --dir ./storybook-static
|
|
@@ -276,6 +289,77 @@ decorators: [(Story) => <SafeAreaProvider><SafeAreaView edges={['top']}><Story /
|
|
|
276
289
|
the table (or to be stricter); it does not move or crop anything. Requires the app's Scry probe, since the
|
|
277
290
|
frame comes from it.
|
|
278
291
|
|
|
292
|
+
### Capture Command (web, build-free)
|
|
293
|
+
|
|
294
|
+
Capture every story of a web Storybook into an SCF bundle without building Storybook, then
|
|
295
|
+
upload the bundle. It needs `@scrymore/scry-deployer` 0.14.0 or newer.
|
|
296
|
+
|
|
297
|
+
```bash
|
|
298
|
+
npx @scrymore/scry-deployer capture web # writes .scry/capture and .scry/capture-report.json
|
|
299
|
+
npx @scrymore/scry-deployer upload .scry/capture # validate and upload the bundle
|
|
300
|
+
```
|
|
301
|
+
|
|
302
|
+
`capture web` starts the project's own Vite dev server, renders each story in headless Chromium
|
|
303
|
+
and writes one image and one structure tree per story. The upload makes the stories searchable
|
|
304
|
+
in Scry. It does not host a browsable Storybook and it does not produce a coverage report; the
|
|
305
|
+
default deploy command still does both.
|
|
306
|
+
|
|
307
|
+
What the project needs:
|
|
308
|
+
|
|
309
|
+
- Storybook 10 on a Vite framework with the React renderer (for example `@storybook/react-vite`).
|
|
310
|
+
Any other Storybook version, builder or renderer stops with a message that says which.
|
|
311
|
+
- `storybook` and `vite` installed in the project. They are resolved from the project.
|
|
312
|
+
- Playwright and its Chromium (`npx playwright install chromium`). A run by hand uses the
|
|
313
|
+
project's Playwright when it has one and otherwise the copy that comes with the deployer's
|
|
314
|
+
dependencies. The generated workflow needs `playwright` (or `@playwright/test`) in the
|
|
315
|
+
project, because it installs Chromium with the project's own Playwright.
|
|
316
|
+
- Node 20.19 or newer.
|
|
317
|
+
|
|
318
|
+
To run it in GitHub Actions, add `--capture web` to `init` (new project) or `update-workflows`
|
|
319
|
+
(project already set up):
|
|
320
|
+
|
|
321
|
+
```bash
|
|
322
|
+
npx -y @scrymore/scry-deployer@^0.14.0 init --project-id YOUR_PROJECT_ID --api-key YOUR_API_KEY --capture web
|
|
323
|
+
npx -y @scrymore/scry-deployer@^0.14.0 update-workflows --capture web
|
|
324
|
+
```
|
|
325
|
+
|
|
326
|
+
Keep the `@^0.14.0`. A deployer older than 0.14.0 (for example one npx has cached) does not
|
|
327
|
+
know `--capture`, ignores it without an error and writes the two default workflows only.
|
|
328
|
+
|
|
329
|
+
Run it at the repository root. The option first checks that the project qualifies. The check
|
|
330
|
+
loads the project's Storybook and Vite config, as Storybook itself does; run it only in a
|
|
331
|
+
repository you trust. Scry, GitHub and npm credentials are removed from the environment of
|
|
332
|
+
that check. If the project does not qualify, the command prints the reason, writes nothing
|
|
333
|
+
and exits 1. If it does:
|
|
334
|
+
|
|
335
|
+
- `.github/workflows/scry-capture-web.yml` is written. On a push to `main` or `master` it
|
|
336
|
+
captures every story and uploads the bundle. If the default branch has another name, change
|
|
337
|
+
`branches` in the file, or the workflow never runs on a push. A run started by hand
|
|
338
|
+
(`workflow_dispatch`) on the default branch uploads; on any other branch it is a dry run
|
|
339
|
+
that validates the bundle and sends nothing.
|
|
340
|
+
- `.github/workflows/deploy-storybook.yml` is written with `--no-analysis` in place of
|
|
341
|
+
`--with-analysis`. It still builds and hosts Storybook and reports coverage. It no longer
|
|
342
|
+
takes the screenshots a second time. (Coverage with `--coverage-execute` still renders the
|
|
343
|
+
stories to run them.)
|
|
344
|
+
- `.github/workflows/deploy-pr-preview.yml` is the same as without the option. Pull requests
|
|
345
|
+
keep their preview, their comment and their screenshots.
|
|
346
|
+
|
|
347
|
+
Pass `--config-dir <dir>` when the Storybook config is not in `.storybook`.
|
|
348
|
+
|
|
349
|
+
Limit in this version: the Storybook project must be at the repository root. Run from a
|
|
350
|
+
subfolder of the repository (a monorepo package), the option stops and writes nothing. For
|
|
351
|
+
such a project, copy `templates/workflows/scry-capture-web.yml` by hand and add
|
|
352
|
+
`working-directory`.
|
|
353
|
+
|
|
354
|
+
The workflow installs the project with its own package manager and lockfile (npm, pnpm, yarn
|
|
355
|
+
or bun). For pnpm it uses the version in `packageManager` in `package.json` when there is
|
|
356
|
+
one; otherwise pnpm 10, or pnpm 8 when the lockfile is older than version 9.
|
|
357
|
+
|
|
358
|
+
To go back, run `update-workflows` without the option and delete `scry-capture-web.yml`.
|
|
359
|
+
|
|
360
|
+
Flags, per-story settings, the report, limits and CI details are in
|
|
361
|
+
[docs/capture-web.md](docs/capture-web.md).
|
|
362
|
+
|
|
279
363
|
### Options
|
|
280
364
|
|
|
281
365
|
The CLI is configured through a combination of command-line options and environment variables. Command-line options always take precedence.
|
|
@@ -1127,7 +1211,7 @@ gh auth login
|
|
|
1127
1211
|
|
|
1128
1212
|
Or skip GitHub CLI setup and set variables manually:
|
|
1129
1213
|
```bash
|
|
1130
|
-
npx @scrymore/scry-deployer init --
|
|
1214
|
+
npx @scrymore/scry-deployer init --project-id xxx --api-key yyy --skip-gh-setup
|
|
1131
1215
|
```
|
|
1132
1216
|
|
|
1133
1217
|
Then manually add variables in GitHub Settings → Secrets and variables → Actions.
|
|
@@ -1168,6 +1252,9 @@ It detects your package manager from the lockfile and your Storybook build scrip
|
|
|
1168
1252
|
`package.json`, and overwrites `.github/workflows/deploy-storybook.yml` and
|
|
1169
1253
|
`.github/workflows/deploy-pr-preview.yml`. Review the diff if you customised them.
|
|
1170
1254
|
|
|
1255
|
+
With `--capture web` (deployer 0.14.0 or newer) it also writes
|
|
1256
|
+
`.github/workflows/scry-capture-web.yml`; see "Capture Command (web, build-free)" above.
|
|
1257
|
+
|
|
1171
1258
|
### Want to customize the generated workflows?
|
|
1172
1259
|
|
|
1173
1260
|
After running `init`, you can edit:
|
package/bin/cli.js
CHANGED
|
@@ -877,31 +877,65 @@ async function main() {
|
|
|
877
877
|
.option('include-source', { describe: "Also upload each capture's component source text (code.componentFile). Off by default: Scry never needs your code", type: 'boolean', default: false })
|
|
878
878
|
.option('repo-root', { describe: 'Repository root that code.componentFile paths are relative to (default: cwd)', type: 'string' })
|
|
879
879
|
.option('dry-run', { describe: 'Validate and zip only; print where the ZIP is', type: 'boolean', default: false })
|
|
880
|
+
.option('allow-partial-bundle', { type: 'boolean', default: false, hidden: true })
|
|
880
881
|
.option('verbose', { describe: 'Enable verbose logging', type: 'boolean' });
|
|
881
882
|
}, async (argv) => {
|
|
882
883
|
const config = loadConfig(argv);
|
|
883
|
-
const outcome = await runUploadBundle({ ...config, path: argv.path, includeSource: argv.includeSource, repoRoot: argv.repoRoot, source: argv.source, dryRun: argv.dryRun });
|
|
884
|
+
const outcome = await runUploadBundle({ ...config, path: argv.path, includeSource: argv.includeSource, repoRoot: argv.repoRoot, source: argv.source, dryRun: argv.dryRun, allowPartialBundle: argv.allowPartialBundle });
|
|
884
885
|
process.exitCode = outcome.exitCode;
|
|
885
886
|
})
|
|
886
|
-
.command('capture <adapter>', 'Capture stories into a Scry Capture Format bundle (adapters: rn)', (yargs) => {
|
|
887
|
+
.command('capture <adapter>', 'Capture stories into a Scry Capture Format bundle (adapters: rn, web)', (yargs) => {
|
|
887
888
|
return yargs
|
|
888
|
-
.positional('adapter', { describe: 'Capture adapter', choices: ['rn'] })
|
|
889
|
-
.option('platform', { describe: 'ios (Simulator, macOS) or android (emulator)', choices: ['ios', 'android']
|
|
889
|
+
.positional('adapter', { describe: 'Capture adapter', choices: ['rn', 'web'] })
|
|
890
|
+
.option('platform', { describe: 'rn: ios (Simulator, macOS) or android (emulator). Required for rn', choices: ['ios', 'android'] })
|
|
890
891
|
.option('device', { describe: 'Simulator name (e.g. "iPhone 16") or AVD name / adb serial', type: 'string' })
|
|
891
892
|
.option('app', { describe: 'Built app to install first (.app for iOS, .apk for Android)', type: 'string' })
|
|
892
893
|
.option('app-id', { describe: 'Bundle id / package (default: from app.json)', type: 'string' })
|
|
893
894
|
.option('open-url', { describe: 'Deep link to open after launch, e.g. exp://127.0.0.1:8081 for Expo Go (with --app-id host.exp.Exponent) or a dev client URL', type: 'string' })
|
|
894
895
|
.option('build', { describe: 'Build and install the app with `expo run:<platform>` when it is not installed', type: 'boolean', default: false })
|
|
895
|
-
.option('project-dir', { describe: '
|
|
896
|
+
.option('project-dir', { describe: 'Project directory (default: cwd)', type: 'string' })
|
|
896
897
|
.option('out', { describe: 'Bundle output directory (default: <project>/.scry/capture)', type: 'string' })
|
|
897
|
-
.option('stories', { describe: 'Comma-separated story ids to capture (default: all)', type: 'string' })
|
|
898
|
+
.option('stories', { describe: 'Comma-separated story ids to capture (default: all). web: writes images and a report, not an upload bundle', type: 'string' })
|
|
898
899
|
.option('metro', { describe: 'Start Metro with STORYBOOK_ENABLED=true when the Storybook channel is not already up', type: 'boolean', default: true })
|
|
899
900
|
.option('ws-port', { describe: 'Storybook channel port', type: 'number', default: 7007 })
|
|
900
901
|
.option('settle-timeout', { describe: 'Per-story budget in ms to render and settle (two identical frames)', type: 'number', default: 10000 })
|
|
901
902
|
.option('safe-area-inset', { describe: 'iOS: top unsafe-area height in points used to flag captures whose story root starts inside it (default: from the simulator model). Flagged captures get x-scry.captureWarnings ["overlaps_top_unsafe_area"]; wrap your stories in a SafeAreaView decorator', type: 'number' })
|
|
902
903
|
.option('structure', { describe: 'Write an rn-fiber structure tree per story when the app exposes one', type: 'boolean', default: true })
|
|
903
|
-
.option('
|
|
904
|
+
.option('config-dir', { describe: 'web: Storybook config directory (default: .storybook)', type: 'string' })
|
|
905
|
+
.option('workers', { describe: 'web: browser pages capturing at once (default: the CPU cores this process may use, at most 4)', type: 'number' })
|
|
906
|
+
.option('max-dropped', { describe: 'web: exit 1 when more than this many stories fail to capture', type: 'number', default: 0 })
|
|
907
|
+
.option('retries', { describe: 'web: extra tries, on a fresh page, for a story that fails', type: 'number', default: 1 })
|
|
908
|
+
.option('story-timeout', { describe: 'web: per-story budget in ms to render and finish its play function', type: 'number', default: 15000 })
|
|
909
|
+
.option('scale', { describe: 'web: device scale factor of the images, above 0 and at most 4', type: 'number', default: 1 })
|
|
910
|
+
.option('viewport', { describe: 'web: browser viewport WIDTHxHEIGHT', type: 'string', default: '1280x720' })
|
|
911
|
+
.option('fixed-time', { describe: 'web: the instant the page clock starts at for each story (ISO 8601), or "off" for the real clock (default: 2026-11-14T12:00:00Z)', type: 'string' })
|
|
912
|
+
.option('changed-since', { describe: 'web: capture only the stories affected by changes since this git ref. Writes images and a report, never an upload bundle', type: 'string' })
|
|
913
|
+
.option('list', { describe: 'web: print the story ids (with --changed-since: the affected story files) one per line and capture nothing', type: 'boolean', default: false })
|
|
914
|
+
.option('list-ids', { describe: 'web: with --changed-since, print the affected story ids instead of story files', type: 'boolean', default: false })
|
|
915
|
+
.option('report', { describe: 'web: where to write the run report JSON (default: next to the bundle, capture-report.json)', type: 'string' })
|
|
916
|
+
.option('allow-partial-bundle', { type: 'boolean', default: false, hidden: true })
|
|
917
|
+
.option('verbose', { describe: 'Enable verbose logging', type: 'boolean' })
|
|
918
|
+
.check((argv) => {
|
|
919
|
+
if (argv.adapter === 'rn' && !argv.platform) throw new Error('Missing required argument: platform');
|
|
920
|
+
return true;
|
|
921
|
+
});
|
|
904
922
|
}, async (argv) => {
|
|
923
|
+
if (argv.adapter === 'web') {
|
|
924
|
+
const { runCaptureWeb } = require('../lib/capture/web/index.js');
|
|
925
|
+
const logger = createLogger(argv);
|
|
926
|
+
let exitCode = 1;
|
|
927
|
+
try {
|
|
928
|
+
const outcome = await runCaptureWeb(argv, { logger, toolVersion: DEPLOYER_VERSION, gitContext: resolveBuildGitContext() });
|
|
929
|
+
exitCode = outcome.exitCode;
|
|
930
|
+
} catch (error) {
|
|
931
|
+
process.stderr.write(`capture web failed: ${error.message}\n`);
|
|
932
|
+
if (argv.verbose && error.stack) process.stderr.write(`${error.stack}\n`);
|
|
933
|
+
}
|
|
934
|
+
// Storybook's presets and the dev server can leave handles open: end the process once the output is flushed.
|
|
935
|
+
process.exitCode = exitCode;
|
|
936
|
+
process.stdout.write('', () => process.stderr.write('', () => process.exit(exitCode)));
|
|
937
|
+
return;
|
|
938
|
+
}
|
|
905
939
|
const { runCaptureRn } = require('../lib/capture/rn.js');
|
|
906
940
|
const logger = createLogger(argv);
|
|
907
941
|
try {
|
|
@@ -1027,6 +1061,15 @@ async function main() {
|
|
|
1027
1061
|
default: false,
|
|
1028
1062
|
alias: 'skipGhSetup'
|
|
1029
1063
|
})
|
|
1064
|
+
.option('capture', {
|
|
1065
|
+
describe: 'web: also write .github/workflows/scry-capture-web.yml (build-free capture: Storybook 10, a Vite framework, React, Playwright in the project) and stop deploy-storybook.yml taking the screenshots a second time. Run it at the repository root. Stops and writes nothing when the project does not qualify. The check loads the project\'s Storybook and Vite config, as Storybook itself does; run it only in a repository you trust',
|
|
1066
|
+
choices: ['web'],
|
|
1067
|
+
})
|
|
1068
|
+
.option('config-dir', {
|
|
1069
|
+
describe: 'With --capture web: the Storybook config directory, relative to the repository root (default: .storybook)',
|
|
1070
|
+
type: 'string',
|
|
1071
|
+
alias: 'configDir',
|
|
1072
|
+
})
|
|
1030
1073
|
.option('commit-api-key', {
|
|
1031
1074
|
describe: 'Write the API key into the committed config file (not recommended)',
|
|
1032
1075
|
type: 'boolean',
|
|
@@ -1050,6 +1093,8 @@ async function main() {
|
|
|
1050
1093
|
apiUrl: argv.apiUrl,
|
|
1051
1094
|
skipGhSetup: argv.skipGhSetup,
|
|
1052
1095
|
commitApiKey: argv.commitApiKey,
|
|
1096
|
+
capture: argv.capture,
|
|
1097
|
+
configDir: argv.configDir,
|
|
1053
1098
|
verbose: argv.verbose
|
|
1054
1099
|
};
|
|
1055
1100
|
|
|
@@ -1062,6 +1107,15 @@ async function main() {
|
|
|
1062
1107
|
type: 'boolean',
|
|
1063
1108
|
default: false,
|
|
1064
1109
|
})
|
|
1110
|
+
.option('capture', {
|
|
1111
|
+
describe: 'web: also write .github/workflows/scry-capture-web.yml (build-free capture: Storybook 10, a Vite framework, React, Playwright in the project) and stop deploy-storybook.yml taking the screenshots a second time. Run it at the repository root. Stops and writes nothing when the project does not qualify. The check loads the project\'s Storybook and Vite config, as Storybook itself does; run it only in a repository you trust',
|
|
1112
|
+
choices: ['web'],
|
|
1113
|
+
})
|
|
1114
|
+
.option('config-dir', {
|
|
1115
|
+
describe: 'With --capture web: the Storybook config directory, relative to the repository root (default: .storybook)',
|
|
1116
|
+
type: 'string',
|
|
1117
|
+
alias: 'configDir',
|
|
1118
|
+
})
|
|
1065
1119
|
.option('commit-message', {
|
|
1066
1120
|
describe: 'Commit message used with --commit',
|
|
1067
1121
|
type: 'string',
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `--changed-since <ref>`: which story files a change can reach.
|
|
3
|
+
*
|
|
4
|
+
* A story file is affected when a changed file is in its static import graph. Some changes reach
|
|
5
|
+
* every story and are not visible in any one story's graph: the Storybook config directory,
|
|
6
|
+
* anything the preview file imports (global styles, providers), and the root config and lock
|
|
7
|
+
* files. Those select everything. When in doubt, more is selected, never less.
|
|
8
|
+
*/
|
|
9
|
+
const path = require('path');
|
|
10
|
+
const { execFileSync } = require('child_process');
|
|
11
|
+
|
|
12
|
+
const GLOBAL_FILES = [
|
|
13
|
+
/^package\.json$/, /^package-lock\.json$/, /^npm-shrinkwrap\.json$/, /^pnpm-lock\.yaml$/, /^pnpm-workspace\.yaml$/,
|
|
14
|
+
/^yarn\.lock$/, /^bun\.lockb?$/, /^[tj]sconfig(\.[\w-]+)?\.json$/,
|
|
15
|
+
/^(vite|vitest|next|tailwind|postcss|babel|svelte|astro|nuxt)\.config\.[cm]?[jt]s$/,
|
|
16
|
+
/^\.babelrc(\.\w+)?$/, /^\.browserslistrc$/, /^\.env(\.[\w.-]+)?$/,
|
|
17
|
+
];
|
|
18
|
+
|
|
19
|
+
const toPosix = (p) => String(p).split(path.sep).join('/');
|
|
20
|
+
|
|
21
|
+
/** A repo-relative path as a project-relative POSIX path (`../` for files outside the project). */
|
|
22
|
+
function toProjectRelative(file, repoRoot, projectDir) {
|
|
23
|
+
return toPosix(path.relative(projectDir, path.resolve(repoRoot, file)));
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* @param {string} file project-relative POSIX path
|
|
28
|
+
* @returns {string|null} why the change reaches every story, or null
|
|
29
|
+
*/
|
|
30
|
+
function isGlobalChange(file, { configDirRel, previewInputs }) {
|
|
31
|
+
// eslint-disable-next-line sonarjs/super-linear-regex -- a short path from the command line
|
|
32
|
+
const dir = toPosix(configDirRel || '.storybook').replace(/\/+$/, '');
|
|
33
|
+
if (file === dir || file.startsWith(`${dir}/`)) return `Storybook config changed (${file})`;
|
|
34
|
+
if ((previewInputs || []).includes(file)) return `a file the Storybook preview imports changed (${file})`;
|
|
35
|
+
// Root files of the project, or of a directory above it (a monorepo's lock file).
|
|
36
|
+
const atRoot = file.replace(/^(\.\.\/)+/, '');
|
|
37
|
+
if (!atRoot.includes('/') && GLOBAL_FILES.some((re) => re.test(atRoot))) return `${file} changed`;
|
|
38
|
+
return null;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* @param {{graph: Record<string, string[]>, previewInputs?: string[], changedFiles: string[], configDirRel: string}} input
|
|
43
|
+
* graph: story file -> every file in its import graph (project-relative POSIX paths)
|
|
44
|
+
* @returns {{global: boolean, reason: string|null, files: string[]}}
|
|
45
|
+
*/
|
|
46
|
+
function selectAffected({ graph, previewInputs = [], changedFiles: changed, configDirRel }) {
|
|
47
|
+
const all = Object.keys(graph).sort();
|
|
48
|
+
for (const file of changed) {
|
|
49
|
+
const reason = isGlobalChange(file, { configDirRel, previewInputs });
|
|
50
|
+
if (reason) return { global: true, reason, files: all };
|
|
51
|
+
}
|
|
52
|
+
const set = new Set(changed);
|
|
53
|
+
const files = all.filter((story) => set.has(story) || graph[story].some((input) => set.has(input)));
|
|
54
|
+
return { global: false, reason: null, files };
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const splitZ = (out) => String(out || '').split('\0').filter(Boolean);
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Files that differ from `ref` (committed, staged, unstaged and untracked). `A..B` compares two
|
|
61
|
+
* commits instead and ignores the working tree.
|
|
62
|
+
* @returns {{repoRoot: string, files: string[]}} repo-relative POSIX paths
|
|
63
|
+
*/
|
|
64
|
+
function changedFiles(ref, { cwd, exec } = {}) {
|
|
65
|
+
if (!ref || String(ref).startsWith('-')) throw new Error(`--changed-since ${ref}: expected a git ref such as origin/main or HEAD~1.`);
|
|
66
|
+
// eslint-disable-next-line sonarjs/no-os-command-from-path -- git is found on PATH, as everywhere else in this CLI
|
|
67
|
+
const git = exec || ((args, opts) => execFileSync('git', args, { cwd: opts.cwd, encoding: 'utf8', maxBuffer: 256 * 1024 * 1024, stdio: ['ignore', 'pipe', 'pipe'] }));
|
|
68
|
+
let repoRoot;
|
|
69
|
+
try {
|
|
70
|
+
repoRoot = String(git(['rev-parse', '--show-toplevel'], { cwd })).trim();
|
|
71
|
+
} catch (error) {
|
|
72
|
+
throw new Error(`--changed-since needs a git repository (${cwd}): ${firstLine(error)}`);
|
|
73
|
+
}
|
|
74
|
+
const files = new Set();
|
|
75
|
+
try {
|
|
76
|
+
for (const f of splitZ(git(['diff', '--no-ext-diff', '--name-only', '-z', ref, '--'], { cwd: repoRoot }))) files.add(toPosix(f));
|
|
77
|
+
} catch (error) {
|
|
78
|
+
throw new Error(`--changed-since ${ref}: git could not compare against that ref (${firstLine(error)}). In CI, fetch it first (a shallow clone does not have it).`);
|
|
79
|
+
}
|
|
80
|
+
if (!ref.includes('..')) {
|
|
81
|
+
for (const f of splitZ(git(['ls-files', '--others', '--exclude-standard', '-z'], { cwd: repoRoot }))) files.add(toPosix(f));
|
|
82
|
+
}
|
|
83
|
+
return { repoRoot, files: [...files].sort() };
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function firstLine(error) {
|
|
87
|
+
const text = String((error && (error.stderr || error.message)) || error);
|
|
88
|
+
return text.trim().split('\n').pop().trim();
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const CODE_FILE = /\.([cm]?[jt]sx?|json)$/;
|
|
92
|
+
|
|
93
|
+
function applyAlias(spec, alias) {
|
|
94
|
+
for (const entry of alias || []) {
|
|
95
|
+
const { find, replacement } = entry;
|
|
96
|
+
if (typeof replacement !== 'string') continue;
|
|
97
|
+
if (find instanceof RegExp) {
|
|
98
|
+
if (find.test(spec)) return spec.replace(find, replacement);
|
|
99
|
+
} else if (typeof find === 'string' && (spec === find || spec.startsWith(`${find}/`))) {
|
|
100
|
+
return replacement + spec.slice(find.length);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
return spec;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* The static import graph of every story file (and of the preview file), from esbuild's metafile.
|
|
108
|
+
* Packages are left out: a dependency change shows up as a lock file change. An import that cannot
|
|
109
|
+
* be resolved is skipped; a file that is not code is recorded but not read.
|
|
110
|
+
*
|
|
111
|
+
* @returns {Promise<{graph: Record<string, string[]>, previewInputs: string[]}>}
|
|
112
|
+
*/
|
|
113
|
+
async function buildGraph({ projectDir, entries, previewFile, alias, esbuild }) {
|
|
114
|
+
const entryPoints = [...entries, ...(previewFile ? [previewFile] : [])];
|
|
115
|
+
const plugin = {
|
|
116
|
+
name: 'scry-capture-graph',
|
|
117
|
+
setup(build) {
|
|
118
|
+
build.onResolve({ filter: /.*/ }, async (args) => {
|
|
119
|
+
if (args.kind === 'entry-point' || (args.pluginData && args.pluginData.scry)) return null;
|
|
120
|
+
// eslint-disable-next-line sonarjs/super-linear-regex -- runs on the project's own source files, not on untrusted input
|
|
121
|
+
const spec = applyAlias(args.path.replace(/[?#].*$/, ''), alias);
|
|
122
|
+
if (!spec || /^(data|https?|virtual|node):/.test(spec) || spec.startsWith('\0')) return { path: args.path, external: true };
|
|
123
|
+
const resolved = await build.resolve(spec, { resolveDir: args.resolveDir, kind: args.kind, importer: args.importer, pluginData: { scry: true } });
|
|
124
|
+
if (resolved.errors.length) return { path: args.path, external: true };
|
|
125
|
+
if (!resolved.external && /[\\/]node_modules[\\/]/.test(resolved.path)) return { path: args.path, external: true };
|
|
126
|
+
return resolved;
|
|
127
|
+
});
|
|
128
|
+
build.onLoad({ filter: /.*/ }, (args) => (CODE_FILE.test(args.path) ? null : { contents: '', loader: 'js' }));
|
|
129
|
+
},
|
|
130
|
+
};
|
|
131
|
+
const result = await esbuild.build({
|
|
132
|
+
entryPoints,
|
|
133
|
+
absWorkingDir: projectDir,
|
|
134
|
+
bundle: true,
|
|
135
|
+
write: false,
|
|
136
|
+
metafile: true,
|
|
137
|
+
splitting: false,
|
|
138
|
+
format: 'esm',
|
|
139
|
+
platform: 'browser',
|
|
140
|
+
outdir: path.join(projectDir, '.scry-capture-graph-never-written'),
|
|
141
|
+
logLevel: 'silent',
|
|
142
|
+
packages: 'external',
|
|
143
|
+
jsx: 'automatic',
|
|
144
|
+
plugins: [plugin],
|
|
145
|
+
});
|
|
146
|
+
const previewRel = previewFile ? toPosix(path.relative(projectDir, previewFile)) : null;
|
|
147
|
+
const graph = {};
|
|
148
|
+
let previewInputs = [];
|
|
149
|
+
for (const output of Object.values(result.metafile.outputs)) {
|
|
150
|
+
if (!output.entryPoint) continue;
|
|
151
|
+
const entry = toPosix(output.entryPoint);
|
|
152
|
+
const inputs = Object.keys(output.inputs).map(toPosix).sort();
|
|
153
|
+
if (entry === previewRel) previewInputs = inputs;
|
|
154
|
+
else graph[entry] = inputs;
|
|
155
|
+
}
|
|
156
|
+
return { graph, previewInputs };
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
module.exports = { isGlobalChange, selectAffected, changedFiles, toProjectRelative, buildGraph, applyAlias, GLOBAL_FILES };
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* How many CPU cores this process may really use, and the worker count that follows.
|
|
3
|
+
*
|
|
4
|
+
* `os.availableParallelism()` honours the affinity mask (taskset, cpuset), but not a CFS quota:
|
|
5
|
+
* a container limited to 2 CPUs on a 64-core host still reports 64. So the cgroup quota is read
|
|
6
|
+
* too and the smaller number wins.
|
|
7
|
+
*/
|
|
8
|
+
const fs = require('fs');
|
|
9
|
+
const os = require('os');
|
|
10
|
+
|
|
11
|
+
/** Change here when measured numbers say otherwise. */
|
|
12
|
+
const MAX_DEFAULT_WORKERS = 4;
|
|
13
|
+
|
|
14
|
+
function readQuota(readFile) {
|
|
15
|
+
try {
|
|
16
|
+
const [quota, period] = String(readFile('/sys/fs/cgroup/cpu.max')).trim().split(/\s+/);
|
|
17
|
+
if (quota && quota !== 'max' && Number(quota) > 0 && Number(period) > 0) {
|
|
18
|
+
return { cpus: Number(quota) / Number(period), source: 'cgroup-v2' };
|
|
19
|
+
}
|
|
20
|
+
return null;
|
|
21
|
+
} catch {
|
|
22
|
+
// not cgroup v2
|
|
23
|
+
}
|
|
24
|
+
try {
|
|
25
|
+
const quota = Number(String(readFile('/sys/fs/cgroup/cpu/cpu.cfs_quota_us')).trim());
|
|
26
|
+
const period = Number(String(readFile('/sys/fs/cgroup/cpu/cpu.cfs_period_us')).trim());
|
|
27
|
+
if (quota > 0 && period > 0) return { cpus: quota / period, source: 'cgroup-v1' };
|
|
28
|
+
} catch {
|
|
29
|
+
// no cgroup limit readable
|
|
30
|
+
}
|
|
31
|
+
return null;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* @returns {{cores:number, source:'os'|'cgroup-v1'|'cgroup-v2', os:number, cgroup:number|null}}
|
|
36
|
+
*/
|
|
37
|
+
function coresSeen(deps = {}) {
|
|
38
|
+
const availableParallelism = deps.availableParallelism
|
|
39
|
+
|| (typeof os.availableParallelism === 'function' ? () => os.availableParallelism() : () => os.cpus().length);
|
|
40
|
+
const readFile = deps.readFile || ((file) => fs.readFileSync(file, 'utf8'));
|
|
41
|
+
const fromOs = Math.max(1, Math.floor(Number(availableParallelism()) || 1));
|
|
42
|
+
const quota = readQuota(readFile);
|
|
43
|
+
const cgroup = quota ? Math.max(1, Math.floor(quota.cpus)) : null;
|
|
44
|
+
if (cgroup !== null && cgroup < fromOs) return { cores: cgroup, source: quota.source, os: fromOs, cgroup };
|
|
45
|
+
return { cores: fromOs, source: cgroup !== null && cgroup === fromOs ? quota.source : 'os', os: fromOs, cgroup };
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function defaultWorkers(cores) {
|
|
49
|
+
return Math.max(1, Math.min(MAX_DEFAULT_WORKERS, Math.floor(Number(cores) || 1)));
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
module.exports = { coresSeen, defaultWorkers, MAX_DEFAULT_WORKERS };
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The declared story list: ids, titles and names come from Storybook's own index (so they are the
|
|
3
|
+
* ids Storybook generates, auto-titles included); the line of each story and the component it
|
|
4
|
+
* documents are read from the story file's text. A light scan, not a parser: anything it cannot
|
|
5
|
+
* read is left out of the capture, never guessed.
|
|
6
|
+
*/
|
|
7
|
+
const fs = require('fs');
|
|
8
|
+
const path = require('path');
|
|
9
|
+
|
|
10
|
+
const COMPONENT_EXTENSIONS = ['.tsx', '.ts', '.jsx', '.js', '.mjs', '.vue', '.svelte'];
|
|
11
|
+
|
|
12
|
+
// eslint-disable-next-line sonarjs/cognitive-complexity -- one pass over the import clauses of a file
|
|
13
|
+
function importsOf(source) {
|
|
14
|
+
/** local name -> {imported, from} */
|
|
15
|
+
const imports = new Map();
|
|
16
|
+
// eslint-disable-next-line sonarjs/super-linear-regex -- runs on the project's own source files, not on untrusted input
|
|
17
|
+
const re = /import\s+(?:type\s+)?([^;'"]*?)\s+from\s*['"]([^'"]+)['"]/g;
|
|
18
|
+
let m;
|
|
19
|
+
while ((m = re.exec(source))) {
|
|
20
|
+
const clause = m[1];
|
|
21
|
+
const from = m[2];
|
|
22
|
+
// eslint-disable-next-line sonarjs/super-linear-regex -- runs on the project's own source files, not on untrusted input
|
|
23
|
+
const named = /\{([^}]*)\}/.exec(clause);
|
|
24
|
+
if (named) {
|
|
25
|
+
for (const part of named[1].split(',')) {
|
|
26
|
+
const spec = part.trim().replace(/^type\s+/, '');
|
|
27
|
+
if (!spec) continue;
|
|
28
|
+
// eslint-disable-next-line sonarjs/super-linear-regex -- runs on the project's own source files, not on untrusted input
|
|
29
|
+
const [imported, local] = spec.split(/\s+as\s+/).map((s) => s.trim());
|
|
30
|
+
imports.set(local || imported, { imported, from });
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
// eslint-disable-next-line sonarjs/super-linear-regex -- runs on the project's own source files, not on untrusted input
|
|
34
|
+
const rest = clause.replace(/\{[^}]*\}/, '').split(',').map((s) => s.trim()).filter(Boolean);
|
|
35
|
+
for (const item of rest) {
|
|
36
|
+
const ns = /^\*\s+as\s+([\w$]+)$/.exec(item);
|
|
37
|
+
if (ns) imports.set(ns[1], { imported: '*', from });
|
|
38
|
+
else if (/^[\w$]+$/.test(item)) imports.set(item, { imported: 'default', from });
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
return imports;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* @param {string} source story file text
|
|
46
|
+
* @returns {{exports: Record<string, number>, component: string|null, componentImport: string|null}}
|
|
47
|
+
*/
|
|
48
|
+
function scanStoryFile(source) {
|
|
49
|
+
const text = String(source || '');
|
|
50
|
+
const lines = text.split(/\r?\n/);
|
|
51
|
+
const exports = {};
|
|
52
|
+
lines.forEach((line, i) => {
|
|
53
|
+
const direct = /^\s*export\s+(?:const|let|var|function\*?|async\s+function|class)\s+([\w$]+)/.exec(line);
|
|
54
|
+
if (direct) {
|
|
55
|
+
exports[direct[1]] = i + 1;
|
|
56
|
+
return;
|
|
57
|
+
}
|
|
58
|
+
// eslint-disable-next-line sonarjs/super-linear-regex -- runs on the project's own source files, not on untrusted input
|
|
59
|
+
const list = /^\s*export\s*\{([^}]*)\}\s*;?\s*$/.exec(line);
|
|
60
|
+
if (list) {
|
|
61
|
+
for (const part of list[1].split(',')) {
|
|
62
|
+
// eslint-disable-next-line sonarjs/super-linear-regex -- runs on the project's own source files, not on untrusted input
|
|
63
|
+
const names = part.trim().split(/\s+as\s+/);
|
|
64
|
+
const local = (names[0] || '').trim();
|
|
65
|
+
const name = (names[1] || local).trim();
|
|
66
|
+
if (!name || name === 'default' || !/^[\w$]+$/.test(local)) continue;
|
|
67
|
+
// Point at where the story is written, not at the export list.
|
|
68
|
+
const declaredAt = lines.findIndex((l) => new RegExp(`^\\s*(?:const|let|var|function\\*?|class)\\s+${local.replace(/\$/g, '\\$')}\\b`).test(l));
|
|
69
|
+
exports[name] = (declaredAt >= 0 ? declaredAt : i) + 1;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
let component = null;
|
|
75
|
+
let componentImport = null;
|
|
76
|
+
// eslint-disable-next-line sonarjs/super-linear-regex -- runs on the project's own source files, not on untrusted input
|
|
77
|
+
const withoutComments = text.replace(/\/\*[\s\S]*?\*\//g, '').replace(/^\s*\/\/.*$/gm, '');
|
|
78
|
+
const found = /(?:^|[\s,{])component\s*:\s*([\w$]+)(?:\s*\.\s*([\w$]+))?/.exec(withoutComments);
|
|
79
|
+
if (found) {
|
|
80
|
+
const imports = importsOf(withoutComments);
|
|
81
|
+
const local = found[1];
|
|
82
|
+
const member = found[2];
|
|
83
|
+
const imported = imports.get(local);
|
|
84
|
+
if (member) component = member;
|
|
85
|
+
else if (imported && imported.imported !== 'default' && imported.imported !== '*') component = imported.imported;
|
|
86
|
+
else component = local;
|
|
87
|
+
componentImport = imported ? imported.from : null;
|
|
88
|
+
}
|
|
89
|
+
return { exports, component, componentImport };
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const toPosix = (p) => p.split(path.sep).join('/');
|
|
93
|
+
|
|
94
|
+
function insideProject(file, projectDir) {
|
|
95
|
+
const rel = path.relative(projectDir, file);
|
|
96
|
+
return rel && !rel.startsWith('..') && !path.isAbsolute(rel) ? toPosix(rel) : null;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** A relative import of a story file -> the project-relative file it names, when that file exists. */
|
|
100
|
+
function resolveComponentFile(storyFile, spec, projectDir) {
|
|
101
|
+
if (!spec || !spec.startsWith('.')) return null;
|
|
102
|
+
const base = path.resolve(path.dirname(storyFile), spec);
|
|
103
|
+
const candidates = [base, ...COMPONENT_EXTENSIONS.map((e) => base + e), ...COMPONENT_EXTENSIONS.map((e) => path.join(base, `index${e}`))];
|
|
104
|
+
for (const candidate of candidates) {
|
|
105
|
+
try {
|
|
106
|
+
if (fs.statSync(candidate).isFile()) return insideProject(candidate, projectDir);
|
|
107
|
+
} catch {
|
|
108
|
+
// try the next spelling
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
return null;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* @param {Record<string, object>} entries Storybook index entries
|
|
116
|
+
* @param {{projectDir: string, readFile?: (file: string) => string}} ctx
|
|
117
|
+
*/
|
|
118
|
+
function buildDeclared(entries, { projectDir, readFile = (file) => fs.readFileSync(file, 'utf8') }) {
|
|
119
|
+
const scans = new Map();
|
|
120
|
+
const scanOf = (abs) => {
|
|
121
|
+
if (!scans.has(abs)) {
|
|
122
|
+
let scan = null;
|
|
123
|
+
try {
|
|
124
|
+
scan = scanStoryFile(readFile(abs));
|
|
125
|
+
} catch {
|
|
126
|
+
// unreadable: the entry still counts as declared
|
|
127
|
+
}
|
|
128
|
+
scans.set(abs, scan);
|
|
129
|
+
}
|
|
130
|
+
return scans.get(abs);
|
|
131
|
+
};
|
|
132
|
+
|
|
133
|
+
const declared = [];
|
|
134
|
+
for (const entry of Object.values(entries || {})) {
|
|
135
|
+
if (!entry || entry.type !== 'story' || !entry.id) continue;
|
|
136
|
+
const abs = path.resolve(projectDir, entry.importPath || '');
|
|
137
|
+
const file = toPosix(path.relative(projectDir, abs));
|
|
138
|
+
const scan = entry.importPath ? scanOf(abs) : null;
|
|
139
|
+
const exportName = entry.exportName || null;
|
|
140
|
+
let componentFile = null;
|
|
141
|
+
if (entry.componentPath) componentFile = insideProject(path.resolve(projectDir, entry.componentPath), projectDir);
|
|
142
|
+
else if (scan && scan.componentImport) componentFile = resolveComponentFile(abs, scan.componentImport, projectDir);
|
|
143
|
+
declared.push({
|
|
144
|
+
id: entry.id,
|
|
145
|
+
title: entry.title || '',
|
|
146
|
+
name: entry.name || '',
|
|
147
|
+
exportName,
|
|
148
|
+
file,
|
|
149
|
+
line: (scan && exportName && scan.exports[exportName]) || null,
|
|
150
|
+
component: (scan && scan.component) || null,
|
|
151
|
+
componentFile,
|
|
152
|
+
tags: Array.isArray(entry.tags) ? entry.tags.filter((t) => typeof t === 'string') : [],
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
return declared.sort((a, b) => {
|
|
156
|
+
if (a.id === b.id) return 0;
|
|
157
|
+
return a.id < b.id ? -1 : 1;
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
module.exports = { scanStoryFile, buildDeclared, resolveComponentFile };
|