snapdrift 0.15.0 → 0.16.1

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/CHANGELOG.md CHANGED
@@ -2,6 +2,49 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ ## 0.16.1 - 2026-10-27
6
+
7
+ Workspace releases this version:
8
+
9
+ - `@snapdrift/compare-core` 1.7.0 — new public `readPngDimensions` export (PNG IHDR width/height without decoding pixels).
10
+ - `@snapdrift/adapter-fs` 1.7.1 — local capture reads screenshot dimensions from the PNG header instead of fully decoding every PNG, and now depends on `@snapdrift/compare-core ^1.7.0` for that reader.
11
+
12
+ `@snapdrift/manifest` stays 1.8.0 and `@snapdrift/adapter-report-md` stays 1.4.0. Root floors move to `@snapdrift/compare-core ^1.7.0` and `@snapdrift/adapter-fs ^1.7.1`; the previous `adapter-fs` 1.7.0 and `compare-core` 1.6.0 do not satisfy them, so installing `snapdrift` 0.16.1 always gets the shared reader. The dispatcher pins `1cbf629`, the #195 merge commit on `main`, which is the newest commit touching `actions/` and includes the shell-only Playwright install.
13
+
14
+ ### Performance
15
+
16
+ - Hybrid (`provider: "snap"` with a local `baseUrl`) capture uploads screenshots to Snap with up to 4 routes in flight instead of one at a time, and stops starting new uploads after the first failure.
17
+ - The latest-baseline lookup for hybrid diff runs now starts before local capture and overlaps with it.
18
+ - Local Playwright capture reads screenshot width/height from the PNG header instead of fully decoding every PNG, which no longer blocks the event loop for all in-flight routes. A corrupt PNG body is no longer detected at capture time; a buffer without a valid PNG signature or IHDR chunk still fails the route.
19
+ - GitHub Actions install only Playwright's Chromium headless shell (`playwright install --with-deps --only-shell chromium`) instead of full Chromium plus the shell. Capture already launches with `headless: true`, which uses the shell, so rendering is unchanged. Measured on `node:22-bookworm` with Playwright 1.63.0: install 22s -> 15s, browser cache 662 MB -> 269 MB, identical browser version and screenshot bytes.
20
+ - Capture and upload phases log their duration (`Captured N route(s) in Xs`, `Uploaded N screenshot(s) to Snap in Xs`).
21
+
22
+ ### Features
23
+
24
+ - `@snapdrift/compare-core` exports `readPngDimensions(buffer)`, which reads width/height from a PNG's IHDR chunk without decoding pixels and returns `undefined` for a buffer that is too short, lacks the PNG signature, does not start with IHDR, or declares a zero or above-2^31-1 dimension.
25
+
26
+ ### Refactors
27
+
28
+ - Local capture (`@snapdrift/adapter-fs`) and the Snap baseline export (`lib/snap-provider.mjs`) now use the shared `readPngDimensions` instead of their own copies. The Snap baseline export is slightly stricter than before: an exported image whose header is not a valid IHDR (or declares a zero dimension) falls back to the viewport descriptor's dimensions instead of being recorded with the header's values. Requires the `@snapdrift/compare-core` release that adds the export; dependency floors are raised at release time. Closes #194.
29
+
30
+ ## 0.16.0 - 2026-10-05
31
+
32
+ Workspace releases this version:
33
+
34
+ - `@snapdrift/manifest` 1.8.0 — capture engine configuration (`capture: "playwright" | "snap"`) under `provider: "local"`, export `isLocalBaseUrl`, and recognize `snap-batch` capture profile engine.
35
+ - `@snapdrift/adapter-fs` 1.7.0 — Snap Cloud batch screenshot capture engine (`runSnapBatchCapture`) using POST `/v1/screenshots`, capture engine delegation in `runBaselineCapture`, and `isLocalBaseUrl` re-export.
36
+
37
+ `@snapdrift/compare-core` stays 1.6.0 and `@snapdrift/adapter-report-md` stays 1.4.0. Root floors move to `@snapdrift/manifest ^1.8.0` and `@snapdrift/adapter-fs ^1.7.0`. The dispatcher pins `8e82795`, the #191 merge commit on `main`, which includes skipping Playwright installation in composite actions when `capture: "snap"` with a remote `baseUrl`.
38
+
39
+ ### Features
40
+
41
+ - Added Snap Cloud batch screenshot capture engine (`capture: "snap"`) under `provider: "local"`. Dispatches route screenshots concurrently to Snap Cloud's batch screenshot API (`POST /v1/screenshots`), saving significant CI run time by offloading browser execution.
42
+ - Added automatic Playwright setup skipping in composite actions (`actions/baseline` and `actions/pr-diff`) when `capture: "snap"` is configured with a remote `baseUrl`, avoiding unnecessary browser binary downloads.
43
+ - Supported `SNAPDRIFT_CAPTURE_ENGINE` environment variable (`playwright` | `snap`) to override the configured capture engine at runtime.
44
+ - Added actionable validation rejecting loopback and local `baseUrl` (`localhost`, `127.0.0.1`, `::1`) when `capture: "snap"` is used, directing users to use `playwright` or tunnel services.
45
+ - Added capture profile engine validation in `@snapdrift/manifest` to recognize `snap-batch` and prevent comparing local Playwright captures against Snap Cloud batch captures.
46
+ - Added resilient batch capture polling with retries on transient errors (HTTP 429, 5xx on GET status polls, network errors) while safely avoiding POST retries on 5xx to prevent duplicate jobs.
47
+
5
48
  ## 0.15.0 - 2026-09-22
6
49
 
7
50
  Workspace releases this version:
package/README.md CHANGED
@@ -48,7 +48,7 @@ You keep ownership of checkout, build, startup, readiness, and teardown. SnapDri
48
48
 
49
49
  ```yaml
50
50
  - name: SnapDrift Baseline
51
- uses: ranacseruet/snapdrift@v0.15.0
51
+ uses: ranacseruet/snapdrift@v0.16.1
52
52
  with:
53
53
  mode: baseline
54
54
  repo-config-path: .github/snapdrift.json
@@ -60,7 +60,7 @@ With `provider: "snap"`, baseline publication is a complete, fail-closed snapsho
60
60
 
61
61
  ```yaml
62
62
  - name: SnapDrift Report
63
- uses: ranacseruet/snapdrift@v0.15.0
63
+ uses: ranacseruet/snapdrift@v0.16.1
64
64
  with:
65
65
  mode: pr-diff
66
66
  github-token: ${{ secrets.GITHUB_TOKEN }}
package/action.yml CHANGED
@@ -155,7 +155,7 @@ runs:
155
155
  - name: SnapDrift baseline
156
156
  id: baseline
157
157
  if: inputs.mode == 'baseline'
158
- uses: ranacseruet/snapdrift/actions/baseline@7b7b9138416fd16631c5d648b2ddfa9fe4a6a783 # v0.15.0
158
+ uses: ranacseruet/snapdrift/actions/baseline@1cbf62965475bc856218ce46eb46dccf7c05326f # v0.16.1
159
159
  with:
160
160
  repo-config-path: ${{ inputs.repo-config-path }}
161
161
  route-ids: ${{ inputs.route-ids }}
@@ -165,7 +165,7 @@ runs:
165
165
  - name: SnapDrift pull request diff
166
166
  id: pr-diff
167
167
  if: inputs.mode == 'pr-diff'
168
- uses: ranacseruet/snapdrift/actions/pr-diff@7b7b9138416fd16631c5d648b2ddfa9fe4a6a783 # v0.15.0
168
+ uses: ranacseruet/snapdrift/actions/pr-diff@1cbf62965475bc856218ce46eb46dccf7c05326f # v0.16.1
169
169
  with:
170
170
  github-token: ${{ inputs.github-token }}
171
171
  repo-config-path: ${{ inputs.repo-config-path }}
@@ -78,17 +78,19 @@ runs:
78
78
  const outputs = [
79
79
  `artifact_name=${config.baselineArtifactName}`,
80
80
  `provider=${config.provider || 'local'}`,
81
+ `capture_engine=${process.env.SNAPDRIFT_CAPTURE_ENGINE || config.capture || 'playwright'}`,
81
82
  `on_unavailable=${config.snap?.onUnavailable || 'fail'}`,
82
- `snap_local_capture=${(config.provider || 'local') === 'snap' && isLocalBaseUrl(config.baseUrl) ? 'true' : 'false'}`
83
+ `snap_local_capture=${(config.provider || 'local') === 'snap' && isLocalBaseUrl(config.baseUrl) ? 'true' : 'false'}`,
84
+ `is_local_base_url=${isLocalBaseUrl(config.baseUrl) ? 'true' : 'false'}`
83
85
  ].join('\n') + '\n';
84
86
  await fs.appendFile(process.env.GITHUB_OUTPUT, outputs);
85
87
  EOF
86
88
 
87
89
  - name: Install Playwright Chromium
88
- if: steps.config.outputs.provider != 'snap' || steps.config.outputs.on_unavailable == 'fallback-local' || steps.config.outputs.snap_local_capture == 'true'
90
+ if: (steps.config.outputs.provider != 'snap' && (steps.config.outputs.capture_engine != 'snap' || steps.config.outputs.is_local_base_url == 'true')) || steps.config.outputs.on_unavailable == 'fallback-local' || steps.config.outputs.snap_local_capture == 'true'
89
91
  shell: bash
90
92
  run: |
91
- "$ACTION_ROOT/node_modules/.bin/playwright" install --with-deps chromium
93
+ "$ACTION_ROOT/node_modules/.bin/playwright" install --with-deps --only-shell chromium
92
94
 
93
95
  - id: capture
94
96
  shell: bash
@@ -48,7 +48,7 @@ runs:
48
48
  - name: Install Playwright Chromium
49
49
  shell: bash
50
50
  run: |
51
- "$ACTION_ROOT/node_modules/.bin/playwright" install --with-deps chromium
51
+ "$ACTION_ROOT/node_modules/.bin/playwright" install --with-deps --only-shell chromium
52
52
 
53
53
  - id: capture
54
54
  shell: bash
@@ -251,8 +251,10 @@ runs:
251
251
  const { config } = await loadSnapdriftConfig(process.env.REPO_CONFIG_PATH || undefined);
252
252
  const outputs = [
253
253
  `provider=${config.provider || 'local'}`,
254
+ `capture_engine=${process.env.SNAPDRIFT_CAPTURE_ENGINE || config.capture || 'playwright'}`,
254
255
  `on_unavailable=${config.snap?.onUnavailable || 'fail'}`,
255
- `snap_local_capture=${(config.provider || 'local') === 'snap' && isLocalBaseUrl(config.baseUrl) ? 'true' : 'false'}`
256
+ `snap_local_capture=${(config.provider || 'local') === 'snap' && isLocalBaseUrl(config.baseUrl) ? 'true' : 'false'}`,
257
+ `is_local_base_url=${isLocalBaseUrl(config.baseUrl) ? 'true' : 'false'}`
256
258
  ].join('\n') + '\n';
257
259
  await fs.appendFile(process.env.GITHUB_OUTPUT, outputs);
258
260
  EOF
@@ -268,10 +270,10 @@ runs:
268
270
  exit 1
269
271
 
270
272
  - name: Install Playwright Chromium
271
- if: steps.scope.outputs.should_run == 'true' && (steps.config.outputs.provider != 'snap' || steps.config.outputs.on_unavailable == 'fallback-local' || steps.config.outputs.snap_local_capture == 'true')
273
+ if: steps.scope.outputs.should_run == 'true' && ((steps.config.outputs.provider != 'snap' && (steps.config.outputs.capture_engine != 'snap' || steps.config.outputs.is_local_base_url == 'true')) || steps.config.outputs.on_unavailable == 'fallback-local' || steps.config.outputs.snap_local_capture == 'true')
272
274
  shell: bash
273
275
  run: |
274
- "$ACTION_ROOT/node_modules/.bin/playwright" install --with-deps chromium
276
+ "$ACTION_ROOT/node_modules/.bin/playwright" install --with-deps --only-shell chromium
275
277
 
276
278
  - id: capture
277
279
  if: steps.scope.outputs.should_run == 'true'
package/docs/contracts.md CHANGED
@@ -32,6 +32,7 @@ SnapDrift reads runtime behavior from `.github/snapdrift.json` by default.
32
32
 
33
33
  | Field | Type | Description |
34
34
  |:------|:-----|:------------|
35
+ | `capture` | `string` | Capture engine for `provider: "local"`: `"playwright"` (default) or `"snap"` (Snap Cloud batch screenshot API) |
35
36
  | `selection.sharedPrefixes` | `string[]` | Prefixes that force the full route set |
36
37
  | `selection.sharedExact` | `string[]` | Exact files that force the full route set |
37
38
  | `provider` | `string` | `"local"` (default) or `"snap"` for hosted backend |
@@ -42,6 +43,8 @@ SnapDrift reads runtime behavior from `.github/snapdrift.json` by default.
42
43
  | `snap.onUnavailable` | `string` | Behavior when Snap is unreachable: `"fail"` (default), `"warn-and-skip"`, or `"fallback-local"` |
43
44
  | `diff.comparisonPolicy` | `{ "version": 1 \| 2, "threshold": number }` | Optional explicit comparison policy. Deprecated v1 remains the compatibility default; new configurations should use v2 for bounded vertical row alignment. `threshold` must match `diff.threshold` |
44
45
 
46
+ When `capture: "snap"` is set (or overridden via `SNAPDRIFT_CAPTURE_ENGINE=snap`), SnapDrift routes baseline and diff captures to Snap Cloud's batch screenshot API (`POST /v1/screenshots`) instead of launching local Chromium via Playwright. Rendered PNGs are downloaded in parallel and diffed locally via `@snapdrift/compare-core`. This requires a public or preview `baseUrl` (loopback and private network URLs like `localhost`, `127.0.0.1`, `::1` are rejected) and an API key (configured in `snap.apiKeyEnv` / `snap.apiKey` or via `SNAP_API_KEY`). When `capture: "snap"` is used with a remote `baseUrl`, GitHub Actions wrapper actions (`actions/baseline`, `actions/pr-diff`) skip the `playwright install --with-deps --only-shell chromium` step, accelerating CI workflows.
47
+
45
48
  When `provider: "snap"` is set, the `snap` block is required. Exactly one of `snap.apiKeyEnv` or `snap.apiKey` must be present. `snap.apiKey` accepts `${VAR}` interpolation (for example `"${SNAP_API_KEY}"`); the referenced environment variable must be set at runtime or the config loader throws.
46
49
 
47
50
  Changed-file scoping treats a GitHub `renamed` record as both the current
@@ -550,6 +553,8 @@ Publication sends `publicationMode: "complete"` and the source run id both as to
550
553
 
551
554
  If `baseUrl` resolves to a local address (see [`isLocalBaseUrl`](#islocalbaseurl-detection) below), SnapDrift runs Playwright on the runner to render the page and uploads the resulting screenshots to Snap. This is necessary whenever your `baseUrl` is a server only the runner can reach (the common case) — Snap's render worker cannot reach a `127.0.0.1` or `localhost` server.
552
555
 
556
+ In the hybrid path, the latest-baseline lookup for diff runs starts before local capture so it overlaps with rendering, and the per-route capture-create and `local-result` uploads run with up to 4 routes in flight. The first failed upload stops further uploads and fails the capture. Local screenshot dimensions come from the PNG header (signature and IHDR are validated; pixel data is not decoded at capture time).
557
+
553
558
  The hybrid path is transparent to the user: the same provider factory picks it, and the output `results.json` carries `provider: "snap"` plus `captureMode: "local-upload"` so downstream consumers can tell which path produced the run. The action's `Install Playwright Chromium` step is gated on this hybrid, so a `provider: "snap"` config with a remote `baseUrl` will not download Playwright Chromium.
554
559
 
555
560
  ### API contract
@@ -46,7 +46,7 @@ SnapDrift owns route selection, capture, comparison, skipped-report generation,
46
46
 
47
47
  ```yaml
48
48
  - name: SnapDrift Baseline
49
- uses: ranacseruet/snapdrift@v0.15.0
49
+ uses: ranacseruet/snapdrift@v0.16.1
50
50
  with:
51
51
  mode: baseline
52
52
  repo-config-path: .github/snapdrift.json
@@ -71,7 +71,7 @@ Then add SnapDrift after the app is running:
71
71
 
72
72
  ```yaml
73
73
  - name: SnapDrift Report
74
- uses: ranacseruet/snapdrift@v0.15.0
74
+ uses: ranacseruet/snapdrift@v0.16.1
75
75
  with:
76
76
  mode: pr-diff
77
77
  github-token: ${{ secrets.GITHUB_TOKEN }}
@@ -86,8 +86,8 @@ The wrappers remain published in their own right, and are equivalent to the disp
86
86
 
87
87
  | Entry point | Equivalent to |
88
88
  |-------------|---------------|
89
- | `ranacseruet/snapdrift@v0.15.0` with `mode: baseline` | `ranacseruet/snapdrift/actions/baseline@v0.15.0` |
90
- | `ranacseruet/snapdrift@v0.15.0` with `mode: pr-diff` | `ranacseruet/snapdrift/actions/pr-diff@v0.15.0` |
89
+ | `ranacseruet/snapdrift@v0.16.1` with `mode: baseline` | `ranacseruet/snapdrift/actions/baseline@v0.16.1` |
90
+ | `ranacseruet/snapdrift@v0.16.1` with `mode: pr-diff` | `ranacseruet/snapdrift/actions/pr-diff@v0.16.1` |
91
91
 
92
92
  Use the wrappers directly when you want to skip the dispatcher's input indirection, and the lower-level `capture`, `compare`, `scope`, `resolve-baseline`, `stage`, `comment`, and `enforce` actions when you need to orchestrate the stages yourself.
93
93
 
@@ -130,7 +130,7 @@ jobs:
130
130
  done
131
131
 
132
132
  - name: SnapDrift Report
133
- uses: ranacseruet/snapdrift@v0.15.0
133
+ uses: ranacseruet/snapdrift@v0.16.1
134
134
  with:
135
135
  mode: pr-diff
136
136
  github-token: ${{ secrets.GITHUB_TOKEN }}
@@ -170,7 +170,7 @@ jobs:
170
170
  done
171
171
 
172
172
  - name: SnapDrift Report
173
- uses: ranacseruet/snapdrift@v0.15.0
173
+ uses: ranacseruet/snapdrift@v0.16.1
174
174
  with:
175
175
  mode: pr-diff
176
176
  github-token: ${{ secrets.GITHUB_TOKEN }}
@@ -270,6 +270,32 @@ If you're adopting SnapDrift as a replacement for the upstream `snap/github-acti
270
270
  snapdrift init --from-snap-action .github/workflows/snap.yml
271
271
  ```
272
272
 
273
+ ## Fast CI with Snap Cloud Batch Screenshots (`capture: "snap"`)
274
+
275
+ When your application deploys preview URLs (e.g., Vercel, Netlify, Cloudflare Pages, AWS Amplify) or runs on a publicly accessible staging server during CI, you can offload screenshot rendering to Snap Cloud while keeping comparison and artifact management local (`provider: "local"`):
276
+
277
+ ```json
278
+ {
279
+ "baseUrl": "https://preview-pr-123.example.com",
280
+ "capture": "snap",
281
+ "snap": {
282
+ "apiKeyEnv": "SNAP_API_KEY"
283
+ },
284
+ "routes": [
285
+ { "id": "home-desktop", "path": "/", "viewport": "desktop" },
286
+ { "id": "pricing-desktop", "path": "/pricing", "viewport": "desktop" }
287
+ ]
288
+ }
289
+ ```
290
+
291
+ ### Why use `capture: "snap"`?
292
+ - **Skips Playwright Installation in CI:** The GitHub Actions wrapper actions (`actions/baseline` and `actions/pr-diff`) detect `capture: "snap"` with a remote `baseUrl` and skip `playwright install --with-deps --only-shell chromium`, saving 45–90 seconds per workflow run.
293
+ - **Parallel Cloud Rendering:** Snap Cloud renders full-page screenshots concurrently via its batch API (`POST /v1/screenshots`).
294
+ - **Local Diff Engine:** Screenshots are downloaded and diffed locally on the runner with `@snapdrift/compare-core`, keeping full artifact bundles and PR comments in GitHub Actions without requiring hosted project configuration.
295
+
296
+ > [!NOTE]
297
+ > `capture: "snap"` requires a public or preview URL reachable by Snap Cloud. If `baseUrl` points to `localhost` or `127.0.0.1`, SnapDrift will fail with a clear configuration error because Snap Cloud cannot access loopback addresses. For local development or local dev servers, use `capture: "playwright"` (the default).
298
+
273
299
  ## Low-level actions
274
300
 
275
301
  The `pr-diff` wrapper composes the following low-level steps. They're still available for custom orchestration but most consumers don't need to reach for them:
@@ -0,0 +1,147 @@
1
+ # Design Specification: Snap Cloud Batch Screenshot Capture Engine
2
+
3
+ **Date:** 2026-10-05
4
+ **Status:** Approved
5
+ **Author:** Pair programming session (Antigravity & Rana)
6
+
7
+ ---
8
+
9
+ ## 1. Context & Motivation
10
+
11
+ SnapDrift currently offers two provider workflows:
12
+ 1. **`provider: "local"`**: Executes Playwright locally on the runner to capture screenshots into PNGs, then runs pure-JS pixel comparison (`@snapdrift/compare-core`) and stores baselines in GitHub Actions artifacts.
13
+ 2. **`provider: "snap"`**: Connects to Snap Cloud's Visual Regression service (`/v1/visual/*`), requiring a Snap project ID and hosted baseline management.
14
+
15
+ In CI workflows using `provider: "local"`, the primary speed bottleneck is running Playwright on the runner:
16
+ - Downloading and installing Chromium and OS dependencies (`playwright install --with-deps chromium`) adds 45–90 seconds per CI job.
17
+ - Headless rendering on limited CI runner CPU/RAM slows down capture of multi-route configurations.
18
+
19
+ Snap Cloud provides a public Batch Screenshot API (`POST /v1/screenshots` with `items: [...]`) capable of asynchronously capturing up to 50 URLs in parallel on hosted render workers and returning signed image URLs.
20
+
21
+ By adding a pluggable **Snap Cloud batch capture engine** to `provider: "local"`, repositories with public or preview URLs can offload screenshot rendering to Snap Cloud, skip Playwright installation in CI entirely, and continue using GitHub Actions for zero-setup baseline storage, diffing, and PR commenting.
22
+
23
+ ---
24
+
25
+ ## 2. Configuration Contract
26
+
27
+ In `.github/snapdrift.json` (or inline config):
28
+
29
+ ```json
30
+ {
31
+ "provider": "local",
32
+ "capture": "snap",
33
+ "baseUrl": "https://preview.example.com",
34
+ "routes": [
35
+ { "id": "home", "path": "/", "viewport": "desktop" },
36
+ { "id": "pricing", "path": "/pricing", "viewport": "mobile" }
37
+ ]
38
+ }
39
+ ```
40
+
41
+ ### Schema Rules
42
+ - **`capture`**: Optional string. Allowed values: `"playwright"` (default) | `"snap"`. Overridable via `SNAPDRIFT_CAPTURE_ENGINE` environment variable.
43
+ - **Authentication**: When `capture: "snap"`, authentication uses `process.env.SNAP_API_KEY`. No project ID is required.
44
+ - **API URL**: Defaults internally to `https://snap.i2dev.com`.
45
+ - **Base URL Validation**:
46
+ - `isLocalBaseUrl(config.baseUrl)` evaluates loopback addresses (`localhost`, `127.0.0.1`, `::1`, `0.0.0.0`).
47
+ - If `baseUrl` is local and `capture: "snap"` is configured:
48
+ - In CLI/local development, if Playwright is available, it gracefully falls back to local Playwright with a notice, or errors if unresolvable.
49
+ - In CI workflows targeting public preview deployments, `baseUrl` is remote and Snap Cloud batch capture executes.
50
+
51
+ ---
52
+
53
+ ## 3. Data Flow & Batch Lifecycle
54
+
55
+ ```
56
+ [Selected Routes]
57
+ │
58
+ ▼
59
+ 1. Map routes to batch items (url, viewport)
60
+ │
61
+ ▼
62
+ 2. POST https://snap.i2dev.com/v1/screenshots (Bearer SNAP_API_KEY)
63
+ Body: { format: "png", fullPage: true, items: [...] }
64
+ │
65
+ ▼ Returns { batchId, status: "queued", statusUrl }
66
+ 3. Poll GET /v1/screenshots/:batchId every 1.5s
67
+ │
68
+ ▼ status: "completed"
69
+ 4. Download PNGs in parallel from item.imageUrl -> screenshots/<sanitizedRouteId>.png
70
+ │
71
+ ▼
72
+ 5. Inspect image dimensions and write results.json & manifest.json
73
+ │
74
+ ▼
75
+ 6. Run local pixel comparison (@snapdrift/compare-core)
76
+ ```
77
+
78
+ ### Route & Viewport Mapping
79
+ - Viewports are resolved via `@snapdrift/manifest` presets:
80
+ - `"desktop"` → `{ width: 1440, height: 900 }`
81
+ - `"mobile"` → `{ width: 390, height: 844 }`
82
+ - Custom objects `{ width, height }` are passed directly.
83
+ - Full target URLs are constructed via `new URL(route.path, config.baseUrl).href`.
84
+
85
+ ### Polling & Timeout
86
+ - Poll interval: 1.5 seconds.
87
+ - Monotonic operation deadline: 5 minutes.
88
+ - Stops when `status === "completed"`.
89
+
90
+ ### Artifact Generation
91
+ - Downloaded PNGs are written to `<screenshotsRoot>/screenshots/<sanitizedRouteId>.png`.
92
+ - Output structure matches `runBaselineCapture`:
93
+ - `manifest.json`: lists screenshots with route id, path, viewport, relative imagePath, and dimensions.
94
+ - `results.json`: records capture metadata with engine `snap-batch`.
95
+
96
+ ---
97
+
98
+ ## 4. Error Handling & Resilience
99
+
100
+ 1. **Individual Route Failure in Batch**:
101
+ - Snap Cloud returns batches even if some URLs fail (`status: "failed"` on specific items).
102
+ - SnapDrift adheres to its strict baseline contract: any navigation error or HTTP failure rejects the capture to prevent committing broken states.
103
+ - Halts immediately with: `Route "<id>" failed cloud capture: <error.message> (<error.code>)`.
104
+ 2. **Authentication (401)**:
105
+ - Fails fast with: `Missing or invalid SNAP_API_KEY for Snap Cloud batch screenshot capture.`
106
+ 3. **Transient Server Errors (5xx)**:
107
+ - Retries up to 3 times with exponential backoff (1s, 2s, 4s).
108
+ 4. **Rate Limits (429)**:
109
+ - Honors `Retry-After` header when available. Surfaces quota exhaustion errors clearly.
110
+ 5. **Private Addresses (400 `unsafe_url`)**:
111
+ - Prevented ahead of time via early `isLocalBaseUrl` check.
112
+
113
+ ---
114
+
115
+ ## 5. GitHub Actions Optimization
116
+
117
+ In `actions/baseline/action.yml` and `actions/pr-diff/action.yml`:
118
+ Playwright installation is skipped when `capture: "snap"` and `baseUrl` is remote:
119
+
120
+ ```yaml
121
+ - name: Install Playwright Chromium
122
+ if: >
123
+ steps.scope.outputs.should_run == 'true' &&
124
+ (
125
+ (steps.config.outputs.provider == 'local' && steps.config.outputs.capture_engine != 'snap') ||
126
+ steps.config.outputs.snap_local_capture == 'true' ||
127
+ steps.config.outputs.on_unavailable == 'fallback-local'
128
+ )
129
+ ```
130
+
131
+ This cuts CI setup time by 45–90 seconds per run on pull requests.
132
+
133
+ ---
134
+
135
+ ## 6. Testing Strategy
136
+
137
+ 1. **`@snapdrift/manifest` Tests**:
138
+ - Validate `capture` field (`"playwright"`, `"snap"`).
139
+ - Rejection of invalid capture engine strings.
140
+ 2. **`@snapdrift/adapter-fs` Tests**:
141
+ - Unit tests for `runSnapBatchCapture` with mocked HTTP responses:
142
+ - Successful batch submission, polling cycle, and image download.
143
+ - Propagation of single-item failure in batch.
144
+ - Handling 401, 429, and 5xx retries.
145
+ - Verification of output `manifest.json`, `results.json`, and file paths.
146
+ 3. **Action Contract Tests**:
147
+ - Verify composite action YAML outputs and Playwright installation condition logic.
@@ -82,7 +82,7 @@ jobs:
82
82
 
83
83
  - name: Publish SnapDrift baseline
84
84
  if: steps.baseline_candidate.outputs.current == 'true'
85
- uses: ranacseruet/snapdrift@v0.15.0
85
+ uses: ranacseruet/snapdrift@v0.16.1
86
86
  with:
87
87
  mode: baseline
88
88
  repo-config-path: .github/snapdrift.json
@@ -1,4 +1,4 @@
1
1
  // @ts-check
2
2
  // Re-exports from packages — this module is a thin shim.
3
3
 
4
- export { runBaselineCapture } from '@snapdrift/adapter-fs';
4
+ export { runBaselineCapture, runSnapBatchCapture } from '@snapdrift/adapter-fs';
@@ -4,13 +4,12 @@ import { execFileSync } from 'node:child_process';
4
4
  import crypto from 'node:crypto';
5
5
  import fs from 'node:fs/promises';
6
6
  import fsSync from 'node:fs';
7
- import net from 'node:net';
8
7
  import os from 'node:os';
9
8
  import path from 'node:path';
10
9
 
11
10
  import { makeMarkdown, buildReportCommentBody } from '@snapdrift/adapter-report-md';
12
11
  import { loadSnapdriftConfig, runBaselineCapture } from '@snapdrift/adapter-fs';
13
- import { COMPARISON_FALLBACK_REASONS, COMPARISON_ROW_KINDS } from '@snapdrift/compare-core';
12
+ import { COMPARISON_FALLBACK_REASONS, COMPARISON_ROW_KINDS, readPngDimensions } from '@snapdrift/compare-core';
14
13
  import {
15
14
  selectConfiguredRoutes,
16
15
  splitCommaList,
@@ -18,7 +17,8 @@ import {
18
17
  VIEWPORT_PRESETS,
19
18
  viewportHash,
20
19
  assertUniqueRouteIdFilenames,
21
- sanitizeRouteId
20
+ sanitizeRouteId,
21
+ isLocalBaseUrl
22
22
  } from '@snapdrift/manifest';
23
23
 
24
24
  /** @typedef {import('../types/visual-diff-types').VisualProvider} VisualProvider */
@@ -47,6 +47,9 @@ const BINARY_REQUEST_TIMEOUT_MS = 120 * 1000;
47
47
  const POLL_INTERVAL_MS = 2000;
48
48
  const MAX_OPERATION_DURATION_MS = 10 * 60 * 1000;
49
49
  const MAX_STABLE_INCOMPLETE_POLLS = 30;
50
+ // Local-capture uploads are independent per route; a small pool hides round-trip
51
+ // latency without flooding the API or holding many base64 images in memory.
52
+ const LOCAL_UPLOAD_CONCURRENCY = 4;
50
53
  const BASELINE_RUN_SUCCESS_STATUS = 'new';
51
54
  const BASELINE_CAPTURE_SUCCESS_STATUS = 'new';
52
55
  const TERMINAL_CAPTURE_STATUSES = new Set(['new', 'diffed', 'error']);
@@ -64,6 +67,35 @@ function formatDuration(milliseconds) {
64
67
  return `${seconds} seconds`;
65
68
  }
66
69
 
70
+ /**
71
+ * Runs `task` over `items` with at most `limit` in flight. Stops starting new
72
+ * work after the first failure and rejects with that first error, so a failed
73
+ * upload does not keep fanning requests out to Snap.
74
+ *
75
+ * @template T
76
+ * @param {T[]} items
77
+ * @param {number} limit
78
+ * @param {(item: T) => Promise<void>} task
79
+ * @returns {Promise<void>}
80
+ */
81
+ async function runWithConcurrency(items, limit, task) {
82
+ let next = 0;
83
+ /** @type {{ error: unknown } | undefined} */
84
+ let failure;
85
+ const worker = async () => {
86
+ while (!failure && next < items.length) {
87
+ const item = items[next++];
88
+ try {
89
+ await task(item);
90
+ } catch (error) {
91
+ failure ??= { error };
92
+ }
93
+ }
94
+ };
95
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
96
+ if (failure) throw failure.error;
97
+ }
98
+
67
99
  const OPERATION_LIMIT_TEXT = formatDuration(MAX_OPERATION_DURATION_MS);
68
100
 
69
101
  /** @returns {number} A monotonic timestamp in milliseconds. */
@@ -565,31 +597,7 @@ function baselineIdForRun(runId) {
565
597
  return `bsl_${crypto.createHash('sha256').update(runId).digest('hex').slice(0, 24)}`;
566
598
  }
567
599
 
568
- /**
569
- * @param {string | undefined} baseUrl
570
- * @returns {boolean}
571
- */
572
- export function isLocalBaseUrl(baseUrl) {
573
- if (!baseUrl) {
574
- return false;
575
- }
576
-
577
- let hostname;
578
- try {
579
- hostname = new URL(baseUrl).hostname.toLowerCase();
580
- } catch {
581
- return false;
582
- }
583
-
584
- const normalized = hostname.replace(/^\[/, '').replace(/\]$/, '');
585
- if (normalized === 'localhost' || normalized.endsWith('.localhost')) {
586
- return true;
587
- }
588
- if (normalized === '::1' || normalized === '0.0.0.0') {
589
- return true;
590
- }
591
- return net.isIP(normalized) === 4 && normalized.startsWith('127.');
592
- }
600
+ export { isLocalBaseUrl };
593
601
 
594
602
  /**
595
603
  * @param {string} repoSlug
@@ -677,7 +685,6 @@ function getPackageVersion() {
677
685
  }
678
686
 
679
687
  const TAR_BLOCK_SIZE = 512;
680
- const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
681
688
 
682
689
  /**
683
690
  * Parse a plain ustar-style tar archive (512-byte headers, bodies padded to
@@ -720,20 +727,6 @@ function parseTarEntries(archive) {
720
727
  return entries;
721
728
  }
722
729
 
723
- /**
724
- * Read the pixel dimensions from a PNG's IHDR chunk. Returns null when the
725
- * bytes are not a PNG (e.g. a JPEG export) or are too short.
726
- *
727
- * @param {Buffer} bytes
728
- * @returns {{ width: number, height: number } | null}
729
- */
730
- function readPngDimensions(bytes) {
731
- if (bytes.length < 24 || !bytes.subarray(0, PNG_SIGNATURE.length).equals(PNG_SIGNATURE)) {
732
- return null;
733
- }
734
- return { width: bytes.readUInt32BE(16), height: bytes.readUInt32BE(20) };
735
- }
736
-
737
730
  /**
738
731
  * @param {string | undefined} json
739
732
  * @returns {any}
@@ -1910,6 +1903,14 @@ export class SnapProvider {
1910
1903
  * @returns {Promise<CaptureResult>}
1911
1904
  */
1912
1905
  async #captureLocalAndUpload(options) {
1906
+ // The latest-baseline lookup is read-only and independent of the screenshots,
1907
+ // so start it now and let it overlap with local capture. Its own deadline keeps
1908
+ // capture time out of the Snap operation budget. A rejection is held until we
1909
+ // await it below, so a capture failure first never leaves an unhandled one.
1910
+ const baselineLookup =
1911
+ options.purpose === 'diff' ? this.#resolveLatestBaselineId() : Promise.resolve(/** @type {string | null} */ (null));
1912
+ baselineLookup.catch(() => {});
1913
+
1913
1914
  const localCapture = await this.#localCaptureFn({
1914
1915
  configPath: options.configPath,
1915
1916
  routeIds: options.routeIds,
@@ -1939,7 +1940,7 @@ export class SnapProvider {
1939
1940
  // omit the baselineId. Captures then settle to "new" server-side (no
1940
1941
  // comparison), and publishBaseline harvests their object keys. A diff run
1941
1942
  // attaches the latest baseline so the backend can compare against it.
1942
- const baselineId = options.purpose === 'diff' ? await this.#resolveLatestBaselineId(operation) : null;
1943
+ const baselineId = await baselineLookup;
1943
1944
 
1944
1945
  const runResponse = await this.#request(
1945
1946
  'POST',
@@ -1974,7 +1975,8 @@ export class SnapProvider {
1974
1975
  assertComparisonPolicyAcknowledged(runResponse?.comparisonPolicy, options.comparisonPolicy, 'Snap local-upload run creation');
1975
1976
  }
1976
1977
 
1977
- for (const { route, manifestEntry } of uploads) {
1978
+ const uploadStartedAt = Date.now();
1979
+ await runWithConcurrency(uploads, LOCAL_UPLOAD_CONCURRENCY, async ({ route, manifestEntry }) => {
1978
1980
  const captureId = `cap_${crypto.randomUUID().replace(/-/g, '').slice(0, 24)}`;
1979
1981
  const viewportDescriptor = resolveViewportDescriptor(route.viewport);
1980
1982
 
@@ -2010,7 +2012,8 @@ export class SnapProvider {
2010
2012
  this.#generateIdempotencyKey(),
2011
2013
  operation
2012
2014
  );
2013
- }
2015
+ });
2016
+ process.stderr.write(`[SnapDrift] Uploaded ${uploads.length} screenshot(s) to Snap in ${((Date.now() - uploadStartedAt) / 1000).toFixed(1)}s.\n`);
2014
2017
 
2015
2018
  const snapResults = {
2016
2019
  ...localResults,
@@ -12,7 +12,9 @@ export {
12
12
  splitCommaList,
13
13
  VALID_DIFF_MODES,
14
14
  VALID_PROVIDER_VALUES,
15
- VALID_ON_UNAVAILABLE_MODES
15
+ VALID_CAPTURE_ENGINES,
16
+ VALID_ON_UNAVAILABLE_MODES,
17
+ isLocalBaseUrl
16
18
  } from '@snapdrift/manifest';
17
19
 
18
20
  export {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "snapdrift",
3
- "version": "0.15.0",
3
+ "version": "0.16.1",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "SnapDrift captures, compares, and reports UI drift for Playwright-based app checks.",
@@ -103,10 +103,10 @@
103
103
  "registry": "https://registry.npmjs.org"
104
104
  },
105
105
  "dependencies": {
106
- "@snapdrift/adapter-fs": "^1.6.0",
106
+ "@snapdrift/adapter-fs": "^1.7.1",
107
107
  "@snapdrift/adapter-report-md": "^1.4.0",
108
- "@snapdrift/compare-core": "^1.6.0",
109
- "@snapdrift/manifest": "^1.7.0",
108
+ "@snapdrift/compare-core": "^1.7.0",
109
+ "@snapdrift/manifest": "^1.8.0",
110
110
  "js-yaml": "^5.4.0",
111
111
  "playwright": "^1.59.1",
112
112
  "pngjs": "^7.0.0"
@@ -87,6 +87,7 @@ export interface VisualRegressionConfig {
87
87
  };
88
88
  selection?: VisualRegressionSelectionConfig;
89
89
  provider?: 'local' | 'snap';
90
+ capture?: 'playwright' | 'snap';
90
91
  snap?: SnapConfig;
91
92
  }
92
93
 
@@ -127,6 +128,7 @@ export interface VisualBaselineResults {
127
128
  screenshotsRoot?: string;
128
129
  routes: VisualBaselineRouteResult[];
129
130
  passed?: boolean;
131
+ engine?: string;
130
132
  }
131
133
 
132
134
  /** Exact route/viewport capture identity persisted for hosted baseline validation. */