@mizchi/vlmkit-capture 0.6.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 mizchi
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,51 @@
1
+ # @mizchi/vlmkit-capture
2
+
3
+ Playwright / Crater capture infrastructure for VRT — viewport discovery,
4
+ multi-route capture, prescanner integration.
5
+
6
+ Part of the [`vrt`](https://github.com/mizchi/vrt) monorepo.
7
+
8
+ ## Install
9
+
10
+ ```bash
11
+ pnpm add @mizchi/vlmkit-capture
12
+ ```
13
+
14
+ ## Usage
15
+
16
+ ```ts
17
+ import { discoverViewports, resolveCaptureRoutes } from "@mizchi/vlmkit-capture";
18
+
19
+ const html = await readFile("page.html", "utf-8");
20
+ const { viewports, breakpoints } = discoverViewports(html, {
21
+ randomSamples: 1,
22
+ maxViewports: 15,
23
+ });
24
+
25
+ const routeSet = resolveCaptureRoutes({
26
+ cwd: process.cwd(),
27
+ configPath: "vrt.config.json",
28
+ });
29
+ ```
30
+
31
+ `capturer.ts` (Playwright bootstrap) is intentionally **not** in the barrel —
32
+ deep-import when you need it:
33
+
34
+ ```ts
35
+ import { capturePage } from "@mizchi/vlmkit-capture/capturer.ts";
36
+ ```
37
+
38
+ ## What's included
39
+
40
+ | Module | Purpose |
41
+ |---|---|
42
+ | `capture-config` | `vrt.config.json` resolution + route schema. |
43
+ | `viewport-discovery` | Parse CSS media queries to suggest test viewports. |
44
+ | `crater-client` | Bidi-protocol client for the Crater browser engine. |
45
+ | `playwright-analyzer` | Auto-detect Playwright config from project. |
46
+ | `prescanner` | Pre-flight check (server reachability, breakpoints). |
47
+ | `capturer` (deep import) | Playwright-based screenshot capture. |
48
+
49
+ ## License
50
+
51
+ MIT
package/package.json ADDED
@@ -0,0 +1,36 @@
1
+ {
2
+ "name": "@mizchi/vlmkit-capture",
3
+ "version": "0.6.0",
4
+ "description": "Playwright + Crater capture infrastructure for VRT — viewport discovery, multi-route capture, prescanner.",
5
+ "license": "MIT",
6
+ "author": "mizchi",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/mizchi/vlmkit.git",
10
+ "directory": "packages/vlmkit-capture"
11
+ },
12
+ "homepage": "https://github.com/mizchi/vlmkit/tree/main/packages/vlmkit-capture#readme",
13
+ "bugs": {
14
+ "url": "https://github.com/mizchi/vlmkit/issues"
15
+ },
16
+ "type": "module",
17
+ "files": [
18
+ "src/**/*.ts",
19
+ "!src/**/*.test.ts",
20
+ "README.md",
21
+ "LICENSE"
22
+ ],
23
+ "exports": {
24
+ ".": "./src/index.ts",
25
+ "./*.ts": "./src/*.ts"
26
+ },
27
+ "dependencies": {
28
+ "playwright": "^1.58.2",
29
+ "pngjs": "^7.0.0",
30
+ "ws": "^8.20.0",
31
+ "@mizchi/vlmkit-core": "0.6.0"
32
+ },
33
+ "scripts": {
34
+ "test": "node --test 'src/**/*.test.ts'"
35
+ }
36
+ }
@@ -0,0 +1,219 @@
1
+ /**
2
+ * Capture configuration loader for `vrt workflow init|capture`.
3
+ *
4
+ * Allows external projects to drive `e2e/vrt-capture.spec.ts` without
5
+ * editing the spec by sourcing routes from `vrt.config.json` (or any
6
+ * file pointed at by `--config` / `VRT_CONFIG_PATH`).
7
+ */
8
+ import { existsSync, readFileSync } from "node:fs";
9
+ import { dirname, isAbsolute, resolve } from "node:path";
10
+
11
+ export interface CaptureRoute {
12
+ name: string;
13
+ path: string;
14
+ waitFor?: string;
15
+ }
16
+
17
+ export interface CaptureConfig {
18
+ baseUrl?: string;
19
+ routes?: CaptureRoute[];
20
+ }
21
+
22
+ export interface CaptureRouteSet {
23
+ baseUrl: string;
24
+ routes: CaptureRoute[];
25
+ source: "env" | "config" | "default";
26
+ configPath?: string;
27
+ }
28
+
29
+ export const DEFAULT_CAPTURE_BASE_URL = "http://127.0.0.1:4174";
30
+
31
+ /**
32
+ * Built-in fallback used when no config or env override is provided.
33
+ * Kept for vrt's own development workflow; external projects should
34
+ * supply their own routes via `vrt.config.json`.
35
+ */
36
+ export const DEFAULT_CAPTURE_ROUTES: CaptureRoute[] = [
37
+ { name: "home", path: "/", waitFor: "main" },
38
+ { name: "readme", path: "/readme", waitFor: "article" },
39
+ { name: "files", path: "/files", waitFor: "main" },
40
+ { name: "issues", path: "/issues", waitFor: "main" },
41
+ { name: "pulls", path: "/pulls", waitFor: "main" },
42
+ ];
43
+
44
+ export const DEFAULT_CAPTURE_CONFIG_FILE = "vrt.config.json";
45
+
46
+ export function parseCaptureConfig(raw: string): CaptureConfig {
47
+ let parsed: unknown;
48
+ try {
49
+ parsed = JSON.parse(raw);
50
+ } catch (error) {
51
+ throw new Error(`Invalid capture config JSON: ${String(error)}`);
52
+ }
53
+
54
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
55
+ throw new Error("Capture config must be an object");
56
+ }
57
+
58
+ const record = parsed as Record<string, unknown>;
59
+ const baseUrl = record.baseUrl == null
60
+ ? undefined
61
+ : parseNonEmptyString(record.baseUrl, "capture config baseUrl must be a non-empty string");
62
+
63
+ // `capture.routes` is preferred so it coexists cleanly with snapshot `routes`.
64
+ const captureSection = record.capture;
65
+ const routesSource = pickRoutesSource(captureSection, record.routes);
66
+ const routes = routesSource === undefined ? undefined : parseCaptureRoutes(routesSource);
67
+
68
+ return { baseUrl, routes };
69
+ }
70
+
71
+ function pickRoutesSource(captureSection: unknown, topLevelRoutes: unknown): unknown {
72
+ if (captureSection !== undefined && captureSection !== null) {
73
+ if (typeof captureSection !== "object" || Array.isArray(captureSection)) {
74
+ throw new Error("capture config `capture` must be an object");
75
+ }
76
+ const inner = (captureSection as Record<string, unknown>).routes;
77
+ if (inner !== undefined) return inner;
78
+ }
79
+ return topLevelRoutes;
80
+ }
81
+
82
+ function parseCaptureRoutes(value: unknown): CaptureRoute[] {
83
+ if (!Array.isArray(value)) {
84
+ throw new Error("capture config routes must be an array");
85
+ }
86
+
87
+ return value.map((entry, index) => parseCaptureRoute(entry, index));
88
+ }
89
+
90
+ function parseCaptureRoute(entry: unknown, index: number): CaptureRoute {
91
+ if (typeof entry === "string") {
92
+ const path = entry.trim();
93
+ if (!path) {
94
+ throw new Error(`capture config route at index ${index} must be a non-empty string`);
95
+ }
96
+ return { name: routeNameFromPath(path), path };
97
+ }
98
+
99
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
100
+ throw new Error(`capture config route at index ${index} must be a string or object`);
101
+ }
102
+
103
+ const record = entry as Record<string, unknown>;
104
+ const pathValue = record.path ?? record.url;
105
+ const path = parseNonEmptyString(pathValue, `capture config route at index ${index} must have a path`);
106
+
107
+ const nameRaw = record.name ?? record.label;
108
+ const name = nameRaw === undefined
109
+ ? routeNameFromPath(path)
110
+ : parseNonEmptyString(nameRaw, `capture config route at index ${index} has an invalid name`);
111
+
112
+ const waitForRaw = record.waitFor ?? record.wait_for;
113
+ const route: CaptureRoute = { name, path };
114
+ if (waitForRaw !== undefined) {
115
+ route.waitFor = parseNonEmptyString(
116
+ waitForRaw,
117
+ `capture config route at index ${index} has an invalid waitFor`,
118
+ );
119
+ }
120
+ return route;
121
+ }
122
+
123
+ export function routeNameFromPath(path: string): string {
124
+ const trimmed = path.split("?")[0]!.split("#")[0]!;
125
+ const cleaned = trimmed.replace(/^\/+|\/+$/g, "");
126
+ if (!cleaned) return "home";
127
+ const safe = cleaned.replace(/[^a-zA-Z0-9]+/g, "_").replace(/^_+|_+$/g, "").toLowerCase();
128
+ return safe || "home";
129
+ }
130
+
131
+ export interface LoadCaptureConfigOptions {
132
+ configPath?: string;
133
+ cwd?: string;
134
+ envRoutes?: string;
135
+ envBaseUrl?: string;
136
+ envConfigPath?: string;
137
+ }
138
+
139
+ /**
140
+ * Resolve the route set to use for a capture run.
141
+ *
142
+ * Precedence (highest first):
143
+ * 1. `VRT_CAPTURE_ROUTES` env var (JSON-encoded array)
144
+ * 2. Explicit config path (CLI / `VRT_CONFIG_PATH`)
145
+ * 3. `vrt.config.json` discovered in `cwd`
146
+ * 4. Built-in defaults
147
+ */
148
+ export function resolveCaptureRoutes(options: LoadCaptureConfigOptions = {}): CaptureRouteSet {
149
+ const cwd = options.cwd ?? process.cwd();
150
+ const envBaseUrl = options.envBaseUrl?.trim();
151
+
152
+ const envRoutes = options.envRoutes;
153
+ if (envRoutes && envRoutes.trim().length > 0) {
154
+ const routes = parseCaptureRoutes(JSON.parse(envRoutes));
155
+ return {
156
+ baseUrl: envBaseUrl || DEFAULT_CAPTURE_BASE_URL,
157
+ routes,
158
+ source: "env",
159
+ };
160
+ }
161
+
162
+ const configPath = resolveConfigPath(options.configPath, options.envConfigPath, cwd);
163
+ if (configPath) {
164
+ const raw = readFileSync(configPath, "utf-8");
165
+ const config = parseCaptureConfig(raw);
166
+ const routes = config.routes ?? DEFAULT_CAPTURE_ROUTES;
167
+ return {
168
+ baseUrl: envBaseUrl || config.baseUrl || DEFAULT_CAPTURE_BASE_URL,
169
+ routes,
170
+ source: "config",
171
+ configPath,
172
+ };
173
+ }
174
+
175
+ return {
176
+ baseUrl: envBaseUrl || DEFAULT_CAPTURE_BASE_URL,
177
+ routes: DEFAULT_CAPTURE_ROUTES,
178
+ source: "default",
179
+ };
180
+ }
181
+
182
+ function resolveConfigPath(
183
+ explicit: string | undefined,
184
+ fromEnv: string | undefined,
185
+ cwd: string,
186
+ ): string | undefined {
187
+ const candidate = explicit ?? fromEnv;
188
+ if (candidate && candidate.trim().length > 0) {
189
+ const absolute = isAbsolute(candidate) ? candidate : resolve(cwd, candidate);
190
+ if (!existsSync(absolute)) {
191
+ throw new Error(`Capture config not found: ${absolute}`);
192
+ }
193
+ return absolute;
194
+ }
195
+
196
+ const defaultPath = resolve(cwd, DEFAULT_CAPTURE_CONFIG_FILE);
197
+ return existsSync(defaultPath) ? defaultPath : undefined;
198
+ }
199
+
200
+ function parseNonEmptyString(value: unknown, message: string): string {
201
+ if (typeof value !== "string" || value.trim() === "") {
202
+ throw new Error(message);
203
+ }
204
+ return value;
205
+ }
206
+
207
+ /**
208
+ * Helper for unit tests / non-Playwright callers: read & normalize a file.
209
+ */
210
+ export function loadCaptureConfigFromFile(configPath: string): CaptureConfig {
211
+ if (!existsSync(configPath)) {
212
+ throw new Error(`Capture config not found: ${configPath}`);
213
+ }
214
+ return parseCaptureConfig(readFileSync(configPath, "utf-8"));
215
+ }
216
+
217
+ export function captureConfigDir(configPath: string): string {
218
+ return dirname(configPath);
219
+ }
@@ -0,0 +1,138 @@
1
+ /**
2
+ * Browser launch abstraction.
3
+ *
4
+ * Lets every consumer pick between launching Chromium locally and connecting
5
+ * to a remote Chrome DevTools Protocol endpoint such as Cloudflare's
6
+ * Browser Run service (https://api.cloudflare.com/client/v4/accounts/<id>/browser-rendering/devtools/browser).
7
+ *
8
+ * The factory only knows how to *open* a Browser. Page/context creation is
9
+ * left to the caller so existing capture code can keep its current
10
+ * `browser.newPage({viewport})` style.
11
+ */
12
+ import { chromium, type Browser } from "playwright";
13
+
14
+ export type CaptureBackendKind = "local" | "cloudflare-cdp";
15
+
16
+ export interface CaptureBackend {
17
+ readonly kind: CaptureBackendKind;
18
+ /** Human-readable label used in logs. */
19
+ readonly label: string;
20
+ launch(): Promise<Browser>;
21
+ close(browser: Browser): Promise<void>;
22
+ }
23
+
24
+ export interface CloudflareCdpOptions {
25
+ accountId: string;
26
+ apiToken: string;
27
+ /** Override the default CF CDP URL (useful for tests / private deployments). */
28
+ endpoint?: string;
29
+ }
30
+
31
+ export function buildCloudflareCdpUrl(opts: { accountId: string; endpoint?: string }): string {
32
+ if (opts.endpoint && opts.endpoint.length > 0) return opts.endpoint;
33
+ const account = opts.accountId.trim();
34
+ if (account.length === 0) {
35
+ throw new Error("Cloudflare account id is required to build the CDP URL");
36
+ }
37
+ return `wss://api.cloudflare.com/client/v4/accounts/${account}/browser-rendering/devtools/browser`;
38
+ }
39
+
40
+ export function createLocalCapturer(): CaptureBackend {
41
+ return {
42
+ kind: "local",
43
+ label: "local chromium",
44
+ async launch() {
45
+ return chromium.launch();
46
+ },
47
+ async close(browser) {
48
+ await browser.close();
49
+ },
50
+ };
51
+ }
52
+
53
+ export function createCloudflareCdpCapturer(opts: CloudflareCdpOptions): CaptureBackend {
54
+ if (!opts.apiToken || opts.apiToken.trim().length === 0) {
55
+ throw new Error("Cloudflare API token is required for the cloudflare-cdp backend");
56
+ }
57
+ const wsEndpoint = buildCloudflareCdpUrl(opts);
58
+ const headers = { Authorization: `Bearer ${opts.apiToken}` };
59
+
60
+ return {
61
+ kind: "cloudflare-cdp",
62
+ label: `cloudflare browser run (${maskAccount(opts.accountId)})`,
63
+ async launch() {
64
+ return chromium.connectOverCDP(wsEndpoint, { headers });
65
+ },
66
+ async close(browser) {
67
+ // For remote browsers, close() releases the WebSocket but does not
68
+ // terminate the CF session — that's managed server-side.
69
+ await browser.close();
70
+ },
71
+ };
72
+ }
73
+
74
+ function maskAccount(id: string): string {
75
+ if (id.length <= 8) return id;
76
+ return `${id.slice(0, 4)}…${id.slice(-4)}`;
77
+ }
78
+
79
+ export interface ResolveCaptureBackendOptions {
80
+ /** Value from `--backend` CLI flag (e.g. "local", "cloudflare"). */
81
+ backendFlag?: string;
82
+ env?: NodeJS.ProcessEnv;
83
+ }
84
+
85
+ export interface ResolvedCaptureBackend {
86
+ backend: CaptureBackend;
87
+ source: "flag" | "env" | "default";
88
+ }
89
+
90
+ /**
91
+ * Resolution order:
92
+ * 1. Explicit `--backend` flag
93
+ * 2. `VRT_CAPTURE_BACKEND` env var
94
+ * 3. Default local
95
+ *
96
+ * For the Cloudflare backend, credentials come from env (`CLOUDFLARE_ACCOUNT_ID`
97
+ * + `CLOUDFLARE_API_TOKEN`) regardless of how the backend was selected, so
98
+ * CI configs can stay declarative.
99
+ */
100
+ export function resolveCaptureBackend(
101
+ options: ResolveCaptureBackendOptions = {},
102
+ ): ResolvedCaptureBackend {
103
+ const env = options.env ?? process.env;
104
+ const explicit = options.backendFlag?.trim().toLowerCase();
105
+ const envChoice = env.VRT_CAPTURE_BACKEND?.trim().toLowerCase();
106
+
107
+ const choice = explicit || envChoice || "local";
108
+ const source: ResolvedCaptureBackend["source"] = explicit
109
+ ? "flag"
110
+ : envChoice
111
+ ? "env"
112
+ : "default";
113
+
114
+ switch (choice) {
115
+ case "local":
116
+ case "chromium":
117
+ return { backend: createLocalCapturer(), source };
118
+ case "cloudflare":
119
+ case "cloudflare-cdp":
120
+ case "browser-run": {
121
+ const accountId = env.CLOUDFLARE_ACCOUNT_ID?.trim();
122
+ const apiToken = env.CLOUDFLARE_API_TOKEN?.trim();
123
+ const endpoint = env.CLOUDFLARE_BROWSER_RUN_ENDPOINT?.trim();
124
+ if (!accountId) {
125
+ throw new Error("CLOUDFLARE_ACCOUNT_ID is required when --backend cloudflare is selected");
126
+ }
127
+ if (!apiToken) {
128
+ throw new Error("CLOUDFLARE_API_TOKEN is required when --backend cloudflare is selected");
129
+ }
130
+ return {
131
+ backend: createCloudflareCdpCapturer({ accountId, apiToken, endpoint }),
132
+ source,
133
+ };
134
+ }
135
+ default:
136
+ throw new Error(`Unknown capture backend: ${choice}`);
137
+ }
138
+ }