uiport 0.0.0-bootstrap.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/CHANGELOG.md +23 -0
- package/CODE_OF_CONDUCT.md +83 -0
- package/CONTRIBUTING.md +30 -0
- package/GOVERNANCE.md +9 -0
- package/LICENSE +21 -0
- package/NOTICE +12 -0
- package/README.md +101 -0
- package/README.pt-BR.md +97 -0
- package/SECURITY.md +12 -0
- package/bin/cli.mjs +114 -0
- package/docs/architecture.md +32 -0
- package/docs/demo.png +0 -0
- package/docs/migration.md +29 -0
- package/docs/support.md +49 -0
- package/examples/css-motion/index.html +3 -0
- package/examples/responsive-hero/index.html +39 -0
- package/examples/responsive-hero/section.svg +1 -0
- package/package.json +79 -0
- package/scripts/browser-host.mjs +41 -0
- package/scripts/browser-process.mjs +115 -0
- package/scripts/browser-resources.mjs +74 -0
- package/scripts/capture.mjs +307 -0
- package/scripts/css-context.mjs +174 -0
- package/scripts/dom.mjs +412 -0
- package/scripts/lib.mjs +365 -0
- package/scripts/options.mjs +178 -0
- package/scripts/resources.mjs +265 -0
- package/scripts/serve.mjs +26 -0
- package/scripts/validate.mjs +212 -0
- package/skills/uiport/SKILL.md +20 -0
- package/uiport.md +155 -0
package/scripts/lib.mjs
ADDED
|
@@ -0,0 +1,365 @@
|
|
|
1
|
+
import crypto from "node:crypto";
|
|
2
|
+
import fs from "node:fs/promises";
|
|
3
|
+
import fsSync from "node:fs";
|
|
4
|
+
import http from "node:http";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import { performance } from "node:perf_hooks";
|
|
7
|
+
import { startBrowser } from "./browser-process.mjs";
|
|
8
|
+
|
|
9
|
+
export const sha256 = (buffer) =>
|
|
10
|
+
crypto.createHash("sha256").update(buffer).digest("hex");
|
|
11
|
+
export const escapeHtml = (value) =>
|
|
12
|
+
String(value)
|
|
13
|
+
.replaceAll("&", "&")
|
|
14
|
+
.replaceAll("<", "<")
|
|
15
|
+
.replaceAll(">", ">")
|
|
16
|
+
.replaceAll('"', """);
|
|
17
|
+
export const serializeAttributes = (attributes) =>
|
|
18
|
+
attributes
|
|
19
|
+
.map(
|
|
20
|
+
({ name, value }) =>
|
|
21
|
+
` ${name}="${escapeHtml(value).replaceAll("'", "'")}"`,
|
|
22
|
+
)
|
|
23
|
+
.join("");
|
|
24
|
+
export const jsonForInlineScript = (value) =>
|
|
25
|
+
JSON.stringify(value)
|
|
26
|
+
.replaceAll("<", "\\u003c")
|
|
27
|
+
.replaceAll(">", "\\u003e")
|
|
28
|
+
.replaceAll("&", "\\u0026");
|
|
29
|
+
export function normalizeUrl(value) {
|
|
30
|
+
const url = new URL(value);
|
|
31
|
+
url.hash = "";
|
|
32
|
+
return url.href;
|
|
33
|
+
}
|
|
34
|
+
export function redactedUrl(value) {
|
|
35
|
+
try {
|
|
36
|
+
const u = new URL(value);
|
|
37
|
+
u.username = "";
|
|
38
|
+
u.password = "";
|
|
39
|
+
u.search = "";
|
|
40
|
+
u.hash = "";
|
|
41
|
+
return u.href;
|
|
42
|
+
} catch {
|
|
43
|
+
return "(invalid URL)";
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
export function safeErrorMessage(error) {
|
|
47
|
+
// Keep the useful first line, excluding Playwright's verbose call log and
|
|
48
|
+
// source snippets. Redact every URL, not just the originally requested one.
|
|
49
|
+
return String(error?.message || "Operation failed")
|
|
50
|
+
.split(/[\r\n]/, 1)[0]
|
|
51
|
+
.replace(/https?:\/\/[^\s<>"'`]+/gi, (url) => redactedUrl(url));
|
|
52
|
+
}
|
|
53
|
+
export function limitation(list, code, message) {
|
|
54
|
+
if (!list.some((item) => item.code === code && item.message === message))
|
|
55
|
+
list.push({ code, message });
|
|
56
|
+
}
|
|
57
|
+
export const log = (message) => process.stderr.write(`${message}\n`);
|
|
58
|
+
|
|
59
|
+
export function extensionFor(url, contentType = "") {
|
|
60
|
+
const mime = contentType.split(";")[0].toLowerCase();
|
|
61
|
+
const extension = new Map([
|
|
62
|
+
["text/css", ".css"],
|
|
63
|
+
["text/javascript", ".js"],
|
|
64
|
+
["application/javascript", ".js"],
|
|
65
|
+
["application/ecmascript", ".js"],
|
|
66
|
+
["text/ecmascript", ".js"],
|
|
67
|
+
["image/svg+xml", ".svg"],
|
|
68
|
+
["image/png", ".png"],
|
|
69
|
+
["image/jpeg", ".jpg"],
|
|
70
|
+
["image/webp", ".webp"],
|
|
71
|
+
["image/avif", ".avif"],
|
|
72
|
+
["image/gif", ".gif"],
|
|
73
|
+
["font/woff2", ".woff2"],
|
|
74
|
+
["font/woff", ".woff"],
|
|
75
|
+
["font/ttf", ".ttf"],
|
|
76
|
+
["font/otf", ".otf"],
|
|
77
|
+
["video/mp4", ".mp4"],
|
|
78
|
+
["video/webm", ".webm"],
|
|
79
|
+
]).get(mime);
|
|
80
|
+
if (extension) return extension;
|
|
81
|
+
const ext = path.extname(new URL(url).pathname).toLowerCase();
|
|
82
|
+
return /^\.[a-z0-9]{1,8}$/.test(ext) ? ext : ".bin";
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export async function inspectOutput(directory) {
|
|
86
|
+
const destination = path.resolve(directory);
|
|
87
|
+
if (destination === path.parse(destination).root)
|
|
88
|
+
throw new Error("Refusing a filesystem root as output");
|
|
89
|
+
let existing = false;
|
|
90
|
+
try {
|
|
91
|
+
const stat = await fs.lstat(destination);
|
|
92
|
+
if (
|
|
93
|
+
!stat.isDirectory() ||
|
|
94
|
+
stat.isSymbolicLink() ||
|
|
95
|
+
(await fs.readdir(destination)).length
|
|
96
|
+
)
|
|
97
|
+
throw new Error(
|
|
98
|
+
"Output must be a new or empty directory (not a symlink)",
|
|
99
|
+
);
|
|
100
|
+
existing = true;
|
|
101
|
+
} catch (error) {
|
|
102
|
+
if (error.code !== "ENOENT") throw error;
|
|
103
|
+
}
|
|
104
|
+
return { destination, existing };
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** Stage alongside the destination; never delete or overwrite a user's existing output. */
|
|
108
|
+
export async function stageOutput(directory) {
|
|
109
|
+
const { destination, existing } = await inspectOutput(directory);
|
|
110
|
+
await fs.mkdir(path.dirname(destination), { recursive: true });
|
|
111
|
+
const temporary = await fs.mkdtemp(
|
|
112
|
+
path.join(path.dirname(destination), ".uiport-"),
|
|
113
|
+
);
|
|
114
|
+
let committed = false;
|
|
115
|
+
return {
|
|
116
|
+
directory: temporary,
|
|
117
|
+
async commit() {
|
|
118
|
+
// Recheck immediately before moving. Exclusive mkdir prevents replacing a concurrent output.
|
|
119
|
+
if (existing) await fs.rmdir(destination); // only succeeds when still empty
|
|
120
|
+
await fs.mkdir(destination);
|
|
121
|
+
const moved = [];
|
|
122
|
+
try {
|
|
123
|
+
for (const name of await fs.readdir(temporary)) {
|
|
124
|
+
await fs.rename(
|
|
125
|
+
path.join(temporary, name),
|
|
126
|
+
path.join(destination, name),
|
|
127
|
+
);
|
|
128
|
+
moved.push(name);
|
|
129
|
+
}
|
|
130
|
+
committed = true;
|
|
131
|
+
} catch (error) {
|
|
132
|
+
for (const name of moved)
|
|
133
|
+
await fs
|
|
134
|
+
.rename(path.join(destination, name), path.join(temporary, name))
|
|
135
|
+
.catch(() => {});
|
|
136
|
+
await fs.rmdir(destination).catch(() => {});
|
|
137
|
+
throw error;
|
|
138
|
+
}
|
|
139
|
+
},
|
|
140
|
+
async cleanup() {
|
|
141
|
+
await fs.rm(temporary, { recursive: true, force: true });
|
|
142
|
+
if (existing && !committed)
|
|
143
|
+
await fs.mkdir(destination, { recursive: true });
|
|
144
|
+
},
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
export async function waitForPageStable(page, settleMs) {
|
|
149
|
+
await page.waitForLoadState("domcontentloaded");
|
|
150
|
+
await page.waitForLoadState("networkidle", { timeout: 2000 }).catch(() => {});
|
|
151
|
+
await page.evaluate(async () => {
|
|
152
|
+
await Promise.race([
|
|
153
|
+
Promise.all([
|
|
154
|
+
document.fonts?.ready,
|
|
155
|
+
...[...document.images].map((img) => img.decode?.().catch(() => {})),
|
|
156
|
+
]),
|
|
157
|
+
new Promise((resolve) => setTimeout(resolve, 2000)),
|
|
158
|
+
]);
|
|
159
|
+
});
|
|
160
|
+
await page.waitForTimeout(settleMs);
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
export async function scrollForLazyContent(page, maxSteps = 80) {
|
|
164
|
+
return page.evaluate(async (maxSteps) => {
|
|
165
|
+
const root = document.scrollingElement || document.documentElement;
|
|
166
|
+
const step = Math.max(240, Math.floor(innerHeight * 0.7));
|
|
167
|
+
let position = 0,
|
|
168
|
+
count = 0;
|
|
169
|
+
while (position < root.scrollHeight && count < maxSteps) {
|
|
170
|
+
root.scrollTo(0, position);
|
|
171
|
+
await new Promise((resolve) => setTimeout(resolve, 30));
|
|
172
|
+
position += step;
|
|
173
|
+
count++;
|
|
174
|
+
}
|
|
175
|
+
const truncated = position < root.scrollHeight;
|
|
176
|
+
root.scrollTo(0, 0);
|
|
177
|
+
return truncated;
|
|
178
|
+
}, maxSteps);
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
export function mimeForFile(filePath) {
|
|
182
|
+
return (
|
|
183
|
+
new Map([
|
|
184
|
+
[".html", "text/html; charset=utf-8"],
|
|
185
|
+
[".css", "text/css; charset=utf-8"],
|
|
186
|
+
[".js", "text/javascript"],
|
|
187
|
+
[".mjs", "text/javascript"],
|
|
188
|
+
[".svg", "image/svg+xml"],
|
|
189
|
+
[".png", "image/png"],
|
|
190
|
+
[".jpg", "image/jpeg"],
|
|
191
|
+
[".jpeg", "image/jpeg"],
|
|
192
|
+
[".webp", "image/webp"],
|
|
193
|
+
[".avif", "image/avif"],
|
|
194
|
+
[".gif", "image/gif"],
|
|
195
|
+
[".woff2", "font/woff2"],
|
|
196
|
+
[".woff", "font/woff"],
|
|
197
|
+
[".ttf", "font/ttf"],
|
|
198
|
+
[".mp4", "video/mp4"],
|
|
199
|
+
[".webm", "video/webm"],
|
|
200
|
+
[".json", "application/json"],
|
|
201
|
+
[".wasm", "application/wasm"],
|
|
202
|
+
]).get(path.extname(filePath).toLowerCase()) || "application/octet-stream"
|
|
203
|
+
);
|
|
204
|
+
}
|
|
205
|
+
const within = (root, file) => {
|
|
206
|
+
const relative = path.relative(root, file);
|
|
207
|
+
return (
|
|
208
|
+
relative !== ".." &&
|
|
209
|
+
!relative.startsWith(`..${path.sep}`) &&
|
|
210
|
+
!path.isAbsolute(relative)
|
|
211
|
+
);
|
|
212
|
+
};
|
|
213
|
+
export async function startStaticServer(rootDirectory, requestedPort = 0) {
|
|
214
|
+
const root = await fs.realpath(rootDirectory);
|
|
215
|
+
if (!(await fs.stat(root)).isDirectory())
|
|
216
|
+
throw new Error("Server root must be a directory");
|
|
217
|
+
const server = http.createServer(async (request, response) => {
|
|
218
|
+
try {
|
|
219
|
+
if (!["GET", "HEAD"].includes(request.method)) {
|
|
220
|
+
response.writeHead(405).end();
|
|
221
|
+
return;
|
|
222
|
+
}
|
|
223
|
+
const pathname = decodeURIComponent(
|
|
224
|
+
new URL(request.url || "/", "http://localhost").pathname,
|
|
225
|
+
);
|
|
226
|
+
if (pathname === "/favicon.ico") {
|
|
227
|
+
response.writeHead(204).end();
|
|
228
|
+
return;
|
|
229
|
+
}
|
|
230
|
+
let file = path.resolve(root, `.${pathname}`);
|
|
231
|
+
if (!within(root, file)) {
|
|
232
|
+
response.writeHead(403).end("Forbidden");
|
|
233
|
+
return;
|
|
234
|
+
}
|
|
235
|
+
file = await fs.realpath(file);
|
|
236
|
+
if ((await fs.stat(file)).isDirectory())
|
|
237
|
+
file = await fs.realpath(path.join(file, "index.html"));
|
|
238
|
+
if (!within(root, file)) {
|
|
239
|
+
response.writeHead(403).end("Forbidden");
|
|
240
|
+
return;
|
|
241
|
+
}
|
|
242
|
+
if (!(await fs.stat(file)).isFile()) {
|
|
243
|
+
response.writeHead(404).end();
|
|
244
|
+
return;
|
|
245
|
+
}
|
|
246
|
+
response.writeHead(200, {
|
|
247
|
+
"Content-Type": mimeForFile(file),
|
|
248
|
+
"Cache-Control": "no-store",
|
|
249
|
+
"X-Content-Type-Options": "nosniff",
|
|
250
|
+
});
|
|
251
|
+
if (request.method === "HEAD") response.end();
|
|
252
|
+
else {
|
|
253
|
+
const stream = fsSync.createReadStream(file);
|
|
254
|
+
stream.on("error", () => response.destroy());
|
|
255
|
+
stream.pipe(response);
|
|
256
|
+
}
|
|
257
|
+
} catch {
|
|
258
|
+
response.writeHead(404).end("Not found");
|
|
259
|
+
}
|
|
260
|
+
});
|
|
261
|
+
await new Promise((resolve, reject) => {
|
|
262
|
+
server.once("error", reject);
|
|
263
|
+
server.listen(requestedPort, "127.0.0.1", resolve);
|
|
264
|
+
});
|
|
265
|
+
const port = server.address().port;
|
|
266
|
+
return {
|
|
267
|
+
port,
|
|
268
|
+
url: `http://127.0.0.1:${port}`,
|
|
269
|
+
close: () =>
|
|
270
|
+
new Promise((resolve) => {
|
|
271
|
+
server.close(resolve);
|
|
272
|
+
server.closeAllConnections();
|
|
273
|
+
}),
|
|
274
|
+
};
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
export async function launchChromium(chromium, life) {
|
|
278
|
+
const override = process.env.UIPORT_BROWSER_PATH;
|
|
279
|
+
const launch = (options) =>
|
|
280
|
+
startBrowser(
|
|
281
|
+
chromium,
|
|
282
|
+
{
|
|
283
|
+
headless: true,
|
|
284
|
+
...options,
|
|
285
|
+
timeout: life?.remaining() ?? 30000,
|
|
286
|
+
},
|
|
287
|
+
life,
|
|
288
|
+
);
|
|
289
|
+
if (override) {
|
|
290
|
+
if (!fsSync.existsSync(override))
|
|
291
|
+
throw new Error("UIPORT_BROWSER_PATH does not exist");
|
|
292
|
+
return {
|
|
293
|
+
...(await launch({ executablePath: override }).catch((error) => {
|
|
294
|
+
life?.check();
|
|
295
|
+
throw new Error(
|
|
296
|
+
"Could not start UIPORT_BROWSER_PATH; check the executable or run: uiport browser install",
|
|
297
|
+
{ cause: error },
|
|
298
|
+
);
|
|
299
|
+
})),
|
|
300
|
+
selected: "explicit path",
|
|
301
|
+
};
|
|
302
|
+
}
|
|
303
|
+
for (const channel of [undefined, "chrome", "msedge"]) {
|
|
304
|
+
life?.check();
|
|
305
|
+
try {
|
|
306
|
+
return {
|
|
307
|
+
...(await launch(channel ? { channel } : {})),
|
|
308
|
+
selected: channel || "Playwright Chromium",
|
|
309
|
+
};
|
|
310
|
+
} catch {
|
|
311
|
+
life?.check();
|
|
312
|
+
/* try next installed browser */
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
throw new Error(
|
|
316
|
+
"No supported browser found. Run: uiport browser install (or set UIPORT_BROWSER_PATH).",
|
|
317
|
+
);
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
/** Tracks resources so timeouts and SIGINT/SIGTERM also close failed runs. */
|
|
321
|
+
export function lifecycle(timeoutMs) {
|
|
322
|
+
const deadline = performance.now() + timeoutMs;
|
|
323
|
+
const controller = new AbortController();
|
|
324
|
+
const cleanups = [];
|
|
325
|
+
let reason;
|
|
326
|
+
let cleanupPromise;
|
|
327
|
+
const cleanup = () =>
|
|
328
|
+
(cleanupPromise ||= (async () => {
|
|
329
|
+
for (const fn of [...cleanups].reverse()) await fn().catch(() => {});
|
|
330
|
+
})());
|
|
331
|
+
const cancel = (message) => {
|
|
332
|
+
reason ||= new Error(message);
|
|
333
|
+
controller.abort(reason);
|
|
334
|
+
void cleanup();
|
|
335
|
+
};
|
|
336
|
+
const interrupt = () => cancel("Operation cancelled");
|
|
337
|
+
process.once("SIGINT", interrupt);
|
|
338
|
+
process.once("SIGTERM", interrupt);
|
|
339
|
+
const timer = setTimeout(
|
|
340
|
+
() => cancel(`Operation exceeded ${timeoutMs} ms`),
|
|
341
|
+
timeoutMs,
|
|
342
|
+
);
|
|
343
|
+
return {
|
|
344
|
+
signal: controller.signal,
|
|
345
|
+
add(fn) {
|
|
346
|
+
cleanups.push(fn);
|
|
347
|
+
if (controller.signal.aborted) void fn().catch(() => {});
|
|
348
|
+
},
|
|
349
|
+
check() {
|
|
350
|
+
if (!reason && performance.now() >= deadline)
|
|
351
|
+
cancel(`Operation exceeded ${timeoutMs} ms`);
|
|
352
|
+
if (reason) throw reason;
|
|
353
|
+
},
|
|
354
|
+
remaining() {
|
|
355
|
+
this.check();
|
|
356
|
+
return Math.max(1, Math.ceil(deadline - performance.now()));
|
|
357
|
+
},
|
|
358
|
+
async close() {
|
|
359
|
+
clearTimeout(timer);
|
|
360
|
+
process.removeListener("SIGINT", interrupt);
|
|
361
|
+
process.removeListener("SIGTERM", interrupt);
|
|
362
|
+
await cleanup();
|
|
363
|
+
},
|
|
364
|
+
};
|
|
365
|
+
}
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
|
|
4
|
+
export const common = ["json", "help", "version"];
|
|
5
|
+
export const browserOptions = [
|
|
6
|
+
"url",
|
|
7
|
+
"selector",
|
|
8
|
+
"viewports",
|
|
9
|
+
"wait",
|
|
10
|
+
"locale",
|
|
11
|
+
"color-scheme",
|
|
12
|
+
"timeout",
|
|
13
|
+
];
|
|
14
|
+
export const allowed = {
|
|
15
|
+
capture: [
|
|
16
|
+
...common,
|
|
17
|
+
...browserOptions,
|
|
18
|
+
"out",
|
|
19
|
+
"max-resource-mb",
|
|
20
|
+
"max-total-mb",
|
|
21
|
+
"omit-scripts",
|
|
22
|
+
"max-scroll-steps",
|
|
23
|
+
],
|
|
24
|
+
validate: [
|
|
25
|
+
...common,
|
|
26
|
+
...browserOptions,
|
|
27
|
+
"dir",
|
|
28
|
+
"max-diff-ratio",
|
|
29
|
+
"allow-external",
|
|
30
|
+
"max-scroll-steps",
|
|
31
|
+
],
|
|
32
|
+
serve: [...common, "dir", "port"],
|
|
33
|
+
browser: common,
|
|
34
|
+
};
|
|
35
|
+
const booleans = new Set([
|
|
36
|
+
"json",
|
|
37
|
+
"help",
|
|
38
|
+
"version",
|
|
39
|
+
"allow-external",
|
|
40
|
+
"omit-scripts",
|
|
41
|
+
]);
|
|
42
|
+
|
|
43
|
+
/** @param {string[]} argv @param {string[]} keys */
|
|
44
|
+
export function parseArgs(argv, keys) {
|
|
45
|
+
/** @type {Record<string, string | boolean>} */
|
|
46
|
+
const result = {};
|
|
47
|
+
for (let i = 0; i < argv.length; i++) {
|
|
48
|
+
const token = argv[i];
|
|
49
|
+
if (!token.startsWith("--"))
|
|
50
|
+
throw new Error(`Unexpected argument: ${token}`);
|
|
51
|
+
const [key, ...parts] = token.slice(2).split("=");
|
|
52
|
+
if (!keys.includes(key)) throw new Error(`Unknown option: --${key}`);
|
|
53
|
+
if (Object.hasOwn(result, key))
|
|
54
|
+
throw new Error(`Repeated option: --${key}`);
|
|
55
|
+
if (booleans.has(key)) {
|
|
56
|
+
if (parts.length) throw new Error(`--${key} does not accept a value`);
|
|
57
|
+
result[key] = true;
|
|
58
|
+
} else {
|
|
59
|
+
const value = parts.length ? parts.join("=") : argv[++i];
|
|
60
|
+
if (!value || value.startsWith("--"))
|
|
61
|
+
throw new Error(`Missing value for --${key}`);
|
|
62
|
+
result[key] = value;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
return result;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** @param {Record<string, string | boolean>} args @param {string} key */
|
|
69
|
+
export function required(args, key) {
|
|
70
|
+
const value = args[key];
|
|
71
|
+
if (typeof value !== "string" || !value.trim())
|
|
72
|
+
throw new Error(`Missing required --${key}`);
|
|
73
|
+
return value.trim();
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** @param {unknown} value @param {string} key @param {number} fallback @param {number} min @param {number} max */
|
|
77
|
+
export function numeric(value, key, fallback, min, max) {
|
|
78
|
+
const n = value === undefined ? fallback : Number(value);
|
|
79
|
+
if (typeof value === "boolean" || !Number.isFinite(n) || n < min || n > max) {
|
|
80
|
+
throw new Error(
|
|
81
|
+
`--${key} must be a finite number between ${min} and ${max}`,
|
|
82
|
+
);
|
|
83
|
+
}
|
|
84
|
+
return n;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** @param {string} [value] */
|
|
88
|
+
export function parseViewports(value = "1440x900,1024x768,768x1024,375x812") {
|
|
89
|
+
const seen = new Set();
|
|
90
|
+
const items = value
|
|
91
|
+
.split(",")
|
|
92
|
+
.map((item) => {
|
|
93
|
+
const match = /^(\d{2,4})x(\d{2,4})$/i.exec(item.trim());
|
|
94
|
+
if (!match)
|
|
95
|
+
throw new Error(`Invalid viewport '${item}'. Use WIDTHxHEIGHT.`);
|
|
96
|
+
const width = Number(match[1]),
|
|
97
|
+
height = Number(match[2]);
|
|
98
|
+
if (width < 200 || height < 200 || width > 3840 || height > 3840)
|
|
99
|
+
throw new Error("Viewport dimensions must be between 200 and 3840");
|
|
100
|
+
return { width, height, name: `${width}x${height}` };
|
|
101
|
+
})
|
|
102
|
+
.filter((v) => !seen.has(v.name) && seen.add(v.name));
|
|
103
|
+
if (!items.length || items.length > 8)
|
|
104
|
+
throw new Error("Use between 1 and 8 viewports");
|
|
105
|
+
return items;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** @param {string} value */
|
|
109
|
+
export function httpUrl(value) {
|
|
110
|
+
const url = new URL(value);
|
|
111
|
+
if (
|
|
112
|
+
!["http:", "https:"].includes(url.protocol) ||
|
|
113
|
+
url.username ||
|
|
114
|
+
url.password
|
|
115
|
+
)
|
|
116
|
+
throw new Error("--url must be HTTP(S) without embedded credentials");
|
|
117
|
+
return url.href;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** @param {string} command @param {Record<string, string | boolean>} args */
|
|
121
|
+
export function optionsFor(command, args) {
|
|
122
|
+
const options = {
|
|
123
|
+
json: args.json === true,
|
|
124
|
+
omitScripts: args["omit-scripts"] === true,
|
|
125
|
+
sourceUrl: "",
|
|
126
|
+
selector: "",
|
|
127
|
+
directory: "",
|
|
128
|
+
viewports: parseViewports(
|
|
129
|
+
typeof args.viewports === "string" ? args.viewports : undefined,
|
|
130
|
+
),
|
|
131
|
+
settleMs: numeric(args.wait, "wait", 1200, 0, 60000),
|
|
132
|
+
timeoutMs: numeric(args.timeout, "timeout", 120000, 1000, 600000),
|
|
133
|
+
locale: typeof args.locale === "string" ? args.locale : "pt-BR",
|
|
134
|
+
colorScheme: /** @type {'light' | 'dark'} */ (
|
|
135
|
+
args["color-scheme"] || "light"
|
|
136
|
+
),
|
|
137
|
+
maxResourceBytes:
|
|
138
|
+
numeric(args["max-resource-mb"], "max-resource-mb", 20, 0.001, 100) *
|
|
139
|
+
1024 *
|
|
140
|
+
1024,
|
|
141
|
+
maxTotalBytes:
|
|
142
|
+
numeric(args["max-total-mb"], "max-total-mb", 100, 0.001, 500) *
|
|
143
|
+
1024 *
|
|
144
|
+
1024,
|
|
145
|
+
maxScrollSteps: numeric(
|
|
146
|
+
args["max-scroll-steps"],
|
|
147
|
+
"max-scroll-steps",
|
|
148
|
+
80,
|
|
149
|
+
1,
|
|
150
|
+
1000,
|
|
151
|
+
),
|
|
152
|
+
maximumDifferenceRatio: numeric(
|
|
153
|
+
args["max-diff-ratio"],
|
|
154
|
+
"max-diff-ratio",
|
|
155
|
+
0.02,
|
|
156
|
+
0,
|
|
157
|
+
1,
|
|
158
|
+
),
|
|
159
|
+
allowExternal: args["allow-external"] === true,
|
|
160
|
+
port: numeric(args.port, "port", 4173, 0, 65535),
|
|
161
|
+
};
|
|
162
|
+
if (!["light", "dark"].includes(options.colorScheme))
|
|
163
|
+
throw new Error("--color-scheme must be light or dark");
|
|
164
|
+
if (
|
|
165
|
+
!Number.isInteger(options.port) ||
|
|
166
|
+
!Number.isInteger(options.maxScrollSteps)
|
|
167
|
+
)
|
|
168
|
+
throw new Error("--port and --max-scroll-steps must be integers");
|
|
169
|
+
if (command === "capture" || command === "validate") {
|
|
170
|
+
options.sourceUrl = httpUrl(required(args, "url"));
|
|
171
|
+
options.selector = required(args, "selector");
|
|
172
|
+
}
|
|
173
|
+
if (["capture", "validate", "serve"].includes(command))
|
|
174
|
+
options.directory = path.resolve(
|
|
175
|
+
required(args, command === "capture" ? "out" : "dir"),
|
|
176
|
+
);
|
|
177
|
+
return options;
|
|
178
|
+
}
|