@mizchi/vlmkit-capture 0.8.0 → 0.8.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.
Files changed (39) hide show
  1. package/dist/batch-prescan.d.mts +51 -0
  2. package/dist/batch-prescan.mjs +66 -0
  3. package/dist/capture-config.d.mts +50 -0
  4. package/dist/capture-config.mjs +164 -0
  5. package/dist/capturer.d.mts +45 -0
  6. package/dist/capturer.mjs +94 -0
  7. package/dist/cloudflare-quick-actions.d.mts +114 -0
  8. package/dist/cloudflare-quick-actions.mjs +142 -0
  9. package/dist/crater-client.d.mts +159 -0
  10. package/dist/crater-client.mjs +362 -0
  11. package/dist/crater-smoke.d.mts +98 -0
  12. package/dist/crater-smoke.mjs +269 -0
  13. package/dist/crater-wasm.d.mts +65 -0
  14. package/dist/crater-wasm.mjs +132 -0
  15. package/{src/detection-types.ts → dist/detection-types.d.mts} +4 -2
  16. package/dist/detection-types.mjs +1 -0
  17. package/dist/index.d.mts +12 -0
  18. package/dist/index.mjs +11 -0
  19. package/dist/playwright-analyzer.d.mts +38 -0
  20. package/dist/playwright-analyzer.mjs +117 -0
  21. package/dist/playwright-launch-error.d.mts +7 -0
  22. package/dist/playwright-launch-error.mjs +25 -0
  23. package/dist/prescanner.d.mts +39 -0
  24. package/dist/prescanner.mjs +61 -0
  25. package/dist/viewport-discovery.d.mts +114 -0
  26. package/dist/viewport-discovery.mjs +294 -0
  27. package/package.json +18 -6
  28. package/src/batch-prescan.ts +0 -115
  29. package/src/capture-config.ts +0 -219
  30. package/src/capturer.ts +0 -138
  31. package/src/cloudflare-quick-actions.ts +0 -304
  32. package/src/crater-client.ts +0 -537
  33. package/src/crater-smoke.ts +0 -336
  34. package/src/crater-wasm.ts +0 -260
  35. package/src/index.ts +0 -157
  36. package/src/playwright-analyzer.ts +0 -180
  37. package/src/playwright-launch-error.ts +0 -41
  38. package/src/prescanner.ts +0 -123
  39. package/src/viewport-discovery.ts +0 -455
@@ -0,0 +1,142 @@
1
+ //#region src/cloudflare-quick-actions.ts
2
+ function buildCloudflareQuickActionEndpoint(input) {
3
+ const base = `${(input.apiBase ?? "https://api.cloudflare.com/client/v4").replace(/\/$/u, "")}/accounts/${encodeURIComponent(input.accountId)}/browser-rendering/${input.action}`;
4
+ return input.jobId ? `${base}/${encodeURIComponent(input.jobId)}` : base;
5
+ }
6
+ function resolveCloudflareQuickActionsConfig(env = process.env) {
7
+ const accountId = env.CLOUDFLARE_ACCOUNT_ID?.trim();
8
+ if (!accountId) throw new Error("CLOUDFLARE_ACCOUNT_ID is required for Cloudflare Quick Actions");
9
+ const apiToken = env.CLOUDFLARE_API_TOKEN?.trim();
10
+ if (!apiToken) throw new Error("CLOUDFLARE_API_TOKEN is required for Cloudflare Quick Actions");
11
+ return {
12
+ accountId,
13
+ apiToken,
14
+ apiBase: env.CLOUDFLARE_BROWSER_RENDERING_API_BASE?.trim() || void 0
15
+ };
16
+ }
17
+ function createCloudflareQuickActionsClient(config) {
18
+ const fetchImpl = config.fetch ?? fetch;
19
+ const headers = {
20
+ Authorization: `Bearer ${config.apiToken}`,
21
+ "Content-Type": "application/json"
22
+ };
23
+ async function post(action, body) {
24
+ const response = await fetchImpl(buildCloudflareQuickActionEndpoint({
25
+ accountId: config.accountId,
26
+ action,
27
+ apiBase: config.apiBase
28
+ }), {
29
+ method: "POST",
30
+ headers,
31
+ body: JSON.stringify(body)
32
+ });
33
+ if (!response.ok) throw new Error(`Cloudflare ${action} failed: ${response.status} ${await response.text()}`);
34
+ return response;
35
+ }
36
+ return {
37
+ async screenshot(input) {
38
+ if (!input.url && !input.html) throw new Error("Cloudflare screenshot requires url or html");
39
+ const response = await post("screenshot", input);
40
+ const browserMsHeader = response.headers.get("x-browser-ms-used");
41
+ return {
42
+ bytes: await response.arrayBuffer(),
43
+ contentType: response.headers.get("content-type") ?? "image/png",
44
+ browserMsUsed: browserMsHeader ? Number(browserMsHeader) : void 0
45
+ };
46
+ },
47
+ async startCrawl(input) {
48
+ return { jobId: normalizeCrawlJobId(await (await post("crawl", input)).json()) };
49
+ },
50
+ async getCrawlResult(jobId) {
51
+ const response = await fetchImpl(buildCloudflareQuickActionEndpoint({
52
+ accountId: config.accountId,
53
+ action: "crawl",
54
+ jobId,
55
+ apiBase: config.apiBase
56
+ }), {
57
+ method: "GET",
58
+ headers: { Authorization: `Bearer ${config.apiToken}` }
59
+ });
60
+ if (!response.ok) throw new Error(`Cloudflare crawl result failed: ${response.status} ${await response.text()}`);
61
+ return normalizeCrawlResult(await response.json());
62
+ }
63
+ };
64
+ }
65
+ function extractCloudflareCrawlRoutes(result, options = {}) {
66
+ const base = options.baseUrl ? new URL(options.baseUrl) : void 0;
67
+ const seen = /* @__PURE__ */ new Set();
68
+ const routes = [];
69
+ for (const record of result.records) {
70
+ if (record.status !== "completed") continue;
71
+ const rawUrl = record.metadata?.url ?? record.url;
72
+ let parsed;
73
+ try {
74
+ parsed = new URL(rawUrl);
75
+ } catch {
76
+ continue;
77
+ }
78
+ if (base && parsed.origin !== base.origin) continue;
79
+ const path = parsed.pathname + parsed.search;
80
+ if (seen.has(path)) continue;
81
+ seen.add(path);
82
+ const route = {
83
+ url: rawUrl,
84
+ path
85
+ };
86
+ if (record.metadata?.title) route.title = record.metadata.title;
87
+ routes.push(route);
88
+ }
89
+ return routes;
90
+ }
91
+ function normalizeCrawlJobId(parsed) {
92
+ if (typeof parsed === "string") return parsed;
93
+ if (isRecord(parsed)) {
94
+ if (typeof parsed.result === "string") return parsed.result;
95
+ if (isRecord(parsed.result) && typeof parsed.result.id === "string") return parsed.result.id;
96
+ if (typeof parsed.id === "string") return parsed.id;
97
+ }
98
+ throw new Error("Cloudflare crawl response did not include a job id");
99
+ }
100
+ function normalizeCrawlResult(parsed) {
101
+ const value = isRecord(parsed) && isRecord(parsed.result) ? parsed.result : parsed;
102
+ if (!isRecord(value)) throw new Error("Cloudflare crawl result must be an object");
103
+ return {
104
+ id: readString(value, "id"),
105
+ status: readString(value, "status"),
106
+ browserSecondsUsed: readNumber(value, "browserSecondsUsed"),
107
+ total: readNumber(value, "total"),
108
+ finished: readNumber(value, "finished"),
109
+ records: Array.isArray(value.records) ? value.records.filter(isRecord).map(normalizeCrawlRecord) : []
110
+ };
111
+ }
112
+ function normalizeCrawlRecord(value) {
113
+ return {
114
+ url: readString(value, "url"),
115
+ status: readString(value, "status"),
116
+ metadata: isRecord(value.metadata) ? {
117
+ status: readNumber(value.metadata, "status"),
118
+ url: readOptionalString(value.metadata, "url"),
119
+ title: readOptionalString(value.metadata, "title")
120
+ } : void 0,
121
+ html: readOptionalString(value, "html"),
122
+ markdown: readOptionalString(value, "markdown"),
123
+ json: value.json
124
+ };
125
+ }
126
+ function isRecord(value) {
127
+ return Boolean(value && typeof value === "object" && !Array.isArray(value));
128
+ }
129
+ function readString(record, key) {
130
+ const value = record[key];
131
+ return typeof value === "string" ? value : "";
132
+ }
133
+ function readOptionalString(record, key) {
134
+ const value = record[key];
135
+ return typeof value === "string" ? value : void 0;
136
+ }
137
+ function readNumber(record, key) {
138
+ const value = record[key];
139
+ return typeof value === "number" ? value : void 0;
140
+ }
141
+ //#endregion
142
+ export { buildCloudflareQuickActionEndpoint, createCloudflareQuickActionsClient, extractCloudflareCrawlRoutes, resolveCloudflareQuickActionsConfig };
@@ -0,0 +1,159 @@
1
+ //#region src/crater-client.d.ts
2
+ declare const DEFAULT_BIDI_URL = "ws://127.0.0.1:9222";
3
+ declare const VLMKIT_CRATER_BIDI_URL_ENV = "VLMKIT_CRATER_BIDI_URL";
4
+ declare const CRATER_BIDI_URL_ENV = "CRATER_BIDI_URL";
5
+ declare const VLMKIT_CRATER_ROOT_ENV = "VLMKIT_CRATER_ROOT";
6
+ declare const CRATER_ROOT_ENV = "CRATER_ROOT";
7
+ interface ResolveCraterBidiUrlOptions {
8
+ env?: Partial<Record<typeof VLMKIT_CRATER_BIDI_URL_ENV | typeof CRATER_BIDI_URL_ENV | typeof VLMKIT_CRATER_ROOT_ENV | typeof CRATER_ROOT_ENV, string | undefined>>;
9
+ craterRoot?: string;
10
+ urlFile?: string;
11
+ }
12
+ declare function resolveCraterBidiUrl(options?: ResolveCraterBidiUrlOptions): string;
13
+ interface CraterResponsiveBreakpoint {
14
+ axis: "width";
15
+ op: "ge" | "gt" | "le" | "lt";
16
+ valuePx: number;
17
+ raw: string;
18
+ normalized: string;
19
+ guards: string[];
20
+ ruleCount: number;
21
+ }
22
+ interface CraterBreakpointDiscoveryDiagnostics {
23
+ stylesheetCount: number;
24
+ ruleCount: number;
25
+ externalStylesheetLinks: string[];
26
+ ignoredQueries: string[];
27
+ unsupportedQueries: string[];
28
+ }
29
+ interface CraterRuleViewportMapEntry {
30
+ selector: string;
31
+ properties: string[];
32
+ mediaCondition: string;
33
+ activeAtWidths: number[];
34
+ inactiveAtWidths: number[];
35
+ }
36
+ interface CraterRuleViewportMap {
37
+ rules: CraterRuleViewportMapEntry[];
38
+ }
39
+ interface CraterComputedStyleWithState {
40
+ normal: Record<string, string>;
41
+ forced: Record<string, string>;
42
+ diff: Array<{
43
+ property: string;
44
+ normal: string;
45
+ forced: string;
46
+ }>;
47
+ }
48
+ type CraterCssMutationAction = "remove" | {
49
+ override: string;
50
+ };
51
+ interface CraterCssMutation {
52
+ selector: string;
53
+ property: string;
54
+ action?: CraterCssMutationAction;
55
+ }
56
+ interface CraterRenderVariant {
57
+ id: string;
58
+ mutations: CraterCssMutation[];
59
+ }
60
+ interface CraterBatchRenderResult {
61
+ results: Array<{
62
+ id: string;
63
+ paintTree?: PaintNode | null;
64
+ }>;
65
+ }
66
+ interface CraterBreakpointDiscoveryResult {
67
+ breakpoints: CraterResponsiveBreakpoint[];
68
+ diagnostics?: CraterBreakpointDiscoveryDiagnostics;
69
+ }
70
+ declare class CraterClient {
71
+ private ws;
72
+ private commandId;
73
+ private pendingCommands;
74
+ private contextId;
75
+ private url;
76
+ constructor(url?: string);
77
+ connect(): Promise<void>;
78
+ close(): Promise<void>;
79
+ setViewport(width: number, height: number): Promise<void>;
80
+ setContent(html: string): Promise<void>;
81
+ evaluate<T>(expression: string, awaitPromise?: boolean): Promise<T>;
82
+ /** PNG screenshot (Buffer) */
83
+ captureScreenshot(): Promise<Buffer>;
84
+ /** Raw RGBA data (pixelmatch compatible) */
85
+ capturePaintData(): Promise<{
86
+ width: number;
87
+ height: number;
88
+ data: Uint8Array;
89
+ }>;
90
+ /** Raw RGBA -> PNG Buffer conversion */
91
+ capturePng(): Promise<{
92
+ png: Buffer;
93
+ width: number;
94
+ height: number;
95
+ }>;
96
+ captureComputedStyles(properties: string[]): Promise<Map<string, Record<string, string>>>;
97
+ private captureNativeComputedStyles;
98
+ getResponsiveBreakpoints(options?: {
99
+ mode?: "live-inline" | "html-inline";
100
+ axis?: "width";
101
+ includeDiagnostics?: boolean;
102
+ }): Promise<CraterBreakpointDiscoveryResult>;
103
+ /** CSS rule → viewport mapping (#33) */
104
+ getCssRuleViewportMap(viewportWidths?: number[]): Promise<CraterRuleViewportMap>;
105
+ /** Required test viewports (#33) */
106
+ getRequiredTestViewports(): Promise<{
107
+ viewports: Array<{
108
+ width: number;
109
+ reason: string;
110
+ }>;
111
+ }>;
112
+ /** Computed styles with forced pseudo-class state (#34) */
113
+ getComputedStylesWithState(selector: string, forcedStates: string[], properties: string[]): Promise<CraterComputedStyleWithState>;
114
+ /** Batch variant rendering (#28) */
115
+ batchRender(baseHtml: string, viewport: {
116
+ width: number;
117
+ height: number;
118
+ }, variants: CraterRenderVariant[]): Promise<CraterBatchRenderResult>;
119
+ private requireContextId;
120
+ private handleMessage;
121
+ private sendBidi;
122
+ /** Paint tree (render tree JSON) */
123
+ capturePaintTree(): Promise<PaintNode>;
124
+ }
125
+ interface PaintNode {
126
+ id?: string;
127
+ tag?: string;
128
+ x: number;
129
+ y: number;
130
+ w: number;
131
+ h: number;
132
+ ox?: string;
133
+ oy?: string;
134
+ p?: PaintProps;
135
+ text?: string;
136
+ ch?: PaintNode[];
137
+ }
138
+ interface PaintProps {
139
+ op?: number;
140
+ c?: number[];
141
+ bg?: number[];
142
+ fs?: number;
143
+ ib?: boolean;
144
+ vis?: string;
145
+ br?: number[];
146
+ }
147
+ interface PaintTreeChange {
148
+ path: string;
149
+ type: "geometry" | "paint" | "text" | "added" | "removed";
150
+ property?: string;
151
+ before?: string;
152
+ after?: string;
153
+ }
154
+ /** Compare two paint trees and return the diff */
155
+ declare function diffPaintTrees(baseline: PaintNode, current: PaintNode, path?: string): PaintTreeChange[];
156
+ /** Check if crater server is running */
157
+ declare function isCraterAvailable(url?: string): Promise<boolean>;
158
+ //#endregion
159
+ export { CRATER_BIDI_URL_ENV, CRATER_ROOT_ENV, CraterBatchRenderResult, CraterBreakpointDiscoveryDiagnostics, CraterBreakpointDiscoveryResult, CraterClient, CraterComputedStyleWithState, CraterCssMutation, CraterCssMutationAction, CraterRenderVariant, CraterResponsiveBreakpoint, CraterRuleViewportMap, CraterRuleViewportMapEntry, DEFAULT_BIDI_URL, PaintNode, PaintProps, PaintTreeChange, ResolveCraterBidiUrlOptions, VLMKIT_CRATER_BIDI_URL_ENV, VLMKIT_CRATER_ROOT_ENV, diffPaintTrees, isCraterAvailable, resolveCraterBidiUrl };
@@ -0,0 +1,362 @@
1
+ import WebSocket from "ws";
2
+ import { PNG } from "pngjs";
3
+ import { existsSync, readFileSync } from "node:fs";
4
+ import { resolve } from "node:path";
5
+ import { buildComputedStyleCaptureJsonExpression, computedStyleSnapshotToMap, hasMeaningfulComputedStyleSnapshot, parseComputedStyleSnapshot } from "@mizchi/vlmkit-core/computed-style-capture.ts";
6
+ //#region src/crater-client.ts
7
+ /**
8
+ * Crater BiDi client
9
+ *
10
+ * Lightweight client connecting to mizchi/crater WebDriver BiDi server
11
+ * for HTML rendering + screenshot capture.
12
+ *
13
+ * Start crater server:
14
+ * cd ~/ghq/github.com/mizchi/crater
15
+ * just build-bidi && just start-bidi-with-font
16
+ */
17
+ const DEFAULT_BIDI_URL = "ws://127.0.0.1:9222";
18
+ const VLMKIT_CRATER_BIDI_URL_ENV = "VLMKIT_CRATER_BIDI_URL";
19
+ const CRATER_BIDI_URL_ENV = "CRATER_BIDI_URL";
20
+ const VLMKIT_CRATER_ROOT_ENV = "VLMKIT_CRATER_ROOT";
21
+ const CRATER_ROOT_ENV = "CRATER_ROOT";
22
+ function resolveCraterBidiUrl(options = {}) {
23
+ const env = options.env ?? process.env;
24
+ const fromEnv = env["VLMKIT_CRATER_BIDI_URL"] ?? env["CRATER_BIDI_URL"];
25
+ if (fromEnv?.trim()) return fromEnv.trim();
26
+ const fileCandidates = [options.urlFile, resolveCraterBidiUrlFile(options.craterRoot ?? env["VLMKIT_CRATER_ROOT"] ?? env["CRATER_ROOT"])].filter((candidate) => Boolean(candidate));
27
+ for (const candidate of fileCandidates) try {
28
+ if (!existsSync(candidate)) continue;
29
+ const value = readFileSync(candidate, "utf-8").trim();
30
+ if (value) return value;
31
+ } catch {}
32
+ return DEFAULT_BIDI_URL;
33
+ }
34
+ function resolveCraterBidiUrlFile(craterRoot) {
35
+ return craterRoot?.trim() ? resolve(craterRoot, ".bidi-ws-url") : void 0;
36
+ }
37
+ var CraterClient = class {
38
+ ws = null;
39
+ commandId = 0;
40
+ pendingCommands = /* @__PURE__ */ new Map();
41
+ contextId = null;
42
+ url;
43
+ constructor(url = resolveCraterBidiUrl()) {
44
+ this.url = url;
45
+ }
46
+ async connect() {
47
+ await new Promise((resolve, reject) => {
48
+ this.ws = new WebSocket(this.url);
49
+ this.ws.on("open", async () => {
50
+ try {
51
+ this.contextId = (await this.sendBidi("browsingContext.create", { type: "tab" })).result.context;
52
+ resolve();
53
+ } catch (error) {
54
+ reject(error);
55
+ }
56
+ });
57
+ this.ws.on("error", (error) => reject(error));
58
+ this.ws.on("message", (data) => this.handleMessage(data.toString()));
59
+ });
60
+ }
61
+ async close() {
62
+ if (this.contextId) try {
63
+ await this.sendBidi("browsingContext.close", { context: this.contextId });
64
+ } catch (e) {
65
+ console.warn("[crater] close context failed:", e instanceof Error ? e.message : e);
66
+ }
67
+ this.contextId = null;
68
+ this.ws?.close();
69
+ this.ws = null;
70
+ }
71
+ async setViewport(width, height) {
72
+ await this.sendBidi("browsingContext.setViewport", {
73
+ context: this.requireContextId(),
74
+ viewport: {
75
+ width,
76
+ height
77
+ }
78
+ });
79
+ }
80
+ async setContent(html) {
81
+ const dataUrl = `data:text/html;base64,${Buffer.from(html).toString("base64")}`;
82
+ await this.sendBidi("browsingContext.navigate", {
83
+ context: this.requireContextId(),
84
+ url: dataUrl,
85
+ wait: "complete"
86
+ });
87
+ await this.evaluate(`__loadHTML(${JSON.stringify(html)})`);
88
+ await this.evaluate(`(async () => await __executeScripts())()`, true);
89
+ }
90
+ async evaluate(expression, awaitPromise = false) {
91
+ const resp = await this.sendBidi("script.evaluate", {
92
+ expression,
93
+ target: { context: this.requireContextId() },
94
+ awaitPromise: awaitPromise || expression.includes("await ") || expression.includes("new Promise")
95
+ });
96
+ if (resp.type === "error") throw new Error(resp.message || resp.error || "script.evaluate failed");
97
+ const result = resp.result;
98
+ if (result.exceptionDetails) throw new Error(JSON.stringify(result.exceptionDetails));
99
+ return result.result?.value;
100
+ }
101
+ /** PNG screenshot (Buffer) */
102
+ async captureScreenshot() {
103
+ const resp = await this.sendBidi("browsingContext.captureScreenshotData", {
104
+ context: this.requireContextId(),
105
+ origin: "viewport"
106
+ });
107
+ if (resp.type === "error") throw new Error(resp.message || resp.error || "captureScreenshotData failed");
108
+ return Buffer.from(String(resp.result || ""), "base64");
109
+ }
110
+ /** Raw RGBA data (pixelmatch compatible) */
111
+ async capturePaintData() {
112
+ const resp = await this.sendBidi("browsingContext.capturePaintData", {
113
+ context: this.requireContextId(),
114
+ origin: "viewport"
115
+ }, 12e4);
116
+ if (resp.type === "error") throw new Error(resp.message || resp.error || "capturePaintData failed");
117
+ const result = resp.result;
118
+ return {
119
+ width: Number(result.width ?? 0),
120
+ height: Number(result.height ?? 0),
121
+ data: Uint8Array.from(Buffer.from(String(result.data || ""), "base64"))
122
+ };
123
+ }
124
+ /** Raw RGBA -> PNG Buffer conversion */
125
+ async capturePng() {
126
+ const { width, height, data } = await this.capturePaintData();
127
+ const png = new PNG({
128
+ width,
129
+ height
130
+ });
131
+ png.data = Buffer.from(data);
132
+ return {
133
+ png: PNG.sync.write(png),
134
+ width,
135
+ height
136
+ };
137
+ }
138
+ async captureComputedStyles(properties) {
139
+ const nativeSnapshot = await this.captureNativeComputedStyles(properties);
140
+ if (nativeSnapshot) return nativeSnapshot;
141
+ const snapshot = parseComputedStyleSnapshot(await this.evaluate(buildComputedStyleCaptureJsonExpression(properties)));
142
+ if (!hasMeaningfulComputedStyleSnapshot(snapshot)) return /* @__PURE__ */ new Map();
143
+ return computedStyleSnapshotToMap(snapshot);
144
+ }
145
+ async captureNativeComputedStyles(properties) {
146
+ let context;
147
+ try {
148
+ context = this.requireContextId();
149
+ } catch {
150
+ return null;
151
+ }
152
+ try {
153
+ const resp = await this.sendBidi("browsingContext.getAllComputedStyles", {
154
+ context,
155
+ properties
156
+ }, 3e4);
157
+ if (resp.type === "error") return null;
158
+ const result = resp.result;
159
+ const snapshot = parseComputedStyleSnapshot(result?.styles ?? {});
160
+ if (!hasMeaningfulComputedStyleSnapshot(snapshot)) return /* @__PURE__ */ new Map();
161
+ return computedStyleSnapshotToMap(snapshot);
162
+ } catch {
163
+ return null;
164
+ }
165
+ }
166
+ async getResponsiveBreakpoints(options = {}) {
167
+ const resp = await this.sendBidi("browsingContext.getResponsiveBreakpoints", {
168
+ context: this.requireContextId(),
169
+ mode: options.mode ?? "live-inline",
170
+ axis: options.axis ?? "width",
171
+ includeDiagnostics: options.includeDiagnostics ?? true
172
+ }, 3e4);
173
+ if (resp.type === "error") throw new Error(resp.message || resp.error || "getResponsiveBreakpoints failed");
174
+ const result = resp.result;
175
+ return {
176
+ breakpoints: result?.breakpoints ?? [],
177
+ diagnostics: result?.diagnostics
178
+ };
179
+ }
180
+ /** CSS rule → viewport mapping (#33) */
181
+ async getCssRuleViewportMap(viewportWidths) {
182
+ const resp = await this.sendBidi("browsingContext.getCssRuleViewportMap", {
183
+ context: this.requireContextId(),
184
+ ...viewportWidths ? { viewportWidths } : {}
185
+ }, 3e4);
186
+ if (resp.type === "error") throw new Error(resp.message || resp.error || "getCssRuleViewportMap failed");
187
+ return resp.result ?? { rules: [] };
188
+ }
189
+ /** Required test viewports (#33) */
190
+ async getRequiredTestViewports() {
191
+ const resp = await this.sendBidi("browsingContext.getRequiredTestViewports", { context: this.requireContextId() }, 3e4);
192
+ if (resp.type === "error") throw new Error(resp.message || resp.error || "getRequiredTestViewports failed");
193
+ return resp.result ?? { viewports: [] };
194
+ }
195
+ /** Computed styles with forced pseudo-class state (#34) */
196
+ async getComputedStylesWithState(selector, forcedStates, properties) {
197
+ const resp = await this.sendBidi("browsingContext.getComputedStylesWithState", {
198
+ context: this.requireContextId(),
199
+ selector,
200
+ forcedStates,
201
+ properties
202
+ }, 3e4);
203
+ if (resp.type === "error") throw new Error(resp.message || resp.error || "getComputedStylesWithState failed");
204
+ return resp.result ?? {
205
+ normal: {},
206
+ forced: {},
207
+ diff: []
208
+ };
209
+ }
210
+ /** Batch variant rendering (#28) */
211
+ async batchRender(baseHtml, viewport, variants) {
212
+ const resp = await this.sendBidi("browsingContext.batchRender", {
213
+ context: this.requireContextId(),
214
+ baseHtml,
215
+ viewport,
216
+ variants
217
+ }, 12e4);
218
+ if (resp.type === "error") throw new Error(resp.message || resp.error || "batchRender failed");
219
+ return resp.result ?? { results: [] };
220
+ }
221
+ requireContextId() {
222
+ if (!this.contextId) throw new Error("Not connected. Call connect() first.");
223
+ return this.contextId;
224
+ }
225
+ handleMessage(data) {
226
+ let msg;
227
+ try {
228
+ msg = JSON.parse(data);
229
+ } catch {
230
+ console.warn("[crater] invalid JSON from BiDi:", data.slice(0, 200));
231
+ return;
232
+ }
233
+ if (typeof msg.id !== "number") return;
234
+ const pending = this.pendingCommands.get(msg.id);
235
+ if (pending) {
236
+ this.pendingCommands.delete(msg.id);
237
+ pending.resolve(msg);
238
+ }
239
+ }
240
+ sendBidi(method, params, timeoutMs = 1e4) {
241
+ return new Promise((resolve, reject) => {
242
+ const id = ++this.commandId;
243
+ const timer = setTimeout(() => {
244
+ this.pendingCommands.delete(id);
245
+ reject(/* @__PURE__ */ new Error(`BiDi command ${method} timed out after ${timeoutMs}ms`));
246
+ }, timeoutMs);
247
+ this.pendingCommands.set(id, {
248
+ resolve: (resp) => {
249
+ clearTimeout(timer);
250
+ resolve(resp);
251
+ },
252
+ reject: (err) => {
253
+ clearTimeout(timer);
254
+ reject(err);
255
+ }
256
+ });
257
+ this.ws?.send(JSON.stringify({
258
+ id,
259
+ method,
260
+ params
261
+ }));
262
+ });
263
+ }
264
+ /** Paint tree (render tree JSON) */
265
+ async capturePaintTree() {
266
+ const resp = await this.sendBidi("browsingContext.capturePaintTree", { context: this.requireContextId() }, 12e4);
267
+ if (resp.type === "error") throw new Error(resp.message || resp.error || "capturePaintTree failed");
268
+ const result = resp.result;
269
+ return JSON.parse(result.paintTree || "{}");
270
+ }
271
+ };
272
+ /** Compare two paint trees and return the diff */
273
+ function diffPaintTrees(baseline, current, path = "root") {
274
+ const changes = [];
275
+ if (baseline.x !== current.x || baseline.y !== current.y || baseline.w !== current.w || baseline.h !== current.h) changes.push({
276
+ path,
277
+ type: "geometry",
278
+ property: "bounds",
279
+ before: `${baseline.x},${baseline.y} ${baseline.w}x${baseline.h}`,
280
+ after: `${current.x},${current.y} ${current.w}x${current.h}`
281
+ });
282
+ if (baseline.p && current.p) {
283
+ const bp = baseline.p;
284
+ const cp = current.p;
285
+ if (bp.op !== cp.op) changes.push({
286
+ path,
287
+ type: "paint",
288
+ property: "opacity",
289
+ before: String(bp.op),
290
+ after: String(cp.op)
291
+ });
292
+ if (JSON.stringify(bp.c) !== JSON.stringify(cp.c)) changes.push({
293
+ path,
294
+ type: "paint",
295
+ property: "color",
296
+ before: JSON.stringify(bp.c),
297
+ after: JSON.stringify(cp.c)
298
+ });
299
+ if (JSON.stringify(bp.bg) !== JSON.stringify(cp.bg)) changes.push({
300
+ path,
301
+ type: "paint",
302
+ property: "background",
303
+ before: JSON.stringify(bp.bg),
304
+ after: JSON.stringify(cp.bg)
305
+ });
306
+ if (bp.fs !== cp.fs) changes.push({
307
+ path,
308
+ type: "paint",
309
+ property: "font-size",
310
+ before: String(bp.fs),
311
+ after: String(cp.fs)
312
+ });
313
+ if (bp.ib !== cp.ib) changes.push({
314
+ path,
315
+ type: "paint",
316
+ property: "font-weight",
317
+ before: String(bp.ib),
318
+ after: String(cp.ib)
319
+ });
320
+ if (JSON.stringify(bp.br) !== JSON.stringify(cp.br)) changes.push({
321
+ path,
322
+ type: "paint",
323
+ property: "border-radius",
324
+ before: JSON.stringify(bp.br),
325
+ after: JSON.stringify(cp.br)
326
+ });
327
+ }
328
+ if (baseline.text !== current.text) changes.push({
329
+ path,
330
+ type: "text",
331
+ before: baseline.text,
332
+ after: current.text
333
+ });
334
+ const bch = baseline.ch ?? [];
335
+ const cch = current.ch ?? [];
336
+ const maxLen = Math.max(bch.length, cch.length);
337
+ for (let i = 0; i < maxLen; i++) {
338
+ const childPath = `${path} > ${(cch[i] ?? bch[i])?.tag ?? "?"}[${i}]`;
339
+ if (i >= bch.length) changes.push({
340
+ path: childPath,
341
+ type: "added"
342
+ });
343
+ else if (i >= cch.length) changes.push({
344
+ path: childPath,
345
+ type: "removed"
346
+ });
347
+ else changes.push(...diffPaintTrees(bch[i], cch[i], childPath));
348
+ }
349
+ return changes;
350
+ }
351
+ /** Check if crater server is running */
352
+ async function isCraterAvailable(url = resolveCraterBidiUrl()) {
353
+ try {
354
+ const httpUrl = url.replace("ws://", "http://");
355
+ const resp = await fetch(httpUrl, { signal: AbortSignal.timeout(2e3) });
356
+ return resp.ok || resp.status === 426;
357
+ } catch {
358
+ return false;
359
+ }
360
+ }
361
+ //#endregion
362
+ export { CRATER_BIDI_URL_ENV, CRATER_ROOT_ENV, CraterClient, DEFAULT_BIDI_URL, VLMKIT_CRATER_BIDI_URL_ENV, VLMKIT_CRATER_ROOT_ENV, diffPaintTrees, isCraterAvailable, resolveCraterBidiUrl };