@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 +21 -0
- package/README.md +51 -0
- package/package.json +36 -0
- package/src/capture-config.ts +219 -0
- package/src/capturer.ts +138 -0
- package/src/crater-client.ts +443 -0
- package/src/detection-types.ts +16 -0
- package/src/index.ts +86 -0
- package/src/playwright-analyzer.ts +180 -0
- package/src/playwright-launch-error.ts +41 -0
- package/src/prescanner.ts +69 -0
- package/src/viewport-discovery.ts +267 -0
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
import { readFile, readdir, stat } from "node:fs/promises";
|
|
2
|
+
import { join, relative, basename } from "node:path";
|
|
3
|
+
import type {
|
|
4
|
+
PlaywrightReport,
|
|
5
|
+
TestSuite,
|
|
6
|
+
TestSpec,
|
|
7
|
+
VrtSnapshot,
|
|
8
|
+
Attachment,
|
|
9
|
+
} from "@mizchi/vlmkit-core/types.ts";
|
|
10
|
+
|
|
11
|
+
export interface AnalyzedReport {
|
|
12
|
+
snapshots: VrtSnapshot[];
|
|
13
|
+
failedTests: FailedTest[];
|
|
14
|
+
stats: ReportStats;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export interface FailedTest {
|
|
18
|
+
testId: string;
|
|
19
|
+
title: string;
|
|
20
|
+
project: string;
|
|
21
|
+
errors: string[];
|
|
22
|
+
attachments: Attachment[];
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface ReportStats {
|
|
26
|
+
total: number;
|
|
27
|
+
passed: number;
|
|
28
|
+
failed: number;
|
|
29
|
+
skipped: number;
|
|
30
|
+
flaky: number;
|
|
31
|
+
duration: number;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Playwright JSON レポートを読み込み、構造化された VRT データに変換する
|
|
36
|
+
*/
|
|
37
|
+
export async function analyzeReport(
|
|
38
|
+
reportPath: string
|
|
39
|
+
): Promise<AnalyzedReport> {
|
|
40
|
+
const raw = await readFile(reportPath, "utf-8");
|
|
41
|
+
const report: PlaywrightReport = JSON.parse(raw);
|
|
42
|
+
|
|
43
|
+
const snapshots: VrtSnapshot[] = [];
|
|
44
|
+
const failedTests: FailedTest[] = [];
|
|
45
|
+
const stats: ReportStats = {
|
|
46
|
+
total: 0,
|
|
47
|
+
passed: 0,
|
|
48
|
+
failed: 0,
|
|
49
|
+
skipped: 0,
|
|
50
|
+
flaky: 0,
|
|
51
|
+
duration: 0,
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
function walkSuites(suites: TestSuite[], prefix: string = "") {
|
|
55
|
+
for (const suite of suites) {
|
|
56
|
+
const suitePath = prefix ? `${prefix} > ${suite.title}` : suite.title;
|
|
57
|
+
|
|
58
|
+
for (const spec of suite.specs) {
|
|
59
|
+
processSpec(spec, suitePath);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
if (suite.suites) {
|
|
63
|
+
walkSuites(suite.suites, suitePath);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function processSpec(spec: TestSpec, suitePath: string) {
|
|
69
|
+
for (const test of spec.tests) {
|
|
70
|
+
stats.total++;
|
|
71
|
+
stats.duration += test.duration;
|
|
72
|
+
|
|
73
|
+
const testId = `${suitePath} > ${spec.title}[${test.projectName}]`;
|
|
74
|
+
|
|
75
|
+
if (test.status === "skipped") {
|
|
76
|
+
stats.skipped++;
|
|
77
|
+
continue;
|
|
78
|
+
}
|
|
79
|
+
if (test.status === "flaky") stats.flaky++;
|
|
80
|
+
if (test.status === "expected") stats.passed++;
|
|
81
|
+
if (test.status === "unexpected") stats.failed++;
|
|
82
|
+
|
|
83
|
+
// 各 attempt からスクリーンショットを抽出
|
|
84
|
+
for (const attempt of test.results) {
|
|
85
|
+
const screenshots = attempt.attachments.filter(
|
|
86
|
+
(a) =>
|
|
87
|
+
a.contentType === "image/png" && a.path && !a.name.includes("trace")
|
|
88
|
+
);
|
|
89
|
+
|
|
90
|
+
for (const screenshot of screenshots) {
|
|
91
|
+
snapshots.push({
|
|
92
|
+
testId,
|
|
93
|
+
testTitle: spec.title,
|
|
94
|
+
projectName: test.projectName,
|
|
95
|
+
screenshotPath: screenshot.path!,
|
|
96
|
+
status: test.status === "expected" ? "unchanged" : "changed",
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
if (attempt.errors.length > 0) {
|
|
101
|
+
failedTests.push({
|
|
102
|
+
testId,
|
|
103
|
+
title: spec.title,
|
|
104
|
+
project: test.projectName,
|
|
105
|
+
errors: attempt.errors.map((e) => e.message),
|
|
106
|
+
attachments: attempt.attachments,
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
walkSuites(report.suites);
|
|
114
|
+
|
|
115
|
+
return { snapshots, failedTests, stats };
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* test-results ディレクトリからスクリーンショットファイルを収集し、
|
|
120
|
+
* ベースラインとの対応関係を構築する
|
|
121
|
+
*/
|
|
122
|
+
export async function collectScreenshots(
|
|
123
|
+
resultsDir: string,
|
|
124
|
+
baselineDir: string
|
|
125
|
+
): Promise<VrtSnapshot[]> {
|
|
126
|
+
const snapshots: VrtSnapshot[] = [];
|
|
127
|
+
|
|
128
|
+
async function walk(dir: string) {
|
|
129
|
+
let entries;
|
|
130
|
+
try {
|
|
131
|
+
entries = await readdir(dir, { withFileTypes: true });
|
|
132
|
+
} catch {
|
|
133
|
+
return;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
for (const entry of entries) {
|
|
137
|
+
const fullPath = join(dir, entry.name);
|
|
138
|
+
if (entry.isDirectory()) {
|
|
139
|
+
await walk(fullPath);
|
|
140
|
+
} else if (entry.name.endsWith(".png") && !entry.name.includes("diff")) {
|
|
141
|
+
const relPath = relative(resultsDir, fullPath);
|
|
142
|
+
const baselinePath = join(baselineDir, relPath);
|
|
143
|
+
let baselineExists = false;
|
|
144
|
+
try {
|
|
145
|
+
await stat(baselinePath);
|
|
146
|
+
baselineExists = true;
|
|
147
|
+
} catch {
|
|
148
|
+
// baseline doesn't exist
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
snapshots.push({
|
|
152
|
+
testId: relPath.replace(/\.png$/, ""),
|
|
153
|
+
testTitle: basename(relPath, ".png"),
|
|
154
|
+
projectName: relPath.split("/")[0] || "default",
|
|
155
|
+
screenshotPath: fullPath,
|
|
156
|
+
baselinePath: baselineExists ? baselinePath : undefined,
|
|
157
|
+
status: baselineExists ? "unchanged" : "new",
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
await walk(resultsDir);
|
|
164
|
+
return snapshots;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* レポートの統計サマリを人間可読な文字列にする
|
|
169
|
+
*/
|
|
170
|
+
export function formatStats(stats: ReportStats): string {
|
|
171
|
+
const lines = [
|
|
172
|
+
`Total: ${stats.total} tests`,
|
|
173
|
+
`Passed: ${stats.passed}`,
|
|
174
|
+
`Failed: ${stats.failed}`,
|
|
175
|
+
`Skipped: ${stats.skipped}`,
|
|
176
|
+
`Flaky: ${stats.flaky}`,
|
|
177
|
+
`Duration: ${(stats.duration / 1000).toFixed(1)}s`,
|
|
178
|
+
];
|
|
179
|
+
return lines.join("\n");
|
|
180
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
const FORMATTED_SANDBOX_MARKER = "Codex/macOS sandbox restriction";
|
|
2
|
+
const RAW_SANDBOX_SIGNAL_PATTERNS = [
|
|
3
|
+
"Operation not permitted",
|
|
4
|
+
"Permission denied",
|
|
5
|
+
"MachPortRendezvousServer",
|
|
6
|
+
"bootstrap_check_in",
|
|
7
|
+
"mach_port_rendezvous_mac.cc",
|
|
8
|
+
] as const;
|
|
9
|
+
|
|
10
|
+
function normalizeErrorMessage(error: unknown): string {
|
|
11
|
+
if (error instanceof Error) return error.message;
|
|
12
|
+
return String(error).replace(/^Error:\s*/, "");
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function isPlaywrightSandboxRestrictionError(error: unknown): boolean {
|
|
16
|
+
const message = normalizeErrorMessage(error);
|
|
17
|
+
return message.includes(FORMATTED_SANDBOX_MARKER)
|
|
18
|
+
|| (
|
|
19
|
+
message.includes("browserType.launch:")
|
|
20
|
+
&& RAW_SANDBOX_SIGNAL_PATTERNS.some((pattern) => message.includes(pattern))
|
|
21
|
+
);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function formatPlaywrightLaunchError(
|
|
25
|
+
error: unknown,
|
|
26
|
+
options: { commandHint?: string } = {},
|
|
27
|
+
): string {
|
|
28
|
+
const message = normalizeErrorMessage(error);
|
|
29
|
+
if (!isPlaywrightSandboxRestrictionError(error)) return message;
|
|
30
|
+
if (message.includes(FORMATTED_SANDBOX_MARKER)) return message;
|
|
31
|
+
|
|
32
|
+
const hintBody = !options.commandHint
|
|
33
|
+
? "Re-run outside the Codex sandbox or in CI"
|
|
34
|
+
: /re-?run outside the codex sandbox/i.test(options.commandHint)
|
|
35
|
+
? options.commandHint
|
|
36
|
+
: `Re-run outside the Codex sandbox or ${options.commandHint}`;
|
|
37
|
+
const hint = ` ${hintBody}.`;
|
|
38
|
+
|
|
39
|
+
const originalLine = message.split("\n").find((line) => line.trim().length > 0) ?? message;
|
|
40
|
+
return `Playwright browser launch is blocked by a ${FORMATTED_SANDBOX_MARKER}. Chromium itself is likely fine.${hint}\nOriginal error: ${originalLine}`;
|
|
41
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import type { ViewportDetectionResult } from "./detection-types.ts";
|
|
2
|
+
|
|
3
|
+
export type PrescannerResolvedBy = "crater" | "chromium" | "none";
|
|
4
|
+
|
|
5
|
+
export interface PrescannerTrialResolution {
|
|
6
|
+
craterDetected: boolean;
|
|
7
|
+
fallbackUsed: boolean;
|
|
8
|
+
finalDetected: boolean;
|
|
9
|
+
resolvedBy: PrescannerResolvedBy;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export interface PrescannerTrialSummary {
|
|
13
|
+
total: number;
|
|
14
|
+
detected: number;
|
|
15
|
+
craterResolved: number;
|
|
16
|
+
chromiumFallbacks: number;
|
|
17
|
+
chromiumDetected: number;
|
|
18
|
+
passedAfterFallback: number;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function hasCraterPrescanSignal(viewports: ViewportDetectionResult[]): boolean {
|
|
22
|
+
return viewports.some((viewport) => viewport.visualDiffDetected || viewport.paintTreeDiffCount > 0);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function hasAnyDetectionSignal(viewports: ViewportDetectionResult[]): boolean {
|
|
26
|
+
return viewports.some((viewport) =>
|
|
27
|
+
viewport.visualDiffDetected ||
|
|
28
|
+
viewport.a11yDiffDetected ||
|
|
29
|
+
viewport.computedStyleDiffCount > 0 ||
|
|
30
|
+
viewport.hoverDiffDetected ||
|
|
31
|
+
viewport.paintTreeDiffCount > 0,
|
|
32
|
+
);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function resolvePrescannerTrial(
|
|
36
|
+
craterViewports: ViewportDetectionResult[],
|
|
37
|
+
chromiumViewports: ViewportDetectionResult[] = [],
|
|
38
|
+
): PrescannerTrialResolution {
|
|
39
|
+
const craterDetected = hasCraterPrescanSignal(craterViewports);
|
|
40
|
+
if (craterDetected) {
|
|
41
|
+
return {
|
|
42
|
+
craterDetected: true,
|
|
43
|
+
fallbackUsed: false,
|
|
44
|
+
finalDetected: true,
|
|
45
|
+
resolvedBy: "crater",
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const chromiumDetected = hasAnyDetectionSignal(chromiumViewports);
|
|
50
|
+
return {
|
|
51
|
+
craterDetected: false,
|
|
52
|
+
fallbackUsed: true,
|
|
53
|
+
finalDetected: chromiumDetected,
|
|
54
|
+
resolvedBy: chromiumDetected ? "chromium" : "none",
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export function summarizePrescannerTrials(
|
|
59
|
+
resolutions: PrescannerTrialResolution[],
|
|
60
|
+
): PrescannerTrialSummary {
|
|
61
|
+
return {
|
|
62
|
+
total: resolutions.length,
|
|
63
|
+
detected: resolutions.filter((resolution) => resolution.finalDetected).length,
|
|
64
|
+
craterResolved: resolutions.filter((resolution) => resolution.resolvedBy === "crater").length,
|
|
65
|
+
chromiumFallbacks: resolutions.filter((resolution) => resolution.fallbackUsed).length,
|
|
66
|
+
chromiumDetected: resolutions.filter((resolution) => resolution.resolvedBy === "chromium").length,
|
|
67
|
+
passedAfterFallback: resolutions.filter((resolution) => resolution.resolvedBy === "none").length,
|
|
68
|
+
};
|
|
69
|
+
}
|
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Viewport Discovery -- discover breakpoints from CSS and generate boundary-check viewports
|
|
3
|
+
*
|
|
4
|
+
* Extracts breakpoints from @media queries and generates viewport lists
|
|
5
|
+
* at boundary +/-1px + random samples within ranges (quickcheck-style).
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
// ---- Types ----
|
|
9
|
+
|
|
10
|
+
export interface Breakpoint {
|
|
11
|
+
value: number; // px
|
|
12
|
+
type: "min-width" | "max-width";
|
|
13
|
+
raw: string; // e.g. "(min-width: 768px)"
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export interface ResponsiveBreakpoint {
|
|
17
|
+
axis: "width";
|
|
18
|
+
op: "ge" | "gt" | "le" | "lt";
|
|
19
|
+
valuePx: number;
|
|
20
|
+
raw: string;
|
|
21
|
+
normalized: string;
|
|
22
|
+
guards: string[];
|
|
23
|
+
ruleCount: number;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export interface ViewportSpec {
|
|
27
|
+
width: number;
|
|
28
|
+
height: number;
|
|
29
|
+
label: string;
|
|
30
|
+
reason: string; // why this viewport was chosen
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface DiscoveryResult {
|
|
34
|
+
breakpoints: Breakpoint[];
|
|
35
|
+
responsiveBreakpoints: ResponsiveBreakpoint[];
|
|
36
|
+
viewports: ViewportSpec[];
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
type ViewportBreakpoint = Breakpoint | ResponsiveBreakpoint;
|
|
40
|
+
|
|
41
|
+
// ---- Breakpoint extraction ----
|
|
42
|
+
|
|
43
|
+
const MEDIA_PATTERN = /@media\s+([^{]+)\{/g;
|
|
44
|
+
const WIDTH_PATTERN = /\(\s*(min|max)-width\s*:\s*([\d.]+)(px|rem|em)\s*\)/g;
|
|
45
|
+
|
|
46
|
+
/** Extract all breakpoints from CSS text */
|
|
47
|
+
export function extractBreakpoints(css: string): Breakpoint[] {
|
|
48
|
+
const breakpoints = new Map<string, Breakpoint>(); // dedupe by key
|
|
49
|
+
|
|
50
|
+
for (const mediaMatch of css.matchAll(MEDIA_PATTERN)) {
|
|
51
|
+
const condition = mediaMatch[1].trim();
|
|
52
|
+
for (const widthMatch of condition.matchAll(WIDTH_PATTERN)) {
|
|
53
|
+
const type = `${widthMatch[1]}-width` as "min-width" | "max-width";
|
|
54
|
+
let value = parseFloat(widthMatch[2]);
|
|
55
|
+
const unit = widthMatch[3];
|
|
56
|
+
// rem/em → px (assume 16px base)
|
|
57
|
+
if (unit === "rem" || unit === "em") value *= 16;
|
|
58
|
+
value = Math.round(value);
|
|
59
|
+
|
|
60
|
+
const key = `${type}:${value}`;
|
|
61
|
+
if (!breakpoints.has(key)) {
|
|
62
|
+
breakpoints.set(key, { value, type, raw: `(${type}: ${value}px)` });
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
return [...breakpoints.values()].sort((a, b) => a.value - b.value);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Extract breakpoints from HTML <style> */
|
|
71
|
+
export function extractBreakpointsFromHtml(html: string): Breakpoint[] {
|
|
72
|
+
const styleMatch = html.match(/<style[^>]*>([\s\S]*?)<\/style>/g);
|
|
73
|
+
if (!styleMatch) return [];
|
|
74
|
+
const css = styleMatch.map((s) => s.replace(/<\/?style[^>]*>/g, "")).join("\n");
|
|
75
|
+
return extractBreakpoints(css);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function isResponsiveBreakpoint(
|
|
79
|
+
breakpoint: ViewportBreakpoint,
|
|
80
|
+
): breakpoint is ResponsiveBreakpoint {
|
|
81
|
+
return "axis" in breakpoint;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function normalizeResponsiveBreakpoint(
|
|
85
|
+
breakpoint: ViewportBreakpoint,
|
|
86
|
+
): ResponsiveBreakpoint {
|
|
87
|
+
if (isResponsiveBreakpoint(breakpoint)) {
|
|
88
|
+
const guards = [...new Set(breakpoint.guards)].sort((a, b) => a.localeCompare(b));
|
|
89
|
+
return {
|
|
90
|
+
axis: breakpoint.axis,
|
|
91
|
+
op: breakpoint.op,
|
|
92
|
+
valuePx: breakpoint.valuePx,
|
|
93
|
+
raw: breakpoint.raw,
|
|
94
|
+
normalized: breakpoint.normalized,
|
|
95
|
+
guards,
|
|
96
|
+
ruleCount: breakpoint.ruleCount ?? 1,
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const op = breakpoint.type === "min-width" ? "ge" : "le";
|
|
101
|
+
const operator = op === "ge" ? ">=" : "<=";
|
|
102
|
+
return {
|
|
103
|
+
axis: "width",
|
|
104
|
+
op,
|
|
105
|
+
valuePx: breakpoint.value,
|
|
106
|
+
raw: breakpoint.raw,
|
|
107
|
+
normalized: `(width ${operator} ${breakpoint.value}px)`,
|
|
108
|
+
guards: [],
|
|
109
|
+
ruleCount: 1,
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function compareResponsiveBreakpoint(
|
|
114
|
+
left: ResponsiveBreakpoint,
|
|
115
|
+
right: ResponsiveBreakpoint,
|
|
116
|
+
): number {
|
|
117
|
+
if (left.valuePx !== right.valuePx) return left.valuePx - right.valuePx;
|
|
118
|
+
const order = { lt: 0, le: 1, ge: 2, gt: 3 } as const;
|
|
119
|
+
if (order[left.op] !== order[right.op]) return order[left.op] - order[right.op];
|
|
120
|
+
return left.guards.join("|").localeCompare(right.guards.join("|"));
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export function toResponsiveBreakpoints(
|
|
124
|
+
breakpoints: ViewportBreakpoint[],
|
|
125
|
+
): ResponsiveBreakpoint[] {
|
|
126
|
+
const merged = new Map<string, ResponsiveBreakpoint>();
|
|
127
|
+
|
|
128
|
+
for (const breakpoint of breakpoints) {
|
|
129
|
+
const normalized = normalizeResponsiveBreakpoint(breakpoint);
|
|
130
|
+
const key = [
|
|
131
|
+
normalized.axis,
|
|
132
|
+
normalized.op,
|
|
133
|
+
normalized.valuePx,
|
|
134
|
+
normalized.guards.join("&"),
|
|
135
|
+
].join(":");
|
|
136
|
+
const existing = merged.get(key);
|
|
137
|
+
if (existing) {
|
|
138
|
+
existing.ruleCount += normalized.ruleCount;
|
|
139
|
+
continue;
|
|
140
|
+
}
|
|
141
|
+
merged.set(key, { ...normalized });
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
return [...merged.values()].sort(compareResponsiveBreakpoint);
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
export function mergeResponsiveBreakpoints(
|
|
148
|
+
...collections: ViewportBreakpoint[][]
|
|
149
|
+
): ResponsiveBreakpoint[] {
|
|
150
|
+
return toResponsiveBreakpoints(collections.flat());
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
export function extractResponsiveBreakpointsFromHtml(
|
|
154
|
+
html: string,
|
|
155
|
+
): ResponsiveBreakpoint[] {
|
|
156
|
+
return toResponsiveBreakpoints(extractBreakpointsFromHtml(html));
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// ---- Viewport generation ----
|
|
160
|
+
|
|
161
|
+
export interface ViewportOptions {
|
|
162
|
+
height?: number; // default: 900
|
|
163
|
+
maxViewports?: number; // upper limit (cost control)
|
|
164
|
+
randomSamples?: number; // random samples within range (default: 0)
|
|
165
|
+
seed?: number; // random seed
|
|
166
|
+
includeStandard?: boolean; // include standard viewports (375, 1280, 1440) (default: true)
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
const STANDARD_VIEWPORTS: Array<{ width: number; label: string }> = [
|
|
170
|
+
{ width: 375, label: "mobile" },
|
|
171
|
+
{ width: 1280, label: "desktop" },
|
|
172
|
+
{ width: 1440, label: "wide" },
|
|
173
|
+
];
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* Generate viewport list from breakpoints (quickcheck-style).
|
|
177
|
+
*
|
|
178
|
+
* For each breakpoint:
|
|
179
|
+
* - boundary +1px: just after breakpoint activates
|
|
180
|
+
* - boundary -1px: just before breakpoint activates
|
|
181
|
+
* - (optional) random samples within range
|
|
182
|
+
*/
|
|
183
|
+
export function generateViewports(
|
|
184
|
+
breakpoints: ViewportBreakpoint[],
|
|
185
|
+
options: ViewportOptions = {},
|
|
186
|
+
): ViewportSpec[] {
|
|
187
|
+
const responsiveBreakpoints = toResponsiveBreakpoints(breakpoints);
|
|
188
|
+
const height = options.height ?? 900;
|
|
189
|
+
const maxViewports = options.maxViewports ?? 20;
|
|
190
|
+
const randomSamples = options.randomSamples ?? 0;
|
|
191
|
+
const includeStandard = options.includeStandard ?? true;
|
|
192
|
+
const seed = options.seed ?? 42;
|
|
193
|
+
|
|
194
|
+
const viewportMap = new Map<number, ViewportSpec>();
|
|
195
|
+
|
|
196
|
+
function add(width: number, label: string, reason: string) {
|
|
197
|
+
if (width < 320 || width > 2560) return;
|
|
198
|
+
if (!viewportMap.has(width)) {
|
|
199
|
+
viewportMap.set(width, { width, height, label, reason });
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
// Standard viewports
|
|
204
|
+
if (includeStandard) {
|
|
205
|
+
for (const sv of STANDARD_VIEWPORTS) {
|
|
206
|
+
add(sv.width, sv.label, "standard");
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
// Boundary viewports for each breakpoint
|
|
211
|
+
for (const bp of responsiveBreakpoints) {
|
|
212
|
+
if (bp.op === "ge") {
|
|
213
|
+
add(bp.valuePx - 1, `below-${bp.valuePx}`, `${bp.raw} boundary-below`);
|
|
214
|
+
add(bp.valuePx, `at-${bp.valuePx}`, `${bp.raw} boundary-at`);
|
|
215
|
+
} else if (bp.op === "gt") {
|
|
216
|
+
add(bp.valuePx, `at-${bp.valuePx}`, `${bp.raw} boundary-at`);
|
|
217
|
+
add(bp.valuePx + 1, `above-${bp.valuePx}`, `${bp.raw} boundary-above`);
|
|
218
|
+
} else if (bp.op === "le") {
|
|
219
|
+
add(bp.valuePx, `at-${bp.valuePx}`, `${bp.raw} boundary-at`);
|
|
220
|
+
add(bp.valuePx + 1, `above-${bp.valuePx}`, `${bp.raw} boundary-above`);
|
|
221
|
+
} else {
|
|
222
|
+
add(bp.valuePx - 1, `below-${bp.valuePx}`, `${bp.raw} boundary-below`);
|
|
223
|
+
add(bp.valuePx, `at-${bp.valuePx}`, `${bp.raw} boundary-at`);
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
// Random samples within breakpoint ranges
|
|
228
|
+
if (randomSamples > 0 && responsiveBreakpoints.length > 0) {
|
|
229
|
+
const allWidths = [...new Set(responsiveBreakpoints.map((b) => b.valuePx))].sort((a, b) => a - b);
|
|
230
|
+
const ranges: Array<[number, number]> = [];
|
|
231
|
+
|
|
232
|
+
// Build ranges: [320, bp1], [bp1, bp2], ..., [bpN, 1920]
|
|
233
|
+
ranges.push([320, allWidths[0] - 1]);
|
|
234
|
+
for (let i = 0; i < allWidths.length - 1; i++) {
|
|
235
|
+
ranges.push([allWidths[i], allWidths[i + 1] - 1]);
|
|
236
|
+
}
|
|
237
|
+
ranges.push([allWidths[allWidths.length - 1], 1920]);
|
|
238
|
+
|
|
239
|
+
let s = seed;
|
|
240
|
+
const rand = () => { s = (s * 1664525 + 1013904223) & 0x7fffffff; return s / 0x7fffffff; };
|
|
241
|
+
|
|
242
|
+
for (const [lo, hi] of ranges) {
|
|
243
|
+
if (hi - lo < 2) continue;
|
|
244
|
+
for (let j = 0; j < randomSamples; j++) {
|
|
245
|
+
const w = Math.round(lo + rand() * (hi - lo));
|
|
246
|
+
add(w, `sample-${w}`, `random sample in [${lo}, ${hi}]`);
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
// Sort by width and limit
|
|
252
|
+
const sorted = [...viewportMap.values()].sort((a, b) => a.width - b.width);
|
|
253
|
+
return sorted.slice(0, maxViewports);
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/**
|
|
257
|
+
* Discover breakpoints from HTML and generate boundary-check viewports.
|
|
258
|
+
*/
|
|
259
|
+
export function discoverViewports(
|
|
260
|
+
html: string,
|
|
261
|
+
options: ViewportOptions = {},
|
|
262
|
+
): DiscoveryResult {
|
|
263
|
+
const breakpoints = extractBreakpointsFromHtml(html);
|
|
264
|
+
const responsiveBreakpoints = toResponsiveBreakpoints(breakpoints);
|
|
265
|
+
const viewports = generateViewports(responsiveBreakpoints, options);
|
|
266
|
+
return { breakpoints, responsiveBreakpoints, viewports };
|
|
267
|
+
}
|