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