webguardx 0.1.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.
@@ -0,0 +1,1944 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __esm = (fn, res) => function __init() {
10
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
11
+ };
12
+ var __export = (target, all) => {
13
+ for (var name in all)
14
+ __defProp(target, name, { get: all[name], enumerable: true });
15
+ };
16
+ var __copyProps = (to, from, except, desc) => {
17
+ if (from && typeof from === "object" || typeof from === "function") {
18
+ for (let key of __getOwnPropNames(from))
19
+ if (!__hasOwnProp.call(to, key) && key !== except)
20
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
21
+ }
22
+ return to;
23
+ };
24
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
25
+ // If the importer is in node compatibility mode or this is not an ESM
26
+ // file that has been converted to a CommonJS file using a Babel-
27
+ // compatible transform (i.e. "__esModule" has not been set), then set
28
+ // "default" to the CommonJS "module.exports" for node compatibility.
29
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
30
+ mod
31
+ ));
32
+
33
+ // node_modules/tsup/assets/cjs_shims.js
34
+ var getImportMetaUrl, importMetaUrl;
35
+ var init_cjs_shims = __esm({
36
+ "node_modules/tsup/assets/cjs_shims.js"() {
37
+ "use strict";
38
+ getImportMetaUrl = () => typeof document === "undefined" ? new URL(`file:${__filename}`).href : document.currentScript && document.currentScript.tagName.toUpperCase() === "SCRIPT" ? document.currentScript.src : new URL("main.js", document.baseURI).href;
39
+ importMetaUrl = /* @__PURE__ */ getImportMetaUrl();
40
+ }
41
+ });
42
+
43
+ // src/utils/logger.ts
44
+ var import_chalk, log;
45
+ var init_logger = __esm({
46
+ "src/utils/logger.ts"() {
47
+ "use strict";
48
+ init_cjs_shims();
49
+ import_chalk = __toESM(require("chalk"), 1);
50
+ log = {
51
+ info(msg) {
52
+ console.log(import_chalk.default.blue("i"), msg);
53
+ },
54
+ success(msg) {
55
+ console.log(import_chalk.default.green("\u2713"), msg);
56
+ },
57
+ warn(msg) {
58
+ console.log(import_chalk.default.yellow("\u26A0"), msg);
59
+ },
60
+ error(msg) {
61
+ console.log(import_chalk.default.red("\u2717"), msg);
62
+ },
63
+ dim(msg) {
64
+ console.log(import_chalk.default.dim(msg));
65
+ },
66
+ plain(msg) {
67
+ console.log(msg);
68
+ }
69
+ };
70
+ }
71
+ });
72
+
73
+ // src/utils/fs.ts
74
+ function ensureDir(dir) {
75
+ if (!import_fs2.default.existsSync(dir)) {
76
+ import_fs2.default.mkdirSync(dir, { recursive: true });
77
+ }
78
+ }
79
+ function cleanDir(dir) {
80
+ if (import_fs2.default.existsSync(dir)) {
81
+ import_fs2.default.rmSync(dir, { recursive: true, force: true });
82
+ }
83
+ }
84
+ function writeJson(filePath, data) {
85
+ ensureDir(import_path2.default.dirname(filePath));
86
+ import_fs2.default.writeFileSync(filePath, JSON.stringify(data, null, 2));
87
+ }
88
+ var import_fs2, import_path2;
89
+ var init_fs = __esm({
90
+ "src/utils/fs.ts"() {
91
+ "use strict";
92
+ init_cjs_shims();
93
+ import_fs2 = __toESM(require("fs"), 1);
94
+ import_path2 = __toESM(require("path"), 1);
95
+ }
96
+ });
97
+
98
+ // src/reporters/html.ts
99
+ var html_exports = {};
100
+ __export(html_exports, {
101
+ reportHtml: () => reportHtml
102
+ });
103
+ function escapeHtml(str) {
104
+ return str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
105
+ }
106
+ function severityIcon(severity) {
107
+ switch (severity) {
108
+ case "pass":
109
+ return "&#x2713;";
110
+ case "fail":
111
+ return "&#x2717;";
112
+ case "warning":
113
+ return "&#x26A0;";
114
+ case "skip":
115
+ return "&#x25CB;";
116
+ default:
117
+ return "?";
118
+ }
119
+ }
120
+ function severityClass(severity) {
121
+ return `severity-${severity}`;
122
+ }
123
+ function renderAuditRow(audit) {
124
+ return `
125
+ <tr class="${severityClass(audit.severity)}">
126
+ <td class="icon">${severityIcon(audit.severity)}</td>
127
+ <td>${escapeHtml(audit.audit)}</td>
128
+ <td>${escapeHtml(audit.message)}</td>
129
+ <td class="duration">${audit.duration ? `${audit.duration}ms` : "\u2014"}</td>
130
+ </tr>`;
131
+ }
132
+ function renderPageSection(page) {
133
+ const failCount = page.audits.filter((a) => a.severity === "fail").length;
134
+ const status = failCount > 0 ? "fail" : "pass";
135
+ return `
136
+ <div class="page-section">
137
+ <h2 class="page-header ${status}">
138
+ <span class="page-name">${escapeHtml(page.page)}</span>
139
+ <span class="page-path">${escapeHtml(page.path)}</span>
140
+ <span class="page-duration">${(page.duration / 1e3).toFixed(1)}s</span>
141
+ </h2>
142
+ <table class="audit-table">
143
+ <thead>
144
+ <tr>
145
+ <th class="icon-col"></th>
146
+ <th>Audit</th>
147
+ <th>Result</th>
148
+ <th>Duration</th>
149
+ </tr>
150
+ </thead>
151
+ <tbody>
152
+ ${page.audits.map(renderAuditRow).join("")}
153
+ </tbody>
154
+ </table>
155
+ </div>`;
156
+ }
157
+ function buildHtml(result) {
158
+ const { summary } = result;
159
+ const overallStatus = summary.failed > 0 ? "FAIL" : summary.warnings > 0 ? "PASS (with warnings)" : "PASS";
160
+ const statusClass = summary.failed > 0 ? "fail" : summary.warnings > 0 ? "warning" : "pass";
161
+ return `<!DOCTYPE html>
162
+ <html lang="en">
163
+ <head>
164
+ <meta charset="UTF-8">
165
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
166
+ <title>Webguardx Report \u2014 ${escapeHtml(result.config.baseURL)}</title>
167
+ <style>
168
+ :root {
169
+ --pass: #22c55e;
170
+ --fail: #ef4444;
171
+ --warning: #f59e0b;
172
+ --skip: #94a3b8;
173
+ --bg: #0f172a;
174
+ --surface: #1e293b;
175
+ --text: #e2e8f0;
176
+ --text-dim: #94a3b8;
177
+ --border: #334155;
178
+ }
179
+
180
+ * { box-sizing: border-box; margin: 0; padding: 0; }
181
+
182
+ body {
183
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
184
+ background: var(--bg);
185
+ color: var(--text);
186
+ line-height: 1.6;
187
+ padding: 2rem;
188
+ }
189
+
190
+ .container { max-width: 900px; margin: 0 auto; }
191
+
192
+ header {
193
+ text-align: center;
194
+ margin-bottom: 2rem;
195
+ padding-bottom: 1.5rem;
196
+ border-bottom: 1px solid var(--border);
197
+ }
198
+
199
+ header h1 {
200
+ font-size: 1.75rem;
201
+ font-weight: 700;
202
+ margin-bottom: 0.5rem;
203
+ }
204
+
205
+ header .meta {
206
+ color: var(--text-dim);
207
+ font-size: 0.875rem;
208
+ }
209
+
210
+ .summary-grid {
211
+ display: grid;
212
+ grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
213
+ gap: 1rem;
214
+ margin-bottom: 2rem;
215
+ }
216
+
217
+ .summary-card {
218
+ background: var(--surface);
219
+ border-radius: 8px;
220
+ padding: 1rem;
221
+ text-align: center;
222
+ border: 1px solid var(--border);
223
+ }
224
+
225
+ .summary-card .value {
226
+ font-size: 2rem;
227
+ font-weight: 700;
228
+ }
229
+
230
+ .summary-card .label {
231
+ font-size: 0.75rem;
232
+ color: var(--text-dim);
233
+ text-transform: uppercase;
234
+ letter-spacing: 0.05em;
235
+ }
236
+
237
+ .summary-card.pass .value { color: var(--pass); }
238
+ .summary-card.fail .value { color: var(--fail); }
239
+ .summary-card.warning .value { color: var(--warning); }
240
+ .summary-card.skip .value { color: var(--skip); }
241
+
242
+ .overall-status {
243
+ text-align: center;
244
+ font-size: 1.25rem;
245
+ font-weight: 700;
246
+ padding: 0.75rem;
247
+ border-radius: 8px;
248
+ margin-bottom: 2rem;
249
+ }
250
+
251
+ .overall-status.pass { background: rgba(34,197,94,0.15); color: var(--pass); }
252
+ .overall-status.fail { background: rgba(239,68,68,0.15); color: var(--fail); }
253
+ .overall-status.warning { background: rgba(245,158,11,0.15); color: var(--warning); }
254
+
255
+ .page-section {
256
+ background: var(--surface);
257
+ border-radius: 8px;
258
+ margin-bottom: 1.5rem;
259
+ border: 1px solid var(--border);
260
+ overflow: hidden;
261
+ }
262
+
263
+ .page-header {
264
+ padding: 1rem 1.25rem;
265
+ display: flex;
266
+ align-items: center;
267
+ gap: 0.75rem;
268
+ border-bottom: 1px solid var(--border);
269
+ }
270
+
271
+ .page-header.fail { border-left: 4px solid var(--fail); }
272
+ .page-header.pass { border-left: 4px solid var(--pass); }
273
+
274
+ .page-name { font-weight: 600; }
275
+ .page-path { color: var(--text-dim); font-size: 0.875rem; }
276
+ .page-duration { margin-left: auto; color: var(--text-dim); font-size: 0.875rem; }
277
+
278
+ .audit-table {
279
+ width: 100%;
280
+ border-collapse: collapse;
281
+ }
282
+
283
+ .audit-table th {
284
+ text-align: left;
285
+ padding: 0.5rem 1rem;
286
+ font-size: 0.75rem;
287
+ text-transform: uppercase;
288
+ color: var(--text-dim);
289
+ border-bottom: 1px solid var(--border);
290
+ }
291
+
292
+ .audit-table td {
293
+ padding: 0.6rem 1rem;
294
+ border-bottom: 1px solid var(--border);
295
+ }
296
+
297
+ .audit-table tr:last-child td { border-bottom: none; }
298
+
299
+ .icon-col { width: 40px; }
300
+ .icon { text-align: center; font-size: 1.1rem; }
301
+ .duration { color: var(--text-dim); font-size: 0.875rem; }
302
+
303
+ .severity-pass .icon { color: var(--pass); }
304
+ .severity-fail .icon { color: var(--fail); }
305
+ .severity-warning .icon { color: var(--warning); }
306
+ .severity-skip .icon { color: var(--skip); }
307
+
308
+ footer {
309
+ text-align: center;
310
+ margin-top: 2rem;
311
+ padding-top: 1rem;
312
+ border-top: 1px solid var(--border);
313
+ color: var(--text-dim);
314
+ font-size: 0.75rem;
315
+ }
316
+
317
+ footer a { color: var(--text-dim); }
318
+ </style>
319
+ </head>
320
+ <body>
321
+ <div class="container">
322
+ <header>
323
+ <h1>Webguardx Report</h1>
324
+ <div class="meta">
325
+ ${escapeHtml(result.config.baseURL)} &bull;
326
+ ${escapeHtml(result.timestamp)} &bull;
327
+ ${result.config.auditsEnabled.join(", ")}
328
+ </div>
329
+ </header>
330
+
331
+ <div class="overall-status ${statusClass}">${overallStatus}</div>
332
+
333
+ <div class="summary-grid">
334
+ <div class="summary-card">
335
+ <div class="value">${summary.totalAudits}</div>
336
+ <div class="label">Total</div>
337
+ </div>
338
+ <div class="summary-card pass">
339
+ <div class="value">${summary.passed}</div>
340
+ <div class="label">Passed</div>
341
+ </div>
342
+ <div class="summary-card fail">
343
+ <div class="value">${summary.failed}</div>
344
+ <div class="label">Failed</div>
345
+ </div>
346
+ <div class="summary-card warning">
347
+ <div class="value">${summary.warnings}</div>
348
+ <div class="label">Warnings</div>
349
+ </div>
350
+ <div class="summary-card skip">
351
+ <div class="value">${summary.skipped}</div>
352
+ <div class="label">Skipped</div>
353
+ </div>
354
+ <div class="summary-card">
355
+ <div class="value">${(summary.duration / 1e3).toFixed(1)}s</div>
356
+ <div class="label">Duration</div>
357
+ </div>
358
+ </div>
359
+
360
+ ${result.pages.map(renderPageSection).join("")}
361
+
362
+ <footer>
363
+ Generated by <a href="https://github.com/user/webguardx">webguardx</a>
364
+ </footer>
365
+ </div>
366
+ </body>
367
+ </html>`;
368
+ }
369
+ function reportHtml(result, runDir) {
370
+ const filePath = import_path12.default.join(runDir, "report.html");
371
+ ensureDir(runDir);
372
+ import_fs14.default.writeFileSync(filePath, buildHtml(result), "utf-8");
373
+ log.dim(` HTML report: ${filePath}`);
374
+ }
375
+ var import_fs14, import_path12;
376
+ var init_html = __esm({
377
+ "src/reporters/html.ts"() {
378
+ "use strict";
379
+ init_cjs_shims();
380
+ import_fs14 = __toESM(require("fs"), 1);
381
+ import_path12 = __toESM(require("path"), 1);
382
+ init_fs();
383
+ init_logger();
384
+ }
385
+ });
386
+
387
+ // src/bin/cli.ts
388
+ init_cjs_shims();
389
+ var import_commander = require("commander");
390
+ var import_path15 = __toESM(require("path"), 1);
391
+ var import_fs19 = __toESM(require("fs"), 1);
392
+ var import_chalk3 = __toESM(require("chalk"), 1);
393
+
394
+ // src/config/loader.ts
395
+ init_cjs_shims();
396
+ var import_path = __toESM(require("path"), 1);
397
+ var import_fs = __toESM(require("fs"), 1);
398
+
399
+ // src/config/schema.ts
400
+ init_cjs_shims();
401
+ var import_zod = require("zod");
402
+ var AuthApiLoginSchema = import_zod.z.object({
403
+ method: import_zod.z.literal("api-login"),
404
+ loginUrl: import_zod.z.string().url(),
405
+ payload: import_zod.z.record(import_zod.z.string()),
406
+ headers: import_zod.z.record(import_zod.z.string()).optional()
407
+ });
408
+ var AuthFormLoginSchema = import_zod.z.object({
409
+ method: import_zod.z.literal("form-login"),
410
+ loginUrl: import_zod.z.string().url(),
411
+ fields: import_zod.z.array(
412
+ import_zod.z.object({
413
+ selector: import_zod.z.string(),
414
+ value: import_zod.z.string()
415
+ })
416
+ ),
417
+ submitSelector: import_zod.z.string(),
418
+ waitAfterLogin: import_zod.z.string().optional()
419
+ });
420
+ var AuthCookieSchema = import_zod.z.object({
421
+ method: import_zod.z.literal("cookie"),
422
+ cookies: import_zod.z.array(
423
+ import_zod.z.object({
424
+ name: import_zod.z.string(),
425
+ value: import_zod.z.string(),
426
+ domain: import_zod.z.string(),
427
+ path: import_zod.z.string().default("/")
428
+ })
429
+ )
430
+ });
431
+ var AuthBearerSchema = import_zod.z.object({
432
+ method: import_zod.z.literal("bearer-token"),
433
+ token: import_zod.z.string()
434
+ });
435
+ var AuthNoneSchema = import_zod.z.object({
436
+ method: import_zod.z.literal("none")
437
+ });
438
+ var AuthSchema = import_zod.z.discriminatedUnion("method", [
439
+ AuthApiLoginSchema,
440
+ AuthFormLoginSchema,
441
+ AuthCookieSchema,
442
+ AuthBearerSchema,
443
+ AuthNoneSchema
444
+ ]);
445
+ var PageSchema = import_zod.z.object({
446
+ name: import_zod.z.string(),
447
+ path: import_zod.z.string(),
448
+ expectedStatus: import_zod.z.number().default(200),
449
+ skipAudits: import_zod.z.array(import_zod.z.string()).optional()
450
+ });
451
+ var LighthouseThresholdsSchema = import_zod.z.object({
452
+ performance: import_zod.z.number().min(0).max(100).default(50),
453
+ accessibility: import_zod.z.number().min(0).max(100).default(90),
454
+ bestPractices: import_zod.z.number().min(0).max(100).default(80),
455
+ seo: import_zod.z.number().min(0).max(100).default(80)
456
+ }).partial();
457
+ var WebguardConfigSchema = import_zod.z.object({
458
+ baseURL: import_zod.z.string().url(),
459
+ pages: import_zod.z.array(PageSchema).min(1),
460
+ auth: AuthSchema.default({ method: "none" }),
461
+ // Open record — built-in keys have defaults, custom audit keys are allowed
462
+ audits: import_zod.z.record(import_zod.z.string(), import_zod.z.boolean()).default({
463
+ httpStatus: true,
464
+ contentVisibility: true,
465
+ accessibility: true,
466
+ lighthouse: false,
467
+ brokenLinks: false,
468
+ consoleErrors: true
469
+ }),
470
+ // Custom audits defined inline in config
471
+ customAudits: import_zod.z.array(import_zod.z.any()).default([]),
472
+ // Plugins — objects or string paths to npm packages / local files
473
+ plugins: import_zod.z.array(import_zod.z.any()).default([]),
474
+ wcagTags: import_zod.z.array(import_zod.z.string()).default(["wcag2a", "wcag2aa", "wcag21a", "wcag21aa"]),
475
+ lighthouseThresholds: LighthouseThresholdsSchema.default({}),
476
+ retry: import_zod.z.object({
477
+ maxRetries: import_zod.z.number().min(1).default(3),
478
+ delayMs: import_zod.z.number().min(0).default(5e3)
479
+ }).default({}),
480
+ runner: import_zod.z.object({
481
+ concurrency: import_zod.z.number().min(1).default(1),
482
+ failFast: import_zod.z.boolean().default(false)
483
+ }).default({}),
484
+ browser: import_zod.z.object({
485
+ headless: import_zod.z.boolean().default(true),
486
+ timeout: import_zod.z.number().default(6e4),
487
+ viewport: import_zod.z.object({
488
+ width: import_zod.z.number().default(1280),
489
+ height: import_zod.z.number().default(720)
490
+ }).default({})
491
+ }).default({}),
492
+ output: import_zod.z.object({
493
+ dir: import_zod.z.string().default("./webguard-results"),
494
+ formats: import_zod.z.array(import_zod.z.enum(["terminal", "html", "json", "junit"])).default(["terminal", "html", "json"]),
495
+ screenshots: import_zod.z.boolean().default(true),
496
+ screenshotOnFailOnly: import_zod.z.boolean().default(false)
497
+ }).default({}),
498
+ baseline: import_zod.z.object({
499
+ enabled: import_zod.z.boolean().default(false),
500
+ updateOnPass: import_zod.z.boolean().default(true)
501
+ }).default({}),
502
+ notifications: import_zod.z.array(import_zod.z.any()).default([])
503
+ });
504
+
505
+ // src/config/loader.ts
506
+ init_logger();
507
+ var CONFIG_NAMES = [
508
+ "webguard.config.ts",
509
+ "webguard.config.js",
510
+ "webguard.config.mjs",
511
+ "webguard.config.json"
512
+ ];
513
+ async function loadConfig(configPath) {
514
+ const resolvedPath = configPath ? import_path.default.resolve(configPath) : findConfigFile();
515
+ if (!resolvedPath) {
516
+ throw new Error(
517
+ `No webguard config found. Run "webguardx init" to create one, or specify --config <path>.`
518
+ );
519
+ }
520
+ log.info(`Loading config from ${import_path.default.relative(process.cwd(), resolvedPath)}`);
521
+ let rawConfig;
522
+ if (resolvedPath.endsWith(".json")) {
523
+ const content = import_fs.default.readFileSync(resolvedPath, "utf-8");
524
+ rawConfig = JSON.parse(content);
525
+ } else {
526
+ const { createJiti } = await import("jiti");
527
+ const jiti = createJiti(importMetaUrl);
528
+ const mod = await jiti.import(resolvedPath);
529
+ rawConfig = mod.default ?? mod;
530
+ }
531
+ const result = WebguardConfigSchema.safeParse(rawConfig);
532
+ if (!result.success) {
533
+ const errors = result.error.issues.map((i) => ` - ${i.path.join(".")}: ${i.message}`).join("\n");
534
+ throw new Error(`Invalid webguard config:
535
+ ${errors}`);
536
+ }
537
+ return result.data;
538
+ }
539
+ function findConfigFile() {
540
+ const cwd = process.cwd();
541
+ for (const name of CONFIG_NAMES) {
542
+ const fullPath = import_path.default.join(cwd, name);
543
+ if (import_fs.default.existsSync(fullPath)) {
544
+ return fullPath;
545
+ }
546
+ }
547
+ return null;
548
+ }
549
+
550
+ // src/runner/index.ts
551
+ init_cjs_shims();
552
+ var import_playwright4 = require("playwright");
553
+
554
+ // src/auth/index.ts
555
+ init_cjs_shims();
556
+
557
+ // src/auth/strategies/api-login.ts
558
+ init_cjs_shims();
559
+ var import_playwright = require("playwright");
560
+ var import_path3 = __toESM(require("path"), 1);
561
+ init_fs();
562
+ async function apiLogin(config, outputDir) {
563
+ const authDir = import_path3.default.join(outputDir, ".auth");
564
+ ensureDir(authDir);
565
+ const storagePath = import_path3.default.join(authDir, "storageState.json");
566
+ const origin = new URL(config.loginUrl).origin;
567
+ const context = await import_playwright.request.newContext({ baseURL: origin });
568
+ const response = await context.post(config.loginUrl, {
569
+ data: config.payload,
570
+ headers: {
571
+ "content-type": "application/json",
572
+ accept: "application/json",
573
+ ...config.headers
574
+ }
575
+ });
576
+ if (!response.ok()) {
577
+ const body = await response.text();
578
+ await context.dispose();
579
+ throw new Error(`Login failed (HTTP ${response.status()}): ${body}`);
580
+ }
581
+ await context.storageState({ path: storagePath });
582
+ await context.dispose();
583
+ return { storageStatePath: storagePath };
584
+ }
585
+
586
+ // src/auth/strategies/form-login.ts
587
+ init_cjs_shims();
588
+ var import_playwright2 = require("playwright");
589
+ var import_path4 = __toESM(require("path"), 1);
590
+ init_fs();
591
+ async function formLogin(config, outputDir) {
592
+ const authDir = import_path4.default.join(outputDir, ".auth");
593
+ ensureDir(authDir);
594
+ const storagePath = import_path4.default.join(authDir, "storageState.json");
595
+ const browser = await import_playwright2.chromium.launch({ headless: true });
596
+ const context = await browser.newContext();
597
+ const page = await context.newPage();
598
+ await page.goto(config.loginUrl);
599
+ for (const field of config.fields) {
600
+ await page.fill(field.selector, field.value);
601
+ }
602
+ await page.click(config.submitSelector);
603
+ if (config.waitAfterLogin) {
604
+ if (config.waitAfterLogin.startsWith("http")) {
605
+ await page.waitForURL(config.waitAfterLogin);
606
+ } else {
607
+ await page.waitForSelector(config.waitAfterLogin);
608
+ }
609
+ } else {
610
+ await page.waitForLoadState("networkidle");
611
+ }
612
+ await context.storageState({ path: storagePath });
613
+ await browser.close();
614
+ return { storageStatePath: storagePath };
615
+ }
616
+
617
+ // src/auth/strategies/cookie-inject.ts
618
+ init_cjs_shims();
619
+ var import_fs5 = __toESM(require("fs"), 1);
620
+ var import_path5 = __toESM(require("path"), 1);
621
+ init_fs();
622
+ async function cookieInject(config, outputDir) {
623
+ const authDir = import_path5.default.join(outputDir, ".auth");
624
+ ensureDir(authDir);
625
+ const storagePath = import_path5.default.join(authDir, "storageState.json");
626
+ const storageState = {
627
+ cookies: config.cookies.map((c) => ({
628
+ name: c.name,
629
+ value: c.value,
630
+ domain: c.domain,
631
+ path: c.path || "/",
632
+ expires: -1,
633
+ httpOnly: false,
634
+ secure: true,
635
+ sameSite: "Lax"
636
+ })),
637
+ origins: []
638
+ };
639
+ import_fs5.default.writeFileSync(storagePath, JSON.stringify(storageState, null, 2));
640
+ return { storageStatePath: storagePath };
641
+ }
642
+
643
+ // src/auth/strategies/bearer-token.ts
644
+ init_cjs_shims();
645
+ var import_fs7 = __toESM(require("fs"), 1);
646
+ var import_path6 = __toESM(require("path"), 1);
647
+ init_fs();
648
+ async function bearerToken(config, outputDir) {
649
+ const authDir = import_path6.default.join(outputDir, ".auth");
650
+ ensureDir(authDir);
651
+ const storagePath = import_path6.default.join(authDir, "storageState.json");
652
+ import_fs7.default.writeFileSync(
653
+ storagePath,
654
+ JSON.stringify({ cookies: [], origins: [] })
655
+ );
656
+ return {
657
+ storageStatePath: storagePath,
658
+ extraHeaders: { Authorization: `Bearer ${config.token}` }
659
+ };
660
+ }
661
+
662
+ // src/auth/index.ts
663
+ init_logger();
664
+ async function authenticate(authConfig, outputDir) {
665
+ if (authConfig.method === "none") {
666
+ return null;
667
+ }
668
+ log.info(`Authenticating via ${authConfig.method}...`);
669
+ let result;
670
+ switch (authConfig.method) {
671
+ case "api-login":
672
+ result = await apiLogin(authConfig, outputDir);
673
+ break;
674
+ case "form-login":
675
+ result = await formLogin(authConfig, outputDir);
676
+ break;
677
+ case "cookie":
678
+ result = await cookieInject(authConfig, outputDir);
679
+ break;
680
+ case "bearer-token":
681
+ result = await bearerToken(authConfig, outputDir);
682
+ break;
683
+ }
684
+ log.success("Authenticated successfully");
685
+ return result;
686
+ }
687
+
688
+ // src/audits/index.ts
689
+ init_cjs_shims();
690
+
691
+ // src/audits/http-status.ts
692
+ init_cjs_shims();
693
+ var HttpStatusAudit = {
694
+ name: "httpStatus",
695
+ description: "Verify the page returns the expected HTTP status code",
696
+ async run(ctx) {
697
+ const status = ctx.navigationResponse?.status() ?? 0;
698
+ const expected = ctx.pageEntry.expectedStatus ?? 200;
699
+ return {
700
+ audit: this.name,
701
+ page: ctx.pageEntry.name,
702
+ passed: status === expected,
703
+ severity: status === expected ? "pass" : "fail",
704
+ message: status === expected ? `HTTP ${status} OK` : `Expected HTTP ${expected}, got ${status}`,
705
+ details: { status, expected }
706
+ };
707
+ }
708
+ };
709
+
710
+ // src/audits/content-visibility.ts
711
+ init_cjs_shims();
712
+ var ContentVisibilityAudit = {
713
+ name: "contentVisibility",
714
+ description: "Verify the page has visible rendered content",
715
+ async run(ctx) {
716
+ const { page } = ctx;
717
+ const bodyVisible = await page.locator("body").isVisible().catch(() => false);
718
+ if (!bodyVisible) {
719
+ return {
720
+ audit: this.name,
721
+ page: ctx.pageEntry.name,
722
+ passed: false,
723
+ severity: "fail",
724
+ message: "Page body is not visible",
725
+ details: { bodyVisible: false, textLength: 0, elementCount: 0 }
726
+ };
727
+ }
728
+ const bodyText = await page.locator("body").innerText().catch(() => "");
729
+ const textLength = bodyText.trim().length;
730
+ const elementCount = await page.locator(
731
+ "body h1, body h2, body p, body main, body div, body section, body nav, body header"
732
+ ).count();
733
+ const passed = textLength > 0 && elementCount > 0;
734
+ return {
735
+ audit: this.name,
736
+ page: ctx.pageEntry.name,
737
+ passed,
738
+ severity: passed ? "pass" : "fail",
739
+ message: passed ? `${elementCount} elements visible` : `Content check failed (text: ${textLength} chars, elements: ${elementCount})`,
740
+ details: { bodyVisible: true, textLength, elementCount }
741
+ };
742
+ }
743
+ };
744
+
745
+ // src/audits/accessibility.ts
746
+ init_cjs_shims();
747
+ var import_playwright3 = __toESM(require("@axe-core/playwright"), 1);
748
+ var import_path7 = __toESM(require("path"), 1);
749
+
750
+ // src/utils/sanitize.ts
751
+ init_cjs_shims();
752
+ function sanitize(name) {
753
+ return name.replace(/[^a-zA-Z0-9_-]/g, "_");
754
+ }
755
+
756
+ // src/audits/accessibility.ts
757
+ init_fs();
758
+ var AccessibilityAudit = {
759
+ name: "accessibility",
760
+ description: "WCAG accessibility audit via axe-core",
761
+ async run(ctx) {
762
+ const results = await new import_playwright3.default({ page: ctx.page }).withTags(ctx.config.wcagTags).analyze();
763
+ const violations = results.violations;
764
+ if (violations.length > 0) {
765
+ const summary = violations.map((v) => ({
766
+ rule: v.id,
767
+ impact: v.impact,
768
+ description: v.description,
769
+ helpUrl: v.helpUrl,
770
+ elements: v.nodes.length
771
+ }));
772
+ const pageDir = import_path7.default.join(
773
+ ctx.runDir,
774
+ "screenshots",
775
+ sanitize(ctx.pageEntry.name)
776
+ );
777
+ writeJson(import_path7.default.join(pageDir, "a11y-violations.json"), summary);
778
+ }
779
+ return {
780
+ audit: this.name,
781
+ page: ctx.pageEntry.name,
782
+ passed: violations.length === 0,
783
+ severity: violations.length === 0 ? "pass" : "warning",
784
+ message: violations.length === 0 ? "0 violations" : `${violations.length} violation(s)`,
785
+ details: {
786
+ violationCount: violations.length,
787
+ violations: violations.map((v) => ({
788
+ rule: v.id,
789
+ impact: v.impact,
790
+ description: v.description,
791
+ elements: v.nodes.length
792
+ }))
793
+ }
794
+ };
795
+ }
796
+ };
797
+
798
+ // src/audits/lighthouse.ts
799
+ init_cjs_shims();
800
+ var import_path8 = __toESM(require("path"), 1);
801
+ init_fs();
802
+ var LighthouseAudit = {
803
+ name: "lighthouse",
804
+ description: "Lighthouse performance, accessibility, best practices, and SEO audit",
805
+ async run(ctx) {
806
+ let lighthouse;
807
+ let chromeLauncher;
808
+ try {
809
+ lighthouse = await import("lighthouse");
810
+ chromeLauncher = await import("chrome-launcher");
811
+ } catch {
812
+ return {
813
+ audit: this.name,
814
+ page: ctx.pageEntry.name,
815
+ passed: false,
816
+ severity: "skip",
817
+ message: "Lighthouse not installed. Run: npm install lighthouse chrome-launcher"
818
+ };
819
+ }
820
+ const chrome = await chromeLauncher.launch({
821
+ chromeFlags: ["--headless", "--no-sandbox"]
822
+ });
823
+ const url = `${ctx.config.baseURL}${ctx.pageEntry.path}`;
824
+ const thresholds = ctx.config.lighthouseThresholds;
825
+ try {
826
+ const result = await lighthouse.default(url, {
827
+ port: chrome.port,
828
+ output: "json",
829
+ logLevel: "error",
830
+ onlyCategories: [
831
+ "performance",
832
+ "accessibility",
833
+ "best-practices",
834
+ "seo"
835
+ ]
836
+ });
837
+ await chrome.kill();
838
+ if (!result?.lhr) {
839
+ return {
840
+ audit: this.name,
841
+ page: ctx.pageEntry.name,
842
+ passed: false,
843
+ severity: "fail",
844
+ message: "Lighthouse failed to produce results"
845
+ };
846
+ }
847
+ const scores = {
848
+ performance: Math.round(
849
+ (result.lhr.categories.performance?.score ?? 0) * 100
850
+ ),
851
+ accessibility: Math.round(
852
+ (result.lhr.categories.accessibility?.score ?? 0) * 100
853
+ ),
854
+ bestPractices: Math.round(
855
+ (result.lhr.categories["best-practices"]?.score ?? 0) * 100
856
+ ),
857
+ seo: Math.round((result.lhr.categories.seo?.score ?? 0) * 100)
858
+ };
859
+ const failures = [];
860
+ if (thresholds.performance && scores.performance < thresholds.performance)
861
+ failures.push(
862
+ `Performance: ${scores.performance} < ${thresholds.performance}`
863
+ );
864
+ if (thresholds.accessibility && scores.accessibility < thresholds.accessibility)
865
+ failures.push(
866
+ `Accessibility: ${scores.accessibility} < ${thresholds.accessibility}`
867
+ );
868
+ if (thresholds.bestPractices && scores.bestPractices < thresholds.bestPractices)
869
+ failures.push(
870
+ `Best Practices: ${scores.bestPractices} < ${thresholds.bestPractices}`
871
+ );
872
+ if (thresholds.seo && scores.seo < thresholds.seo)
873
+ failures.push(`SEO: ${scores.seo} < ${thresholds.seo}`);
874
+ const pageDir = import_path8.default.join(
875
+ ctx.runDir,
876
+ "screenshots",
877
+ sanitize(ctx.pageEntry.name)
878
+ );
879
+ ensureDir(pageDir);
880
+ writeJson(import_path8.default.join(pageDir, "lighthouse-report.json"), result.lhr);
881
+ return {
882
+ audit: this.name,
883
+ page: ctx.pageEntry.name,
884
+ passed: failures.length === 0,
885
+ severity: failures.length > 0 ? "fail" : "pass",
886
+ message: failures.length > 0 ? `Failed: ${failures.join("; ")}` : `perf=${scores.performance} a11y=${scores.accessibility} bp=${scores.bestPractices} seo=${scores.seo}`,
887
+ details: { scores, thresholds, failures }
888
+ };
889
+ } catch (err) {
890
+ await chrome.kill().catch(() => {
891
+ });
892
+ return {
893
+ audit: this.name,
894
+ page: ctx.pageEntry.name,
895
+ passed: false,
896
+ severity: "fail",
897
+ message: `Lighthouse error: ${err.message}`
898
+ };
899
+ }
900
+ }
901
+ };
902
+
903
+ // src/audits/broken-links.ts
904
+ init_cjs_shims();
905
+ var BrokenLinksAudit = {
906
+ name: "brokenLinks",
907
+ description: "Find broken links (4xx/5xx) on the page",
908
+ async run(ctx) {
909
+ const links = await ctx.page.$$eval(
910
+ "a[href]",
911
+ (anchors) => anchors.map((a) => a.getAttribute("href")).filter((href) => !!href)
912
+ );
913
+ const baseOrigin = new URL(ctx.config.baseURL).origin;
914
+ const uniqueLinks = [
915
+ ...new Set(
916
+ links.map((href) => {
917
+ try {
918
+ return new URL(href, ctx.config.baseURL).href;
919
+ } catch {
920
+ return null;
921
+ }
922
+ }).filter(
923
+ (url) => !!url && (url.startsWith("http://") || url.startsWith("https://"))
924
+ )
925
+ )
926
+ ];
927
+ const broken = [];
928
+ for (const url of uniqueLinks) {
929
+ try {
930
+ const response = await ctx.page.request.head(url, { timeout: 1e4 });
931
+ if (response.status() >= 400) {
932
+ broken.push({ url, status: response.status() });
933
+ }
934
+ } catch {
935
+ broken.push({ url, status: 0 });
936
+ }
937
+ }
938
+ return {
939
+ audit: this.name,
940
+ page: ctx.pageEntry.name,
941
+ passed: broken.length === 0,
942
+ severity: broken.length > 0 ? "warning" : "pass",
943
+ message: broken.length === 0 ? `All ${uniqueLinks.length} links valid` : `${broken.length} broken link(s) of ${uniqueLinks.length}`,
944
+ details: { totalLinks: uniqueLinks.length, broken }
945
+ };
946
+ }
947
+ };
948
+
949
+ // src/audits/console-errors.ts
950
+ init_cjs_shims();
951
+ var ConsoleErrorsAudit = {
952
+ name: "consoleErrors",
953
+ description: "Capture browser console errors and warnings",
954
+ async run(ctx) {
955
+ const messages = ctx.consoleMessages;
956
+ const errors = messages.filter((m) => m.type === "error");
957
+ const warnings = messages.filter((m) => m.type === "warning");
958
+ return {
959
+ audit: this.name,
960
+ page: ctx.pageEntry.name,
961
+ passed: errors.length === 0,
962
+ severity: errors.length > 0 ? "fail" : warnings.length > 0 ? "warning" : "pass",
963
+ message: errors.length === 0 && warnings.length === 0 ? "0 errors" : `${errors.length} error(s), ${warnings.length} warning(s)`,
964
+ details: {
965
+ errors: errors.map((e) => e.text),
966
+ warnings: warnings.map((w) => w.text)
967
+ }
968
+ };
969
+ }
970
+ };
971
+
972
+ // src/audits/index.ts
973
+ var BUILTIN_AUDITS = {
974
+ httpStatus: HttpStatusAudit,
975
+ contentVisibility: ContentVisibilityAudit,
976
+ accessibility: AccessibilityAudit,
977
+ lighthouse: LighthouseAudit,
978
+ brokenLinks: BrokenLinksAudit,
979
+ consoleErrors: ConsoleErrorsAudit
980
+ };
981
+ function getEnabledAudits(auditsConfig, pluginAudits = [], customAudits = []) {
982
+ const allAudits = { ...BUILTIN_AUDITS };
983
+ for (const audit of [...pluginAudits, ...customAudits]) {
984
+ allAudits[audit.name] = audit;
985
+ }
986
+ const enabled = [];
987
+ for (const [name, audit] of Object.entries(allAudits)) {
988
+ const isEnabled = auditsConfig[name] ?? true;
989
+ if (isEnabled) {
990
+ enabled.push(audit);
991
+ }
992
+ }
993
+ return enabled;
994
+ }
995
+
996
+ // src/runner/page-runner.ts
997
+ init_cjs_shims();
998
+ var import_path9 = __toESM(require("path"), 1);
999
+
1000
+ // src/runner/retry.ts
1001
+ init_cjs_shims();
1002
+
1003
+ // src/utils/sleep.ts
1004
+ init_cjs_shims();
1005
+ function sleep(ms) {
1006
+ return new Promise((resolve) => setTimeout(resolve, ms));
1007
+ }
1008
+
1009
+ // src/runner/retry.ts
1010
+ init_logger();
1011
+ async function navigateWithRetry(page, url, retry, waitUntil = "domcontentloaded") {
1012
+ let lastError = null;
1013
+ for (let attempt = 1; attempt <= retry.maxRetries; attempt++) {
1014
+ try {
1015
+ const response = await page.goto(url, {
1016
+ waitUntil,
1017
+ timeout: 3e4
1018
+ });
1019
+ if (response && response.ok()) {
1020
+ return response;
1021
+ }
1022
+ if (attempt < retry.maxRetries) {
1023
+ log.warn(
1024
+ `Attempt ${attempt}/${retry.maxRetries} for ${url} returned ${response?.status()}. Retrying in ${retry.delayMs / 1e3}s...`
1025
+ );
1026
+ await sleep(retry.delayMs);
1027
+ }
1028
+ if (attempt === retry.maxRetries) return response;
1029
+ } catch (error) {
1030
+ lastError = error;
1031
+ if (attempt < retry.maxRetries) {
1032
+ log.warn(
1033
+ `Attempt ${attempt}/${retry.maxRetries} for ${url} failed. Retrying in ${retry.delayMs / 1e3}s...`
1034
+ );
1035
+ await sleep(retry.delayMs);
1036
+ }
1037
+ }
1038
+ }
1039
+ throw lastError ?? new Error(`Failed to load ${url} after ${retry.maxRetries} attempts`);
1040
+ }
1041
+
1042
+ // src/runner/page-runner.ts
1043
+ init_fs();
1044
+ init_logger();
1045
+ async function runPageAudits(pageEntry, config, browserContext, audits, runDir, registry) {
1046
+ const start = Date.now();
1047
+ const url = `${config.baseURL}${pageEntry.path}`;
1048
+ const page = await browserContext.newPage();
1049
+ if (registry) {
1050
+ await registry.runHook("beforePage", { config, pageEntry, page });
1051
+ }
1052
+ const consoleMessages = [];
1053
+ page.on("console", (msg) => {
1054
+ consoleMessages.push({ type: msg.type(), text: msg.text() });
1055
+ });
1056
+ let navigationResponse = null;
1057
+ try {
1058
+ navigationResponse = await navigateWithRetry(
1059
+ page,
1060
+ url,
1061
+ config.retry,
1062
+ "domcontentloaded"
1063
+ );
1064
+ } catch (err) {
1065
+ log.error(`Failed to navigate to ${url}: ${err.message}`);
1066
+ }
1067
+ const ctx = {
1068
+ page,
1069
+ browserContext,
1070
+ pageEntry,
1071
+ config,
1072
+ runDir,
1073
+ navigationResponse,
1074
+ consoleMessages
1075
+ };
1076
+ const pageAudits = audits.filter(
1077
+ (a) => !pageEntry.skipAudits?.includes(a.name)
1078
+ );
1079
+ const auditResults = [];
1080
+ for (const audit of pageAudits) {
1081
+ if (registry) {
1082
+ await registry.runHook("beforeAudit", { audit, auditContext: ctx });
1083
+ }
1084
+ const auditStart = Date.now();
1085
+ let result;
1086
+ try {
1087
+ result = await audit.run(ctx);
1088
+ result.duration = Date.now() - auditStart;
1089
+ } catch (err) {
1090
+ result = {
1091
+ audit: audit.name,
1092
+ page: pageEntry.name,
1093
+ passed: false,
1094
+ severity: "fail",
1095
+ message: `Audit error: ${err.message}`,
1096
+ duration: Date.now() - auditStart
1097
+ };
1098
+ }
1099
+ auditResults.push(result);
1100
+ if (registry) {
1101
+ await registry.runHook("afterAudit", { audit, result });
1102
+ }
1103
+ }
1104
+ let screenshotPath;
1105
+ if (config.output.screenshots) {
1106
+ const anyFailed = auditResults.some((r) => !r.passed);
1107
+ if (!config.output.screenshotOnFailOnly || anyFailed) {
1108
+ try {
1109
+ const pageDir = import_path9.default.join(runDir, "screenshots", sanitize(pageEntry.name));
1110
+ ensureDir(pageDir);
1111
+ const status = anyFailed ? "fail" : "pass";
1112
+ screenshotPath = import_path9.default.join(pageDir, `page-${status}.png`);
1113
+ await page.screenshot({ path: screenshotPath, fullPage: true });
1114
+ } catch {
1115
+ }
1116
+ }
1117
+ }
1118
+ const pageResult = {
1119
+ page: pageEntry.name,
1120
+ path: pageEntry.path,
1121
+ url,
1122
+ audits: auditResults,
1123
+ screenshotPath,
1124
+ duration: Date.now() - start
1125
+ };
1126
+ if (registry) {
1127
+ await registry.runHook("afterPage", { config, pageEntry, pageResult });
1128
+ }
1129
+ await page.close();
1130
+ return pageResult;
1131
+ }
1132
+
1133
+ // src/runner/parallel.ts
1134
+ init_cjs_shims();
1135
+ init_logger();
1136
+ async function runPagesParallel(pages, config, browserContext, audits, runDir, registry, concurrency, failFast) {
1137
+ const results = new Array(pages.length);
1138
+ let currentIndex = 0;
1139
+ let aborted = false;
1140
+ async function worker() {
1141
+ while (!aborted) {
1142
+ const index = currentIndex++;
1143
+ if (index >= pages.length) break;
1144
+ const pageEntry = pages[index];
1145
+ log.plain(` [${index + 1}/${pages.length}] ${pageEntry.name} (${pageEntry.path})`);
1146
+ const result = await runPageAudits(
1147
+ pageEntry,
1148
+ config,
1149
+ browserContext,
1150
+ audits,
1151
+ runDir,
1152
+ registry
1153
+ );
1154
+ results[index] = result;
1155
+ for (const audit of result.audits) {
1156
+ const icon = audit.passed ? " \u2713" : audit.severity === "warning" ? " \u26A0" : " \u2717";
1157
+ const duration = audit.duration ? `${audit.duration}ms` : "";
1158
+ log.plain(
1159
+ `${icon} ${audit.audit.padEnd(20)} ${audit.message.padEnd(30)} ${duration}`
1160
+ );
1161
+ }
1162
+ log.plain("");
1163
+ if (failFast && result.audits.some((a) => a.severity === "fail")) {
1164
+ log.warn("Fail fast enabled \u2014 stopping after first failure");
1165
+ aborted = true;
1166
+ }
1167
+ }
1168
+ }
1169
+ const workerCount = Math.min(concurrency, pages.length);
1170
+ const workers = Array.from({ length: workerCount }, () => worker());
1171
+ await Promise.all(workers);
1172
+ return results.filter(Boolean);
1173
+ }
1174
+
1175
+ // src/runner/setup.ts
1176
+ init_cjs_shims();
1177
+ var import_path10 = __toESM(require("path"), 1);
1178
+ init_fs();
1179
+ function setupRunDirectory(outputBaseDir) {
1180
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
1181
+ const runDir = import_path10.default.join(outputBaseDir, `run-${timestamp}`);
1182
+ const screenshotsDir = import_path10.default.join(runDir, "screenshots");
1183
+ cleanDir(outputBaseDir);
1184
+ ensureDir(screenshotsDir);
1185
+ return { runDir, screenshotsDir };
1186
+ }
1187
+
1188
+ // src/reporters/index.ts
1189
+ init_cjs_shims();
1190
+
1191
+ // src/reporters/json.ts
1192
+ init_cjs_shims();
1193
+ var import_path11 = __toESM(require("path"), 1);
1194
+ init_fs();
1195
+ init_logger();
1196
+ function reportJson(result, runDir) {
1197
+ const filePath = import_path11.default.join(runDir, "results.json");
1198
+ writeJson(filePath, result);
1199
+ log.dim(` JSON report: ${filePath}`);
1200
+ }
1201
+
1202
+ // src/reporters/terminal.ts
1203
+ init_cjs_shims();
1204
+ var import_chalk2 = __toESM(require("chalk"), 1);
1205
+ function reportTerminal(result) {
1206
+ const { summary } = result;
1207
+ console.log("");
1208
+ console.log(import_chalk2.default.bold("\u2500".repeat(60)));
1209
+ console.log(import_chalk2.default.bold(" Summary"));
1210
+ console.log(import_chalk2.default.bold("\u2500".repeat(60)));
1211
+ console.log("");
1212
+ console.log(` Total audits: ${summary.totalAudits}`);
1213
+ console.log(
1214
+ ` ${import_chalk2.default.green("\u2713 Passed:")} ${summary.passed}`
1215
+ );
1216
+ if (summary.failed > 0) {
1217
+ console.log(
1218
+ ` ${import_chalk2.default.red("\u2717 Failed:")} ${summary.failed}`
1219
+ );
1220
+ }
1221
+ if (summary.warnings > 0) {
1222
+ console.log(
1223
+ ` ${import_chalk2.default.yellow("\u26A0 Warnings:")} ${summary.warnings}`
1224
+ );
1225
+ }
1226
+ if (summary.skipped > 0) {
1227
+ console.log(
1228
+ ` ${import_chalk2.default.dim("\u25CB Skipped:")} ${summary.skipped}`
1229
+ );
1230
+ }
1231
+ console.log(
1232
+ ` Duration: ${(summary.duration / 1e3).toFixed(1)}s`
1233
+ );
1234
+ console.log("");
1235
+ const failedAudits = result.pages.flatMap(
1236
+ (p) => p.audits.filter((a) => a.severity === "fail")
1237
+ );
1238
+ if (failedAudits.length > 0) {
1239
+ console.log(import_chalk2.default.red.bold(" Failed Audits:"));
1240
+ for (const audit of failedAudits) {
1241
+ console.log(
1242
+ import_chalk2.default.red(` \u2717 ${audit.page} \u2192 ${audit.audit}: ${audit.message}`)
1243
+ );
1244
+ }
1245
+ console.log("");
1246
+ }
1247
+ if (summary.failed > 0) {
1248
+ console.log(
1249
+ import_chalk2.default.red.bold(` Result: FAIL (${summary.failed} failure(s))`)
1250
+ );
1251
+ } else if (summary.warnings > 0) {
1252
+ console.log(
1253
+ import_chalk2.default.yellow.bold(` Result: PASS with ${summary.warnings} warning(s)`)
1254
+ );
1255
+ } else {
1256
+ console.log(import_chalk2.default.green.bold(" Result: PASS"));
1257
+ }
1258
+ console.log("");
1259
+ }
1260
+
1261
+ // src/reporters/index.ts
1262
+ init_html();
1263
+
1264
+ // src/reporters/junit.ts
1265
+ init_cjs_shims();
1266
+ var import_fs16 = __toESM(require("fs"), 1);
1267
+ var import_path13 = __toESM(require("path"), 1);
1268
+ init_fs();
1269
+ init_logger();
1270
+ function escapeXml(str) {
1271
+ return str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
1272
+ }
1273
+ function buildTestCase(audit) {
1274
+ const name = escapeXml(`${audit.page} - ${audit.audit}`);
1275
+ const time = audit.duration ? (audit.duration / 1e3).toFixed(3) : "0.000";
1276
+ if (audit.severity === "pass") {
1277
+ return ` <testcase name="${name}" classname="${escapeXml(audit.page)}" time="${time}" />
1278
+ `;
1279
+ }
1280
+ if (audit.severity === "skip") {
1281
+ return ` <testcase name="${name}" classname="${escapeXml(audit.page)}" time="${time}">
1282
+ <skipped message="${escapeXml(audit.message)}" />
1283
+ </testcase>
1284
+ `;
1285
+ }
1286
+ const tag = audit.severity === "fail" ? "failure" : "failure";
1287
+ return ` <testcase name="${name}" classname="${escapeXml(audit.page)}" time="${time}">
1288
+ <${tag} message="${escapeXml(audit.message)}" type="${escapeXml(audit.severity)}">${escapeXml(audit.message)}</${tag}>
1289
+ </testcase>
1290
+ `;
1291
+ }
1292
+ function buildTestSuite(page, index) {
1293
+ const tests = page.audits.length;
1294
+ const failures = page.audits.filter((a) => a.severity === "fail").length;
1295
+ const skipped = page.audits.filter((a) => a.severity === "skip").length;
1296
+ const time = (page.duration / 1e3).toFixed(3);
1297
+ let xml = ` <testsuite name="${escapeXml(page.page)}" tests="${tests}" failures="${failures}" skipped="${skipped}" time="${time}" id="${index}">
1298
+ `;
1299
+ for (const audit of page.audits) {
1300
+ xml += buildTestCase(audit);
1301
+ }
1302
+ xml += ` </testsuite>
1303
+ `;
1304
+ return xml;
1305
+ }
1306
+ function reportJunit(result, runDir) {
1307
+ const { summary } = result;
1308
+ const time = (summary.duration / 1e3).toFixed(3);
1309
+ let xml = `<?xml version="1.0" encoding="UTF-8"?>
1310
+ `;
1311
+ xml += `<testsuites name="webguardx" tests="${summary.totalAudits}" failures="${summary.failed}" skipped="${summary.skipped}" time="${time}">
1312
+ `;
1313
+ result.pages.forEach((page, i) => {
1314
+ xml += buildTestSuite(page, i);
1315
+ });
1316
+ xml += `</testsuites>
1317
+ `;
1318
+ const filePath = import_path13.default.join(runDir, "results.xml");
1319
+ ensureDir(runDir);
1320
+ import_fs16.default.writeFileSync(filePath, xml, "utf-8");
1321
+ log.dim(` JUnit report: ${filePath}`);
1322
+ }
1323
+
1324
+ // src/reporters/screenshot.ts
1325
+ init_cjs_shims();
1326
+ init_logger();
1327
+ function reportScreenshots(result) {
1328
+ const captured = result.pages.filter((p) => p.screenshotPath);
1329
+ if (captured.length > 0) {
1330
+ log.dim(` Screenshots: ${captured.length} page(s) captured`);
1331
+ }
1332
+ }
1333
+
1334
+ // src/reporters/index.ts
1335
+ init_logger();
1336
+ async function runReporters(result, config, runDir, pluginReporters = []) {
1337
+ const formats = config.output.formats;
1338
+ if (formats.includes("terminal")) {
1339
+ reportTerminal(result);
1340
+ }
1341
+ log.dim(" Output:");
1342
+ if (formats.includes("json")) {
1343
+ reportJson(result, runDir);
1344
+ }
1345
+ if (formats.includes("html")) {
1346
+ reportHtml(result, runDir);
1347
+ }
1348
+ if (formats.includes("junit")) {
1349
+ reportJunit(result, runDir);
1350
+ }
1351
+ if (config.output.screenshots) {
1352
+ reportScreenshots(result);
1353
+ }
1354
+ for (const reporter of pluginReporters) {
1355
+ try {
1356
+ await reporter.run(result, runDir, config);
1357
+ log.dim(` ${reporter.name}: done`);
1358
+ } catch (err) {
1359
+ log.warn(`Reporter '${reporter.name}' failed: ${err.message}`);
1360
+ }
1361
+ }
1362
+ log.plain("");
1363
+ }
1364
+
1365
+ // src/plugins/index.ts
1366
+ init_cjs_shims();
1367
+
1368
+ // src/plugins/registry.ts
1369
+ init_cjs_shims();
1370
+ init_logger();
1371
+ var PluginRegistry = class {
1372
+ plugins = [];
1373
+ register(plugin) {
1374
+ this.plugins.push(plugin);
1375
+ }
1376
+ getPluginAudits() {
1377
+ return this.plugins.flatMap((p) => p.audits ?? []);
1378
+ }
1379
+ getPluginReporters() {
1380
+ return this.plugins.flatMap((p) => p.reporters ?? []);
1381
+ }
1382
+ async runHook(hookName, ctx) {
1383
+ for (const plugin of this.plugins) {
1384
+ const hook = plugin.hooks?.[hookName];
1385
+ if (hook) {
1386
+ try {
1387
+ await hook(ctx);
1388
+ } catch (err) {
1389
+ log.warn(
1390
+ `Plugin '${plugin.name}' hook '${hookName}' failed: ${err.message}`
1391
+ );
1392
+ }
1393
+ }
1394
+ }
1395
+ }
1396
+ };
1397
+
1398
+ // src/plugins/loader.ts
1399
+ init_cjs_shims();
1400
+ init_logger();
1401
+ async function loadPlugins(pluginEntries) {
1402
+ const plugins = [];
1403
+ for (const entry of pluginEntries) {
1404
+ if (typeof entry === "string") {
1405
+ try {
1406
+ const { createJiti } = await import("jiti");
1407
+ const jiti = createJiti(importMetaUrl);
1408
+ const mod = await jiti.import(entry);
1409
+ const plugin = mod.default ?? mod;
1410
+ plugins.push(plugin);
1411
+ log.dim(` Loaded plugin: ${plugin.name ?? entry}`);
1412
+ } catch (err) {
1413
+ log.warn(`Failed to load plugin '${entry}': ${err.message}`);
1414
+ }
1415
+ } else {
1416
+ plugins.push(entry);
1417
+ }
1418
+ }
1419
+ return plugins;
1420
+ }
1421
+
1422
+ // src/runner/index.ts
1423
+ init_logger();
1424
+ async function run(config, options = {}) {
1425
+ const start = Date.now();
1426
+ if (options.headed !== void 0) {
1427
+ config.browser.headless = !options.headed;
1428
+ }
1429
+ const registry = new PluginRegistry();
1430
+ if (config.plugins.length > 0) {
1431
+ const plugins = await loadPlugins(config.plugins);
1432
+ for (const plugin of plugins) {
1433
+ registry.register(plugin);
1434
+ }
1435
+ }
1436
+ const { runDir } = setupRunDirectory(config.output.dir);
1437
+ const authResult = await authenticate(config.auth, runDir);
1438
+ const browser = await import_playwright4.chromium.launch({
1439
+ headless: config.browser.headless
1440
+ });
1441
+ const contextOptions = {
1442
+ viewport: config.browser.viewport
1443
+ };
1444
+ if (authResult?.storageStatePath) {
1445
+ contextOptions.storageState = authResult.storageStatePath;
1446
+ }
1447
+ if (authResult?.extraHeaders) {
1448
+ contextOptions.extraHTTPHeaders = authResult.extraHeaders;
1449
+ }
1450
+ const browserContext = await browser.newContext(contextOptions);
1451
+ await registry.runHook("beforeAll", { config, browserContext });
1452
+ let audits = getEnabledAudits(
1453
+ config.audits,
1454
+ registry.getPluginAudits(),
1455
+ config.customAudits
1456
+ );
1457
+ if (options.auditsFilter?.length) {
1458
+ audits = audits.filter((a) => options.auditsFilter.includes(a.name));
1459
+ }
1460
+ const enabledAuditNames = audits.map((a) => a.name);
1461
+ let pages = config.pages;
1462
+ if (options.pagesFilter?.length) {
1463
+ pages = pages.filter((p) => options.pagesFilter.includes(p.name));
1464
+ }
1465
+ log.plain("");
1466
+ log.info(`Base URL: ${config.baseURL}`);
1467
+ log.info(`Pages: ${pages.length}`);
1468
+ log.info(`Audits: ${enabledAuditNames.join(", ")}`);
1469
+ if (config.plugins.length > 0) {
1470
+ log.info(`Plugins: ${config.plugins.length}`);
1471
+ }
1472
+ if (config.runner.concurrency > 1) {
1473
+ log.info(`Workers: ${config.runner.concurrency}`);
1474
+ }
1475
+ log.plain("");
1476
+ let pageResults;
1477
+ if (config.runner.concurrency > 1) {
1478
+ pageResults = await runPagesParallel(
1479
+ pages,
1480
+ config,
1481
+ browserContext,
1482
+ audits,
1483
+ runDir,
1484
+ registry,
1485
+ config.runner.concurrency,
1486
+ config.runner.failFast
1487
+ );
1488
+ } else {
1489
+ pageResults = [];
1490
+ for (let i = 0; i < pages.length; i++) {
1491
+ const pageEntry = pages[i];
1492
+ log.plain(` [${i + 1}/${pages.length}] ${pageEntry.name} (${pageEntry.path})`);
1493
+ const result = await runPageAudits(
1494
+ pageEntry,
1495
+ config,
1496
+ browserContext,
1497
+ audits,
1498
+ runDir,
1499
+ registry
1500
+ );
1501
+ pageResults.push(result);
1502
+ for (const audit of result.audits) {
1503
+ const icon = audit.passed ? " \u2713" : audit.severity === "warning" ? " \u26A0" : " \u2717";
1504
+ const duration = audit.duration ? `${audit.duration}ms` : "";
1505
+ log.plain(`${icon} ${audit.audit.padEnd(20)} ${audit.message.padEnd(30)} ${duration}`);
1506
+ }
1507
+ log.plain("");
1508
+ if (config.runner.failFast && result.audits.some((a) => a.severity === "fail")) {
1509
+ log.warn("Fail fast enabled \u2014 stopping after first failure");
1510
+ break;
1511
+ }
1512
+ }
1513
+ }
1514
+ await browserContext.close();
1515
+ await browser.close();
1516
+ const allAudits = pageResults.flatMap((p) => p.audits);
1517
+ const runResult = {
1518
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1519
+ config: {
1520
+ baseURL: config.baseURL,
1521
+ totalPages: pages.length,
1522
+ auditsEnabled: enabledAuditNames
1523
+ },
1524
+ pages: pageResults,
1525
+ summary: {
1526
+ totalAudits: allAudits.length,
1527
+ passed: allAudits.filter((a) => a.severity === "pass").length,
1528
+ failed: allAudits.filter((a) => a.severity === "fail").length,
1529
+ warnings: allAudits.filter((a) => a.severity === "warning").length,
1530
+ skipped: allAudits.filter((a) => a.severity === "skip").length,
1531
+ duration: Date.now() - start
1532
+ }
1533
+ };
1534
+ await registry.runHook("afterAll", { config, result: runResult });
1535
+ await runReporters(runResult, config, runDir, registry.getPluginReporters());
1536
+ return runResult;
1537
+ }
1538
+
1539
+ // src/baseline/index.ts
1540
+ init_cjs_shims();
1541
+
1542
+ // src/baseline/storage.ts
1543
+ init_cjs_shims();
1544
+ var import_path14 = __toESM(require("path"), 1);
1545
+ var import_fs18 = __toESM(require("fs"), 1);
1546
+ init_logger();
1547
+ var BASELINE_FILENAME = "baseline.json";
1548
+ function saveBaseline(result, outputDir) {
1549
+ const baselinePath = import_path14.default.join(outputDir, BASELINE_FILENAME);
1550
+ import_fs18.default.writeFileSync(baselinePath, JSON.stringify(result, null, 2));
1551
+ log.success(`Baseline saved: ${baselinePath}`);
1552
+ }
1553
+ function loadBaseline(outputDir) {
1554
+ const baselinePath = import_path14.default.join(outputDir, BASELINE_FILENAME);
1555
+ if (!import_fs18.default.existsSync(baselinePath)) return null;
1556
+ try {
1557
+ return JSON.parse(import_fs18.default.readFileSync(baselinePath, "utf-8"));
1558
+ } catch {
1559
+ log.warn("Failed to parse baseline file");
1560
+ return null;
1561
+ }
1562
+ }
1563
+
1564
+ // src/baseline/diff.ts
1565
+ init_cjs_shims();
1566
+ function compareRuns(baseline, current) {
1567
+ const changes = [];
1568
+ const baselineMap = /* @__PURE__ */ new Map();
1569
+ for (const page of baseline.pages) {
1570
+ for (const audit of page.audits) {
1571
+ baselineMap.set(`${page.page}::${audit.audit}`, {
1572
+ severity: audit.severity,
1573
+ message: audit.message
1574
+ });
1575
+ }
1576
+ }
1577
+ const currentMap = /* @__PURE__ */ new Map();
1578
+ for (const page of current.pages) {
1579
+ for (const audit of page.audits) {
1580
+ const key = `${page.page}::${audit.audit}`;
1581
+ const entry = { severity: audit.severity, message: audit.message };
1582
+ currentMap.set(key, entry);
1583
+ const prev = baselineMap.get(key);
1584
+ if (!prev) {
1585
+ changes.push({
1586
+ page: page.page,
1587
+ audit: audit.audit,
1588
+ type: "new",
1589
+ current: entry
1590
+ });
1591
+ } else if (prev.severity !== audit.severity) {
1592
+ const type = audit.severity === "pass" || audit.severity === "skip" ? "improvement" : "regression";
1593
+ changes.push({
1594
+ page: page.page,
1595
+ audit: audit.audit,
1596
+ type,
1597
+ baseline: prev,
1598
+ current: entry
1599
+ });
1600
+ } else {
1601
+ changes.push({
1602
+ page: page.page,
1603
+ audit: audit.audit,
1604
+ type: "unchanged",
1605
+ baseline: prev,
1606
+ current: entry
1607
+ });
1608
+ }
1609
+ }
1610
+ }
1611
+ for (const [key, val] of baselineMap) {
1612
+ if (!currentMap.has(key)) {
1613
+ const [page, audit] = key.split("::");
1614
+ changes.push({ page, audit, type: "removed", baseline: val });
1615
+ }
1616
+ }
1617
+ return {
1618
+ baselineTimestamp: baseline.timestamp,
1619
+ currentTimestamp: current.timestamp,
1620
+ changes,
1621
+ summary: {
1622
+ regressions: changes.filter((c) => c.type === "regression").length,
1623
+ improvements: changes.filter((c) => c.type === "improvement").length,
1624
+ unchanged: changes.filter((c) => c.type === "unchanged").length,
1625
+ newAudits: changes.filter((c) => c.type === "new").length,
1626
+ removedAudits: changes.filter((c) => c.type === "removed").length
1627
+ }
1628
+ };
1629
+ }
1630
+
1631
+ // src/bin/cli.ts
1632
+ init_logger();
1633
+ var pkg = JSON.parse(
1634
+ import_fs19.default.readFileSync(new URL("../../package.json", importMetaUrl), "utf-8")
1635
+ );
1636
+ var program = new import_commander.Command();
1637
+ program.name("webguardx").description("Full-page web audit framework").version(pkg.version);
1638
+ program.command("init").description("Scaffold a webguard config in the current directory").action(async () => {
1639
+ const cwd = process.cwd();
1640
+ const configPath = import_path15.default.join(cwd, "webguard.config.ts");
1641
+ if (import_fs19.default.existsSync(configPath)) {
1642
+ log.warn("webguard.config.ts already exists. Skipping.");
1643
+ return;
1644
+ }
1645
+ const templatesDir = import_path15.default.resolve(
1646
+ new URL("../../templates/init", importMetaUrl).pathname
1647
+ );
1648
+ const templateConfig = import_path15.default.join(templatesDir, "webguard.config.ts");
1649
+ if (import_fs19.default.existsSync(templateConfig)) {
1650
+ import_fs19.default.copyFileSync(templateConfig, configPath);
1651
+ log.success("Created webguard.config.ts");
1652
+ } else {
1653
+ import_fs19.default.writeFileSync(
1654
+ configPath,
1655
+ `import { defineConfig } from "webguardx";
1656
+
1657
+ export default defineConfig({
1658
+ baseURL: "https://example.com",
1659
+
1660
+ pages: [
1661
+ { name: "Home", path: "/" },
1662
+ { name: "About", path: "/about" },
1663
+ ],
1664
+
1665
+ auth: {
1666
+ method: "none",
1667
+ },
1668
+
1669
+ audits: {
1670
+ httpStatus: true,
1671
+ contentVisibility: true,
1672
+ accessibility: true,
1673
+ lighthouse: false,
1674
+ brokenLinks: false,
1675
+ consoleErrors: true,
1676
+ },
1677
+
1678
+ output: {
1679
+ dir: "./webguard-results",
1680
+ formats: ["terminal", "html", "json"],
1681
+ screenshots: true,
1682
+ },
1683
+ });
1684
+ `,
1685
+ "utf-8"
1686
+ );
1687
+ log.success("Created webguard.config.ts");
1688
+ }
1689
+ const envExampleDest = import_path15.default.join(cwd, ".env.example");
1690
+ if (!import_fs19.default.existsSync(envExampleDest)) {
1691
+ const templateEnv = import_path15.default.join(templatesDir, ".env.example");
1692
+ if (import_fs19.default.existsSync(templateEnv)) {
1693
+ import_fs19.default.copyFileSync(templateEnv, envExampleDest);
1694
+ } else {
1695
+ import_fs19.default.writeFileSync(
1696
+ envExampleDest,
1697
+ `# Webguard environment variables
1698
+ # EMAIL=user@example.com
1699
+ # PASSWORD=your-password
1700
+ `,
1701
+ "utf-8"
1702
+ );
1703
+ }
1704
+ log.success("Created .env.example");
1705
+ }
1706
+ const gitignorePath = import_path15.default.join(cwd, ".gitignore");
1707
+ const gitignoreEntries = ["webguard-results/", ".env"];
1708
+ if (import_fs19.default.existsSync(gitignorePath)) {
1709
+ const existing = import_fs19.default.readFileSync(gitignorePath, "utf-8");
1710
+ const toAdd = gitignoreEntries.filter(
1711
+ (e) => !existing.includes(e)
1712
+ );
1713
+ if (toAdd.length > 0) {
1714
+ import_fs19.default.appendFileSync(
1715
+ gitignorePath,
1716
+ `
1717
+ # Webguard
1718
+ ${toAdd.join("\n")}
1719
+ `
1720
+ );
1721
+ log.success("Updated .gitignore");
1722
+ }
1723
+ } else {
1724
+ import_fs19.default.writeFileSync(
1725
+ gitignorePath,
1726
+ `node_modules/
1727
+ # Webguard
1728
+ ${gitignoreEntries.join("\n")}
1729
+ `,
1730
+ "utf-8"
1731
+ );
1732
+ log.success("Created .gitignore");
1733
+ }
1734
+ console.log("");
1735
+ log.info("Next steps:");
1736
+ log.plain(" 1. Edit webguard.config.ts with your pages & auth");
1737
+ log.plain(" 2. Run: npx webguard run");
1738
+ console.log("");
1739
+ });
1740
+ program.command("run").description("Run all audits").option("-c, --config <path>", "Path to config file").option("--headed", "Run browser in headed mode").option(
1741
+ "--pages <names>",
1742
+ "Comma-separated page names to audit",
1743
+ (val) => val.split(",").map((s) => s.trim())
1744
+ ).option(
1745
+ "--audits <names>",
1746
+ "Comma-separated audit names to run",
1747
+ (val) => val.split(",").map((s) => s.trim())
1748
+ ).option("--diff", "Compare results with saved baseline").action(async (opts) => {
1749
+ try {
1750
+ const dotenv = await import("dotenv");
1751
+ dotenv.config();
1752
+ console.log("");
1753
+ console.log(
1754
+ import_chalk3.default.bold(` webguard ${import_chalk3.default.dim(`v${pkg.version}`)}`)
1755
+ );
1756
+ console.log("");
1757
+ const config = await loadConfig(opts.config);
1758
+ const result = await run(config, {
1759
+ headed: opts.headed,
1760
+ pagesFilter: opts.pages,
1761
+ auditsFilter: opts.audits
1762
+ });
1763
+ if (opts.diff || config.baseline.enabled) {
1764
+ const outputDir = import_path15.default.resolve(config.output.dir);
1765
+ const baseline = loadBaseline(outputDir);
1766
+ if (baseline) {
1767
+ const comparison = compareRuns(baseline, result);
1768
+ console.log(import_chalk3.default.bold(" Baseline Comparison:"));
1769
+ if (comparison.summary.regressions > 0) {
1770
+ console.log(import_chalk3.default.red(` ${comparison.summary.regressions} regression(s)`));
1771
+ }
1772
+ if (comparison.summary.improvements > 0) {
1773
+ console.log(import_chalk3.default.green(` ${comparison.summary.improvements} improvement(s)`));
1774
+ }
1775
+ console.log(import_chalk3.default.dim(` ${comparison.summary.unchanged} unchanged`));
1776
+ if (comparison.summary.newAudits > 0) {
1777
+ console.log(import_chalk3.default.blue(` ${comparison.summary.newAudits} new audit(s)`));
1778
+ }
1779
+ console.log("");
1780
+ } else {
1781
+ log.dim(" No baseline found. Run 'webguard baseline save' to create one.");
1782
+ }
1783
+ if (config.baseline.updateOnPass && result.summary.failed === 0) {
1784
+ saveBaseline(result, import_path15.default.resolve(config.output.dir));
1785
+ }
1786
+ }
1787
+ if (result.summary.failed > 0) {
1788
+ process.exit(1);
1789
+ }
1790
+ } catch (err) {
1791
+ log.error(err.message);
1792
+ process.exit(1);
1793
+ }
1794
+ });
1795
+ program.command("report").description("Open or regenerate the HTML report from the last run").option("-c, --config <path>", "Path to config file").option("--open", "Open the report in default browser").action(async (opts) => {
1796
+ try {
1797
+ const config = await loadConfig(opts.config);
1798
+ const outputDir = import_path15.default.resolve(config.output.dir);
1799
+ if (!import_fs19.default.existsSync(outputDir)) {
1800
+ log.error(`No output directory found at ${outputDir}`);
1801
+ process.exit(1);
1802
+ }
1803
+ const runs = import_fs19.default.readdirSync(outputDir).filter((d) => d.startsWith("run-")).sort().reverse();
1804
+ if (runs.length === 0) {
1805
+ log.error("No runs found. Run 'webguard run' first.");
1806
+ process.exit(1);
1807
+ }
1808
+ const latestRun = import_path15.default.join(outputDir, runs[0]);
1809
+ const htmlReport = import_path15.default.join(latestRun, "report.html");
1810
+ const jsonReport = import_path15.default.join(latestRun, "results.json");
1811
+ if (!import_fs19.default.existsSync(htmlReport) && import_fs19.default.existsSync(jsonReport)) {
1812
+ const { reportHtml: reportHtml2 } = await Promise.resolve().then(() => (init_html(), html_exports));
1813
+ const result = JSON.parse(import_fs19.default.readFileSync(jsonReport, "utf-8"));
1814
+ reportHtml2(result, latestRun);
1815
+ log.success("Regenerated HTML report");
1816
+ }
1817
+ if (import_fs19.default.existsSync(htmlReport)) {
1818
+ log.info(`Report: ${htmlReport}`);
1819
+ if (opts.open) {
1820
+ const { exec } = await import("child_process");
1821
+ const openCmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "start" : "xdg-open";
1822
+ exec(`${openCmd} "${htmlReport}"`);
1823
+ }
1824
+ } else {
1825
+ log.error("No HTML report found. Run 'webguard run' first.");
1826
+ process.exit(1);
1827
+ }
1828
+ } catch (err) {
1829
+ log.error(err.message);
1830
+ process.exit(1);
1831
+ }
1832
+ });
1833
+ program.command("validate").description("Validate config file without running audits").option("-c, --config <path>", "Path to config file").action(async (opts) => {
1834
+ try {
1835
+ const config = await loadConfig(opts.config);
1836
+ log.success("Config is valid");
1837
+ log.info(`Base URL: ${config.baseURL}`);
1838
+ log.info(`Pages: ${config.pages.length}`);
1839
+ log.info(`Audits: ${Object.entries(config.audits).filter(([, v]) => v).map(([k]) => k).join(", ")}`);
1840
+ if (config.plugins.length > 0) {
1841
+ log.info(`Plugins: ${config.plugins.length}`);
1842
+ }
1843
+ } catch (err) {
1844
+ log.error(err.message);
1845
+ process.exit(1);
1846
+ }
1847
+ });
1848
+ var baselineCmd = program.command("baseline").description("Manage baseline for regression comparison");
1849
+ baselineCmd.command("save").description("Save the latest run as baseline").option("-c, --config <path>", "Path to config file").action(async (opts) => {
1850
+ try {
1851
+ const config = await loadConfig(opts.config);
1852
+ const outputDir = import_path15.default.resolve(config.output.dir);
1853
+ const runs = import_fs19.default.readdirSync(outputDir).filter((d) => d.startsWith("run-")).sort().reverse();
1854
+ if (runs.length === 0) {
1855
+ log.error("No runs found. Run 'webguard run' first.");
1856
+ process.exit(1);
1857
+ }
1858
+ const latestRun = import_path15.default.join(outputDir, runs[0]);
1859
+ const jsonReport = import_path15.default.join(latestRun, "results.json");
1860
+ if (!import_fs19.default.existsSync(jsonReport)) {
1861
+ log.error("No results.json found in latest run.");
1862
+ process.exit(1);
1863
+ }
1864
+ const result = JSON.parse(import_fs19.default.readFileSync(jsonReport, "utf-8"));
1865
+ saveBaseline(result, outputDir);
1866
+ } catch (err) {
1867
+ log.error(err.message);
1868
+ process.exit(1);
1869
+ }
1870
+ });
1871
+ baselineCmd.command("show").description("Show current baseline summary").option("-c, --config <path>", "Path to config file").action(async (opts) => {
1872
+ try {
1873
+ const config = await loadConfig(opts.config);
1874
+ const outputDir = import_path15.default.resolve(config.output.dir);
1875
+ const baseline = loadBaseline(outputDir);
1876
+ if (!baseline) {
1877
+ log.info("No baseline saved yet.");
1878
+ return;
1879
+ }
1880
+ log.info(`Baseline from: ${baseline.timestamp}`);
1881
+ log.info(`Pages: ${baseline.pages.length}`);
1882
+ log.info(
1883
+ `Results: ${baseline.summary.passed} passed, ${baseline.summary.failed} failed, ${baseline.summary.warnings} warnings`
1884
+ );
1885
+ } catch (err) {
1886
+ log.error(err.message);
1887
+ process.exit(1);
1888
+ }
1889
+ });
1890
+ program.command("diff").description("Compare the latest run with the baseline").option("-c, --config <path>", "Path to config file").action(async (opts) => {
1891
+ try {
1892
+ const config = await loadConfig(opts.config);
1893
+ const outputDir = import_path15.default.resolve(config.output.dir);
1894
+ const baseline = loadBaseline(outputDir);
1895
+ if (!baseline) {
1896
+ log.error("No baseline found. Run 'webguard baseline save' first.");
1897
+ process.exit(1);
1898
+ }
1899
+ const runs = import_fs19.default.readdirSync(outputDir).filter((d) => d.startsWith("run-")).sort().reverse();
1900
+ if (runs.length === 0) {
1901
+ log.error("No runs found. Run 'webguard run' first.");
1902
+ process.exit(1);
1903
+ }
1904
+ const latestRun = import_path15.default.join(outputDir, runs[0]);
1905
+ const jsonReport = import_path15.default.join(latestRun, "results.json");
1906
+ if (!import_fs19.default.existsSync(jsonReport)) {
1907
+ log.error("No results.json found in latest run.");
1908
+ process.exit(1);
1909
+ }
1910
+ const current = JSON.parse(import_fs19.default.readFileSync(jsonReport, "utf-8"));
1911
+ const comparison = compareRuns(baseline, current);
1912
+ console.log("");
1913
+ console.log(import_chalk3.default.bold(" Baseline Comparison"));
1914
+ console.log(import_chalk3.default.dim(` ${comparison.baselineTimestamp} \u2192 ${comparison.currentTimestamp}`));
1915
+ console.log("");
1916
+ if (comparison.summary.regressions > 0) {
1917
+ console.log(import_chalk3.default.red.bold(` Regressions: ${comparison.summary.regressions}`));
1918
+ for (const c of comparison.changes.filter((x) => x.type === "regression")) {
1919
+ console.log(import_chalk3.default.red(` \u2717 ${c.page} \u2192 ${c.audit}: ${c.baseline?.severity} \u2192 ${c.current?.severity}`));
1920
+ }
1921
+ console.log("");
1922
+ }
1923
+ if (comparison.summary.improvements > 0) {
1924
+ console.log(import_chalk3.default.green.bold(` Improvements: ${comparison.summary.improvements}`));
1925
+ for (const c of comparison.changes.filter((x) => x.type === "improvement")) {
1926
+ console.log(import_chalk3.default.green(` \u2713 ${c.page} \u2192 ${c.audit}: ${c.baseline?.severity} \u2192 ${c.current?.severity}`));
1927
+ }
1928
+ console.log("");
1929
+ }
1930
+ console.log(import_chalk3.default.dim(` Unchanged: ${comparison.summary.unchanged}`));
1931
+ if (comparison.summary.newAudits > 0) {
1932
+ console.log(import_chalk3.default.blue(` New audits: ${comparison.summary.newAudits}`));
1933
+ }
1934
+ if (comparison.summary.removedAudits > 0) {
1935
+ console.log(import_chalk3.default.yellow(` Removed audits: ${comparison.summary.removedAudits}`));
1936
+ }
1937
+ console.log("");
1938
+ } catch (err) {
1939
+ log.error(err.message);
1940
+ process.exit(1);
1941
+ }
1942
+ });
1943
+ program.parse();
1944
+ //# sourceMappingURL=cli.cjs.map